DeepSeekService.php 734 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265
  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 App\Services\PointsService;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Log;
  14. use Illuminate\Support\Facades\Redis;
  15. use OSS\Core\OssException;
  16. use OSS\OssClient;
  17. use Smalot\PdfParser\Parser as PdfParser;
  18. use TCPDF;
  19. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  20. use Predis\Command\Traits\Get\Get;
  21. class DeepSeekService
  22. {
  23. private $url;
  24. private $api_key;
  25. private $sys_message;
  26. private $headers;
  27. private $valid_text_models;
  28. private $gpt_text_models;
  29. protected $aiImageGenerationService;
  30. protected $pointsService;
  31. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  32. $this->aiImageGenerationService = $aiImageGenerationService;
  33. $this->pointsService = $pointsService;
  34. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  35. $this->api_key = env('DEEPSEEK_API_KEY');
  36. $this->headers = [
  37. 'Authorization' => 'Bearer '.$this->api_key,
  38. 'Content-Type' => 'application/json; charset=UTF-8'
  39. ];
  40. // 火山引擎模型列表
  41. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  42. // GPT文本模型列表
  43. $this->gpt_text_models = BaseConst::GPT_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. * 通用文生文方法 - 支持多模型流式输出和图片输入
  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. // 如果没有提供messages,则根据system_prompt、content和images构建
  122. if (empty($messages)) {
  123. $messages = [];
  124. // 添加系统提示词
  125. if (!empty($systemPrompt)) {
  126. $messages[] = [
  127. 'role' => 'system',
  128. 'content' => $systemPrompt
  129. ];
  130. }
  131. // 构建用户消息内容(支持文本+图片)
  132. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  133. $userMessage = [
  134. 'role' => 'user',
  135. 'content' => []
  136. ];
  137. // 添加文本内容
  138. if (!empty($prompt)) {
  139. $userMessage['content'][] = [
  140. 'type' => 'text',
  141. 'text' => $prompt
  142. ];
  143. }
  144. // 处理上传的图片文件
  145. if (!empty($images)) {
  146. if (!is_array($images)) {
  147. $images = [$images];
  148. }
  149. foreach ($images as $image) {
  150. $imageBase64 = $this->processImageToBase64($image);
  151. if ($imageBase64) {
  152. $userMessage['content'][] = [
  153. 'type' => 'image_url',
  154. 'image_url' => [
  155. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  156. ]
  157. ];
  158. }
  159. }
  160. }
  161. // 处理图片URL
  162. if (!empty($imageUrls)) {
  163. if (!is_array($imageUrls)) {
  164. $imageUrls = [$imageUrls];
  165. }
  166. foreach ($imageUrls as $url) {
  167. if (!empty($url)) {
  168. $userMessage['content'][] = [
  169. 'type' => 'image_url',
  170. 'image_url' => [
  171. 'url' => $url
  172. ]
  173. ];
  174. }
  175. }
  176. }
  177. // 如果只有文本内容,简化为字符串格式
  178. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  179. $userMessage['content'] = $userMessage['content'][0]['text'];
  180. }
  181. $messages[] = $userMessage;
  182. }
  183. }
  184. // 验证messages不为空
  185. if (empty($messages)) {
  186. Utils::throwError('20003:请提供有效的对话内容');
  187. }
  188. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  189. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  190. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  191. if ($model === 'deepseek-chat') {
  192. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  193. $model = 'deepseek-v4-flash';
  194. $thinkingMode = 'disabled';
  195. } elseif ($model === 'deepseek-reasoner') {
  196. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  197. $model = 'deepseek-v4-flash';
  198. $thinkingMode = 'enabled';
  199. }
  200. // 构建请求参数
  201. $post_data = [
  202. 'model' => $model,
  203. 'messages' => $messages,
  204. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  205. 'temperature' => getProp($data, 'temperature', 1),
  206. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  207. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  208. 'thinking' => ['type' => $thinkingMode],
  209. 'stream' => true // 启用流式输出
  210. ];
  211. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  212. // 添加可选参数
  213. if (isset($data['top_p'])) {
  214. $post_data['top_p'] = $data['top_p'];
  215. }
  216. if (isset($data['response_format'])) {
  217. $post_data['response_format'] = $data['response_format'];
  218. }
  219. // 根据模型类型选择调用方法
  220. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  221. // DeepSeek 官方模型使用 DeepSeek API
  222. return $this->deepSeekStreamResponse($post_data);
  223. } else if (in_array($model, $this->gpt_text_models)) {
  224. // GPT 模型使用 TokenRouter API
  225. return $this->gpt54StreamResponse($post_data);
  226. } else if (in_array($model, $this->valid_text_models)) {
  227. // 火山引擎支持的模型使用火山引擎 API
  228. return $this->volcEngineChatCompletion($post_data);
  229. } else {
  230. Utils::throwError('20003:不支持的模型: ' . $model);
  231. }
  232. }
  233. public function createGenerateText($data) {
  234. $file = getProp($data, 'file');
  235. $uid = Site::getUid();
  236. $cpid = Site::getCpid();
  237. if (!$file) {
  238. Utils::throwError('20003:请上传文件');
  239. }
  240. // 提取文件内容
  241. $content = $this->extractFileContent($file);
  242. if (!$content) {
  243. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  244. }
  245. // 获取原始文件名(不含扩展名)作为script_name
  246. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  247. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  248. // 字节安全剥离,不依赖服务器locale设置
  249. $originalName = $file->getClientOriginalName();
  250. $extension = $file->getClientOriginalExtension();
  251. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  252. ? substr($originalName, 0, -strlen($extension) - 1)
  253. : $originalName;
  254. if ($script_name === '') {
  255. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  256. }
  257. // 如果同一用户的剧本名存在则提示
  258. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  259. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  260. }
  261. // 插入数据到mp_scripts表
  262. $script_id = DB::table('mp_scripts')->insertGetId([
  263. 'script_name' => $script_name,
  264. 'user_id' => $uid,
  265. 'cpid' => $cpid,
  266. 'content' => $content,
  267. 'created_at' => date('Y-m-d H:i:s'),
  268. 'updated_at' => date('Y-m-d H:i:s')
  269. ]);
  270. return [
  271. 'script_id' => $script_id,
  272. 'script_name' => $script_name
  273. ];
  274. }
  275. /**
  276. * AI对话调用成功后的积分扣费(返回结果前调用)
  277. *
  278. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  279. *
  280. * @param int $uid
  281. * @param int $tokens
  282. * @param array $chargeInfo
  283. * @return void
  284. */
  285. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo): void
  286. {
  287. $result = $this->pointsService->recordChatCharge(
  288. $uid,
  289. PointsService::CHAT_CHARGE_POINTS,
  290. $tokens,
  291. $chargeInfo
  292. );
  293. if (empty($result['charged'])) {
  294. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  295. }
  296. }
  297. /**
  298. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  299. *
  300. * @param array $data 请求参数
  301. * @return array 返回结果数组
  302. */
  303. public function newGenerateText($data) {
  304. // 获取请求参数
  305. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  306. $messages = getProp($data, 'messages', []);
  307. $systemPrompt = getProp($data, 'system_prompt', '');
  308. $prompt = getProp($data, 'prompt', '');
  309. $images = getProp($data, 'images', []); // 支持多张图片
  310. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  311. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  312. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  313. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  314. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  315. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  316. $generateTaskId = 0;
  317. $uid = Site::getUid();
  318. if ($script_id > 0) {
  319. $existingTask = DB::table('mp_script_generate_tasks')
  320. ->where('uid', $uid)
  321. ->where('script_id', $script_id)
  322. ->orderByDesc('id')
  323. ->first();
  324. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  325. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  326. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  327. }
  328. }
  329. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  330. $originalContent = '';
  331. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  332. if ($script_id > 0) {
  333. $script = DB::table('mp_scripts')
  334. ->where('id', $script_id)
  335. ->where('is_deleted', 0)
  336. ->first();
  337. if (!$script) {
  338. Utils::throwError('20003:剧本不存在或已删除');
  339. }
  340. $originalContent = $script->content ?? '';
  341. if (empty($originalContent)) {
  342. Utils::throwError('20003:剧本内容为空');
  343. }
  344. $hasValidScript = true;
  345. // 将剧本内容添加到提示词前面
  346. if (!empty($originalContent)) {
  347. if (!empty($prompt)) {
  348. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  349. } else {
  350. $prompt = "原文内容:\n" . $originalContent;
  351. }
  352. }
  353. }
  354. // 新增: 如果提供了template_id,从数据库获取template_prompt
  355. if ($templateId > 0) {
  356. $template = DB::table('mp_prompt_templates')
  357. ->where('id', $templateId)
  358. ->where('is_deleted', 0)
  359. ->first();
  360. if (!$template) {
  361. Utils::throwError('20003:模板不存在或已删除');
  362. }
  363. $templatePrompt = $template->template_prompt ?? '';
  364. // 将模板提示词和用户输入的prompt组合
  365. // 模板为准,用户输入作为补充要求
  366. if (!empty($templatePrompt)) {
  367. if (!empty($prompt)) {
  368. $prompt = $templatePrompt . "\n\n" . $prompt;
  369. } else {
  370. $prompt = $templatePrompt;
  371. }
  372. }
  373. }
  374. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  375. if (empty($messages)) {
  376. $messages = [];
  377. // 添加系统提示词
  378. if (!empty($systemPrompt)) {
  379. $messages[] = [
  380. 'role' => 'system',
  381. 'content' => $systemPrompt
  382. ];
  383. }
  384. // 构建用户消息内容(支持文本+图片)
  385. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  386. $userMessage = [
  387. 'role' => 'user',
  388. 'content' => []
  389. ];
  390. // 添加文本内容
  391. if (!empty($prompt)) {
  392. $userMessage['content'][] = [
  393. 'type' => 'text',
  394. 'text' => $prompt
  395. ];
  396. }
  397. // 处理上传的图片文件
  398. if (!empty($images)) {
  399. if (!is_array($images)) {
  400. $images = [$images];
  401. }
  402. foreach ($images as $image) {
  403. $imageBase64 = $this->processImageToBase64($image);
  404. if ($imageBase64) {
  405. $userMessage['content'][] = [
  406. 'type' => 'image_url',
  407. 'image_url' => [
  408. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  409. ]
  410. ];
  411. }
  412. }
  413. }
  414. // 处理图片URL
  415. if (!empty($imageUrls)) {
  416. if (!is_array($imageUrls)) {
  417. $imageUrls = [$imageUrls];
  418. }
  419. foreach ($imageUrls as $url) {
  420. if (!empty($url)) {
  421. $userMessage['content'][] = [
  422. 'type' => 'image_url',
  423. 'image_url' => [
  424. 'url' => $url
  425. ]
  426. ];
  427. }
  428. }
  429. }
  430. // 如果只有文本内容,简化为字符串格式
  431. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  432. $userMessage['content'] = $userMessage['content'][0]['text'];
  433. }
  434. $messages[] = $userMessage;
  435. }
  436. }
  437. // 验证messages不为空
  438. if (empty($messages)) {
  439. Utils::throwError('20003:请提供有效的对话内容');
  440. }
  441. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  442. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  443. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  444. if ($model === 'deepseek-chat') {
  445. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  446. $model = 'deepseek-v4-flash';
  447. $thinkingMode = 'disabled';
  448. } elseif ($model === 'deepseek-reasoner') {
  449. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  450. $model = 'deepseek-v4-flash';
  451. $thinkingMode = 'enabled';
  452. }
  453. // 构建请求参数(非流式)
  454. $post_data = [
  455. 'model' => $model,
  456. 'messages' => $messages,
  457. 'temperature' => getProp($data, 'temperature', 1),
  458. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  459. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  460. 'thinking' => ['type' => $thinkingMode],
  461. 'stream' => false // 非流式输出
  462. ];
  463. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  464. // 添加可选参数
  465. if (isset($data['top_p'])) {
  466. $post_data['top_p'] = $data['top_p'];
  467. }
  468. // 新增: 根据response_format设置响应格式
  469. if ($responseFormat === 'json') {
  470. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  471. $hasJsonKeyword = false;
  472. foreach ($post_data['messages'] as $message) {
  473. if (isset($message['content'])) {
  474. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  475. if (stripos($content, 'json') !== false) {
  476. $hasJsonKeyword = true;
  477. break;
  478. }
  479. }
  480. }
  481. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  482. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  483. if (!$hasJsonKeyword) {
  484. $lastMessageIndex = count($post_data['messages']) - 1;
  485. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  486. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  487. // 如果content是字符串,直接追加
  488. if (is_string($lastContent)) {
  489. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  490. }
  491. // 如果content是数组(包含文本和图片),在文本部分追加
  492. else if (is_array($lastContent)) {
  493. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  494. if ($contentPart['type'] === 'text') {
  495. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  496. break;
  497. }
  498. }
  499. }
  500. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  501. }
  502. }
  503. // 设置response_format参数(所有支持的模型)
  504. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  505. // DeepSeek模型
  506. $post_data['response_format'] = ['type' => 'json_object'];
  507. } else if (in_array($model, $this->gpt_text_models)) {
  508. // GPT模型
  509. $post_data['response_format'] = ['type' => 'json_object'];
  510. } else if (in_array($model, $this->valid_text_models)) {
  511. // 火山引擎模型
  512. $post_data['response_format'] = ['type' => 'json_object'];
  513. }
  514. }
  515. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  516. if ($script_id > 0) {
  517. $uid = Site::getUid();
  518. // 创建新的生成任务
  519. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  520. 'uid' => $uid,
  521. 'script_id' => $script_id,
  522. 'sequence' => $sequence,
  523. 'status' => 'processing',
  524. 'prompt' => getProp($data, 'prompt', ''),
  525. 'started_at' => date('Y-m-d H:i:s'),
  526. 'created_at' => date('Y-m-d H:i:s'),
  527. 'updated_at' => date('Y-m-d H:i:s')
  528. ]);
  529. }
  530. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  531. if ($hasValidScript) {
  532. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  533. }
  534. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  535. try {
  536. $aiResult = null;
  537. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  538. // DeepSeek 官方模型使用现有的 chatOnly 方法
  539. $result = $this->chatOnly($post_data);
  540. // 记录实际使用的模型
  541. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  542. $aiResult = [
  543. 'content' => $result['fullContent'],
  544. 'reasoning_content' => $result['fullReasoningContent'],
  545. 'usage' => $result['usage'],
  546. 'model' => $model,
  547. 'finish_reason' => 'stop'
  548. ];
  549. } else if (in_array($model, $this->gpt_text_models)) {
  550. // GPT 模型使用现有的 gpt54ChatOnly 方法
  551. $result = $this->gpt54ChatOnly($post_data);
  552. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  553. $aiResult = [
  554. 'content' => $result['fullContent'],
  555. 'reasoning_content' => '',
  556. 'usage' => $result['usage'],
  557. 'model' => $model,
  558. 'finish_reason' => 'stop'
  559. ];
  560. } else if (in_array($model, $this->valid_text_models)) {
  561. // 火山引擎支持的模型使用火山引擎 API(非流式)
  562. $post_data['stream'] = false;
  563. $result = $this->volcEngineChatCompletion($post_data);
  564. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  565. 'requested_model' => $model,
  566. 'result_keys' => array_keys($result),
  567. 'has_fullContent' => isset($result['fullContent']),
  568. 'has_content' => isset($result['content'])
  569. ]);
  570. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  571. $aiResult = [
  572. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  573. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  574. 'usage' => $result['usage'] ?? [],
  575. 'model' => $model,
  576. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  577. ];
  578. } else {
  579. Utils::throwError('20003:不支持的模型: ' . $model);
  580. }
  581. } catch (\Exception $e) {
  582. // 生成失败,更新任务状态
  583. if ($generateTaskId) {
  584. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  585. 'status' => 'failed',
  586. 'error_message' => $e->getMessage(),
  587. 'completed_at' => date('Y-m-d H:i:s'),
  588. 'updated_at' => date('Y-m-d H:i:s')
  589. ]);
  590. }
  591. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  592. }
  593. // 生成成功,更新任务状态
  594. if ($generateTaskId && $aiResult) {
  595. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  596. 'status' => 'success',
  597. 'result' => getProp($aiResult, 'content', ''),
  598. 'completed_at' => date('Y-m-d H:i:s'),
  599. 'updated_at' => date('Y-m-d H:i:s')
  600. ]);
  601. $aiResult['generate_task_id'] = $generateTaskId;
  602. }
  603. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  604. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  605. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  606. 'model' => $model,
  607. 'script_id' => $script_id,
  608. 'sequence' => $sequence,
  609. 'source' => 'newGenerateText',
  610. ]);
  611. }
  612. // 新增: 如果提供了script_id,保存对话记录
  613. if ($script_id > 0 && $aiResult) {
  614. try {
  615. $uid = Site::getUid();
  616. $now = now();
  617. // 获取用户原始的prompt(不包含剧本内容)
  618. $originalPrompt = getProp($data, 'prompt', '');
  619. $recordsToInsert = [
  620. [
  621. 'uid' => $uid,
  622. 'script_id' => $script_id,
  623. 'sequence' => $sequence,
  624. 'role' => 'user',
  625. 'content' => $originalPrompt,
  626. 'created_at' => $now,
  627. 'updated_at' => $now,
  628. ],
  629. [
  630. 'uid' => $uid,
  631. 'script_id' => $script_id,
  632. 'sequence' => $sequence,
  633. 'role' => 'assistant',
  634. 'content' => $aiResult['content'],
  635. 'created_at' => $now,
  636. 'updated_at' => $now,
  637. ]
  638. ];
  639. DB::table('mp_script_records')->insert($recordsToInsert);
  640. // 获取刚插入的记录ID(假设按插入顺序返回)
  641. $insertedRecords = DB::table('mp_script_records')
  642. ->where('uid', $uid)
  643. ->where('script_id', $script_id)
  644. ->where('sequence', $sequence)
  645. ->orderBy('id', 'desc')
  646. ->limit(2)
  647. ->get()
  648. ->map(function ($record) {
  649. return [
  650. 'rid' => $record->id,
  651. 'script_id' => $record->script_id,
  652. 'sequence' => $record->sequence,
  653. 'role' => $record->role,
  654. 'content' => $record->content,
  655. 'created_at' => $record->created_at,
  656. ];
  657. })
  658. ->reverse()
  659. ->values()
  660. ->toArray();
  661. // 将记录信息添加到返回结果中
  662. $aiResult['records'] = $insertedRecords;
  663. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  664. } catch (\Exception $e) {
  665. // 记录错误但不影响主流程
  666. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  667. }
  668. }
  669. return $aiResult;
  670. }
  671. /**
  672. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  673. *
  674. * @param array $data
  675. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  676. */
  677. public function getScriptGenerateTasks($data) {
  678. $uid = Site::getUid();
  679. return DB::table('mp_script_generate_tasks as t')
  680. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  681. ->where('t.uid', $uid)
  682. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  683. ->orderByDesc('t.id')
  684. ->paginate(15);
  685. }
  686. public function saveScriptChatHistory($data) {
  687. $uid = Site::getUid();
  688. $rid = getProp($data, 'rid');
  689. $script_id = getProp($data, 'script_id');
  690. $sequence = getProp($data, 'sequence', 0);
  691. $content = getProp($data, 'content');
  692. if (!$rid) {
  693. Utils::throwError('20003:请选择对话记录ID');
  694. }
  695. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  696. if (!$record) {
  697. Utils::throwError('20003:对话记录不存在');
  698. }
  699. if (!$script_id) {
  700. Utils::throwError('20003:请选择剧本');
  701. }
  702. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  703. if (!$script) {
  704. Utils::throwError('20003:剧本不存在');
  705. }
  706. // 批量插入数据
  707. return DB::table('mp_script_records')->where('id', $rid)->update([
  708. 'content' => $content,
  709. 'updated_at' => date('Y-m-d H:i:s')
  710. ]);
  711. }
  712. /**
  713. * 获取剧本的历史对话记录
  714. *
  715. * @param array $data 请求参数
  716. * @return array 返回历史记录数组
  717. */
  718. public function getScriptChatHistory($data) {
  719. $uid = Site::getUid();
  720. $script_id = getProp($data, 'script_id');
  721. $rid = getProp($data, 'rid');
  722. $sequence = getProp($data, 'sequence', null);
  723. if (!$script_id) {
  724. Utils::throwError('20003:请提供剧本ID');
  725. }
  726. // 验证剧本是否存在
  727. $script = DB::table('mp_scripts')
  728. ->where('id', $script_id)
  729. ->where('is_deleted', 0)
  730. ->first();
  731. if (!$script) {
  732. Utils::throwError('20003:剧本不存在');
  733. }
  734. // 构建查询
  735. $query = DB::table('mp_script_records')
  736. ->where('script_id', $script_id);
  737. // ->where('uid', $uid);
  738. // 如果提供了 sequence,则过滤指定剧集
  739. if ($sequence !== null) {
  740. $query->where('sequence', $sequence);
  741. }
  742. // 记录ID筛选
  743. if ($rid) {
  744. $query->where('id', $rid);
  745. }
  746. // 查询记录并按 id 正序排序
  747. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  748. ->orderBy('created_at', 'asc')
  749. ->orderBy('id', 'asc')
  750. ->get()
  751. ->map(function ($record) {
  752. return [
  753. 'rid' => $record->id,
  754. 'script_id' => $record->script_id,
  755. 'sequence' => $record->sequence,
  756. 'role' => $record->role,
  757. 'content' => $record->content,
  758. 'products' => $record->products ? json_decode($record->products) : [],
  759. 'created_at' => $record->created_at,
  760. ];
  761. })
  762. ->toArray();
  763. return $records;
  764. }
  765. /**
  766. * 处理图片转换为base64
  767. *
  768. * @param mixed $image 图片文件对象或文件路径
  769. * @return string|null base64编码的图片数据
  770. */
  771. private function processImageToBase64($image) {
  772. try {
  773. // 获取文件路径
  774. if (is_string($image)) {
  775. $filePath = $image;
  776. } else {
  777. // Laravel UploadedFile 对象
  778. $filePath = $image->getRealPath();
  779. }
  780. if (!file_exists($filePath)) {
  781. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  782. return null;
  783. }
  784. // 验证是否为图片文件
  785. $imageInfo = @getimagesize($filePath);
  786. if ($imageInfo === false) {
  787. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  788. return null;
  789. }
  790. // 读取图片并转换为base64
  791. $imageData = file_get_contents($filePath);
  792. $base64Image = base64_encode($imageData);
  793. dLog('deepseek')->info('图片转换成功', [
  794. 'size' => strlen($imageData),
  795. 'type' => $imageInfo['mime']
  796. ]);
  797. return $base64Image;
  798. } catch (\Exception $e) {
  799. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  800. return null;
  801. }
  802. }
  803. private function getArtStylePromptMappings($art_style='')
  804. {
  805. $arr = [
  806. '唯美真人风格' => [
  807. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  808. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  809. ],
  810. '真人古风风格' => [
  811. 'aliases' => ['真人古风风格', '真人古风'],
  812. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  813. ],
  814. '日系动漫风格' => [
  815. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  816. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  817. ],
  818. '国漫风格' => [
  819. 'aliases' => ['国漫风格', '国漫'],
  820. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  821. ],
  822. 'Q版卡通风格' => [
  823. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  824. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  825. ],
  826. '简约扁平风格' => [
  827. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  828. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  829. ],
  830. '武侠风格' => [
  831. 'aliases' => ['武侠风格', '武侠'],
  832. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  833. ],
  834. '古风仙侠风格' => [
  835. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  836. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  837. ],
  838. '新中式水墨风格' => [
  839. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  840. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  841. ],
  842. '写实插画风格' => [
  843. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  844. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  845. ],
  846. '3D卡通风格' => [
  847. 'aliases' => ['3D卡通风格', '3D卡通'],
  848. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  849. ],
  850. '条漫风格' => [
  851. 'aliases' => ['条漫风格', '条漫'],
  852. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  853. ],
  854. '赛博朋克风格' => [
  855. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  856. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  857. ],
  858. '暗黑悬疑风格' => [
  859. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  860. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  861. ],
  862. '治愈清新风格' => [
  863. 'aliases' => ['治愈清新风格', '治愈清新'],
  864. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  865. ],
  866. '3D真人风格' => [
  867. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  868. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  869. ],
  870. ];
  871. if($art_style) {
  872. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  873. }
  874. return $arr;
  875. $arr = [
  876. '唯美真人风格' => [
  877. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  878. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  879. 2. 色彩色调
  880. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  881. 3. 画质精度
  882. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  883. 4. 画面观感
  884. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  885. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  886. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  887. ],
  888. '真人古风风格' => [
  889. 'aliases' => ['真人古风风格', '真人古风'],
  890. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  891. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  892. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  893. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  894. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  895. ],
  896. '日系动漫风格' => [
  897. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  898. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  899. 正向提示词(中文)
  900. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  901. 必须遵守规则
  902. • 全程保持日系动漫风格,不混入其他画风
  903. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  904. • 画面适配所选画面比例,构图居中,主体突出
  905. • 线条干净、色彩统一,不杂乱、不突兀
  906. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  907. ],
  908. '国漫风格' => [
  909. 'aliases' => ['国漫风格', '国漫'],
  910. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  911. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  912. 必须遵守规则
  913. • 严格保持国漫画风,不串风格、不混画风
  914. • 角色形象统一,不随意改变五官、身材、服饰
  915. • 画面构图稳定,适合漫剧叙事展示
  916. • 色调统一,不出现脏色、杂色
  917. 禁止/避免词汇
  918. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  919. ],
  920. 'Q版卡通风格' => [
  921. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  922. 'prompt' => "风格说明
  923. 头大身小,造型可爱圆润,简约干净
  924. 正向提示词(中文)
  925. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  926. 必须遵守规则
  927. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  928. • 角色造型统一,表情可爱,不诡异
  929. • 画面简洁清爽,无多余复杂元素
  930. • 色彩明亮柔和,不刺眼
  931. 禁止/避免词汇
  932. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  933. ],
  934. '简约扁平风格' => [
  935. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  936. 'prompt' => "风格说明
  937. 色块简洁、无复杂渐变,现代极简风
  938. 正向提示词(中文)
  939. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  940. 必须遵守规则
  941. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  942. • 构图简洁,主体突出,无多余装饰
  943. • 色彩统一、干净,不杂乱
  944. 禁止/避免词汇
  945. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  946. ],
  947. '武侠风格' => [
  948. 'aliases' => ['武侠风格', '武侠'],
  949. 'prompt' => "风格说明
  950. 江湖气息,线条硬朗,动作感强
  951. 正向提示词(中文)
  952. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  953. 必须遵守规则
  954. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  955. • 角色形象、服饰、身材比例统一
  956. • 画面动作自然,不扭曲、不畸形
  957. 禁止/避免词汇
  958. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  959. ],
  960. '古风仙侠风格' => [
  961. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  962. 'prompt' => "风格说明
  963. 飘逸汉服、云雾仙气、唯美空灵
  964. 正向提示词(中文)
  965. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  966. 必须遵守规则
  967. • 保持古风仙侠统一画风,不混入现代、科幻元素
  968. • 角色服饰、发型、形象前后一致
  969. • 场景仙气飘逸,色调清雅统一
  970. • 画面唯美柔和,不阴暗、不诡异
  971. 禁止/避免词汇
  972. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  973. ],
  974. '新中式水墨风格' => [
  975. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  976. 'prompt' => "风格说明
  977. 淡墨渲染,毛笔笔触,留白意境
  978. 正向提示词(中文)
  979. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  980. 必须遵守规则
  981. • 严格保持水墨质感,不混入厚涂、写实、卡通
  982. • 色调淡雅统一,不浓艳杂乱
  983. • 画面干净有意境,不堆砌元素
  984. 禁止/避免词汇
  985. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  986. ],
  987. '写实插画风格' => [
  988. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  989. 'prompt' => "风格说明
  990. 接近真人比例,光影真实,质感细腻
  991. 正向提示词(中文)
  992. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  993. 必须遵守规则
  994. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  995. • 角色五官、身材、服饰高度统一
  996. • 画面清晰、光影自然、不扭曲
  997. 禁止/避免词汇
  998. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  999. ],
  1000. '3D卡通风格' => [
  1001. 'aliases' => ['3D卡通风格', '3D卡通'],
  1002. 'prompt' => "风格说明
  1003. 3D建模质感,柔和渲染,圆润可爱
  1004. 正向提示词(中文)
  1005. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  1006. 必须遵守规则
  1007. • 保持3D卡通统一质感,不出现2D杂乱线条
  1008. • 角色模型、比例、形象前后一致
  1009. • 画面干净,不模糊、不穿模
  1010. 禁止/避免词汇
  1011. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  1012. ],
  1013. '条漫风格' => [
  1014. 'aliases' => ['条漫风格', '条漫'],
  1015. 'prompt' => "风格说明
  1016. 纵向分镜,上下滑动阅读,轻量化
  1017. 正向提示词(中文)
  1018. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  1019. 必须遵守规则
  1020. • 保持条漫纵向阅读逻辑,构图简洁
  1021. • 画风统一,不混写实、3D、水墨
  1022. • 画面干净,不杂乱
  1023. 禁止/避免词汇
  1024. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  1025. ],
  1026. '赛博朋克风格' => [
  1027. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1028. 'prompt' => "风格说明
  1029. 霓虹灯光、未来都市、暗色调、科技机械
  1030. 正向提示词(中文)
  1031. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  1032. 必须遵守规则
  1033. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  1034. • 色调以暗调+霓虹为主,色彩统一
  1035. • 画面科技感强,不杂乱
  1036. 禁止/避免词汇
  1037. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  1038. ],
  1039. '暗黑悬疑风格' => [
  1040. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1041. 'prompt' => "风格说明
  1042. 低饱和、冷色调、阴影重、神秘压抑
  1043. 正向提示词(中文)
  1044. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  1045. 必须遵守规则
  1046. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  1047. • 画面氛围压抑神秘,但不低俗、不血腥
  1048. • 角色形象统一,不崩坏
  1049. 禁止/避免词汇
  1050. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  1051. ],
  1052. '治愈清新风格' => [
  1053. 'aliases' => ['治愈清新风格', '治愈清新'],
  1054. 'prompt' => "风格说明
  1055. 马卡龙色系、柔光、温暖干净
  1056. 正向提示词(中文)
  1057. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  1058. 必须遵守规则
  1059. • 保持治愈清新统一色调,不阴暗、不诡异
  1060. • 画面柔和干净,无杂乱元素
  1061. • 角色形象柔和可爱,不狰狞
  1062. 禁止/避免词汇
  1063. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  1064. ],
  1065. ];
  1066. return $arr;
  1067. }
  1068. public function getArtStylePromptByInput($inputArtStyle): string
  1069. {
  1070. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  1071. if ($normalizedInput === '') {
  1072. return '';
  1073. }
  1074. return $this->getArtStylePromptMappings($normalizedInput);
  1075. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  1076. // foreach ($mapping['aliases'] as $alias) {
  1077. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  1078. // if ($normalizedAlias === '') {
  1079. // continue;
  1080. // }
  1081. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  1082. // return $mapping['prompt'];
  1083. // }
  1084. // }
  1085. // }
  1086. return '';
  1087. }
  1088. public function getArtStyleShortPromptByInput($inputArtStyle) {
  1089. $stylePrefixes = [
  1090. '唯美真人风格' => [
  1091. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  1092. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  1093. ],
  1094. '真人古风风格' => [
  1095. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  1096. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  1097. ],
  1098. '日系动漫风格' => [
  1099. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  1100. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  1101. ],
  1102. '国漫风格' => [
  1103. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  1104. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  1105. ],
  1106. 'Q版卡通风格' => [
  1107. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  1108. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  1109. ],
  1110. '简约扁平风格' => [
  1111. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  1112. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  1113. ],
  1114. '武侠风格' => [
  1115. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  1116. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  1117. ],
  1118. '古风仙侠风格' => [
  1119. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  1120. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  1121. ],
  1122. '新中式水墨风格' => [
  1123. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1124. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1125. ],
  1126. '写实插画风格' => [
  1127. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1128. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1129. ],
  1130. '3D卡通风格' => [
  1131. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1132. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  1133. ],
  1134. '条漫风格' => [
  1135. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  1136. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  1137. ],
  1138. '赛博朋克风格' => [
  1139. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  1140. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  1141. ],
  1142. '暗黑悬疑风格' => [
  1143. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  1144. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  1145. ],
  1146. '治愈清新风格' => [
  1147. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1148. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1149. ]
  1150. ];
  1151. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1152. }
  1153. private function normalizeArtStyleInput($value): string
  1154. {
  1155. $value = trim((string)$value);
  1156. if ($value === '') {
  1157. return '';
  1158. }
  1159. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1160. return mb_strtolower($value, 'UTF-8');
  1161. }
  1162. private function replaceArtStyleSection(string $content, string $artStyle): string
  1163. {
  1164. if ($content === '' || $artStyle === '') {
  1165. return $content;
  1166. }
  1167. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1168. if (!preg_match($pattern, $content)) {
  1169. return $content;
  1170. }
  1171. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1172. }
  1173. /**
  1174. * DeepSeek流式输出处理方法
  1175. *
  1176. * @param array $post_data DeepSeek API请求参数
  1177. * @return \Generator 返回生成器,用于流式输出
  1178. */
  1179. private function deepSeekStreamResponse($post_data) {
  1180. // 设置最大输出tokens
  1181. $post_data['max_tokens'] = 300000;
  1182. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  1183. $post_data['stream_options'] = ['include_usage' => true];
  1184. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1185. $response = $client->post($this->url, [
  1186. 'json' => $post_data,
  1187. 'headers' => $this->headers,
  1188. 'stream' => true // 启用流式响应
  1189. ]);
  1190. $body = $response->getBody();
  1191. $fullContent = '';
  1192. $fullReasoningContent = '';
  1193. $usage = [];
  1194. $buffer = '';
  1195. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1196. // 逐行读取流式响应
  1197. while (!$body->eof()) {
  1198. $chunk = $body->read(1024); // 每次读取 1KB
  1199. $buffer .= $chunk;
  1200. // 按行分割
  1201. $lines = explode("\n", $buffer);
  1202. // 保留最后一个不完整的行
  1203. $buffer = array_pop($lines);
  1204. foreach ($lines as $line) {
  1205. $line = trim($line);
  1206. // 跳过空行
  1207. if (empty($line)) {
  1208. continue;
  1209. }
  1210. // 检查是否是 SSE 数据行
  1211. if (strpos($line, 'data: ') !== 0) {
  1212. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1213. continue;
  1214. }
  1215. $data = substr($line, 6); // 移除 "data: " 前缀
  1216. if ($data === '[DONE]') {
  1217. dLog('deepseek')->info('收到结束标记');
  1218. break 2; // 跳出两层循环
  1219. }
  1220. try {
  1221. $json = json_decode($data, true);
  1222. if (json_last_error() !== JSON_ERROR_NONE) {
  1223. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1224. continue;
  1225. }
  1226. if (isset($json['choices'][0]['delta'])) {
  1227. $delta = $json['choices'][0]['delta'];
  1228. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1229. if (isset($delta['reasoning_content'])) {
  1230. $fullReasoningContent .= $delta['reasoning_content'];
  1231. yield [
  1232. 'type' => 'reasoning',
  1233. 'content' => $delta['reasoning_content'],
  1234. 'full_reasoning' => $fullReasoningContent
  1235. ];
  1236. }
  1237. // 处理最终回答内容
  1238. if (isset($delta['content'])) {
  1239. $fullContent .= $delta['content'];
  1240. yield [
  1241. 'type' => 'content',
  1242. 'content' => $delta['content'],
  1243. ];
  1244. }
  1245. }
  1246. // 获取使用统计信息
  1247. if (isset($json['usage'])) {
  1248. $usage = $json['usage'];
  1249. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1250. }
  1251. } catch (\Exception $e) {
  1252. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1253. continue;
  1254. }
  1255. }
  1256. }
  1257. dLog('deepseek')->info('流式读取完成', [
  1258. 'content_length' => strlen($fullContent),
  1259. 'reasoning_length' => strlen($fullReasoningContent)
  1260. ]);
  1261. yield [
  1262. 'type' => 'done',
  1263. 'full_content' => $fullContent,
  1264. 'full_reasoning' => $fullReasoningContent,
  1265. 'usage' => $usage
  1266. ];
  1267. }
  1268. /**
  1269. * GPT 重试次数(env 可配置,默认 5 次)
  1270. */
  1271. private function gptRetryTimes()
  1272. {
  1273. return (int)env('GPT_RETRY_TIMES', 5);
  1274. }
  1275. /**
  1276. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  1277. */
  1278. private function gptRetryInterval()
  1279. {
  1280. return (int)env('GPT_RETRY_INTERVAL', 10);
  1281. }
  1282. /**
  1283. * 判断 GPT 请求异常是否可重试
  1284. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  1285. */
  1286. private function isGptRetryableException(\Exception $e)
  1287. {
  1288. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  1289. return false;
  1290. }
  1291. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1292. $status = $e->getResponse()->getStatusCode();
  1293. return $status >= 500 || $status == 429;
  1294. }
  1295. return true;
  1296. }
  1297. /**
  1298. * GPT 中转站探活:GET /v1/models,5 秒短超时
  1299. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  1300. */
  1301. private function checkGptServiceAvailable()
  1302. {
  1303. $apiKey = env('GPT_54_API_KEY');
  1304. if (empty($apiKey)) {
  1305. return false;
  1306. }
  1307. try {
  1308. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  1309. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  1310. 'headers' => [
  1311. 'Authorization' => 'Bearer ' . $apiKey,
  1312. 'Content-Type' => 'application/json'
  1313. ]
  1314. ]);
  1315. $status = $response->getStatusCode();
  1316. return $status < 500 && $status != 429;
  1317. } catch (\Exception $e) {
  1318. return false;
  1319. }
  1320. }
  1321. /**
  1322. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  1323. * 全部失败抛出友好错误
  1324. */
  1325. private function ensureGptServiceAvailable()
  1326. {
  1327. $maxRetries = $this->gptRetryTimes();
  1328. $interval = $this->gptRetryInterval();
  1329. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  1330. if ($this->checkGptServiceAvailable()) {
  1331. return;
  1332. }
  1333. if ($attempt < $maxRetries) {
  1334. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  1335. 'retry' => $attempt + 1,
  1336. 'max_retries' => $maxRetries
  1337. ]);
  1338. sleep($interval);
  1339. }
  1340. }
  1341. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  1342. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  1343. 'max_retries' => $maxRetries,
  1344. 'interval' => $interval
  1345. ]);
  1346. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  1347. }
  1348. /**
  1349. * GPT 流式输出处理方法
  1350. *
  1351. * @param array $post_data GPT API请求参数
  1352. * @return \Generator 返回生成器,用于流式输出
  1353. */
  1354. private function gpt54StreamResponse($post_data) {
  1355. $apiKey = env('GPT_54_API_KEY');
  1356. if (empty($apiKey)) {
  1357. Utils::throwError('20003:GPT API Key未配置');
  1358. }
  1359. // 先探活,服务不可用时自动重试
  1360. $this->ensureGptServiceAvailable();
  1361. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1362. $headers = [
  1363. 'Authorization' => 'Bearer ' . $apiKey,
  1364. 'Content-Type' => 'application/json'
  1365. ];
  1366. // 移除 thinking 参数,GPT-5.4 不支持
  1367. if (isset($post_data['thinking'])) {
  1368. unset($post_data['thinking']);
  1369. }
  1370. if (isset($post_data['reasoning_effort'])) {
  1371. unset($post_data['reasoning_effort']);
  1372. }
  1373. $post_data['max_completion_tokens'] = 100000;
  1374. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  1375. $post_data['stream_options'] = ['include_usage' => true];
  1376. $maxRetries = $this->gptRetryTimes();
  1377. $interval = $this->gptRetryInterval();
  1378. $attempt = 0;
  1379. while (true) {
  1380. $fullContent = '';
  1381. $usage = [];
  1382. $buffer = '';
  1383. try {
  1384. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  1385. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  1386. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  1387. 'json' => $post_data,
  1388. 'headers' => $headers,
  1389. 'stream' => true // 启用流式响应
  1390. ]);
  1391. $body = $response->getBody();
  1392. dLog('deepseek')->info('开始读取 GPT 流式响应');
  1393. // 逐行读取流式响应
  1394. while (!$body->eof()) {
  1395. $chunk = $body->read(1024); // 每次读取 1KB
  1396. $buffer .= $chunk;
  1397. // 按行分割
  1398. $lines = explode("\n", $buffer);
  1399. // 保留最后一个不完整的行
  1400. $buffer = array_pop($lines);
  1401. foreach ($lines as $line) {
  1402. $line = trim($line);
  1403. // 跳过空行
  1404. if (empty($line)) {
  1405. continue;
  1406. }
  1407. // 检查是否是 SSE 数据行
  1408. if (strpos($line, 'data: ') !== 0) {
  1409. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1410. continue;
  1411. }
  1412. $data = substr($line, 6); // 移除 "data: " 前缀
  1413. if ($data === '[DONE]') {
  1414. dLog('deepseek')->info('收到结束标记');
  1415. break 2; // 跳出 foreach 和流读取循环
  1416. }
  1417. try {
  1418. $json = json_decode($data, true);
  1419. if (json_last_error() !== JSON_ERROR_NONE) {
  1420. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1421. continue;
  1422. }
  1423. if (isset($json['choices'][0]['delta'])) {
  1424. $delta = $json['choices'][0]['delta'];
  1425. // 处理回答内容
  1426. if (isset($delta['content'])) {
  1427. $fullContent .= $delta['content'];
  1428. yield [
  1429. 'type' => 'content',
  1430. 'content' => $delta['content'],
  1431. ];
  1432. }
  1433. }
  1434. // 获取使用统计信息
  1435. if (isset($json['usage'])) {
  1436. $usage = $json['usage'];
  1437. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1438. }
  1439. } catch (\Exception $e) {
  1440. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1441. continue;
  1442. }
  1443. }
  1444. }
  1445. dLog('deepseek')->info('流式读取完成', [
  1446. 'content_length' => strlen($fullContent)
  1447. ]);
  1448. yield [
  1449. 'type' => 'done',
  1450. 'full_content' => $fullContent,
  1451. 'full_reasoning' => '',
  1452. 'usage' => $usage
  1453. ];
  1454. return;
  1455. } catch (\Exception $e) {
  1456. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  1457. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  1458. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  1459. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  1460. throw $e;
  1461. }
  1462. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  1463. 'retry' => $attempt + 1,
  1464. 'max_retries' => $maxRetries,
  1465. 'error' => $e->getMessage()
  1466. ]);
  1467. sleep($interval);
  1468. $attempt++;
  1469. }
  1470. }
  1471. }
  1472. // 与推理模型对话
  1473. public function chatWithReasoner($data) {
  1474. $content = getProp($data, 'content');
  1475. $model = getProp($data, 'model', 'r1');
  1476. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1477. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1478. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1479. if ($model == 'r1') {
  1480. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  1481. $thinkingMode = 'disabled';
  1482. } else {
  1483. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  1484. $thinkingMode = 'disabled';
  1485. }
  1486. // 获取可选情感(根据音色可支持情感选)
  1487. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  1488. $emotion_list = [];
  1489. foreach ($timbre_emotion as $emotion) {
  1490. $tmp = explode(',', $emotion);
  1491. $emotion_list = array_merge($emotion_list, $tmp);
  1492. }
  1493. $emotion_list = array_unique($emotion_list);
  1494. $emotion_str = implode('、', $emotion_list);
  1495. // // 获取可选情感
  1496. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  1497. // $emotion_str = implode('、', $emotion_list);
  1498. // 是否启用情感
  1499. $enable_emotion = getProp($data, 'enable_emotion', 0);
  1500. if ($enable_emotion) {
  1501. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  1502. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1503. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  1504. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  1505. }else {
  1506. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  1507. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1508. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  1509. }
  1510. $messages = [
  1511. [
  1512. 'role' => 'system',
  1513. 'content' => $sys_content
  1514. ],
  1515. [
  1516. 'role' => 'user',
  1517. 'content' => $content
  1518. ]
  1519. ];
  1520. $post_data = [
  1521. 'model' => $model,
  1522. 'messages' => $messages,
  1523. // 'max_tokens' => 8192,
  1524. 'temperature' => 1,
  1525. 'frequency_penalty' => 0,
  1526. 'presence_penalty' => 0,
  1527. 'thinking' => ['type' => $thinkingMode],
  1528. 'response_format' => [
  1529. 'type' => 'text'
  1530. ],
  1531. 'stream' => false
  1532. ];
  1533. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1534. // 根据模型类型选择调用方法
  1535. $fullContent = '';
  1536. $usage = [];
  1537. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1538. // DeepSeek 官方模型使用 DeepSeek API
  1539. $chatResult = $this->chatOnly($post_data);
  1540. } else if (in_array($model, $this->gpt_text_models)) {
  1541. // GPT-5.4 模型使用 TokenRouter API
  1542. $chatResult = $this->gpt54ChatOnly($post_data);
  1543. } else {
  1544. // 其他模型使用火山引擎API
  1545. $chatResult = $this->volcEngineChatCompletion($post_data);
  1546. }
  1547. if (is_array($chatResult)) {
  1548. $fullContent = $chatResult['fullContent'];
  1549. $usage = $chatResult['usage'];
  1550. }
  1551. // 处理获取到的剧本数据
  1552. $script_content = handleScriptWords($fullContent, $enable_emotion);
  1553. $result = [
  1554. 'origin_content' => $fullContent,
  1555. 'roles' => getProp($script_content, 'roles'),
  1556. 'words' => getProp($script_content, 'words'),
  1557. ];
  1558. return $result;
  1559. }
  1560. public function resetParagraphAudio($data) {
  1561. $bid = getProp($data, 'bid');
  1562. $cid = getProp($data, 'cid');
  1563. $version_id = getProp($data, 'version_id');
  1564. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  1565. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  1566. 'generate_status' => '待制作',
  1567. 'updated_at' => date('Y-m-d H:i:s')
  1568. ]);
  1569. }
  1570. public function saveParagraphAudio($data) {
  1571. $bid = getProp($data, 'bid');
  1572. $cid = getProp($data, 'cid');
  1573. $version_id = getProp($data, 'version_id');
  1574. $sequence = getProp($data, 'sequence');
  1575. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  1576. // 获取所有情感
  1577. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1578. $emotion_list = array_flip($emotion_list);
  1579. // 获取音色支持情感
  1580. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  1581. $timbre_emotion = explode(',', $timbre_emotion);
  1582. $emotion = getProp($data, 'emotion');
  1583. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  1584. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  1585. $list = [
  1586. 'bid' => $bid,
  1587. 'cid' => $cid,
  1588. 'version_id' => $version_id,
  1589. 'sequence' => $sequence,
  1590. 'role' => getProp($data, 'role'),
  1591. 'gender' => getProp($data, 'gender'),
  1592. 'text' => trim(getProp($data, 'text')),
  1593. 'emotion' => $emotion,
  1594. 'emotion_type' => $emotion_type,
  1595. 'voice_type' => getProp($data, 'voice_type'),
  1596. 'voice_name' => getProp($data, 'voice_name'),
  1597. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  1598. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  1599. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  1600. 'pitch' => getProp($data, 'pitch', 0),
  1601. // 'paragraph_audio_url' => '',
  1602. 'generate_status' => '制作中',
  1603. 'error_msg' => '',
  1604. 'updated_at' => date('Y-m-d H:i:s')
  1605. ];
  1606. $continue = false;
  1607. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  1608. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  1609. $list['generate_status'] = '制作成功';
  1610. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1611. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  1612. $continue = true;
  1613. }
  1614. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  1615. if ($id) {
  1616. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  1617. }else {
  1618. $list['created_at'] = date('Y-m-d H:i:s');
  1619. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  1620. $boolen = $id ? true : false;
  1621. }
  1622. // 如果更新成功则加入查询队列
  1623. if ($boolen) {
  1624. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  1625. Redis::sadd($redis_key, $id);
  1626. }
  1627. if ($boolen && !$continue) {
  1628. $boolen = false;
  1629. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1630. // 根据ID通过API通知合成音频
  1631. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  1632. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  1633. $response = $result->getBody()->getContents();
  1634. $response_arr = json_decode($response, true);
  1635. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1636. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1637. Log::info('通知火山生成段落音频失败: '.$error_msg);
  1638. Utils::throwError('20003:通知火山生成段落音频失败');
  1639. }
  1640. $boolen = true;
  1641. }
  1642. return $boolen;
  1643. }
  1644. public function insertAudioEffect($data) {
  1645. $audio_id = getProp($data, 'audio_id');
  1646. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1647. $bid = getProp($chapter_audio, 'bid');
  1648. $version_id = getProp($chapter_audio, 'version_id');
  1649. $cid = getProp($chapter_audio, 'cid');
  1650. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1651. $audio_effect_json = getProp($data, 'audio_effect_json');
  1652. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  1653. try {
  1654. DB::beginTransaction();
  1655. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1656. if (!$count) {
  1657. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1658. }else {
  1659. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1660. }
  1661. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1662. 'audio_effect_status' => '添加中',
  1663. 'audio_effect_json' => $audio_effect_json,
  1664. 'updated_at' => date('Y-m-d H:i:s')
  1665. ]);
  1666. if (!$boolen1) {
  1667. DB::rollBack();
  1668. Utils::throwError('20003:更新生成数据失败');
  1669. }
  1670. $id = DB::table('mp_audio_tasks')->insertGetId([
  1671. 'audio_id' => $audio_id,
  1672. 'generate_status' => '执行中',
  1673. 'generate_json' => json_encode([], 256),
  1674. 'bid' => $bid,
  1675. 'book_name' => getProp($chapter_audio, 'book_name'),
  1676. 'version_id' => $version_id,
  1677. 'version_name' => getProp($chapter_audio, 'version_name'),
  1678. 'cid' => $cid,
  1679. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1680. 'task_name' => $task_name,
  1681. 'created_at' => date('Y-m-d H:i:s'),
  1682. 'updated_at' => date('Y-m-d H:i:s')
  1683. ]);
  1684. if (!$id) {
  1685. DB::rollBack();
  1686. Utils::throwError('20003:创建任务失败');
  1687. }
  1688. }catch (\Exception $e) {
  1689. DB::rollBack();
  1690. Utils::throwError('20003:'.$e->getMessage());
  1691. }
  1692. DB::commit();
  1693. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1694. // 根据ID通过API通知合成音频
  1695. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1696. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1697. $response = $result->getBody()->getContents();
  1698. $response_arr = json_decode($response, true);
  1699. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1700. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1701. Log::info('通知火山插入音效失败: '.$error_msg);
  1702. Utils::throwError('20003:通知火山插入音效失败');
  1703. }
  1704. return true;
  1705. }
  1706. public function insertBgm($data) {
  1707. $audio_id = getProp($data, 'audio_id');
  1708. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1709. $bid = getProp($chapter_audio, 'bid');
  1710. $version_id = getProp($chapter_audio, 'version_id');
  1711. $cid = getProp($chapter_audio, 'cid');
  1712. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1713. $bgm_json = getProp($data, 'bgm_json');
  1714. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1715. if (!$bgm_json) {
  1716. $bgm_json = getProp($data, 'audio_effect_json');
  1717. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1718. }
  1719. try {
  1720. DB::beginTransaction();
  1721. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1722. if (!$count) {
  1723. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1724. }else {
  1725. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1726. }
  1727. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1728. 'bgm_status' => '添加中',
  1729. 'bgm_json' => $bgm_json,
  1730. 'updated_at' => date('Y-m-d H:i:s')
  1731. ]);
  1732. if (!$boolen1) {
  1733. DB::rollBack();
  1734. Utils::throwError('20003:更新生成数据失败');
  1735. }
  1736. $id = DB::table('mp_audio_tasks')->insertGetId([
  1737. 'audio_id' => $audio_id,
  1738. 'generate_status' => '执行中',
  1739. 'generate_json' => json_encode([], 256),
  1740. 'bid' => $bid,
  1741. 'book_name' => getProp($chapter_audio, 'book_name'),
  1742. 'version_id' => $version_id,
  1743. 'version_name' => getProp($chapter_audio, 'version_name'),
  1744. 'cid' => $cid,
  1745. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1746. 'task_name' => $task_name,
  1747. 'created_at' => date('Y-m-d H:i:s'),
  1748. 'updated_at' => date('Y-m-d H:i:s')
  1749. ]);
  1750. if (!$id) {
  1751. DB::rollBack();
  1752. Utils::throwError('20003:创建任务失败');
  1753. }
  1754. }catch (\Exception $e) {
  1755. DB::rollBack();
  1756. Utils::throwError('20003:'.$e->getMessage());
  1757. }
  1758. DB::commit();
  1759. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1760. // 根据ID通过API通知合成音频
  1761. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1762. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1763. $response = $result->getBody()->getContents();
  1764. $response_arr = json_decode($response, true);
  1765. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1766. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1767. Log::info('通知火山插入bgm失败: '.$error_msg);
  1768. Utils::throwError('20003:通知火山插入bgm失败');
  1769. }
  1770. return true;
  1771. }
  1772. public function getParagraphAudios($data) {
  1773. $bid = getProp($data, 'bid');
  1774. $cid = getProp($data, 'cid');
  1775. $version_id = getProp($data, 'version_id');
  1776. $sequence = getProp($data, 'sequence');
  1777. // 获取已生成的音频
  1778. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  1779. if ($sequence) $query->where('sequence', $sequence);
  1780. $paragraph_audios = $query->orderBy('sequence')->get();
  1781. $result = [];
  1782. foreach($paragraph_audios as $item) {
  1783. $result[] = [
  1784. 'sequence' => getProp($item, 'sequence'),
  1785. 'role' => getProp($item, 'role'),
  1786. 'gender' => getProp($item, 'gender'),
  1787. 'text' => trim(getProp($item, 'text')),
  1788. 'emotion' => getProp($item, 'emotion'),
  1789. 'emotion_type' => getProp($item, 'emotion_type'),
  1790. 'voice_type' => getProp($item, 'voice_type'),
  1791. 'voice_name' => getProp($item, 'voice_name'),
  1792. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1793. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1794. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1795. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1796. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  1797. ];
  1798. }
  1799. return $result;
  1800. }
  1801. // 新增合成任务
  1802. public function addGenerateTask($data) {
  1803. $bid = getProp($data, 'bid');
  1804. $cid = getProp($data, 'cid');
  1805. $version_id = getProp($data, 'version_id');
  1806. $generate_json = getProp($data, 'generate_json');
  1807. // 获取已生成的音频
  1808. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  1809. $paragraph_list = [];
  1810. foreach($paragraph_audios as $item) {
  1811. $paragraph_list[getProp($item, 'sequence')] = [
  1812. 'role' => getProp($item, 'role'),
  1813. 'gender' => getProp($item, 'gender'),
  1814. 'text' => trim(getProp($item, 'text')),
  1815. 'emotion' => getProp($item, 'emotion'),
  1816. 'emotion_type' => getProp($item, 'emotion_type'),
  1817. 'voice_type' => getProp($item, 'voice_type'),
  1818. 'voice_name' => getProp($item, 'voice_name'),
  1819. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1820. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1821. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1822. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1823. ];
  1824. }
  1825. // 更新角色-音色信息
  1826. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  1827. $existed_role_info = json_decode($existed_role_info, true);
  1828. if (!$existed_role_info) $existed_role_info = [];
  1829. // 获取情感信息
  1830. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1831. $emotion_list = array_flip($emotion_list);
  1832. // 获取音色对应情感组
  1833. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  1834. $timbre_emotion_list = [];
  1835. foreach($timbre_emotions as $item) {
  1836. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  1837. }
  1838. // 构造生成音频的json
  1839. $words = json_decode($generate_json, true);
  1840. // 最终合成前的参数组
  1841. $mp_chapter_paragraph_audios = [];
  1842. $sequence = 1;
  1843. $complete_paragraph_sequences = [];
  1844. foreach($words as &$word) {
  1845. 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:参数格式有误');
  1846. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  1847. $role = getProp($word, 'role');
  1848. $word['gender'] = (int)$word['gender'];
  1849. // 判断音色对应情感是否支持,不支持则调整为中性
  1850. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  1851. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  1852. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  1853. if (isset($emotion_list[getProp($word, 'emotion')])) {
  1854. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  1855. }else {
  1856. $word['emotion'] = '中性';
  1857. $word['emotion_type'] = 'neutral';
  1858. }
  1859. $existed_role_info[$role] = [
  1860. 'timbre_type' => $word['voice_type'],
  1861. 'timbre_name' => $word['voice_name'],
  1862. 'emotion' => $word['emotion'],
  1863. 'emotion_type' => $word['emotion_type'],
  1864. 'speed_ratio' => $word['speed_ratio'],
  1865. 'loudness_ratio'=> $word['loudness_ratio'],
  1866. 'emotion_scale' => $word['emotion_scale'],
  1867. 'pitch' => $word['pitch']
  1868. ];
  1869. $word['paragraph_audio_url'] = '';
  1870. // 判断生成参数是否相同,相同则直接使用已生成的音频
  1871. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  1872. // 如果音频存在并且参数都未改变则使用已生成的音频
  1873. if (getProp($paragraph, 'paragraph_audio_url')) {
  1874. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  1875. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  1876. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  1877. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  1878. // {
  1879. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1880. // }
  1881. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1882. }
  1883. $tmp = $word;
  1884. // 组装章节分句音频数据
  1885. // $tmp['sequence'] = getProp($word, 'sequence');
  1886. // $tmp['text'] = getProp($word, 'text');
  1887. // $tmp['emotion'] = getProp($word, 'emotion');
  1888. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  1889. // $tmp['voice_name'] = getProp($word, 'voice_name');
  1890. // $tmp['voice_type'] = getProp($word, 'voice_type');
  1891. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  1892. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  1893. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  1894. $tmp['bid'] = $bid;
  1895. $tmp['version_id'] = $version_id;
  1896. $tmp['cid'] = $cid;
  1897. $tmp['sequence'] = $sequence;
  1898. $tmp['created_at'] = date('Y-m-d H:i:s');
  1899. $tmp['updated_at'] = date('Y-m-d H:i:s');
  1900. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  1901. $mp_chapter_paragraph_audios[] = $tmp;
  1902. $complete_paragraph_sequences[] = $sequence;
  1903. $sequence++;
  1904. }
  1905. $generate_json = json_encode($words, 256);
  1906. // 判断是否有未生成字幕的段落
  1907. $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();
  1908. if ($no_subtitle_sequences) {
  1909. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  1910. }
  1911. try {
  1912. DB::beginTransaction();
  1913. $role_info = json_encode($existed_role_info, 256);
  1914. $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')]);
  1915. if (!$boolen) {
  1916. DB::rollBack();
  1917. Utils::throwError('20003:更新角色信息失败');
  1918. }
  1919. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  1920. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  1921. if (!$count) {
  1922. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1923. }else {
  1924. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1925. }
  1926. $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')]);
  1927. if (!$boolen1) {
  1928. DB::rollBack();
  1929. Utils::throwError('20003:更新生成数据失败');
  1930. }
  1931. $id = DB::table('mp_audio_tasks')->insertGetId([
  1932. 'audio_id' => getProp($chapter_audio, 'id'),
  1933. 'generate_status' => '执行中',
  1934. 'generate_json' => $generate_json,
  1935. 'bid' => $bid,
  1936. 'book_name' => getProp($chapter_audio, 'book_name'),
  1937. 'version_id' => $version_id,
  1938. 'version_name' => getProp($chapter_audio, 'version_name'),
  1939. 'cid' => $cid,
  1940. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1941. 'task_name' => $task_name,
  1942. 'created_at' => date('Y-m-d H:i:s'),
  1943. 'updated_at' => date('Y-m-d H:i:s')
  1944. ]);
  1945. if (!$id) {
  1946. DB::rollBack();
  1947. Utils::throwError('20003:创建任务失败');
  1948. }
  1949. // 删除不在段落序号范围内的其他数据
  1950. if ($complete_paragraph_sequences) {
  1951. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  1952. }
  1953. // // 删除章节分句音频数据并重新插入
  1954. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  1955. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  1956. // if (!$boolen3) {
  1957. // DB::rollBack();
  1958. // Utils::throwError('20003:更新章节分句音频失败');
  1959. // }
  1960. } catch (\Exception $e) {
  1961. DB::rollBack();
  1962. Utils::throwError('20003:'.$e->getMessage());
  1963. }
  1964. DB::commit();
  1965. // 通知火山生成音频
  1966. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1967. // 根据ID通过API通知合成音频
  1968. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  1969. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  1970. $response = $result->getBody()->getContents();
  1971. $response_arr = json_decode($response, true);
  1972. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1973. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1974. Log::info('通知火山生成音频失败: '.$error_msg);
  1975. Utils::throwError('20003:通知火山生成音频失败');
  1976. }
  1977. return true;
  1978. }
  1979. public function timbreList($data) {
  1980. $gender = getProp($data, 'gender');
  1981. $timbre_name = getProp($data, 'voice_name');
  1982. $category_id = getProp($data, 'category_id');
  1983. $age_stage = getProp($data, 'age_stage');
  1984. $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');
  1985. if ($gender) {
  1986. $query->where('gender', $gender);
  1987. }
  1988. if ($timbre_name) {
  1989. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  1990. }
  1991. if ($category_id) {
  1992. $query->where(function ($query) use ($category_id) {
  1993. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  1994. });
  1995. }
  1996. if ($age_stage) {
  1997. $query->where('age_stage', $age_stage);
  1998. }
  1999. $list = $query->get()->map(function ($value) {
  2000. $value = (array)$value;
  2001. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  2002. return $value;
  2003. })->toArray();
  2004. return $list;
  2005. }
  2006. // 生成火山临时token
  2007. public function setStsToken() {
  2008. // ************* 配置参数 *************
  2009. $method = 'GET';
  2010. $service = 'sts';
  2011. $host = 'open.volcengineapi.com';
  2012. $region = env('VOLC_REGION');
  2013. $endpoint = 'https://open.volcengineapi.com';
  2014. // $endpoint = 'https://tos-cn-beijing.volces.com';
  2015. $access_key = env('VOLC_AK');
  2016. $secret_key = env('VOLC_SK');
  2017. // 获取缓存中的token,如果没有则请求接口
  2018. $token = Redis::get('volc_sts_token');
  2019. if (!$token) {
  2020. // 查询参数
  2021. $query_parameters = [
  2022. 'Action' => 'AssumeRole',
  2023. 'RoleSessionName' => 'user@zw',
  2024. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  2025. 'Version' => '2018-01-01'
  2026. ];
  2027. // 生成URL编码的查询字符串
  2028. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  2029. // 获取签名头信息
  2030. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  2031. // 构建完整URL
  2032. $request_url = $endpoint . '?' . $request_parameters;
  2033. $client = new Client(['verify' => false]);
  2034. $response = $client->get($request_url, ['headers' => $headers]);
  2035. $response_arr = json_decode($response->getBody()->getContents(), true);
  2036. $result = [
  2037. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  2038. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  2039. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  2040. 'Region' => env('VOLC_REGION'),
  2041. 'Endpoint' => env('VOLC_END_POINT'),
  2042. 'Bucket' => env('VOLC_BUCKET'),
  2043. ];
  2044. // 缓存token
  2045. Redis::setex('volc_sts_token', 3000, json_encode($result));
  2046. return $result;
  2047. } else {
  2048. return json_decode($token, true);
  2049. }
  2050. // $response = $response['Response'];
  2051. // $access_key = $response['Credentials']['AccessKeyId'];
  2052. // $secret_key = $response['Credentials']['AccessKeySecret'];
  2053. // $security_token = $response['Credentials']['SecurityToken'];
  2054. // $expiration = $response['Credentials']['Expiration'];
  2055. // dd($response_arr);
  2056. }
  2057. public function emotionGroups($data) {
  2058. $id = getProp($data, 'group_id');
  2059. $group_name = getProp($data, 'group_name');
  2060. $voice_type = getProp($data, 'voice_type');
  2061. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  2062. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  2063. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  2064. if ($group_name) {
  2065. $query->where('group_name', 'like', "%{$group_name}%");
  2066. }
  2067. if ($id) {
  2068. $query->where('id', $id);
  2069. }
  2070. if ($voice_type) {
  2071. $query->where('voice_type', $voice_type);
  2072. }
  2073. return $query->orderBy('id')->get()->map(function ($value) {
  2074. return (array)$value;
  2075. })->toArray();
  2076. }
  2077. private function sign($key, $msg) {
  2078. return hash_hmac('sha256', $msg, $key, true);
  2079. }
  2080. // 生成签名密钥
  2081. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  2082. $kDate = $this->sign($key, $dateStamp);
  2083. $kRegion = $this->sign($kDate, $regionName);
  2084. $kService = $this->sign($kRegion, $serviceName);
  2085. $kSigning = $this->sign($kService, 'request');
  2086. return $kSigning;
  2087. }
  2088. // 获取签名头信息
  2089. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  2090. $contenttype = 'application/x-www-form-urlencoded';
  2091. $accept = 'application/json';
  2092. // 获取当前UTC时间
  2093. $t = new DateTime('now', new DateTimeZone('UTC'));
  2094. $xdate = $t->format('Ymd\THis\Z');
  2095. $datestamp = $t->format('Ymd');
  2096. // 1. 拼接规范请求串
  2097. $canonical_uri = '/';
  2098. $canonical_querystring = $request_parameters;
  2099. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  2100. $signed_headers = 'content-type;host;x-date';
  2101. // 空请求体的SHA256哈希
  2102. $payload_hash = hash('sha256', '');
  2103. $canonical_request = implode("\n", [
  2104. $method,
  2105. $canonical_uri,
  2106. $canonical_querystring,
  2107. $canonical_headers,
  2108. $signed_headers,
  2109. $payload_hash
  2110. ]);
  2111. // 2. 拼接待签名字符串
  2112. $algorithm = 'HMAC-SHA256';
  2113. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  2114. $hashed_canonical_request = hash('sha256', $canonical_request);
  2115. $string_to_sign = implode("\n", [
  2116. $algorithm,
  2117. $xdate,
  2118. $credential_scope,
  2119. $hashed_canonical_request
  2120. ]);
  2121. // 3. 计算签名
  2122. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  2123. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  2124. // 4. 添加签名到请求头
  2125. $authorization_header = sprintf(
  2126. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2127. $algorithm,
  2128. $access_key,
  2129. $credential_scope,
  2130. $signed_headers,
  2131. $signature
  2132. );
  2133. return [
  2134. 'Accept' => $accept,
  2135. 'Content-Type' => $contenttype,
  2136. 'X-Date' => $xdate,
  2137. 'Authorization' => $authorization_header
  2138. ];
  2139. }
  2140. // 文字合成语音(火山引擎)
  2141. public function tts($data) {
  2142. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  2143. $headers = [
  2144. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  2145. 'Content-Type' => 'application/json; charset=UTF-8'
  2146. ];
  2147. $post_data = [
  2148. 'app' => [
  2149. 'appid' => env('VOLC_APPID'),
  2150. 'token' => env('VOLC_TOKEN'),
  2151. 'cluster' => 'volcano_tts'
  2152. ],
  2153. 'user' => [
  2154. 'uid' => 'mp_audio'
  2155. ],
  2156. // 'audio' => [
  2157. // 'voice_type' =>
  2158. // ],
  2159. ];
  2160. }
  2161. public function scriptList($data) {
  2162. $uid = Site::getUid();
  2163. $script_id = getProp($data, 'script_id');
  2164. $script_name = getProp($data, 'script_name');
  2165. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  2166. if ($script_id) {
  2167. $query->where('id', $script_id);
  2168. }
  2169. if ($script_name) {
  2170. $query->where('script_name', 'like', "%{$script_name}%");
  2171. }
  2172. return $query->orderBy('created_at', 'desc')->paginate(12);
  2173. }
  2174. public function scripts($data) {
  2175. $uid = Site::getUid();
  2176. $script_id = getProp($data, 'script_id');
  2177. $script_name = getProp($data, 'script_name');
  2178. $is_products = getProp($data, 'is_products');
  2179. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  2180. if ($script_id) {
  2181. $query->where('id', $script_id);
  2182. }
  2183. if ($is_products !== '') {
  2184. $query->where('is_products', $is_products);
  2185. }
  2186. if ($script_name) {
  2187. $query->where('script_name', 'like', "%{$script_name}%");
  2188. }
  2189. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  2190. return (array)$value;
  2191. })->toArray();
  2192. }
  2193. public function scriptInfo($data) {
  2194. $uid = Site::getUid();
  2195. $script_id = getProp($data, 'script_id');
  2196. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  2197. // ->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();
  2198. ->selectRaw('id as script_id, script_name')->first();
  2199. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2200. $script = (array)$script;
  2201. // 获取分集组信息
  2202. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  2203. ->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')
  2204. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  2205. $value = (array)$value;
  2206. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  2207. return (array)$value;
  2208. })->toArray();
  2209. $script['group'] = $groups;
  2210. return $script;
  2211. }
  2212. public function createScript($data) {
  2213. $script_name = getProp($data, 'script_name');
  2214. $uid = Site::getUid(); // 获取当前用户ID
  2215. $cpid = Site::getCpid(); // 获取当前公司组ID
  2216. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  2217. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  2218. $script_name .= '_'.date('YmdHis');
  2219. }
  2220. return DB::table('mp_scripts')->insertGetId([
  2221. 'script_name' => $script_name,
  2222. 'user_id' => $uid,
  2223. 'cpid' => $cpid,
  2224. 'created_at' => date('Y-m-d H:i:s'),
  2225. 'updated_at' => date('Y-m-d H:i:s')
  2226. ]);
  2227. }
  2228. public function editScript($data) {
  2229. $script_id = getProp($data, 'script_id');
  2230. $script_name = getProp($data, 'script_name');
  2231. $uid = Site::getUid(); // 获取当前用户ID
  2232. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  2233. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  2234. if ($id && (int)$id !== (int)$script_id) {
  2235. $script_name .= '_'.date('YmdHis');
  2236. }
  2237. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2238. 'script_name' => $script_name,
  2239. 'updated_at' => date('Y-m-d H:i:s')
  2240. ]);
  2241. }
  2242. public function delScript($data) {
  2243. $script_id = getProp($data, 'script_id');
  2244. $uid = Site::getUid(); // 获取当前用户ID
  2245. if (!$script_id) Utils::throwError('20003:请选择剧本');
  2246. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2247. 'is_deleted' => 1,
  2248. 'updated_at' => date('Y-m-d H:i:s')
  2249. ]);
  2250. }
  2251. public function createEpisode($data) {
  2252. $script_id = getProp($data, 'script_id');
  2253. $group_name = getProp($data, 'group_name');
  2254. $remark = getProp($data, 'remark');
  2255. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  2256. $uid = Site::getUid(); // 获取当前用户ID
  2257. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  2258. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  2259. $group_name .= '_'.date('YmdHis');
  2260. }
  2261. return DB::table('mp_script_episode_group')->insertGetId([
  2262. 'script_id' => $script_id,
  2263. 'group_name' => $group_name,
  2264. 'user_id' => $uid,
  2265. 'remark' => $remark,
  2266. 'created_at' => date('Y-m-d H:i:s'),
  2267. 'updated_at' => date('Y-m-d H:i:s')
  2268. ]);
  2269. }
  2270. public function editEpisode($data) {
  2271. $group_id = getProp($data, 'group_id');
  2272. $start_episode_number = getProp($data, 'start_episode_number');
  2273. $end_episode_number = getProp($data, 'end_episode_number');
  2274. $group_name = getProp($data, 'group_name');
  2275. $uid = Site::getUid(); // 获取当前用户ID
  2276. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  2277. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  2278. if ($id && (int)$id !== (int)$group_id) {
  2279. $group_name .= '_'.date('YmdHis');
  2280. }
  2281. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2282. 'group_name' => $group_name,
  2283. 'start_episode_number' => $start_episode_number,
  2284. 'end_episode_number' => $end_episode_number,
  2285. 'updated_at' => date('Y-m-d H:i:s')
  2286. ]);
  2287. }
  2288. public function delEpisode($data) {
  2289. $group_id = getProp($data, 'group_id');
  2290. $uid = Site::getUid(); // 获取当前用户ID
  2291. if (!$group_id) Utils::throwError('20003:请选择分集');
  2292. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2293. 'is_deleted' => 1,
  2294. 'updated_at' => date('Y-m-d H:i:s')
  2295. ]);
  2296. }
  2297. /**
  2298. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2299. *
  2300. * @param array $data 包含以下参数:
  2301. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2302. * - question: 用户问题(可选)
  2303. * - model: 使用的模型(r1 或 v3,默认 v3)
  2304. * @return \Generator 返回生成器,用于流式输出
  2305. */
  2306. public function generateEpisodes($data) {
  2307. $script_id = getProp($data, 'script_id');
  2308. $group_id = getProp($data, 'group_id');
  2309. // $file = getProp($data, 'file');
  2310. $file = '';
  2311. $content = getProp($data, 'content', '');
  2312. // $bid = getProp($data, 'bid', 0);
  2313. $bid = 0;
  2314. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2315. if (!$group) {
  2316. Utils::throwError('20003:剧本分集不存在');
  2317. }
  2318. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  2319. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  2320. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  2321. $prompt = getProp($data, 'prompt');
  2322. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  2323. $model = getProp($data, 'model');
  2324. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2325. Utils::throwError('20003:该模型不存在!');
  2326. }
  2327. // 检查是否存在重叠的剧集序号范围
  2328. $exists_groups = DB::table('mp_script_episode_group')
  2329. ->where('script_id', $script_id)
  2330. ->where('id', '<>', $group_id) // 排除当前组
  2331. ->where('is_deleted', 0)
  2332. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2333. // 检查新范围是否与现有范围重叠
  2334. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2335. // 新范围的开始在现有范围内
  2336. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2337. ->where('end_episode_number', '>=', $start_episode_sequence);
  2338. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2339. // 新范围的结束在现有范围内
  2340. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2341. ->where('end_episode_number', '>=', $end_episode_sequence);
  2342. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2343. // 新范围完全包含现有范围
  2344. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2345. ->where('end_episode_number', '<=', $end_episode_sequence);
  2346. });
  2347. })
  2348. ->select('start_episode_number', 'end_episode_number')
  2349. ->get();
  2350. if ($exists_groups->isNotEmpty()) {
  2351. $conflict_ranges = [];
  2352. foreach ($exists_groups as $group) {
  2353. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2354. }
  2355. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2356. }
  2357. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2358. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2359. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2360. if ($model === 'deepseek-chat') {
  2361. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2362. $model = 'deepseek-v4-flash';
  2363. $thinkingMode = 'disabled';
  2364. } elseif ($model === 'deepseek-reasoner') {
  2365. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2366. $model = 'deepseek-v4-flash';
  2367. $thinkingMode = 'enabled';
  2368. }
  2369. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2370. if (!$script) {
  2371. Utils::throwError('20003:剧本不存在');
  2372. }
  2373. $content = getProp($group, 'content');
  2374. if (!$file && !$content && !$bid) {
  2375. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2376. }
  2377. // 提取文件内容
  2378. if ($file) {
  2379. $content = $this->extractFileContent($file);
  2380. if (!$content) {
  2381. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2382. }
  2383. } elseif ($bid) {
  2384. $content = $this->getContentByBid($bid);
  2385. if (!$content) {
  2386. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2387. }
  2388. } elseif ($content) {
  2389. $content = filterContent($content);
  2390. } elseif ($prompt) {
  2391. $content = filterContent($prompt);
  2392. } else {
  2393. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2394. }
  2395. // 构建消息
  2396. $messages = [
  2397. $this->sys_message,
  2398. [
  2399. 'role' => 'user',
  2400. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2401. ]
  2402. ];
  2403. $post_data = [
  2404. 'model' => $model,
  2405. 'messages' => $messages,
  2406. // 'max_tokens' => 8192,
  2407. 'temperature' => 0.7,
  2408. 'frequency_penalty' => 0,
  2409. 'presence_penalty' => 0,
  2410. 'thinking' => ['type' => $thinkingMode],
  2411. 'response_format' => ['type' => 'text'],
  2412. 'stream' => true
  2413. ];
  2414. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2415. // 根据模型类型选择调用方法
  2416. $fullContent = '';
  2417. $fullReasoningContent = '';
  2418. $usage = [];
  2419. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2420. // DeepSeek 官方模型使用 DeepSeek API
  2421. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2422. } else if (in_array($model, $this->gpt_text_models)) {
  2423. // GPT-5.4 模型使用 TokenRouter API
  2424. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2425. } else {
  2426. // 其他模型使用火山引擎API
  2427. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2428. }
  2429. // 处理流式输出
  2430. foreach ($streamGenerator as $chunk) {
  2431. if (isset($chunk['type'])) {
  2432. if ($chunk['type'] === 'done') {
  2433. // 最终结果
  2434. $fullContent = $chunk['full_content'];
  2435. $fullReasoningContent = $chunk['full_reasoning'];
  2436. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2437. } else {
  2438. // 逐块yield数据
  2439. yield $chunk;
  2440. }
  2441. }
  2442. }
  2443. dLog('deepseek')->info('完整内容: '.$fullContent);
  2444. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2445. // 处理完整内容并返回最终结果
  2446. $script_arr = [];
  2447. if ($fullContent) {
  2448. $script_arr = extractScriptContent($fullContent);
  2449. }
  2450. logDB('deepseek', 'info', '解析内容', $script_arr);
  2451. if (!$script_arr['episodes']) {
  2452. Utils::throwError('20003:未生成剧本相关信息');
  2453. // yield [
  2454. // 'type' => 'done',
  2455. // 'script' => $script_arr,
  2456. // 'msg' => '未生成剧本相关信息',
  2457. // 'answer' => $fullContent,
  2458. // 'reasoning' => $fullReasoningContent,
  2459. // 'usage' => $usage
  2460. // ];
  2461. // return ;
  2462. }
  2463. try {
  2464. DB::beginTransaction();
  2465. // // 返回前保存剧本内容
  2466. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2467. // 'content' => $content,
  2468. // 'updated_at' => date('Y-m-d H:i:s')
  2469. // ]);
  2470. // if (!$boolen) {
  2471. // Utils::throwError('20003:保存剧本内容失败');
  2472. // }
  2473. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2474. // 'start_episode_number' => $start_episode_sequence,
  2475. // 'end_episode_number' => $end_episode_sequence,
  2476. // 'updated_at' => date('Y-m-d H:i:s')
  2477. // ]);
  2478. // if (!$boolen1) {
  2479. // Utils::throwError('20003:保存分集失败');
  2480. // }
  2481. $episode_content = '';
  2482. $episodes = [];
  2483. foreach ($script_arr['episodes'] as $item) {
  2484. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  2485. // $episodes[] = [
  2486. // 'script_id' => $script_id,
  2487. // 'episode_number' => $item['episode_number'],
  2488. // 'episode_name' => $item['episode_name'],
  2489. // 'episode_content' => $item['episode_content'],
  2490. // 'created_at' => date('Y-m-d H:i:s'),
  2491. // 'updated_at' => date('Y-m-d H:i:s'),
  2492. // ];
  2493. }
  2494. if ($episode_content) {
  2495. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2496. 'episode_content' => $episode_content,
  2497. 'updated_at' => date('Y-m-d H:i:s')
  2498. ]);
  2499. if (!$boolen2) {
  2500. Utils::throwError('20003:保存分集内容失败');
  2501. }
  2502. }else {
  2503. Utils::throwError('20003:分集剧本解析失败');
  2504. }
  2505. }catch (\Exception $e) {
  2506. DB::rollBack();
  2507. Utils::throwError('20003:'.$e->getMessage());
  2508. }
  2509. DB::commit();
  2510. yield [
  2511. 'type' => 'done',
  2512. 'script' => $script_arr,
  2513. 'episode_content' => $episode_content,
  2514. 'answer' => $fullContent,
  2515. 'reasoning' => $fullReasoningContent,
  2516. 'usage' => $usage
  2517. ];
  2518. }
  2519. public function chatWithFileStream($data) {
  2520. $script_id = getProp($data, 'script_id');
  2521. $group_id = getProp($data, 'group_id');
  2522. $file = getProp($data, 'file');
  2523. $content = getProp($data, 'content', '');
  2524. $bid = getProp($data, 'bid', 0);
  2525. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2526. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2527. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  2528. $prompt = getProp($data, 'prompt');
  2529. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2530. if (!empty($prompt)) {
  2531. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2532. }
  2533. $question = getProp($data, 'question', $baseQuestion);
  2534. $model = getProp($data, 'model');
  2535. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2536. Utils::throwError('20003:该模型不存在!');
  2537. }
  2538. // 检查是否存在重叠的剧集序号范围
  2539. $exists_groups = DB::table('mp_script_episode_group')
  2540. ->where('script_id', $script_id)
  2541. ->where('id', '<>', $group_id)
  2542. ->where('is_deleted', 0)
  2543. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2544. // 检查新范围是否与现有范围重叠
  2545. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2546. // 新范围的开始在现有范围内
  2547. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2548. ->where('end_episode_number', '>=', $start_episode_sequence);
  2549. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2550. // 新范围的结束在现有范围内
  2551. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2552. ->where('end_episode_number', '>=', $end_episode_sequence);
  2553. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2554. // 新范围完全包含现有范围
  2555. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2556. ->where('end_episode_number', '<=', $end_episode_sequence);
  2557. });
  2558. })
  2559. ->select('start_episode_number', 'end_episode_number')
  2560. ->get();
  2561. if ($exists_groups->isNotEmpty()) {
  2562. $conflict_ranges = [];
  2563. foreach ($exists_groups as $group) {
  2564. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2565. }
  2566. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2567. }
  2568. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2569. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2570. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2571. if ($model === 'deepseek-chat') {
  2572. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2573. $model = 'deepseek-v4-flash';
  2574. $thinkingMode = 'disabled';
  2575. } elseif ($model === 'deepseek-reasoner') {
  2576. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2577. $model = 'deepseek-v4-flash';
  2578. $thinkingMode = 'enabled';
  2579. }
  2580. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2581. if (!$script) {
  2582. Utils::throwError('20003:剧本不存在');
  2583. }
  2584. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2585. if (!$group) {
  2586. Utils::throwError('20003:剧本分集不存在');
  2587. }
  2588. if (!$file && !$content && !$bid) {
  2589. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2590. }
  2591. // 提取文件内容
  2592. if ($file) {
  2593. $content = $this->extractFileContent($file);
  2594. if (!$content) {
  2595. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2596. }
  2597. } elseif ($bid) {
  2598. $content = $this->getContentByBid($bid);
  2599. if (!$content) {
  2600. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2601. }
  2602. } elseif ($content) {
  2603. $content = filterContent($content);
  2604. } elseif ($prompt) {
  2605. $content = filterContent($prompt);
  2606. } else {
  2607. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2608. }
  2609. // 构建消息
  2610. $messages = [
  2611. [
  2612. 'role' => 'system',
  2613. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  2614. 强制要求:\n
  2615. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2616. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  2617. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  2618. 普通要求:\n
  2619. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  2620. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  2621. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  2622. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  2623. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  2624. 示例如下:\n
  2625. ###剧本名:西昆仑
  2626. ###故事梗概
  2627. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2628. ###剧本亮点
  2629. 亮点1:绝境奇药,生死一线
  2630. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2631. 亮点2:结拜兄妹,化解尴尬
  2632. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2633. 亮点3:纤发夺命,情愫暗涌
  2634. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2635. ###人物关系
  2636. 阿雪与梁萧之间存在兄妹之情。
  2637. ###核心矛盾
  2638. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2639. ###主体列表
  2640. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2641. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2642. 阴阳球:天地异宝,能化生精气,救人于危难。
  2643. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2644. ###美术风格
  2645. 基础画风风格词:厚涂古风
  2646. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2647. ###场景列表
  2648. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  2649. [
  2650. 'role' => 'user',
  2651. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2652. ]
  2653. ];
  2654. $post_data = [
  2655. 'model' => $model,
  2656. 'messages' => $messages,
  2657. // 'max_tokens' => 8192,
  2658. 'temperature' => 0.7,
  2659. 'frequency_penalty' => 0,
  2660. 'presence_penalty' => 0,
  2661. 'thinking' => ['type' => $thinkingMode],
  2662. 'response_format' => ['type' => 'text'],
  2663. 'stream' => true
  2664. ];
  2665. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2666. // 根据模型类型选择调用方法
  2667. $fullContent = '';
  2668. $fullReasoningContent = '';
  2669. $usage = [];
  2670. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2671. // DeepSeek 官方模型使用 DeepSeek API
  2672. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2673. } else if (in_array($model, $this->gpt_text_models)) {
  2674. // GPT-5.4 模型使用 TokenRouter API
  2675. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2676. } else {
  2677. // 其他模型使用火山引擎API
  2678. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2679. }
  2680. // 处理流式输出
  2681. foreach ($streamGenerator as $chunk) {
  2682. if (isset($chunk['type'])) {
  2683. if ($chunk['type'] === 'done') {
  2684. // 最终结果
  2685. $fullContent = $chunk['full_content'];
  2686. $fullReasoningContent = $chunk['full_reasoning'];
  2687. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2688. } else {
  2689. // 逐块yield数据
  2690. yield $chunk;
  2691. }
  2692. }
  2693. }
  2694. dLog('deepseek')->info('完整内容: '.$fullContent);
  2695. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2696. // 处理完整内容并返回最终结果
  2697. $script_arr = [];
  2698. if ($fullContent) {
  2699. $script_arr = extractScriptContent($fullContent);
  2700. }
  2701. logDB('deepseek', 'info', '解析内容', $script_arr);
  2702. if (!$script_arr['roles']) {
  2703. Utils::throwError('20003:未生成剧本相关信息');
  2704. // yield [
  2705. // 'type' => 'done',
  2706. // 'script' => $script_arr,
  2707. // 'msg' => '未生成剧本相关信息',
  2708. // 'answer' => $fullContent,
  2709. // 'reasoning' => $fullReasoningContent,
  2710. // 'usage' => $usage
  2711. // ];
  2712. }
  2713. try {
  2714. DB::beginTransaction();
  2715. // // 返回前保存剧本内容
  2716. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2717. // 'content' => $content,
  2718. // 'status' => '解析完成',
  2719. // 'updated_at' => date('Y-m-d H:i:s')
  2720. // ]);
  2721. // if (!$boolen) {
  2722. // Utils::throwError('20003:保存剧本内容失败');
  2723. // }
  2724. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2725. 'start_episode_number' => $start_episode_sequence,
  2726. 'end_episode_number' => $end_episode_sequence,
  2727. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2728. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2729. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2730. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2731. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2732. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2733. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2734. 'status' => '解析完成',
  2735. 'content' => $content,
  2736. 'updated_at' => date('Y-m-d H:i:s')
  2737. ]);
  2738. if (!$boolen1) {
  2739. Utils::throwError('20003:保存分集失败');
  2740. }
  2741. // $episodes = [];
  2742. // foreach ($script_arr['episodes'] as $item) {
  2743. // $episodes[] = [
  2744. // 'script_id' => $script_id,
  2745. // 'episode_number' => $item['episode_number'],
  2746. // 'episode_name' => $item['episode_name'],
  2747. // 'episode_content' => $item['episode_content'],
  2748. // 'created_at' => date('Y-m-d H:i:s'),
  2749. // 'updated_at' => date('Y-m-d H:i:s'),
  2750. // ];
  2751. // }
  2752. // if ($episodes) {
  2753. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2754. // if (!$boolen2) {
  2755. // Utils::throwError('20003:保存分集内容失败');
  2756. // }
  2757. // }else {
  2758. // Utils::throwError('20003:分集剧本解析失败');
  2759. // }
  2760. }catch (\Exception $e) {
  2761. DB::rollBack();
  2762. Utils::throwError('20003:'.$e->getMessage());
  2763. }
  2764. DB::commit();
  2765. yield [
  2766. 'type' => 'done',
  2767. 'script' => $script_arr,
  2768. 'answer' => $fullContent,
  2769. 'reasoning' => $fullReasoningContent,
  2770. 'usage' => $usage
  2771. ];
  2772. }
  2773. /**
  2774. * 上传文件识别文字内容并与 DeepSeek 进行对话
  2775. *
  2776. * @param array $data 包含以下参数:
  2777. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2778. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  2779. * - model: 使用的模型(r1 或 v3,默认 v3)
  2780. * @return array
  2781. */
  2782. public function chatWithFile($data) {
  2783. $script_id = getProp($data, 'script_id');
  2784. $file = getProp($data, 'file');
  2785. $content = getProp($data, 'content', '');
  2786. $bid = getProp($data, 'bid', 0);
  2787. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2788. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2789. $prompt = getProp($data, 'prompt');
  2790. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2791. if (!empty($prompt)) {
  2792. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2793. }
  2794. $question = getProp($data, 'question', $baseQuestion);
  2795. // 处理文本模型
  2796. $model = getProp($data, 'model');
  2797. if (!$model) {
  2798. // 用户没有输入,使用默认值
  2799. $model = 'doubao-seed-2-0-mini-260215';
  2800. }
  2801. // 验证模型是否在可用模型表中
  2802. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2803. $model = 'doubao-seed-2-0-mini-260215';
  2804. }
  2805. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2806. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2807. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2808. if ($model === 'deepseek-chat') {
  2809. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2810. $model = 'deepseek-v4-flash';
  2811. $thinkingMode = 'disabled';
  2812. } elseif ($model === 'deepseek-reasoner') {
  2813. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2814. $model = 'deepseek-v4-flash';
  2815. $thinkingMode = 'enabled';
  2816. }
  2817. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2818. if (!$script) {
  2819. Utils::throwError('20003:剧本不存在');
  2820. }
  2821. if (!$file && !$content && !$bid) {
  2822. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2823. }
  2824. // 提取文件内容
  2825. if ($file) {
  2826. $content = $this->extractFileContent($file);
  2827. if (!$content) {
  2828. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2829. }
  2830. } elseif ($bid) {
  2831. $content = $this->getContentByBid($bid);
  2832. if (!$content) {
  2833. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2834. }
  2835. } elseif ($content) {
  2836. $content = filterContent($content);
  2837. } elseif ($prompt) {
  2838. $content = filterContent($prompt);
  2839. } else {
  2840. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2841. }
  2842. // 构建消息
  2843. $messages = [
  2844. $this->sys_message,
  2845. [
  2846. 'role' => 'user',
  2847. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2848. ]
  2849. ];
  2850. $post_data = [
  2851. 'model' => $model,
  2852. 'messages' => $messages,
  2853. // 'max_tokens' => 8192,
  2854. 'temperature' => 0.7,
  2855. 'frequency_penalty' => 0,
  2856. 'presence_penalty' => 0,
  2857. 'thinking' => ['type' => $thinkingMode],
  2858. 'response_format' => ['type' => 'text'],
  2859. 'stream' => false
  2860. ];
  2861. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2862. // 根据模型类型选择调用方法
  2863. $fullContent = '';
  2864. $usage = [];
  2865. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2866. // DeepSeek 官方模型使用 DeepSeek API
  2867. $chatResult = $this->chatOnly($post_data);
  2868. } else if (in_array($model, $this->gpt_text_models)) {
  2869. // GPT-5.4 模型使用 TokenRouter API
  2870. $chatResult = $this->gpt54ChatOnly($post_data);
  2871. } else {
  2872. // 其他模型使用火山引擎API
  2873. $chatResult = $this->volcEngineChatCompletion($post_data);
  2874. }
  2875. if (is_array($chatResult)) {
  2876. $fullContent = $chatResult['fullContent'];
  2877. $usage = $chatResult['usage'];
  2878. }
  2879. $script_arr = [];
  2880. // 处理结果
  2881. if ($fullContent) {
  2882. $script_arr = extractScriptContent($fullContent);
  2883. }
  2884. // 返回前保存剧本内容
  2885. DB::table('mp_scripts')->where('id', $script_id)->update([
  2886. 'content' => $content,
  2887. 'updated_at' => date('Y-m-d H:i:s')
  2888. ]);
  2889. return [
  2890. 'script' => $script_arr,
  2891. 'answer' => $fullContent,
  2892. 'usage' => $usage
  2893. ];
  2894. }
  2895. public function getEpisodeContent($data) {
  2896. $group_id = getProp($data, 'group_id');
  2897. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  2898. }
  2899. public function saveEpisodeContent($data) {
  2900. $script_id = getProp($data, 'script_id');
  2901. $group_id = getProp($data, 'group_id');
  2902. $start_episode_sequence = getProp($data, 'start_episode_number');
  2903. $end_episode_sequence = getProp($data, 'end_episode_number');
  2904. // 检查是否存在重叠的剧集序号范围
  2905. $exists_groups = DB::table('mp_script_episode_group')
  2906. ->where('script_id', $script_id)
  2907. ->where('id', '<>', $group_id) // 排除当前组
  2908. ->where('is_deleted', 0)
  2909. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2910. // 检查新范围是否与现有范围重叠
  2911. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2912. // 新范围的开始在现有范围内
  2913. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2914. ->where('end_episode_number', '>=', $start_episode_sequence);
  2915. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2916. // 新范围的结束在现有范围内
  2917. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2918. ->where('end_episode_number', '>=', $end_episode_sequence);
  2919. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2920. // 新范围完全包含现有范围
  2921. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2922. ->where('end_episode_number', '<=', $end_episode_sequence);
  2923. });
  2924. })
  2925. ->select('start_episode_number', 'end_episode_number')
  2926. ->get();
  2927. if ($exists_groups->isNotEmpty()) {
  2928. $conflict_ranges = [];
  2929. foreach ($exists_groups as $group) {
  2930. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2931. }
  2932. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2933. }
  2934. $episode_content = getProp($data, 'episode_content');
  2935. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  2936. 'content' => $episode_content,
  2937. 'start_episode_number' => $start_episode_sequence,
  2938. 'end_episode_number' => $end_episode_sequence,
  2939. 'updated_at' => date('Y-m-d H:i:s')
  2940. ]);
  2941. $script_arr =getProp($data, 'script', []);
  2942. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  2943. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2944. $script_id = getProp($data, 'script_id');
  2945. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  2946. try {
  2947. DB::beginTransaction();
  2948. $update_data = [
  2949. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2950. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2951. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2952. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2953. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2954. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2955. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2956. 'status' => 3,
  2957. 'start_episode_sequence' => $start_episode_sequence,
  2958. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  2959. 'episode_num' => count($script_arr['episodes']),
  2960. 'updated_at' => date('Y-m-d H:i:s')
  2961. ];
  2962. // 保存剧本内容
  2963. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  2964. if (!$boolen) {
  2965. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  2966. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  2967. Utils::throwError('20003:剧本内容保存失败');
  2968. }
  2969. // 保存分集内容
  2970. // 删除历史分集内容
  2971. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  2972. $episodes = [];
  2973. $sequence = 1;
  2974. foreach ($script_arr['episodes'] as $episode) {
  2975. $segment_number = 1;
  2976. foreach($episode['segments'] as $segment) {
  2977. $episodes[] = [
  2978. 'script_id' => $script_id,
  2979. 'episode_number' => $episode['episode_number'],
  2980. 'title' => $episode['title'],
  2981. // 'content' => $episode['content'],
  2982. 'content' => '',
  2983. 'segment_number' => $segment_number,
  2984. 'segment_content' => $segment['segment_content'],
  2985. 'sequence' => $sequence,
  2986. 'created_at' => date('Y-m-d H:i:s'),
  2987. 'updated_at' => date('Y-m-d H:i:s')
  2988. ];
  2989. $sequence++;
  2990. $segment_number++;
  2991. }
  2992. }
  2993. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2994. if (!$boolen2) {
  2995. dLog('deepseek')->info('分集内容保存失败', $episodes);
  2996. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  2997. Utils::throwError('20003:分集内容保存失败');
  2998. }
  2999. } catch (\Exception $e) {
  3000. DB::rollBack();
  3001. Utils::throwError('20003:'.$e->getMessage());
  3002. }
  3003. DB::commit();
  3004. return true;
  3005. }
  3006. public function getBookContent($data) {
  3007. $bid = getProp($data, 'bid');
  3008. $start_sequence = getProp($data, 'start_sequence');
  3009. $end_sequence = getProp($data, 'end_sequence');
  3010. $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])
  3011. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  3012. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  3013. return $return_content;
  3014. }
  3015. public function exportScript($data) {
  3016. $filename = getProp($data, 'filename');
  3017. $script_id = getProp($data, 'script_id');
  3018. $group_id = getProp($data, 'group_id');
  3019. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  3020. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  3021. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3022. $script = (array)$script;
  3023. // 获取分集组信息
  3024. if ($group_id) {
  3025. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3026. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3027. ->get()->map(function($value) {
  3028. return (array)$value;
  3029. })->toArray();
  3030. }else {
  3031. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3032. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3033. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  3034. return (array)$value;
  3035. })->toArray();
  3036. }
  3037. if (!$groups) Utils::throwError('20003:分集不存在');
  3038. $script['group'] = $groups;
  3039. $export_type = getProp($data, 'export_type', 'txt');
  3040. // 生成文件名
  3041. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  3042. // 根据导出类型生成不同格式的文件
  3043. switch ($export_type) {
  3044. case 'txt':
  3045. return $this->exportScriptAsTxt($script, $filename);
  3046. case 'pdf':
  3047. return $this->exportScriptAsPdf($script, $filename);
  3048. default:
  3049. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  3050. }
  3051. }
  3052. /**
  3053. * 导出剧本为TXT格式
  3054. */
  3055. private function exportScriptAsTxt($script, $filename) {
  3056. // 构建TXT内容
  3057. $content = $this->buildScriptContent($script);
  3058. // 设置响应头,直接下载
  3059. header('Content-Type: text/plain; charset=utf-8');
  3060. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  3061. header('Content-Length: ' . strlen($content));
  3062. // 输出内容并结束
  3063. echo $content;
  3064. exit();
  3065. }
  3066. /**
  3067. * 导出剧本为PDF格式
  3068. */
  3069. private function exportScriptAsPdf($script, $filename) {
  3070. // 使用HTML转PDF的方式来更好地支持中文
  3071. $htmlContent = $this->buildScriptHtmlForPdf($script);
  3072. // 创建PDF实例
  3073. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  3074. // 设置文档信息
  3075. $pdf->SetCreator('剧本导出系统');
  3076. $pdf->SetAuthor('系统');
  3077. $pdf->SetTitle($script['script_name']);
  3078. $pdf->SetSubject('剧本导出');
  3079. // 设置边距
  3080. $pdf->SetMargins(15, 15, 15);
  3081. $pdf->SetAutoPageBreak(TRUE, 15);
  3082. // 添加页面
  3083. $pdf->AddPage();
  3084. // 注册并使用 simsun.ttf 字体
  3085. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  3086. // 使用HTML内容生成PDF
  3087. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  3088. // 直接输出PDF文件供下载
  3089. header('Content-Type: application/pdf');
  3090. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  3091. // 直接输出PDF内容
  3092. $pdf->Output($filename . '.pdf', 'D');
  3093. exit();
  3094. }
  3095. /**
  3096. * 构建用于PDF的HTML内容
  3097. */
  3098. private function buildScriptHtmlForPdf($script) {
  3099. $html = '<style>
  3100. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  3101. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  3102. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  3103. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  3104. .info { margin-bottom: 8px; }
  3105. .group { margin-bottom: 30px; page-break-inside: avoid; }
  3106. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  3107. .segment { margin-bottom: 10px; margin-left: 20px; }
  3108. .episode-content { white-space: pre-wrap; }
  3109. </style>';
  3110. // 标题
  3111. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  3112. // 处理分组数据
  3113. if (!empty($script['group']) && is_array($script['group'])) {
  3114. $groups = (array)$script['group'];
  3115. foreach ($groups as $group) {
  3116. $html .= '<div class="group">';
  3117. // 分组标题
  3118. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  3119. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  3120. // 故事梗概
  3121. if (!empty($group['intro'])) {
  3122. $html .= '<h3>故事梗概</h3>';
  3123. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  3124. }
  3125. // 剧本亮点
  3126. if (!empty($group['highlights'])) {
  3127. $html .= '<h3>剧本亮点</h3>';
  3128. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  3129. }
  3130. // 人物关系
  3131. if (!empty($group['role_relationship'])) {
  3132. $html .= '<h3>人物关系</h3>';
  3133. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  3134. }
  3135. // 核心矛盾
  3136. if (!empty($group['core_contradiction'])) {
  3137. $html .= '<h3>核心矛盾</h3>';
  3138. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  3139. }
  3140. // 主体列表
  3141. if (!empty($group['roles']) && is_array($group['roles'])) {
  3142. $html .= '<h3>主体列表</h3>';
  3143. $html .= '<ul>';
  3144. foreach ($group['roles'] as $role) {
  3145. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  3146. }
  3147. $html .= '</ul>';
  3148. }
  3149. // 美术风格
  3150. if (!empty($group['art_style'])) {
  3151. $html .= '<h3>美术风格</h3>';
  3152. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  3153. }
  3154. // 场景列表
  3155. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3156. $html .= '<h3>场景列表</h3>';
  3157. $html .= '<ul>';
  3158. foreach ($group['scenes'] as $scene) {
  3159. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  3160. }
  3161. $html .= '</ul>';
  3162. }
  3163. // 分集剧本
  3164. if (!empty($group['episode_content'])) {
  3165. $html .= '<h3>分集剧本</h3>';
  3166. // 去除零宽字符和其他不可见字符
  3167. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  3168. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  3169. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  3170. }
  3171. $html .= '</div>';
  3172. }
  3173. }
  3174. return $html;
  3175. }
  3176. /**
  3177. * 构建PDF内容
  3178. */
  3179. private function buildPdfContent($pdf, $script) {
  3180. // 标题
  3181. $pdf->SetFont('dejavusans', 'B', 18);
  3182. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  3183. $pdf->Ln(5);
  3184. // 基本信息
  3185. $pdf->SetFont('dejavusans', '', 12);
  3186. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  3187. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  3188. $pdf->Ln(5);
  3189. // 剧本简介
  3190. if (!empty($script['intro'])) {
  3191. $pdf->SetFont('dejavusans', 'B', 14);
  3192. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  3193. $pdf->SetFont('dejavusans', '', 12);
  3194. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  3195. $pdf->Ln(3);
  3196. }
  3197. // 亮点
  3198. if (!empty($script['highlights'])) {
  3199. $pdf->SetFont('dejavusans', 'B', 14);
  3200. $pdf->Cell(0, 10, '亮点', 0, 1);
  3201. $pdf->SetFont('dejavusans', '', 12);
  3202. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  3203. $pdf->Ln(3);
  3204. }
  3205. // 核心矛盾
  3206. if (!empty($script['core_contradiction'])) {
  3207. $pdf->SetFont('dejavusans', 'B', 14);
  3208. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  3209. $pdf->SetFont('dejavusans', '', 12);
  3210. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  3211. $pdf->Ln(3);
  3212. }
  3213. // 艺术风格
  3214. if (!empty($script['art_style'])) {
  3215. $pdf->SetFont('dejavusans', 'B', 14);
  3216. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  3217. $pdf->SetFont('dejavusans', '', 12);
  3218. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  3219. $pdf->Ln(3);
  3220. }
  3221. // 备注
  3222. if (!empty($script['remark'])) {
  3223. $pdf->SetFont('dejavusans', 'B', 14);
  3224. $pdf->Cell(0, 10, '备注', 0, 1);
  3225. $pdf->SetFont('dejavusans', '', 12);
  3226. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  3227. $pdf->Ln(3);
  3228. }
  3229. // 角色列表
  3230. if (!empty($script['roles']) && is_array($script['roles'])) {
  3231. $pdf->SetFont('dejavusans', 'B', 14);
  3232. $pdf->Cell(0, 10, '角色列表', 0, 1);
  3233. $pdf->SetFont('dejavusans', '', 12);
  3234. foreach ($script['roles'] as $index => $role) {
  3235. if (is_array($role) || is_object($role)) {
  3236. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  3237. } else {
  3238. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  3239. }
  3240. }
  3241. $pdf->Ln(3);
  3242. }
  3243. // 角色关系
  3244. if (!empty($script['role_relationship'])) {
  3245. $pdf->SetFont('dejavusans', 'B', 14);
  3246. $pdf->Cell(0, 10, '角色关系', 0, 1);
  3247. $pdf->SetFont('dejavusans', '', 12);
  3248. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  3249. $pdf->Ln(3);
  3250. }
  3251. // 场景列表
  3252. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  3253. $pdf->SetFont('dejavusans', 'B', 14);
  3254. $pdf->Cell(0, 10, '场景列表', 0, 1);
  3255. $pdf->SetFont('dejavusans', '', 12);
  3256. foreach ($script['scenes'] as $index => $scene) {
  3257. if (is_array($scene) || is_object($scene)) {
  3258. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  3259. } else {
  3260. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  3261. }
  3262. }
  3263. $pdf->Ln(5);
  3264. }
  3265. // 分集内容
  3266. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  3267. $pdf->SetFont('dejavusans', 'B', 16);
  3268. $pdf->Cell(0, 12, '分集内容', 0, 1);
  3269. $pdf->Ln(3);
  3270. foreach ($script['episodes'] as $episode) {
  3271. // 检查是否需要新页面
  3272. if ($pdf->GetY() > 250) {
  3273. $pdf->AddPage();
  3274. }
  3275. $pdf->SetFont('dejavusans', 'B', 14);
  3276. $episodeTitle = '第' . $episode['episode_number'] . '集';
  3277. if (!empty($episode['title'])) {
  3278. $episodeTitle .= ':' . $episode['title'];
  3279. }
  3280. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  3281. // 处理分段内容
  3282. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  3283. $pdf->SetFont('dejavusans', '', 12);
  3284. foreach ($episode['segments'] as $segment) {
  3285. if (!empty($segment['segment_content'])) {
  3286. // 如果有分段编号,显示分段标题
  3287. if (!empty($segment['segment_number'])) {
  3288. $pdf->SetFont('dejavusans', 'B', 12);
  3289. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  3290. $pdf->SetFont('dejavusans', '', 12);
  3291. }
  3292. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  3293. $pdf->Ln(2);
  3294. }
  3295. }
  3296. }
  3297. $pdf->Ln(5);
  3298. }
  3299. }
  3300. }
  3301. /**
  3302. * 构建剧本文本内容
  3303. */
  3304. private function buildScriptContent($script) {
  3305. $content = '';
  3306. $groups = $script['group'];
  3307. $groups = (array)$groups;
  3308. foreach ($groups as $group) {
  3309. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  3310. // 剧本基本信息
  3311. if (!empty($group['intro'])) {
  3312. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  3313. }
  3314. if (!empty($group['highlights'])) {
  3315. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  3316. }
  3317. if (!empty($group['role_relationship'])) {
  3318. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  3319. }
  3320. if (!empty($group['core_contradiction'])) {
  3321. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  3322. }
  3323. if (!empty($group['roles']) && is_array($group['roles'])) {
  3324. $content .= "###主体列表\n";
  3325. foreach ($group['roles'] as $role) {
  3326. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  3327. }
  3328. $content .= "\n\n";
  3329. }
  3330. if (!empty($group['art_style'])) {
  3331. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  3332. }
  3333. // 场景信息
  3334. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3335. $content .= "###场景列表\n";
  3336. foreach ($group['scenes'] as $scene) {
  3337. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  3338. }
  3339. $content .= "\n\n";
  3340. }
  3341. // 分集内容
  3342. if (!empty($group['episode_content'])) {
  3343. $content .= "###分集剧本\n";
  3344. $content .= $group['episode_content'];
  3345. // foreach ($script['episodes'] as $episode) {
  3346. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  3347. // // if (!empty($episode['episode_name'])) {
  3348. // // $content .= ":" . $episode['episode_name'];
  3349. // // }
  3350. // // $content .= "\n";
  3351. // $content .= $episode['episode_content'] . "\n\n";
  3352. // }
  3353. }
  3354. }
  3355. return $content;
  3356. }
  3357. /**
  3358. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3359. *
  3360. * @param array $data 包含以下参数:
  3361. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3362. * - question: 用户问题(可选)
  3363. * - model: 使用的模型(r1 或 v3,默认 v3)
  3364. * @return \Generator 返回生成器,用于流式输出
  3365. */
  3366. public function addChat($data) {
  3367. $uid = Site::getUid();
  3368. $anime_id = getProp($data, 'anime_id');
  3369. if (!$anime_id) Utils::throwError('20003:请选择对话');
  3370. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3371. if (!$anime) Utils::throwError('20003:对话不存在');
  3372. $file = getProp($data, 'file');
  3373. $content = getProp($data, 'content', '');
  3374. $bid = getProp($data, 'bid', 0);
  3375. $script_id = getProp($data, 'script_id', 0);
  3376. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  3377. $prompt = getProp($data, 'prompt');
  3378. $user_anime_name = getProp($anime, 'anime_name');
  3379. // 处理文本模型
  3380. $model = getProp($data, 'model');
  3381. if (!$model) {
  3382. // 用户没有输入,从anime表获取
  3383. $model = getProp($anime, 'model');
  3384. if (!$model) {
  3385. // anime表也没有,使用默认值
  3386. $model = 'doubao-seed-2-0-mini-260215';
  3387. }
  3388. }
  3389. // 验证模型是否在可用模型表中
  3390. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3391. $model = 'doubao-seed-2-0-mini-260215';
  3392. }
  3393. $is_multi = getProp($anime, 'is_multi');
  3394. $is_single = (int)$is_multi !== 1;
  3395. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3396. if ($prompt) {
  3397. $question .= "本次修改要求如下:\n{$prompt}";
  3398. }
  3399. // if (!$file && !$content && !$bid) {
  3400. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3401. // }
  3402. // 提取文件内容
  3403. if ($file) {
  3404. $content = $this->extractFileContent($file);
  3405. if (!$content) {
  3406. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3407. }
  3408. } elseif ($script_id) {
  3409. $content = $this->getContentByScriptId($script_id);
  3410. if (!$content) {
  3411. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3412. }
  3413. } elseif ($bid) {
  3414. $content = $this->getContentByBid($bid);
  3415. if (!$content) {
  3416. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3417. }
  3418. } elseif ($content) {
  3419. $content = filterContent($content);
  3420. } else {
  3421. $content = getProp($anime, 'content');
  3422. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3423. $need_generate_content = true;
  3424. }
  3425. }
  3426. // 美术风格
  3427. $input_art_style = getProp($data, 'art_style');
  3428. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3429. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3430. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3431. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3432. 中年女:邻居阿姨
  3433. 老年男:幽默大爷
  3434. 老年女:婆婆
  3435. 萌娃:奶气萌娃";
  3436. // 判断是否需要生成原文内容
  3437. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3438. // 如果需要生成原文内容,添加额外的要求
  3439. $content_generation_requirement = $need_generate_content
  3440. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3441. : "";
  3442. // 美术风格
  3443. if (!$mappedArtStyle) {
  3444. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3445. }else {
  3446. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3447. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3448. }else {
  3449. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3450. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3451. }
  3452. }
  3453. $systemPrompt = $is_single
  3454. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3455. 强制要求:
  3456. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3457. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3458. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3459. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3460. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3461. 普通要求:
  3462. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3463. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3464. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3465. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3466. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3467. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3468. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3469. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3470. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3471. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3472. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3473. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3474. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3475. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3476. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3477. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3478. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3479. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3480. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3481. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3482. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3483. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3484. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3485. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3486. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3487. 5.{$mappedArtStyle_prompt}\n\n
  3488. 示例如下:\n
  3489. ###剧本名:西昆仑
  3490. ###故事梗概
  3491. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3492. ###剧本亮点
  3493. 亮点1:绝境奇药,生死一线
  3494. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3495. 亮点2:结拜兄妹,化解尴尬
  3496. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3497. 亮点3:纤发夺命,情愫暗涌
  3498. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3499. ###人物关系
  3500. 阿雪与梁萧之间存在兄妹之情。
  3501. ###核心矛盾
  3502. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3503. ###主体列表
  3504. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3505. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3506. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3507. 姿态:站立。}{{甜心小美}}
  3508. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3509. 全景,正面拍摄,青年女性,亚洲人。
  3510. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3511. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3512. 姿态:站立。}{{阳光青年}}
  3513. ###美术风格
  3514. 基础画风风格词:厚涂古风
  3515. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3516. ###场景列表
  3517. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3518. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3519. 无人物。}
  3520. ###分镜剧本
  3521. ##第1幕:徐家老旧厨房 白天 室内
  3522. 分镜1
  3523. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3524. 场景:徐家老旧厨房
  3525. 构图设计:全景,低角度仰视
  3526. 运镜调度:手持拍摄
  3527. 配音角色:旁白
  3528. 出镜角色:许芸-校服装、徐母
  3529. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3530. 画面类型:普通画面
  3531. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3532. 分镜2
  3533. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3534. 场景:徐家老旧厨房
  3535. 构图设计:近景,徐母面部特写
  3536. 运镜调度:固定镜头
  3537. 配音角色:徐母
  3538. 出镜角色:徐母
  3539. 台词内容:问我夜不归宿死哪儿去了。
  3540. 画面类型:对口型
  3541. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3542. ##第2幕:徐家简陋客厅 黄昏 室内
  3543. 分镜3
  3544. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3545. 场景:徐家简陋客厅
  3546. 构图设计:全景,景深虚化
  3547. 运镜调度:固定镜头
  3548. 配音角色:旁白
  3549. 出镜角色:无
  3550. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3551. 画面类型:普通画面
  3552. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3553. 分镜4
  3554. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3555. 场景:徐家简陋客厅
  3556. 构图设计:特写,火车票
  3557. 运镜调度:固定镜头
  3558. 配音角色:旁白
  3559. 出镜角色:无
  3560. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3561. 画面类型:普通画面
  3562. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3563. "
  3564. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3565. 强制要求:\n
  3566. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3567. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3568. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3569. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3570. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3571. 普通要求:\n
  3572. 1.剧本名(必须生成)必须与文档内容高度相关
  3573. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3574. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3575. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3576. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3577. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3578. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3579. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3580. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3581. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3582. 4.{$mappedArtStyle_prompt}\n\n
  3583. 示例如下:\n
  3584. ###剧本名:西昆仑
  3585. ###故事梗概
  3586. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3587. ###剧本亮点
  3588. 亮点1:绝境奇药,生死一线
  3589. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3590. 亮点2:结拜兄妹,化解尴尬
  3591. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3592. 亮点3:纤发夺命,情愫暗涌
  3593. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3594. ###人物关系
  3595. 阿雪与梁萧之间存在兄妹之情。
  3596. ###核心矛盾
  3597. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3598. ###主体列表
  3599. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3600. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3601. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3602. 姿态:站立。}{{甜心小美}}
  3603. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3604. 全景,正面拍摄,青年女性,亚洲人。
  3605. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3606. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3607. 姿态:站立。}{{阳光青年}}
  3608. ###美术风格
  3609. 基础画风风格词:厚涂古风
  3610. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3611. ###场景列表
  3612. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3613. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3614. 无人物。}";
  3615. // 构建消息
  3616. $messages = [
  3617. [
  3618. 'role' => 'system',
  3619. 'content' => $systemPrompt
  3620. ],
  3621. [
  3622. 'role' => 'user',
  3623. 'content' => "以下是文档内容:
  3624. {$content}
  3625. 用户问题:
  3626. {$question}"
  3627. ]
  3628. ];
  3629. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3630. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3631. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3632. if ($model === 'deepseek-chat') {
  3633. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3634. $model = 'deepseek-v4-flash';
  3635. $thinkingMode = 'disabled';
  3636. } elseif ($model === 'deepseek-reasoner') {
  3637. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3638. $model = 'deepseek-v4-flash';
  3639. $thinkingMode = 'enabled';
  3640. }
  3641. $post_data = [
  3642. 'model' => $model,
  3643. 'messages' => $messages,
  3644. // 'max_tokens' => 8192,
  3645. 'temperature' => 0.7,
  3646. 'frequency_penalty' => 0,
  3647. 'presence_penalty' => 0,
  3648. 'response_format' => ['type' => 'text'],
  3649. 'thinking' => ['type'=>$thinkingMode],
  3650. 'stream' => true // 启用流式输出
  3651. ];
  3652. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3653. // 根据模型类型选择调用方法
  3654. $fullContent = '';
  3655. $fullReasoningContent = '';
  3656. $usage = [];
  3657. try {
  3658. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3659. // DeepSeek 官方模型使用 DeepSeek API
  3660. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3661. } else if (in_array($model, $this->gpt_text_models)) {
  3662. // GPT-5.4 模型使用 TokenRouter API
  3663. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3664. } else {
  3665. // 其他模型使用火山引擎API
  3666. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3667. }
  3668. // 验证返回值类型
  3669. if (!is_iterable($streamGenerator)) {
  3670. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3671. dLog('deepseek')->error('addChat流式生成器无效', [
  3672. 'generator_type' => $errorType,
  3673. 'model' => $model,
  3674. 'anime_id' => $anime_id
  3675. ]);
  3676. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  3677. 'type' => $errorType,
  3678. 'model' => $model
  3679. ]);
  3680. yield [
  3681. 'type' => 'error',
  3682. 'script' => [],
  3683. 'episode' => [],
  3684. 'answer' => '',
  3685. 'reasoning' => '',
  3686. 'usage' => [],
  3687. 'error' => '接口返回数据异常,请重新请求'
  3688. ];
  3689. return;
  3690. }
  3691. // 处理流式输出
  3692. foreach ($streamGenerator as $chunk) {
  3693. if (isset($chunk['type'])) {
  3694. if ($chunk['type'] === 'done') {
  3695. // 最终结果
  3696. $fullContent = $chunk['full_content'];
  3697. $fullReasoningContent = $chunk['full_reasoning'];
  3698. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3699. } else {
  3700. // 逐块yield数据
  3701. yield $chunk;
  3702. }
  3703. }
  3704. }
  3705. } catch (\Exception $e) {
  3706. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  3707. 'model' => $model,
  3708. 'anime_id' => $anime_id,
  3709. 'trace' => $e->getTraceAsString()
  3710. ]);
  3711. logDB('deepseek', 'error', 'addChat流式处理失败', [
  3712. 'error' => $e->getMessage(),
  3713. 'model' => $model
  3714. ]);
  3715. yield [
  3716. 'type' => 'error',
  3717. 'script' => [],
  3718. 'episode' => [],
  3719. 'answer' => '',
  3720. 'reasoning' => '',
  3721. 'usage' => [],
  3722. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3723. ];
  3724. return;
  3725. }
  3726. dLog('deepseek')->info('完整内容: '.$fullContent);
  3727. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3728. // 处理完整内容并返回最终结果
  3729. $script_arr = [];
  3730. if ($fullContent) {
  3731. $script_arr = handleScriptContent($fullContent);
  3732. dLog('deepseek')->info('解析内容', $script_arr);
  3733. logDB('deepseek', 'info', '解析内容', $script_arr);
  3734. }
  3735. if (empty($script_arr['roles'])) {
  3736. // 未生成剧本相关内容,保存对话记录并返回提示
  3737. dLog('deepseek')->info('未生成剧本相关的内容');
  3738. try {
  3739. DB::beginTransaction();
  3740. $now = date('Y-m-d H:i:s');
  3741. // 保存对话记录
  3742. $records = [
  3743. [
  3744. 'uid' => $uid,
  3745. 'anime_id' => $anime_id,
  3746. 'sequence' => 0,
  3747. 'role' => 'user',
  3748. 'content' => $prompt,
  3749. 'created_at' => $now,
  3750. 'updated_at' => $now
  3751. ],
  3752. [
  3753. 'uid' => $uid,
  3754. 'anime_id' => $anime_id,
  3755. 'sequence' => 0,
  3756. 'role' => 'assistant',
  3757. // 'content' => $fullContent,
  3758. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  3759. 'created_at' => $now,
  3760. 'updated_at' => $now
  3761. ]
  3762. ];
  3763. DB::table('mp_anime_records')->insert($records);
  3764. DB::commit();
  3765. } catch (\Exception $e) {
  3766. DB::rollBack();
  3767. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3768. }
  3769. yield [
  3770. 'type' => 'done',
  3771. 'script' => [],
  3772. 'episode' => [],
  3773. 'answer' => $fullContent,
  3774. 'reasoning' => $fullReasoningContent,
  3775. 'usage' => $usage,
  3776. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3777. ];
  3778. return;
  3779. }
  3780. // 如果需要生成原文内容,从script_arr中提取
  3781. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3782. $content = $script_arr['content'];
  3783. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  3784. if (!$content) {
  3785. yield [
  3786. 'type' => 'done',
  3787. 'script' => [],
  3788. 'episode' => [],
  3789. 'answer' => $fullContent,
  3790. 'reasoning' => $fullReasoningContent,
  3791. 'usage' => $usage,
  3792. 'error' => '未生成剧本内容,请调整提示词再试'
  3793. ];
  3794. return;
  3795. }
  3796. }
  3797. // 替换美术风格
  3798. if ($mappedArtStyle !== '') {
  3799. $script_arr['art_style'] = $mappedArtStyle;
  3800. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3801. }
  3802. // 新建动漫
  3803. if ($user_anime_name == '新剧本策划') {
  3804. $anime_name = getProp($script_arr, 'script_name');
  3805. // if (!$anime_name) {
  3806. // // 未识别到剧本名,保存对话记录并返回提示
  3807. // dLog('deepseek')->info('未能识别到剧本名称');
  3808. // try {
  3809. // DB::beginTransaction();
  3810. // $now = date('Y-m-d H:i:s');
  3811. // // 保存对话记录
  3812. // $records = [
  3813. // [
  3814. // 'uid' => $uid,
  3815. // 'anime_id' => $anime_id,
  3816. // 'sequence' => 0,
  3817. // 'role' => 'user',
  3818. // 'content' => $prompt,
  3819. // 'created_at' => $now,
  3820. // 'updated_at' => $now
  3821. // ],
  3822. // [
  3823. // 'uid' => $uid,
  3824. // 'anime_id' => $anime_id,
  3825. // 'sequence' => 0,
  3826. // 'role' => 'assistant',
  3827. // 'content' => '未能生成剧本名称,请重试',
  3828. // 'created_at' => $now,
  3829. // 'updated_at' => $now
  3830. // ]
  3831. // ];
  3832. // DB::table('mp_anime_records')->insert($records);
  3833. // DB::commit();
  3834. // } catch (\Exception $e) {
  3835. // DB::rollBack();
  3836. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3837. // }
  3838. // yield [
  3839. // 'type' => 'done',
  3840. // 'script' => [],
  3841. // 'episode' => [],
  3842. // 'answer' => $fullContent,
  3843. // 'reasoning' => $fullReasoningContent,
  3844. // 'usage' => $usage,
  3845. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  3846. // ];
  3847. // return;
  3848. // }
  3849. // 确认对话名称唯一性
  3850. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  3851. $anime_name = $anime_name . '_' . date('YmdHis');
  3852. }
  3853. }else {
  3854. $anime_name = $user_anime_name;
  3855. }
  3856. $table_data = [
  3857. 'user_id' => $uid,
  3858. 'anime_name' => $anime_name,
  3859. 'model' => $model,
  3860. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3861. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3862. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3863. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3864. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3865. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3866. 'art_style_type' => $input_art_style,
  3867. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3868. 'status' => '解析完成',
  3869. 'content' => $content,
  3870. 'is_multi' => $is_multi,
  3871. 'ace_mode' => $ace_mode,
  3872. 'generate_status' => '待执行',
  3873. 'updated_at' => date('Y-m-d H:i:s')
  3874. ];
  3875. if ($table_data['content']) {
  3876. $chapters = splitContent($table_data['content']);
  3877. $chapter_count = count($chapters);
  3878. if ($chapter_count > 0) {
  3879. $table_data['start_episode_sequence'] = 1;
  3880. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3881. }
  3882. }
  3883. // 如果有剧本ID则进行绑定
  3884. if ($script_id) {
  3885. $table_data['script_id'] = $script_id;
  3886. }
  3887. $single_episode = [];
  3888. try {
  3889. DB::beginTransaction();
  3890. $now = date('Y-m-d H:i:s');
  3891. // 更新动漫大纲
  3892. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3893. if (!$boolen) {
  3894. dLog('deepseek')->info('动漫保存失败', $table_data);
  3895. Utils::throwError('20003:动漫保存失败');
  3896. }
  3897. // 保存对话记录
  3898. $records = [
  3899. [
  3900. 'uid' => $uid,
  3901. 'anime_id' => $anime_id,
  3902. 'sequence' => 0,
  3903. 'role' => 'user',
  3904. 'content' => $prompt,
  3905. 'created_at' => date('Y-m-d H:i:s'),
  3906. 'updated_at' => date('Y-m-d H:i:s')
  3907. ],
  3908. [
  3909. 'uid' => $uid,
  3910. 'anime_id' => $anime_id,
  3911. 'sequence' => 0,
  3912. 'role' => 'assistant',
  3913. 'content' => $fullContent,
  3914. 'created_at' => date('Y-m-d H:i:s'),
  3915. 'updated_at' => date('Y-m-d H:i:s')
  3916. ]
  3917. ];
  3918. // 保存对话记录
  3919. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3920. if (!$boolen3) {
  3921. Utils::throwError('20003:对话记录保存失败');
  3922. }
  3923. if ($is_single) {
  3924. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3925. if (empty($episode_arr['acts'])) {
  3926. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3927. }
  3928. $saveResult = $this->saveEpisodeVersionData(
  3929. $anime_id,
  3930. 1,
  3931. $episode_arr,
  3932. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3933. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3934. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  3935. null,
  3936. null,
  3937. false,
  3938. $content,
  3939. $now
  3940. );
  3941. $single_episode = $saveResult['episode'];
  3942. $episode_id = $saveResult['episode_id'];
  3943. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3944. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3945. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3946. 'props' => json_encode($saveResult['merged_props'], 256),
  3947. 'updated_at' => $now
  3948. ]);
  3949. if ($boolen5 === false) {
  3950. Utils::throwError('20003:单剧集主表资源同步失败');
  3951. }
  3952. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3953. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3954. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  3955. $episode_record_content = '确认分镜大纲';
  3956. if ($content !== '') {
  3957. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3958. }
  3959. $episode_records = [
  3960. [
  3961. 'uid' => $uid,
  3962. 'anime_id' => $anime_id,
  3963. 'role' => 'user',
  3964. 'content' => $episode_record_content,
  3965. 'sequence' => 1,
  3966. 'episode_id' => $episode_id,
  3967. 'created_at' => $now,
  3968. 'updated_at' => $now
  3969. ],
  3970. [
  3971. 'uid' => $uid,
  3972. 'anime_id' => $anime_id,
  3973. 'role' => 'assistant',
  3974. 'content' => $fullContent,
  3975. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3976. 'sequence' => 1,
  3977. 'episode_id' => $episode_id,
  3978. 'created_at' => $now,
  3979. 'updated_at' => $now
  3980. ]
  3981. ];
  3982. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3983. if (!$boolen4) {
  3984. Utils::throwError('20003:单剧集分镜记录保存失败');
  3985. }
  3986. }
  3987. }catch (\Exception $e) {
  3988. DB::rollBack();
  3989. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3990. yield [
  3991. 'type' => 'done',
  3992. 'answer' => $fullContent,
  3993. 'reasoning' => $fullReasoningContent,
  3994. 'usage' => $usage,
  3995. 'error' => $e->getMessage(),
  3996. ];
  3997. return;
  3998. }
  3999. DB::commit();
  4000. dLog('deepseek')->info('保存完毕');
  4001. if ($is_single && !empty($single_episode)) {
  4002. // $this->batchSetGlobalRoleImg([
  4003. // 'anime_id' => $anime_id,
  4004. // ]);
  4005. // $this->batchSetGlobalSceneImg([
  4006. // 'anime_id' => $anime_id,
  4007. // ]);
  4008. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4009. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4010. }
  4011. $table_data['anime_id'] = $anime_id;
  4012. $table_data['roles'] = json_decode($table_data['roles'], true);
  4013. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4014. // $table_data['episodes'] = $script_arr['episodes'];
  4015. unset($table_data['created_at']);
  4016. unset($table_data['updated_at']);
  4017. unset($table_data['status']);
  4018. dLog('deepseek')->info('开始返回');
  4019. yield [
  4020. 'type' => 'done',
  4021. 'script' => $table_data,
  4022. 'episode' => $single_episode,
  4023. 'answer' => $fullContent,
  4024. 'reasoning' => $fullReasoningContent,
  4025. 'usage' => $usage
  4026. ];
  4027. }
  4028. public function reGenerateAnime($data) {
  4029. $uid = Site::getUid();
  4030. $file = getProp($data, 'file');
  4031. $content = getProp($data, 'content', '');
  4032. $bid = getProp($data, 'bid', 0);
  4033. $script_id = getProp($data, 'script_id', 0);
  4034. $anime_id = getProp($data, 'anime_id');
  4035. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4036. if (!$anime) {
  4037. Utils::throwError('20003:该对话不存在');
  4038. }
  4039. $user_anime_name = getProp($anime, 'anime_name');
  4040. $prompt = getProp($data, 'prompt');
  4041. // 处理文本模型
  4042. $model = getProp($data, 'model');
  4043. if (!$model) {
  4044. // 用户没有输入,从anime表获取
  4045. $model = getProp($anime, 'model');
  4046. if (!$model) {
  4047. // anime表也没有,使用默认值
  4048. $model = 'doubao-seed-2-0-mini-260215';
  4049. }
  4050. }
  4051. // 验证模型是否在可用模型表中
  4052. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4053. $model = 'doubao-seed-2-0-mini-260215';
  4054. }
  4055. $is_multi = getProp($anime, 'is_multi', 1);
  4056. $is_single = (int)$is_multi !== 1;
  4057. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  4058. if ($is_single) {
  4059. $episode_exists = DB::table('mp_anime_episodes')
  4060. ->where('anime_id', $anime_id)
  4061. ->where('sequence', 1)
  4062. ->exists();
  4063. if ($episode_exists) {
  4064. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  4065. }
  4066. }
  4067. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4068. if ($prompt) {
  4069. $question .= "本次修改要求如下:\n{$prompt}";
  4070. }
  4071. // 提取文件内容
  4072. if ($file) {
  4073. $content = $this->extractFileContent($file);
  4074. if (!$content) {
  4075. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4076. }
  4077. } elseif ($script_id) {
  4078. $content = $this->getContentByScriptId($script_id);
  4079. if (!$content) {
  4080. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4081. }
  4082. } elseif ($bid) {
  4083. $content = $this->getContentByBid($bid);
  4084. if (!$content) {
  4085. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4086. }
  4087. } elseif ($content) {
  4088. $content = filterContent($content);
  4089. }else {
  4090. $content = filterContent(getProp($anime, 'content'));
  4091. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4092. $need_generate_content = true;
  4093. }
  4094. }
  4095. // 判断是否需要生成原文内容
  4096. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4097. // 如果需要生成原文内容,添加额外的要求
  4098. $content_generation_requirement = $need_generate_content
  4099. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4100. : "";
  4101. // 美术风格
  4102. $input_art_style = getProp($anime, 'art_style');
  4103. if (!$input_art_style) {
  4104. $input_art_style = getProp($data, 'art_style');
  4105. }
  4106. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4107. // 美术风格
  4108. if (!$mappedArtStyle) {
  4109. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4110. }else {
  4111. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4112. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4113. }else {
  4114. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4115. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4116. }
  4117. }
  4118. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4119. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4120. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4121. 中年女:邻居阿姨
  4122. 老年男:幽默大爷
  4123. 老年女:婆婆
  4124. 萌娃:奶气萌娃";
  4125. $system_message = ['role'=>'system', 'content'=>$is_single
  4126. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4127. 强制要求:
  4128. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4129. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4130. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4131. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4132. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4133. 普通要求:
  4134. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4135. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4136. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4137. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4138. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4139. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4140. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4141. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4142. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4143. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4144. 3.$mappedArtStyle_prompt\n\n
  4145. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4146. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4147. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4148. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4149. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4150. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4151. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4152. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4153. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4154. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4155. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4156. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4157. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4158. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4159. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4160. 示例如下:\n
  4161. ###剧本名:西昆仑
  4162. ###故事梗概
  4163. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4164. ###剧本亮点
  4165. 亮点1:绝境奇药,生死一线
  4166. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4167. 亮点2:结拜兄妹,化解尴尬
  4168. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4169. 亮点3:纤发夺命,情愫暗涌
  4170. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4171. ###人物关系
  4172. 阿雪与梁萧之间存在兄妹之情。
  4173. ###核心矛盾
  4174. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4175. ###主体列表
  4176. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4177. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4178. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4179. 姿态:站立。}{{甜心小美}}
  4180. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4181. 全景,正面拍摄,青年女性,亚洲人。
  4182. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4183. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4184. 姿态:站立。}{{阳光青年}}
  4185. ###美术风格
  4186. 基础画风风格词:厚涂古风
  4187. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4188. ###场景列表
  4189. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4190. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4191. 无人物。}
  4192. ###分镜剧本
  4193. ##第1幕:徐家老旧厨房 白天 室内
  4194. 分镜1
  4195. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4196. 场景:徐家老旧厨房
  4197. 构图设计:全景,低角度仰视
  4198. 运镜调度:手持拍摄
  4199. 配音角色:旁白
  4200. 出镜角色:许芸-校服装、徐母
  4201. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4202. 画面类型:普通画面
  4203. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4204. 分镜2
  4205. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4206. 场景:徐家老旧厨房
  4207. 构图设计:近景,徐母面部特写
  4208. 运镜调度:固定镜头
  4209. 配音角色:徐母
  4210. 出镜角色:徐母
  4211. 台词内容:问我夜不归宿死哪儿去了。
  4212. 画面类型:对口型
  4213. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4214. ##第2幕:徐家简陋客厅 黄昏 室内
  4215. 分镜3
  4216. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4217. 场景:徐家简陋客厅
  4218. 构图设计:全景,景深虚化
  4219. 运镜调度:固定镜头
  4220. 配音角色:旁白
  4221. 出镜角色:无
  4222. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4223. 画面类型:普通画面
  4224. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4225. 分镜4
  4226. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4227. 场景:徐家简陋客厅
  4228. 构图设计:特写,火车票
  4229. 运镜调度:固定镜头
  4230. 配音角色:旁白
  4231. 出镜角色:无
  4232. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4233. 画面类型:普通画面
  4234. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4235. "
  4236. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4237. 强制要求:\n
  4238. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4239. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4240. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4241. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4242. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4243. 普通要求:\n
  4244. 1.剧本名(必须生成)必须与文档内容高度相关
  4245. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4246. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4247. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4248. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4249. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4250. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4251. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4252. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4253. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4254. 4.$mappedArtStyle_prompt\n\n
  4255. 示例如下:\n
  4256. ###剧本名:西昆仑
  4257. ###故事梗概
  4258. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4259. ###剧本亮点
  4260. 亮点1:绝境奇药,生死一线
  4261. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4262. 亮点2:结拜兄妹,化解尴尬
  4263. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4264. 亮点3:纤发夺命,情愫暗涌
  4265. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4266. ###人物关系
  4267. 阿雪与梁萧之间存在兄妹之情。
  4268. ###核心矛盾
  4269. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4270. ###主体列表
  4271. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4272. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4273. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4274. 姿态:站立。}{{甜心小美}}
  4275. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4276. 全景,正面拍摄,青年女性,亚洲人。
  4277. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4278. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4279. 姿态:站立。}{{阳光青年}}
  4280. ###美术风格
  4281. 基础画风风格词:厚涂古风
  4282. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4283. ###场景列表
  4284. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4285. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4286. 无人物。}"];
  4287. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  4288. $episode_count = $this->extractEpisodeNumber($prompt);
  4289. if ((int)getProp($anime, 'is_multi') !== 1) {
  4290. yield [
  4291. 'type' => 'done',
  4292. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  4293. 'reasoning' => '',
  4294. 'usage' => []
  4295. ];
  4296. return;
  4297. }
  4298. if ($episode_count) {
  4299. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  4300. $system_message = [
  4301. 'role' => 'system',
  4302. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4303. 强制要求:\n
  4304. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4305. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4306. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4307. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4308. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4309. 普通要求:\n
  4310. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4311. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4312. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4313. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4314. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4315. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4316. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4317. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4318. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4319. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  4320. 示例如下:\n
  4321. ###剧本名:西昆仑
  4322. ###故事梗概
  4323. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4324. ###剧本亮点
  4325. 亮点1:绝境奇药,生死一线
  4326. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4327. 亮点2:结拜兄妹,化解尴尬
  4328. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4329. 亮点3:纤发夺命,情愫暗涌
  4330. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4331. ###人物关系
  4332. 阿雪与梁萧之间存在兄妹之情。
  4333. ###核心矛盾
  4334. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4335. ###主体列表
  4336. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4337. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4338. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4339. 姿态:站立。}{{甜心小美}}
  4340. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4341. 全景,正面拍摄,青年女性,亚洲人。
  4342. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4343. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4344. 姿态:站立。}{{阳光青年}}
  4345. ###美术风格
  4346. 基础画风风格词:厚涂古风
  4347. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4348. ###场景列表
  4349. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4350. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4351. 无人物。}
  4352. ###分集详细内容
  4353. ##第1章 重生
  4354. 我重生了。
  4355. 源于一个男人偏执的暗恋。
  4356. ##第2章 相救
  4357. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  4358. 我眼睛扫向站在锅炉后的卞大伟。"
  4359. ];
  4360. // 构建消息
  4361. $messages = [
  4362. $system_message,
  4363. [
  4364. 'role' => 'user',
  4365. 'content' => "以下是文档内容:
  4366. {$content}
  4367. 用户问题:
  4368. {$question}"
  4369. ]
  4370. ];
  4371. }else {
  4372. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  4373. // 构建消息
  4374. $messages = [
  4375. $system_message,
  4376. [
  4377. 'role' => 'user',
  4378. 'content' => "以下是文档内容:
  4379. {$content}
  4380. 用户问题:
  4381. {$question}"
  4382. ]
  4383. ];
  4384. }else {
  4385. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  4386. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  4387. return (array)$value;
  4388. })->toArray();
  4389. array_unshift($messages, $system_message);
  4390. $messages[] = [
  4391. 'role' => 'user',
  4392. 'content' => $prompt
  4393. ];
  4394. }
  4395. }
  4396. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4397. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4398. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4399. if ($model === 'deepseek-chat') {
  4400. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4401. $model = 'deepseek-v4-flash';
  4402. $thinkingMode = 'disabled';
  4403. } elseif ($model === 'deepseek-reasoner') {
  4404. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4405. $model = 'deepseek-v4-flash';
  4406. $thinkingMode = 'enabled';
  4407. }
  4408. $post_data = [
  4409. 'model' => $model,
  4410. 'messages' => $messages,
  4411. // 'max_tokens' => 8192,
  4412. 'temperature' => 0.7,
  4413. 'frequency_penalty' => 0,
  4414. 'presence_penalty' => 0,
  4415. 'response_format' => ['type' => 'text'],
  4416. 'thinking' => ['type' => $thinkingMode],
  4417. 'stream' => true // 启用流式输出
  4418. ];
  4419. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4420. // 根据模型类型选择调用方法
  4421. $fullContent = '';
  4422. $fullReasoningContent = '';
  4423. $usage = [];
  4424. // dd($post_data);
  4425. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  4426. try {
  4427. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4428. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4429. } else if (in_array($model, $this->gpt_text_models)) {
  4430. // GPT-5.4 模型使用 TokenRouter API
  4431. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4432. } else {
  4433. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4434. }
  4435. // 验证返回值类型
  4436. if (!is_iterable($streamGenerator)) {
  4437. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4438. dLog('deepseek')->error('方法名流式生成器无效', [
  4439. 'generator_type' => $errorType,
  4440. 'model' => $model,
  4441. // 添加其他上下文信息
  4442. ]);
  4443. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  4444. 'type' => $errorType,
  4445. 'model' => $model
  4446. ]);
  4447. yield [
  4448. 'type' => 'error',
  4449. // 根据方法返回相应的空数据结构
  4450. 'answer' => '',
  4451. 'reasoning' => '',
  4452. 'usage' => [],
  4453. 'error' => '接口返回数据异常,请重新请求'
  4454. ];
  4455. return;
  4456. }
  4457. // 处理流式输出
  4458. foreach ($streamGenerator as $chunk) {
  4459. if (isset($chunk['type'])) {
  4460. if ($chunk['type'] === 'done') {
  4461. $fullContent = $chunk['full_content'];
  4462. $fullReasoningContent = $chunk['full_reasoning'];
  4463. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4464. } else {
  4465. yield $chunk;
  4466. }
  4467. }
  4468. }
  4469. } catch (\Exception $e) {
  4470. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  4471. 'model' => $model,
  4472. 'trace' => $e->getTraceAsString()
  4473. ]);
  4474. logDB('deepseek', 'error', '方法名流式处理失败', [
  4475. 'error' => $e->getMessage(),
  4476. 'model' => $model
  4477. ]);
  4478. yield [
  4479. 'type' => 'error',
  4480. // 根据方法返回相应的空数据结构
  4481. 'answer' => '',
  4482. 'reasoning' => '',
  4483. 'usage' => [],
  4484. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4485. ];
  4486. return;
  4487. }
  4488. dLog('deepseek')->info('完整内容: '.$fullContent);
  4489. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4490. // 处理完整内容并返回最终结果
  4491. $script_arr = [];
  4492. if ($fullContent) {
  4493. $script_arr = handleScriptContent($fullContent);
  4494. dLog('deepseek')->info('解析内容', $script_arr);
  4495. logDB('deepseek', 'info', '解析内容', $script_arr);
  4496. }
  4497. if (empty($script_arr['roles'])) {
  4498. // 未生成剧本相关内容,保存对话记录并返回提示
  4499. dLog('deepseek')->info('未生成剧本相关的内容');
  4500. try {
  4501. $now = date('Y-m-d H:i:s');
  4502. // 保存对话记录
  4503. $records = [
  4504. [
  4505. 'uid' => $uid,
  4506. 'anime_id' => $anime_id,
  4507. 'sequence' => 0,
  4508. 'role' => 'user',
  4509. 'content' => $prompt,
  4510. 'created_at' => $now,
  4511. 'updated_at' => $now
  4512. ],
  4513. [
  4514. 'uid' => $uid,
  4515. 'anime_id' => $anime_id,
  4516. 'sequence' => 0,
  4517. 'role' => 'assistant',
  4518. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  4519. 'created_at' => $now,
  4520. 'updated_at' => $now
  4521. ]
  4522. ];
  4523. DB::table('mp_anime_records')->insert($records);
  4524. } catch (\Exception $e) {
  4525. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4526. }
  4527. yield [
  4528. 'type' => 'done',
  4529. 'script' => [],
  4530. 'episode' => [],
  4531. 'answer' => $fullContent,
  4532. 'reasoning' => $fullReasoningContent,
  4533. 'usage' => $usage,
  4534. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4535. ];
  4536. return;
  4537. }
  4538. // 替换美术风格
  4539. if ($mappedArtStyle !== '') {
  4540. $script_arr['art_style'] = $mappedArtStyle;
  4541. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4542. }
  4543. if ($user_anime_name != '新剧本策划') {
  4544. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  4545. // 确认对话名称唯一性
  4546. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4547. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  4548. }
  4549. }else {
  4550. $anime_name = $user_anime_name;
  4551. }
  4552. $table_data = [
  4553. 'user_id' => $uid,
  4554. 'model' => $model,
  4555. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4556. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4557. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4558. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4559. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4560. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4561. 'art_style_type' => $input_art_style,
  4562. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4563. 'status' => '解析完成',
  4564. 'generate_status' => '待执行',
  4565. 'updated_at' => date('Y-m-d H:i:s')
  4566. ];
  4567. if ($anime_name) $table_data['anime_name'] = $anime_name;
  4568. // 如果是修改集数,则将content内容更新(会改变原文)
  4569. if (isset($episode_count) && $episode_count > 0) {
  4570. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  4571. $table_data['start_episode_sequence'] = 1;
  4572. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  4573. }else {
  4574. // 如果需要生成原文内容,从script_arr中提取
  4575. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4576. $table_data['content'] = $script_arr['content'];
  4577. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  4578. if (!$table_data['content']) {
  4579. yield [
  4580. 'type' => 'done',
  4581. 'script' => [],
  4582. 'episode' => [],
  4583. 'answer' => $fullContent,
  4584. 'reasoning' => $fullReasoningContent,
  4585. 'usage' => $usage,
  4586. 'error' => '未生成剧本内容,请调整提示词再试'
  4587. ];
  4588. return;
  4589. }
  4590. }
  4591. if (isset($table_data['content']) && $table_data['content']) {
  4592. $chapters = splitContent($table_data['content']);
  4593. $chapter_count = count($chapters);
  4594. if ($chapter_count > 0) {
  4595. $table_data['start_episode_sequence'] = 1;
  4596. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4597. }
  4598. }
  4599. }
  4600. $single_episode = [];
  4601. try {
  4602. DB::beginTransaction();
  4603. $now = date('Y-m-d H:i:s');
  4604. // 更新动漫大纲
  4605. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4606. if (!$boolen) {
  4607. dLog('deepseek')->info('对话修改失败', $table_data);
  4608. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  4609. Utils::throwError('20003:对话修改失败');
  4610. }
  4611. // 保存对话记录
  4612. $records = [
  4613. [
  4614. 'uid' => $uid,
  4615. 'anime_id' => $anime_id,
  4616. 'sequence' => 0,
  4617. 'role' => 'user',
  4618. 'content' => $prompt,
  4619. 'created_at' => $now,
  4620. 'updated_at' => $now
  4621. ],
  4622. [
  4623. 'uid' => $uid,
  4624. 'anime_id' => $anime_id,
  4625. 'sequence' => 0,
  4626. 'role' => 'assistant',
  4627. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4628. 'content' => $fullContent,
  4629. 'created_at' => $now,
  4630. 'updated_at' => $now
  4631. ]
  4632. ];
  4633. // 保存对话记录
  4634. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4635. if (!$boolen3) {
  4636. Utils::throwError('20003:对话记录保存失败');
  4637. }
  4638. // 单剧集模式:生成并保存剧集信息
  4639. if ($is_single) {
  4640. $anime_name = getProp($anime, 'anime_name', '未命名');
  4641. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4642. if (empty($episode_arr['acts'])) {
  4643. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4644. }
  4645. $saveResult = $this->saveEpisodeVersionData(
  4646. $anime_id,
  4647. 1,
  4648. $episode_arr,
  4649. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4650. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4651. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4652. null,
  4653. null,
  4654. false,
  4655. $content,
  4656. $now
  4657. );
  4658. $single_episode = $saveResult['episode'];
  4659. $episode_id = $saveResult['episode_id'];
  4660. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4661. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4662. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4663. 'props' => json_encode($saveResult['merged_props'], 256),
  4664. 'updated_at' => $now
  4665. ]);
  4666. if ($boolen5 === false) {
  4667. Utils::throwError('20003:单剧集主表资源同步失败');
  4668. }
  4669. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4670. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4671. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4672. $episode_record_content = '确认分镜大纲';
  4673. if ($content !== '') {
  4674. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4675. }
  4676. $episode_records = [
  4677. [
  4678. 'uid' => $uid,
  4679. 'anime_id' => $anime_id,
  4680. 'role' => 'user',
  4681. 'content' => $episode_record_content,
  4682. 'sequence' => 1,
  4683. 'episode_id' => $episode_id,
  4684. 'created_at' => $now,
  4685. 'updated_at' => $now
  4686. ],
  4687. [
  4688. 'uid' => $uid,
  4689. 'anime_id' => $anime_id,
  4690. 'role' => 'assistant',
  4691. 'content' => $fullContent,
  4692. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4693. 'sequence' => 1,
  4694. 'episode_id' => $episode_id,
  4695. 'created_at' => $now,
  4696. 'updated_at' => $now
  4697. ]
  4698. ];
  4699. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4700. if (!$boolen4) {
  4701. Utils::throwError('20003:单剧集分镜记录保存失败');
  4702. }
  4703. }
  4704. }catch (\Exception $e) {
  4705. DB::rollBack();
  4706. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  4707. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  4708. yield [
  4709. 'type' => 'done',
  4710. 'answer' => $fullContent,
  4711. 'reasoning' => $fullReasoningContent,
  4712. 'usage' => $usage,
  4713. 'error' => $e->getMessage(),
  4714. ];
  4715. return;
  4716. }
  4717. DB::commit();
  4718. dLog('deepseek')->info('保存完毕');
  4719. if ($is_single && !empty($single_episode)) {
  4720. // $this->batchSetGlobalRoleImg([
  4721. // 'anime_id' => $anime_id,
  4722. // ]);
  4723. // $this->batchSetGlobalSceneImg([
  4724. // 'anime_id' => $anime_id,
  4725. // ]);
  4726. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4727. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4728. }
  4729. $table_data['anime_id'] = $anime_id;
  4730. $table_data['roles'] = json_decode($table_data['roles'], true);
  4731. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4732. unset($table_data['updated_at']);
  4733. unset($table_data['status']);
  4734. yield [
  4735. 'type' => 'done',
  4736. 'script' => $table_data,
  4737. 'episode' => $single_episode,
  4738. 'answer' => $fullContent,
  4739. 'reasoning' => $fullReasoningContent,
  4740. 'usage' => $usage
  4741. ];
  4742. }
  4743. public function chat($data) {
  4744. $uid = Site::getUid();
  4745. $anime_id = getProp($data, 'anime_id');
  4746. $file = getProp($data, 'file');
  4747. $content = getProp($data, 'content', '');
  4748. $bid = getProp($data, 'bid', 0);
  4749. $script_id = getProp($data, 'script_id', 0);
  4750. $episode_number = getProp($data, 'episode_number', 1);
  4751. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4752. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4753. if (!$anime) Utils::throwError('20003:该对话不存在!');
  4754. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  4755. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  4756. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  4757. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  4758. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  4759. $roles = is_array($roles) ? $roles : [];
  4760. $scenes = is_array($scenes) ? $scenes : [];
  4761. // 获取最后一集序号
  4762. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  4763. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  4764. // 转换主体列表和场景列表的格式
  4765. // 获取参考主体或场景
  4766. if ((int)$episode_number === 1) {
  4767. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  4768. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  4769. }else {
  4770. $prev_episode_number = $episode_number - 1;
  4771. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  4772. }
  4773. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  4774. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  4775. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  4776. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  4777. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4778. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4779. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4780. 中年女:邻居阿姨
  4781. 老年男:幽默大爷
  4782. 老年女:婆婆
  4783. 萌娃:奶气萌娃";
  4784. if ($roles_content) {
  4785. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  4786. 主体范围:\n {$roles_content}\n
  4787. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  4788. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4789. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4790. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4791. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4792. }else {
  4793. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4794. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4795. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4796. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4797. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4798. }
  4799. if ($scenes_content) {
  4800. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  4801. 场景范围:\n {$scenes_content}\n
  4802. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  4803. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4804. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4805. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4806. }else {
  4807. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4808. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4809. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4810. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4811. }
  4812. // 提取文件内容
  4813. if ($file) {
  4814. $uploaded_content = $this->extractFileContent($file);
  4815. if (!$uploaded_content) {
  4816. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4817. }
  4818. } elseif ($script_id) {
  4819. $uploaded_content = $this->getContentByScriptId($script_id);
  4820. if (!$uploaded_content) {
  4821. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4822. }
  4823. } elseif ($bid) {
  4824. $uploaded_content = $this->getContentByBid($bid);
  4825. if (!$uploaded_content) {
  4826. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4827. }
  4828. } elseif ($content) {
  4829. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  4830. }
  4831. // elseif ($prompt) {
  4832. // $uploaded_content = filterContent($prompt);
  4833. // }
  4834. else {
  4835. $uploaded_content = '';
  4836. }
  4837. $input_art_style = getProp($anime, 'art_style');
  4838. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4839. // 美术风格
  4840. if (!$mappedArtStyle) {
  4841. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4842. }else {
  4843. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4844. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4845. }else {
  4846. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4847. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4848. }
  4849. }
  4850. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4851. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4852. // 强制要求:
  4853. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4854. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4855. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4856. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4857. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  4858. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  4859. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  4860. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  4861. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  4862. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  4863. // - 分镜要和场景列表、人物主体保持一致\n
  4864. // 普通要求:
  4865. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4866. // {$role_demo}
  4867. // {$scene_demo}
  4868. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4869. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4870. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4871. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4872. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4873. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4874. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4875. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4876. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4877. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4878. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4879. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4880. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4881. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4882. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4883. // 5.$mappedArtStyle_prompt\n\n
  4884. // 示例格式:\n
  4885. // 第1集:隐形的守护者
  4886. // ###故事梗概
  4887. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4888. // ###美术风格
  4889. // 基础画风风格词:韩漫二次元
  4890. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4891. // ###主体列表
  4892. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4893. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4894. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4895. // ###场景列表
  4896. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4897. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4898. // 无人物。}
  4899. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4900. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4901. // 无人物。}
  4902. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4903. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4904. // 无人物。}
  4905. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4906. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4907. // 无人物。}
  4908. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4909. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4910. // 无人物。}
  4911. // ###分镜剧本
  4912. // ##第1幕:徐家老旧厨房 白天 室内
  4913. // 分镜1
  4914. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4915. // 场景:徐家老旧厨房
  4916. // 构图设计:全景,低角度仰视
  4917. // 运镜调度:手持拍摄
  4918. // 配音角色:旁白
  4919. // 出镜角色:许芸-校服装、徐母
  4920. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4921. // 画面类型:普通画面
  4922. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4923. // 分镜2
  4924. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4925. // 场景:徐家老旧厨房
  4926. // 构图设计:近景,徐母面部特写
  4927. // 运镜调度:固定镜头
  4928. // 配音角色:徐母
  4929. // 出镜角色:徐母
  4930. // 台词内容:问我夜不归宿死哪儿去了。
  4931. // 画面类型:对口型
  4932. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4933. // ##第2幕:徐家简陋客厅 黄昏 室内
  4934. // 分镜3
  4935. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4936. // 场景:徐家简陋客厅
  4937. // 构图设计:全景,景深虚化
  4938. // 运镜调度:固定镜头
  4939. // 配音角色:旁白
  4940. // 出镜角色:无
  4941. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4942. // 画面类型:普通画面
  4943. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4944. // 分镜4
  4945. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4946. // 场景:徐家简陋客厅
  4947. // 构图设计:特写,火车票
  4948. // 运镜调度:固定镜头
  4949. // 配音角色:旁白
  4950. // 出镜角色:无
  4951. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4952. // 画面类型:普通画面
  4953. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4954. // \n\n";
  4955. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  4956. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  4957. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  4958. 普通要求:
  4959. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4960. {$role_demo}
  4961. {$scene_demo}
  4962. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4963. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4964. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4965. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  4966. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4967. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4968. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4969. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4970. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4971. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4972. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4973. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4974. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4975. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4976. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4977. 5.$mappedArtStyle_prompt
  4978. 6.《情绪-视听语言映射表》:
  4979. 6.1 场景空间与时间心理学 (Scene & Temporality)
  4980. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4981. -----|---------|------------|----------------
  4982. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  4983. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  4984. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  4985. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  4986. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  4987. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4988. -----|---------|------------|----------------
  4989. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  4990. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  4991. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  4992. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  4993. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  4994. --------|---------|--------------|-------------
  4995. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  4996. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  4997. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  4998. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  4999. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  5000. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  5001. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  5002. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  5003. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  5004. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  5005. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  5006. -----|---------|------------|------------
  5007. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  5008. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  5009. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  5010. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  5011. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  5012. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  5013. --------|---------|--------------|----------
  5014. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  5015. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  5016. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  5017. 6.6 声音设计与潜意识影响 (Soundscape)
  5018. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  5019. -----|---------|------------|------------------
  5020. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  5021. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  5022. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  5023. 理论基石:
  5024. - The Five C's of Cinematography by Joseph V. Mascelli
  5025. - Film Art: An Introduction by David Bordwell
  5026. - Sight, Sound, Motion by Herbert Zettl
  5027. - Notes on the Cinematograph by Robert Bresson
  5028. \n\n
  5029. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  5030. 示例格式:\n
  5031. 第1集:隐形的守护者
  5032. ###故事梗概
  5033. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5034. ###美术风格
  5035. 基础画风风格词:韩漫二次元
  5036. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  5037. ###主体列表
  5038. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  5039. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  5040. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  5041. ###场景列表
  5042. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  5043. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5044. 无人物。}
  5045. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  5046. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  5047. 无人物。}
  5048. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  5049. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5050. 无人物。}
  5051. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5052. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5053. 无人物。}
  5054. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5055. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5056. 无人物。}
  5057. ###分镜剧本
  5058. ##第1幕:徐家老旧厨房 白天 室内
  5059. 分镜1
  5060. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5061. 场景:徐家老旧厨房
  5062. 构图设计:全景,低角度仰视
  5063. 运镜调度:手持拍摄
  5064. 配音角色:旁白
  5065. 出镜角色:许芸-校服装、徐母
  5066. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5067. 画面类型:普通画面
  5068. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5069. 分镜2
  5070. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5071. 场景:徐家老旧厨房
  5072. 构图设计:近景,徐母面部特写
  5073. 运镜调度:固定镜头
  5074. 配音角色:徐母
  5075. 出镜角色:徐母
  5076. 台词内容:问我夜不归宿死哪儿去了。
  5077. 画面类型:对口型
  5078. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5079. ##第2幕:徐家简陋客厅 黄昏 室内
  5080. 分镜3
  5081. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5082. 场景:徐家简陋客厅
  5083. 构图设计:全景,景深虚化
  5084. 运镜调度:固定镜头
  5085. 配音角色:旁白
  5086. 出镜角色:无
  5087. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5088. 画面类型:普通画面
  5089. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5090. 分镜4
  5091. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5092. 场景:徐家简陋客厅
  5093. 构图设计:特写,火车票
  5094. 运镜调度:固定镜头
  5095. 配音角色:旁白
  5096. 出镜角色:无
  5097. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5098. 画面类型:普通画面
  5099. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5100. \n\n";
  5101. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5102. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  5103. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  5104. $prompt = $origin_prompt;
  5105. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  5106. // 获取章节内容
  5107. $full_content = getProp($anime, 'content');
  5108. if ($uploaded_content) {
  5109. $full_content = $uploaded_content;
  5110. }
  5111. // 根据章节内容拆分章节
  5112. $chapters = splitContent($full_content);
  5113. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  5114. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  5115. $messages = [];
  5116. if ($prompt == '确认分镜大纲') {
  5117. // 暂时保留
  5118. $content = $chapter_content;
  5119. if ($is_single) $content = $full_content; // 单剧集使用全文
  5120. if (!$content) {
  5121. Utils::throwError('20003:章节内容无法获取,请确认');
  5122. }
  5123. $question = $is_single
  5124. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  5125. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  5126. // 构建消息
  5127. $messages[] =
  5128. [
  5129. 'role' => 'user',
  5130. 'content' => $question
  5131. ];
  5132. }else if ($prompt == '继续策划下一集') {
  5133. if ($is_single) {
  5134. Utils::throwError('20003:单剧集不支持继续策划下一集');
  5135. }
  5136. $content = $chapter_content;
  5137. if (!$content) {
  5138. Utils::throwError('20003:章节内容无法获取,请确认');
  5139. }
  5140. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  5141. // 获取上一集最后记录
  5142. $prev_sequence = $episode_number - 1;
  5143. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  5144. // 构建消息
  5145. $messages[] =
  5146. [
  5147. 'role' => 'user',
  5148. 'content' => $question
  5149. ];
  5150. }else {
  5151. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  5152. if (!$content) {
  5153. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  5154. }
  5155. if (!$content) {
  5156. Utils::throwError('20003:章节内容无法获取,请确认');
  5157. }
  5158. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  5159. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  5160. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  5161. if ($origin_prompt) {
  5162. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  5163. }
  5164. $messages[] =
  5165. [
  5166. 'role' => 'user',
  5167. 'content' => $question
  5168. ];
  5169. }
  5170. // 处理文本模型
  5171. $model = getProp($data, 'model');
  5172. if (!$model) {
  5173. // 用户没有输入,从anime表获取
  5174. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5175. $model = getProp($anime, 'model');
  5176. if (!$model) {
  5177. // anime表也没有,使用默认值
  5178. $model = 'doubao-seed-2-0-mini-260215';
  5179. }
  5180. }
  5181. // 验证模型是否在可用模型表中
  5182. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5183. $model = 'doubao-seed-2-0-mini-260215';
  5184. }
  5185. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5186. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5187. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5188. if ($model === 'deepseek-chat') {
  5189. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5190. $model = 'deepseek-v4-flash';
  5191. $thinkingMode = 'disabled';
  5192. } elseif ($model === 'deepseek-reasoner') {
  5193. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5194. $model = 'deepseek-v4-flash';
  5195. $thinkingMode = 'enabled';
  5196. }
  5197. $post_data = [
  5198. 'model' => $model,
  5199. 'messages' => $messages,
  5200. // 'max_tokens' => 8192,
  5201. 'temperature' => 0.2,
  5202. 'frequency_penalty' => 0,
  5203. 'presence_penalty' => 0,
  5204. 'response_format' => ['type' => 'text'],
  5205. 'thinking' => ['type' => $thinkingMode],
  5206. 'stream' => true // 启用流式输出
  5207. ];
  5208. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5209. // 根据模型类型选择调用方法
  5210. $fullContent = '';
  5211. $fullReasoningContent = '';
  5212. $usage = [];
  5213. try {
  5214. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5215. // DeepSeek 官方模型使用 DeepSeek API
  5216. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5217. } else if (in_array($model, $this->gpt_text_models)) {
  5218. // GPT-5.4 模型使用 TokenRouter API
  5219. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5220. } else {
  5221. // 其他模型使用火山引擎API
  5222. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5223. }
  5224. // 验证返回值类型
  5225. if (!is_iterable($streamGenerator)) {
  5226. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5227. dLog('deepseek')->error('chat流式生成器无效', [
  5228. 'generator_type' => $errorType,
  5229. 'model' => $model,
  5230. 'anime_id' => $anime_id,
  5231. 'episode_number' => $episode_number
  5232. ]);
  5233. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  5234. 'type' => $errorType,
  5235. 'model' => $model
  5236. ]);
  5237. yield [
  5238. 'type' => 'error',
  5239. 'episode' => [],
  5240. 'answer' => '',
  5241. 'reasoning' => '',
  5242. 'usage' => [],
  5243. 'error' => '接口返回数据异常,请重新请求'
  5244. ];
  5245. return;
  5246. }
  5247. // 处理流式输出
  5248. foreach ($streamGenerator as $chunk) {
  5249. if (isset($chunk['type'])) {
  5250. if ($chunk['type'] === 'done') {
  5251. // 最终结果
  5252. $fullContent = $chunk['full_content'];
  5253. $fullReasoningContent = $chunk['full_reasoning'];
  5254. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5255. } else {
  5256. // 逐块yield数据
  5257. yield $chunk;
  5258. }
  5259. }
  5260. }
  5261. } catch (\Exception $e) {
  5262. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  5263. 'model' => $model,
  5264. 'anime_id' => $anime_id,
  5265. 'episode_number' => $episode_number,
  5266. 'trace' => $e->getTraceAsString()
  5267. ]);
  5268. logDB('deepseek', 'error', 'chat流式处理失败', [
  5269. 'error' => $e->getMessage(),
  5270. 'model' => $model
  5271. ]);
  5272. yield [
  5273. 'type' => 'error',
  5274. 'episode' => [],
  5275. 'answer' => '',
  5276. 'reasoning' => '',
  5277. 'usage' => [],
  5278. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5279. ];
  5280. return;
  5281. }
  5282. dLog('deepseek')->info('完整内容: '.$fullContent);
  5283. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5284. // 处理完整内容并返回最终结果
  5285. $episode_arr = handleEpisodeContent($fullContent);
  5286. logDB('deepseek', 'info', '解析内容', $episode_arr);
  5287. if (empty($episode_arr['acts'])) {
  5288. // 未生成剧本相关内容,保存对话记录并返回提示
  5289. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  5290. try {
  5291. $now = date('Y-m-d H:i:s');
  5292. // 保存对话记录
  5293. $records = [
  5294. [
  5295. 'uid' => $uid,
  5296. 'anime_id' => $anime_id,
  5297. 'sequence' => $episode_number,
  5298. 'role' => 'user',
  5299. 'content' => $prompt,
  5300. 'created_at' => $now,
  5301. 'updated_at' => $now
  5302. ],
  5303. [
  5304. 'uid' => $uid,
  5305. 'anime_id' => $anime_id,
  5306. 'sequence' => $episode_number,
  5307. 'role' => 'assistant',
  5308. 'content' => $fullContent,
  5309. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5310. 'created_at' => $now,
  5311. 'updated_at' => $now
  5312. ]
  5313. ];
  5314. DB::table('mp_anime_records')->insert($records);
  5315. } catch (\Exception $e) {
  5316. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5317. }
  5318. yield [
  5319. 'type' => 'done',
  5320. 'episode' => [],
  5321. 'answer' => $fullContent,
  5322. 'reasoning' => $fullReasoningContent,
  5323. 'usage' => $usage,
  5324. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  5325. ];
  5326. return;
  5327. }
  5328. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  5329. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  5330. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  5331. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  5332. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  5333. $existing_props = is_array($existing_props) ? $existing_props : [];
  5334. $now = date('Y-m-d H:i:s');
  5335. try {
  5336. DB::beginTransaction();
  5337. $saveResult = $this->saveEpisodeVersionData(
  5338. $anime_id,
  5339. $episode_number,
  5340. $episode_arr,
  5341. $existing_roles,
  5342. $existing_scenes,
  5343. $existing_props,
  5344. $current_episode,
  5345. $base_episode,
  5346. $is_regenerate_version,
  5347. $content,
  5348. $now
  5349. );
  5350. $episode = $saveResult['episode'];
  5351. $episode_id = $saveResult['episode_id'];
  5352. $merged_roles = $saveResult['merged_roles'];
  5353. $merged_scenes = $saveResult['merged_scenes'];
  5354. $merged_props = $saveResult['merged_props'];
  5355. $record_content = $origin_prompt;
  5356. if ($uploaded_content !== '') {
  5357. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  5358. }
  5359. $records = [
  5360. [
  5361. 'uid' => $uid,
  5362. 'anime_id' => $anime_id,
  5363. 'role' => 'user',
  5364. 'content' => $record_content,
  5365. 'sequence' => $episode_number,
  5366. 'episode_id' => $episode_id,
  5367. 'created_at' => $now,
  5368. 'updated_at' => $now
  5369. ],
  5370. [
  5371. 'uid' => $uid,
  5372. 'anime_id' => $anime_id,
  5373. 'role' => 'assistant',
  5374. 'content' => $fullContent,
  5375. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5376. 'sequence' => $episode_number,
  5377. 'episode_id' => $episode_id,
  5378. 'created_at' => $now,
  5379. 'updated_at' => $now
  5380. ]
  5381. ];
  5382. $boolen4 = DB::table('mp_anime_records')->insert($records);
  5383. if (!$boolen4) {
  5384. Utils::throwError('20003:对话记录保存失败');
  5385. }
  5386. // 保存模型和内容到anime表
  5387. $update_anime_data = [
  5388. 'model' => $model,
  5389. 'updated_at' => $now
  5390. ];
  5391. if ($uploaded_content) {
  5392. $update_anime_data['content'] = $uploaded_content;
  5393. }
  5394. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  5395. }catch (\Exception $e) {
  5396. DB::rollBack();
  5397. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5398. yield [
  5399. 'type' => 'done',
  5400. 'answer' => $fullContent,
  5401. 'reasoning' => $fullReasoningContent,
  5402. 'usage' => $usage,
  5403. 'error' => $e->getMessage(),
  5404. ];
  5405. return;
  5406. }
  5407. DB::commit();
  5408. if ($is_global_generate_pics) {
  5409. // // 批量生成全局角色图片
  5410. // $this->batchSetGlobalRoleImg([
  5411. // 'anime_id' => $anime_id,
  5412. // ], true);
  5413. // // 批量生成全局场景图片
  5414. // $this->batchSetGlobalSceneImg([
  5415. // 'anime_id' => $anime_id,
  5416. // ], true);
  5417. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5418. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5419. }
  5420. $episode['episode_id'] = $episode_id;
  5421. $episode['roles'] = $merged_roles;
  5422. $episode['scenes'] = $merged_scenes;
  5423. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  5424. yield [
  5425. 'type' => 'done',
  5426. 'episode' => $episode,
  5427. 'answer' => $fullContent,
  5428. 'reasoning' => $fullReasoningContent,
  5429. 'usage' => $usage
  5430. ];
  5431. }
  5432. public function addChatForAce($data) {
  5433. $uid = Site::getUid();
  5434. $anime_id = getProp($data, 'anime_id');
  5435. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5436. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5437. if (!$anime) Utils::throwError('20003:对话不存在');
  5438. $file = getProp($data, 'file');
  5439. $content = getProp($data, 'content', '');
  5440. $bid = getProp($data, 'bid', 0);
  5441. $script_id = getProp($data, 'script_id', 0);
  5442. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5443. $prompt = getProp($data, 'prompt');
  5444. $is_multi = getProp($anime, 'is_multi');
  5445. $is_single = (int)$is_multi !== 1;
  5446. // 积分余额预检(仅单剧集模式收费)
  5447. if ($is_single) {
  5448. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  5449. }
  5450. $extra_products = getProp($data, 'products', []);
  5451. if (!$extra_products) {
  5452. $extra_products = getProp($anime, 'extra_products');
  5453. if ($extra_products) {
  5454. $extra_products = json_decode($extra_products, true);
  5455. }else {
  5456. $extra_products = [];
  5457. }
  5458. }else {
  5459. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5460. }
  5461. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  5462. $anime_script_id = getProp($anime, 'script_id');
  5463. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  5464. $cpid = Site::getCpid();
  5465. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  5466. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  5467. ->where('mapping.script_id', $anime_script_id)
  5468. ->where('product.cpid', $cpid)
  5469. ->where('product.is_deleted', 0);
  5470. $mappings = $script_products_mappings->select(
  5471. 'mapping.product_id',
  5472. 'mapping.episode_number',
  5473. 'product.product_name',
  5474. 'product.type',
  5475. 'product.product',
  5476. 'product.pic_prompt',
  5477. 'product.url',
  5478. 'product.pic_task_id',
  5479. 'product.pic_task_status',
  5480. 'product.three_view_image_url'
  5481. )
  5482. ->get();
  5483. // 按 product_id 分组,合并 episode_number
  5484. $productMap = [];
  5485. foreach ($mappings as $item) {
  5486. $product_id = $item->product_id;
  5487. $product_name = $item->product_name;
  5488. // 处理product_name两边的符号
  5489. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5490. if (!isset($productMap[$product_id])) {
  5491. $productMap[$product_id] = [
  5492. 'product_id' => $product_id,
  5493. 'product_name' => $product_name,
  5494. 'type' => (int)$item->type,
  5495. 'product' => (int)$item->product,
  5496. 'pic_prompt' => $item->pic_prompt,
  5497. 'url' => $item->url,
  5498. 'pic_task_id' => $item->pic_task_id,
  5499. 'pic_task_status' => $item->pic_task_status,
  5500. 'episode_numbers' => [],
  5501. ];
  5502. }
  5503. // 添加 episode_number(去重)
  5504. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  5505. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  5506. }
  5507. }
  5508. // 将查询到的剧本资产合并到extra_products中
  5509. // 先构建extra_products的索引(以product_id为key,用于去重)
  5510. $extraProductsMap = [];
  5511. foreach ($extra_products as $item) {
  5512. $key = getProp($item, 'product_id');
  5513. if ($key) {
  5514. $extraProductsMap[$key] = $item;
  5515. }
  5516. }
  5517. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  5518. foreach ($productMap as $product) {
  5519. $product_id = $product['product_id'];
  5520. // 如果不存在则添加(不带episode_number信息)
  5521. if (!isset($extraProductsMap[$product_id])) {
  5522. $extraProductsMap[$product_id] = [
  5523. 'product_id' => $product['product_id'],
  5524. 'product_name' => $product['product_name'],
  5525. 'type' => $product['type'],
  5526. 'product' => $product['product'],
  5527. 'pic_prompt' => $product['pic_prompt'],
  5528. 'url' => $product['url'],
  5529. 'pic_task_id' => $product['pic_task_id'],
  5530. 'pic_task_status' => $product['pic_task_status'],
  5531. ];
  5532. }
  5533. }
  5534. // 重新赋值给extra_products
  5535. $extra_products = array_values($extraProductsMap);
  5536. }
  5537. $user_anime_name = getProp($anime, 'anime_name');
  5538. // 处理提示词
  5539. if ($prompt && $extra_products) {
  5540. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5541. foreach($extra_products as $item) {
  5542. $product_name = getProp($item, 'product_name');
  5543. if ($product_name) {
  5544. // 替换 {product_name} 为 product_name
  5545. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5546. }
  5547. }
  5548. }
  5549. // 处理文本模型
  5550. $model = getProp($data, 'model');
  5551. if (!$model) {
  5552. // 用户没有输入,从anime表获取
  5553. $model = getProp($anime, 'model');
  5554. if (!$model) {
  5555. // anime表也没有,使用默认值
  5556. $model = 'deepseek-v4-pro';
  5557. }
  5558. }
  5559. // 验证模型是否在可用模型表中
  5560. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5561. $model = 'deepseek-v4-pro';
  5562. }
  5563. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5564. if ($prompt) {
  5565. $question .= "本次修改要求如下:\n{$prompt}";
  5566. }
  5567. // if (!$file && !$content && !$bid) {
  5568. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5569. // }
  5570. // 提取文件内容
  5571. if ($file) {
  5572. $content = $this->extractFileContent($file);
  5573. if (!$content) {
  5574. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5575. }
  5576. } elseif ($script_id) {
  5577. $content = $this->getContentByScriptId($script_id);
  5578. if (!$content) {
  5579. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5580. }
  5581. } elseif ($bid) {
  5582. $content = $this->getContentByBid($bid);
  5583. if (!$content) {
  5584. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5585. }
  5586. } elseif ($content) {
  5587. $content = filterContent($content);
  5588. } else {
  5589. $content = getProp($anime, 'content');
  5590. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5591. $need_generate_content = true;
  5592. }
  5593. }
  5594. // 美术风格
  5595. $input_art_style = getProp($data, 'art_style');
  5596. if (!$input_art_style) {
  5597. $mappedArtStyle = getProp($anime, 'art_style');
  5598. }else {
  5599. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5600. }
  5601. // 判断是否需要生成原文内容
  5602. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5603. // 如果需要生成原文内容,添加额外的要求
  5604. $content_generation_requirement = $need_generate_content
  5605. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5606. : "";
  5607. // 美术风格
  5608. if (!$mappedArtStyle) {
  5609. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5610. }else {
  5611. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5612. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5613. }else {
  5614. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5615. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5616. }
  5617. }
  5618. // 构建主体、场景和道具提示词
  5619. $extra_role_prompt = "\n";
  5620. $extra_scene_prompt = "\n";
  5621. $extra_prop_prompt = "\n";
  5622. $ref_products = []; // 参考资产
  5623. if ($extra_products) {
  5624. foreach($extra_products as $item) {
  5625. $product = getProp($item, 'product');
  5626. $product_name = getProp($item, 'product_name');
  5627. if ($product_name == '旁白') continue;
  5628. $ref_products[$product_name] = $item;
  5629. $pic_prompt = getProp($item, 'pic_prompt');
  5630. if ((int)$product === 1) {
  5631. // 拼接角色信息
  5632. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5633. } elseif ((int)$product === 2) {
  5634. // 拼接场景信息
  5635. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5636. } elseif ((int)$product === 3) {
  5637. // 拼接道具信息
  5638. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5639. }
  5640. }
  5641. // 优化提示词,融入剧本
  5642. if (!empty(trim($extra_role_prompt))) {
  5643. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  5644. }
  5645. if (!empty(trim($extra_scene_prompt))) {
  5646. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  5647. }
  5648. if (!empty(trim($extra_prop_prompt))) {
  5649. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  5650. }
  5651. }
  5652. if ($anime_script_id && $is_single) {
  5653. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  5654. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  5655. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  5656. }else {
  5657. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5658. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5659. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5660. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5661. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5662. {$extra_role_prompt}";
  5663. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5664. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5665. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5666. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5667. {$extra_scene_prompt}";
  5668. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5669. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5670. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5671. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5672. {$extra_prop_prompt}";
  5673. }
  5674. $systemPrompt = $is_single
  5675. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5676. 强制要求:
  5677. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5678. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5679. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5680. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5681. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5682. 普通要求:
  5683. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5684. $role_demo
  5685. $scene_demo
  5686. $prop_demo
  5687. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  5688. 5.1片段分割逻辑(优先级从高到低):
  5689. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  5690. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  5691. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  5692. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  5693. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  5694. - 片段数量格式为: 片段数量:8
  5695. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5696. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  5697. 5.3分镜结构:每个分镜包含以下字段:
  5698. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  5699. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5700. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5701. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5702. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  5703. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5704. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5705. - 运镜:场景+画面描述+运镜
  5706. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  5707. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  5708. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  5709. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  5710. 6.{$mappedArtStyle_prompt}\n\n
  5711. 示例如下:\n
  5712. ###剧本名:西昆仑
  5713. ###故事梗概
  5714. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5715. ###剧本亮点
  5716. 亮点1:绝境奇药,生死一线
  5717. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5718. 亮点2:结拜兄妹,化解尴尬
  5719. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5720. 亮点3:纤发夺命,情愫暗涌
  5721. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5722. ###人物关系
  5723. 阿雪与梁萧之间存在兄妹之情。
  5724. ###核心矛盾
  5725. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5726. ###主体列表
  5727. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5728. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5729. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5730. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5731. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5732. 全景,正面拍摄,青年女性,亚洲人。
  5733. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5734. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5735. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5736. ###美术风格
  5737. 基础画风风格词:厚涂古风
  5738. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5739. ###场景列表
  5740. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5741. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5742. 无人物。}
  5743. ###分段剧本
  5744. 片段数量:8
  5745. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  5746. ##片段1
  5747. 时长:12s
  5748. 分镜1
  5749. 出场角色:刀疤脸
  5750. 场景:边境小镇街道
  5751. 出场道具:酒杯-高脚杯
  5752. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  5753. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  5754. 配音台词:
  5755. 背景音效:
  5756. 分镜2
  5757. 出场角色:刀疤脸
  5758. 场景:悦来酒馆
  5759. 出场道具:酒杯-高脚杯
  5760. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  5761. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  5762. 配音台词:
  5763. 背景音效:
  5764. 分镜3
  5765. 出场角色:刀疤脸
  5766. 场景:悦来酒馆
  5767. 出场道具:酒杯-高脚杯
  5768. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  5769. 运镜:从中景推向令牌特写。
  5770. 配音台词:
  5771. 背景音效:
  5772. 分镜4
  5773. 出场角色:刀疤脸
  5774. 场景:悦来酒馆
  5775. 出场道具:酒杯-高脚杯
  5776. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  5777. 运镜:极速推向酒水溅起的瞬间。
  5778. 配音台词:
  5779. 背景音效:
  5780. 分镜5
  5781. 出场角色:刀疤脸
  5782. 场景:悦来酒馆
  5783. 出场道具:酒杯-高脚杯
  5784. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  5785. 运镜:固定机位,利用倾斜构图制造压迫感。
  5786. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  5787. 背景音效:
  5788. \n\n"
  5789. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5790. 强制要求:\n
  5791. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5792. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5793. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5794. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5795. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5796. 普通要求:\n
  5797. 1.剧本名(必须生成)必须与文档内容高度相关
  5798. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5799. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5800. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5801. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5802. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5803. {$extra_role_prompt}
  5804. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5805. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5806. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5807. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5808. {$extra_scene_prompt}
  5809. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5810. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5811. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5812. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5813. {$extra_prop_prompt}
  5814. 5.{$mappedArtStyle_prompt}\n\n
  5815. 示例如下:\n
  5816. ###剧本名:西昆仑
  5817. ###故事梗概
  5818. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5819. ###剧本亮点
  5820. 亮点1:绝境奇药,生死一线
  5821. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5822. 亮点2:结拜兄妹,化解尴尬
  5823. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5824. 亮点3:纤发夺命,情愫暗涌
  5825. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5826. ###人物关系
  5827. 阿雪与梁萧之间存在兄妹之情。
  5828. ###核心矛盾
  5829. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5830. ###主体列表
  5831. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5832. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5833. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5834. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5835. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5836. 全景,正面拍摄,青年女性,亚洲人。
  5837. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5838. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5839. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5840. ###美术风格
  5841. 基础画风风格词:厚涂古风
  5842. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5843. ###场景列表
  5844. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5845. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5846. 无人物。}
  5847. ###道具列表
  5848. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  5849. // 构建消息
  5850. $messages = [
  5851. [
  5852. 'role' => 'system',
  5853. 'content' => $systemPrompt
  5854. ],
  5855. [
  5856. 'role' => 'user',
  5857. 'content' => "以下是文档内容:
  5858. {$content}
  5859. 用户问题:
  5860. {$question}"
  5861. ]
  5862. ];
  5863. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5864. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5865. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5866. if ($model === 'deepseek-chat') {
  5867. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5868. $model = 'deepseek-v4-flash';
  5869. $thinkingMode = 'disabled';
  5870. } elseif ($model === 'deepseek-reasoner') {
  5871. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5872. $model = 'deepseek-v4-flash';
  5873. $thinkingMode = 'enabled';
  5874. }
  5875. $post_data = [
  5876. 'model' => $model,
  5877. 'messages' => $messages,
  5878. // 'max_tokens' => 8192,
  5879. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  5880. 'frequency_penalty' => 0,
  5881. 'presence_penalty' => 0,
  5882. 'response_format' => ['type' => 'text'],
  5883. 'thinking' => ['type'=>$thinkingMode],
  5884. 'stream' => true // 启用流式输出
  5885. ];
  5886. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5887. // 根据模型类型选择调用方法
  5888. $fullContent = '';
  5889. $fullReasoningContent = '';
  5890. $usage = [];
  5891. try {
  5892. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5893. // DeepSeek 官方模型使用 DeepSeek API
  5894. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5895. } else if (in_array($model, $this->gpt_text_models)) {
  5896. // GPT-5.4 模型使用 TokenRouter API
  5897. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5898. } else {
  5899. // 其他模型使用火山引擎API
  5900. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5901. }
  5902. // 验证返回值类型
  5903. if (!is_iterable($streamGenerator)) {
  5904. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5905. dLog('deepseek')->error('addChat流式生成器无效', [
  5906. 'generator_type' => $errorType,
  5907. 'model' => $model,
  5908. 'anime_id' => $anime_id
  5909. ]);
  5910. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5911. 'type' => $errorType,
  5912. 'model' => $model
  5913. ]);
  5914. yield [
  5915. 'type' => 'error',
  5916. 'script' => [],
  5917. 'episode' => [],
  5918. 'answer' => '',
  5919. 'reasoning' => '',
  5920. 'usage' => [],
  5921. 'error' => '接口返回数据异常,请重新请求'
  5922. ];
  5923. return;
  5924. }
  5925. // 处理流式输出
  5926. foreach ($streamGenerator as $chunk) {
  5927. if (isset($chunk['type'])) {
  5928. if ($chunk['type'] === 'done') {
  5929. // 最终结果
  5930. $fullContent = $chunk['full_content'];
  5931. $fullReasoningContent = $chunk['full_reasoning'];
  5932. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5933. } else {
  5934. // 逐块yield数据
  5935. yield $chunk;
  5936. }
  5937. }
  5938. }
  5939. } catch (\Exception $e) {
  5940. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5941. 'model' => $model,
  5942. 'anime_id' => $anime_id,
  5943. 'trace' => $e->getTraceAsString()
  5944. ]);
  5945. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5946. 'error' => $e->getMessage(),
  5947. 'model' => $model
  5948. ]);
  5949. yield [
  5950. 'type' => 'error',
  5951. 'script' => [],
  5952. 'episode' => [],
  5953. 'answer' => '',
  5954. 'reasoning' => '',
  5955. 'usage' => [],
  5956. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5957. ];
  5958. return;
  5959. }
  5960. dLog('deepseek')->info('完整内容: '.$fullContent);
  5961. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5962. // 处理完整内容并返回最终结果
  5963. $script_arr = [];
  5964. if ($fullContent) {
  5965. $script_arr = handleScriptContentForAce($fullContent);
  5966. dLog('deepseek')->info('解析内容', $script_arr);
  5967. logDB('deepseek', 'info', '解析内容', $script_arr);
  5968. }
  5969. if (empty($script_arr['roles'])) {
  5970. // 未生成剧本相关内容,保存对话记录并返回提示
  5971. dLog('deepseek')->info('未生成剧本相关的内容');
  5972. try {
  5973. DB::beginTransaction();
  5974. $now = date('Y-m-d H:i:s');
  5975. // 保存对话记录
  5976. $records = [
  5977. [
  5978. 'uid' => $uid,
  5979. 'anime_id' => $anime_id,
  5980. 'sequence' => 0,
  5981. 'role' => 'user',
  5982. 'content' => $prompt,
  5983. 'created_at' => $now,
  5984. 'updated_at' => $now
  5985. ],
  5986. [
  5987. 'uid' => $uid,
  5988. 'anime_id' => $anime_id,
  5989. 'sequence' => 0,
  5990. 'role' => 'assistant',
  5991. // 'content' => $fullContent,
  5992. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5993. 'created_at' => $now,
  5994. 'updated_at' => $now
  5995. ]
  5996. ];
  5997. DB::table('mp_anime_records')->insert($records);
  5998. DB::commit();
  5999. } catch (\Exception $e) {
  6000. DB::rollBack();
  6001. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6002. }
  6003. yield [
  6004. 'type' => 'done',
  6005. 'script' => [],
  6006. 'episode' => [],
  6007. 'answer' => $fullContent,
  6008. 'reasoning' => $fullReasoningContent,
  6009. 'usage' => $usage,
  6010. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6011. ];
  6012. return;
  6013. }
  6014. // 如果需要生成原文内容,从script_arr中提取
  6015. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6016. $content = $script_arr['content'];
  6017. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  6018. if (!$content) {
  6019. yield [
  6020. 'type' => 'done',
  6021. 'script' => [],
  6022. 'episode' => [],
  6023. 'answer' => $fullContent,
  6024. 'reasoning' => $fullReasoningContent,
  6025. 'usage' => $usage,
  6026. 'error' => '未生成剧本内容,请调整提示词再试'
  6027. ];
  6028. return;
  6029. }
  6030. }
  6031. // 替换美术风格
  6032. if ($mappedArtStyle !== '') {
  6033. $script_arr['art_style'] = $mappedArtStyle;
  6034. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6035. }
  6036. // 新建动漫
  6037. if ($user_anime_name == '新剧本策划') {
  6038. $anime_name = getProp($script_arr, 'script_name');
  6039. // if (!$anime_name) {
  6040. // // 未识别到剧本名,保存对话记录并返回提示
  6041. // dLog('deepseek')->info('未能识别到剧本名称');
  6042. // try {
  6043. // DB::beginTransaction();
  6044. // $now = date('Y-m-d H:i:s');
  6045. // // 保存对话记录
  6046. // $records = [
  6047. // [
  6048. // 'uid' => $uid,
  6049. // 'anime_id' => $anime_id,
  6050. // 'sequence' => 0,
  6051. // 'role' => 'user',
  6052. // 'content' => $prompt,
  6053. // 'created_at' => $now,
  6054. // 'updated_at' => $now
  6055. // ],
  6056. // [
  6057. // 'uid' => $uid,
  6058. // 'anime_id' => $anime_id,
  6059. // 'sequence' => 0,
  6060. // 'role' => 'assistant',
  6061. // 'content' => '未能生成剧本名称,请重试',
  6062. // 'created_at' => $now,
  6063. // 'updated_at' => $now
  6064. // ]
  6065. // ];
  6066. // DB::table('mp_anime_records')->insert($records);
  6067. // DB::commit();
  6068. // } catch (\Exception $e) {
  6069. // DB::rollBack();
  6070. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6071. // }
  6072. // yield [
  6073. // 'type' => 'done',
  6074. // 'script' => [],
  6075. // 'episode' => [],
  6076. // 'answer' => $fullContent,
  6077. // 'reasoning' => $fullReasoningContent,
  6078. // 'usage' => $usage,
  6079. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6080. // ];
  6081. // return;
  6082. // }
  6083. // 确认对话名称唯一性
  6084. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6085. $anime_name = $anime_name . '_' . date('YmdHis');
  6086. }
  6087. }else {
  6088. $anime_name = $user_anime_name;
  6089. }
  6090. $table_data = [
  6091. 'user_id' => $uid,
  6092. 'anime_name' => $anime_name,
  6093. 'model' => $model,
  6094. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6095. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6096. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6097. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6098. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6099. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6100. 'art_style_type' => $input_art_style,
  6101. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6102. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6103. 'status' => '解析完成',
  6104. 'content' => $content,
  6105. 'is_multi' => $is_multi,
  6106. 'ace_mode' => $ace_mode,
  6107. 'generate_status' => '待执行',
  6108. 'updated_at' => date('Y-m-d H:i:s')
  6109. ];
  6110. if ($table_data['content']) {
  6111. $chapters = splitContent($table_data['content']);
  6112. $chapter_count = count($chapters);
  6113. if ($chapter_count > 0) {
  6114. $table_data['start_episode_sequence'] = 1;
  6115. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6116. }
  6117. }
  6118. if ($extra_products) {
  6119. $table_data['extra_products'] = json_encode($extra_products, 256);
  6120. }
  6121. // 如果有剧本ID则进行绑定
  6122. if ($script_id) {
  6123. $table_data['script_id'] = $script_id;
  6124. }
  6125. $single_episode = [];
  6126. try {
  6127. DB::beginTransaction();
  6128. $now = date('Y-m-d H:i:s');
  6129. // 更新动漫大纲
  6130. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6131. if (!$boolen) {
  6132. dLog('deepseek')->info('动漫保存失败', $table_data);
  6133. Utils::throwError('20003:动漫保存失败');
  6134. }
  6135. // 保存对话记录
  6136. $records = [
  6137. [
  6138. 'uid' => $uid,
  6139. 'anime_id' => $anime_id,
  6140. 'sequence' => 0,
  6141. 'role' => 'user',
  6142. 'content' => $prompt,
  6143. 'created_at' => date('Y-m-d H:i:s'),
  6144. 'updated_at' => date('Y-m-d H:i:s')
  6145. ],
  6146. [
  6147. 'uid' => $uid,
  6148. 'anime_id' => $anime_id,
  6149. 'sequence' => 0,
  6150. 'role' => 'assistant',
  6151. 'content' => $fullContent,
  6152. 'created_at' => date('Y-m-d H:i:s'),
  6153. 'updated_at' => date('Y-m-d H:i:s')
  6154. ]
  6155. ];
  6156. // 保存对话记录
  6157. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6158. if (!$boolen3) {
  6159. Utils::throwError('20003:对话记录保存失败');
  6160. }
  6161. if ($is_single) {
  6162. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6163. if (empty($episode_arr['acts'])) {
  6164. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6165. }
  6166. $saveResult = $this->saveEpisodeVersionData(
  6167. $anime_id,
  6168. 1,
  6169. $episode_arr,
  6170. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6171. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6172. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6173. null,
  6174. null,
  6175. false,
  6176. $content,
  6177. $now,
  6178. $ref_products
  6179. );
  6180. $single_episode = $saveResult['episode'];
  6181. $episode_id = $saveResult['episode_id'];
  6182. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6183. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6184. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6185. 'props' => json_encode($saveResult['merged_props'], 256),
  6186. 'updated_at' => $now
  6187. ]);
  6188. if ($boolen5 === false) {
  6189. Utils::throwError('20003:单剧集主表资源同步失败');
  6190. }
  6191. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6192. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6193. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6194. $episode_record_content = '确认分镜大纲';
  6195. if ($content !== '') {
  6196. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6197. }
  6198. $episode_records = [
  6199. [
  6200. 'uid' => $uid,
  6201. 'anime_id' => $anime_id,
  6202. 'role' => 'user',
  6203. 'content' => $episode_record_content,
  6204. 'sequence' => 1,
  6205. 'episode_id' => $episode_id,
  6206. 'created_at' => $now,
  6207. 'updated_at' => $now
  6208. ],
  6209. [
  6210. 'uid' => $uid,
  6211. 'anime_id' => $anime_id,
  6212. 'role' => 'assistant',
  6213. 'content' => $fullContent,
  6214. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6215. 'sequence' => 1,
  6216. 'episode_id' => $episode_id,
  6217. 'created_at' => $now,
  6218. 'updated_at' => $now
  6219. ]
  6220. ];
  6221. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6222. if (!$boolen4) {
  6223. Utils::throwError('20003:单剧集分镜记录保存失败');
  6224. }
  6225. }
  6226. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6227. if ($is_single && !empty($single_episode)) {
  6228. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6229. 'anime_id' => $anime_id,
  6230. 'episode_id' => $episode_id ?? 0,
  6231. ]);
  6232. }
  6233. }catch (\Exception $e) {
  6234. DB::rollBack();
  6235. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6236. yield [
  6237. 'type' => 'done',
  6238. 'answer' => $fullContent,
  6239. 'reasoning' => $fullReasoningContent,
  6240. 'usage' => $usage,
  6241. 'error' => $e->getMessage(),
  6242. ];
  6243. return;
  6244. }
  6245. DB::commit();
  6246. dLog('deepseek')->info('保存完毕');
  6247. if ($is_single && !empty($single_episode)) {
  6248. // $this->batchSetGlobalRoleImg([
  6249. // 'anime_id' => $anime_id,
  6250. // ]);
  6251. // $this->batchSetGlobalSceneImg([
  6252. // 'anime_id' => $anime_id,
  6253. // ]);
  6254. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6255. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6256. }
  6257. $table_data['anime_id'] = $anime_id;
  6258. $table_data['roles'] = json_decode($table_data['roles'], true);
  6259. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6260. // $table_data['episodes'] = $script_arr['episodes'];
  6261. unset($table_data['created_at']);
  6262. unset($table_data['updated_at']);
  6263. unset($table_data['status']);
  6264. dLog('deepseek')->info('开始返回');
  6265. yield [
  6266. 'type' => 'done',
  6267. 'script' => $table_data,
  6268. 'episode' => $single_episode,
  6269. 'answer' => $fullContent,
  6270. 'reasoning' => $fullReasoningContent,
  6271. 'usage' => $usage
  6272. ];
  6273. }
  6274. public function reGenerateAnimeForAce($data) {
  6275. $uid = Site::getUid();
  6276. $file = getProp($data, 'file');
  6277. $content = getProp($data, 'content', '');
  6278. $bid = getProp($data, 'bid', 0);
  6279. $script_id = getProp($data, 'script_id', 0);
  6280. $anime_id = getProp($data, 'anime_id');
  6281. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6282. if (!$anime) {
  6283. Utils::throwError('20003:该对话不存在');
  6284. }
  6285. $is_multi = getProp($anime, 'is_multi', 1);
  6286. $is_single = (int)$is_multi !== 1;
  6287. // 积分余额预检(仅单剧集模式收费)
  6288. if ($is_single) {
  6289. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  6290. }
  6291. $extra_products = getProp($data, 'products', []);
  6292. if (!$extra_products) {
  6293. $extra_products = getProp($anime, 'extra_products');
  6294. if ($extra_products) {
  6295. $extra_products = json_decode($extra_products, true);
  6296. }else {
  6297. $extra_products = [];
  6298. }
  6299. }else {
  6300. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6301. }
  6302. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6303. $anime_script_id = getProp($anime, 'script_id');
  6304. if ($anime_script_id && $is_single) {
  6305. $cpid = Site::getCpid();
  6306. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6307. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6308. ->where('mapping.script_id', $anime_script_id)
  6309. ->where('product.cpid', $cpid)
  6310. ->where('product.is_deleted', 0);
  6311. $mappings = $script_products_mappings->select(
  6312. 'mapping.product_id',
  6313. 'mapping.episode_number',
  6314. 'product.product_name',
  6315. 'product.type',
  6316. 'product.product',
  6317. 'product.pic_prompt',
  6318. 'product.url',
  6319. 'product.pic_task_id',
  6320. 'product.pic_task_status',
  6321. 'product.three_view_image_url'
  6322. )
  6323. ->get();
  6324. // 按 product_id 分组,合并 episode_number
  6325. $productMap = [];
  6326. foreach ($mappings as $item) {
  6327. $product_id = $item->product_id;
  6328. $product_name = $item->product_name;
  6329. // 处理product_name两边的符号
  6330. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6331. if (!isset($productMap[$product_id])) {
  6332. $productMap[$product_id] = [
  6333. 'product_id' => $product_id,
  6334. 'product_name' => $product_name,
  6335. 'type' => (int)$item->type,
  6336. 'product' => (int)$item->product,
  6337. 'pic_prompt' => $item->pic_prompt,
  6338. 'url' => $item->url,
  6339. 'pic_task_id' => $item->pic_task_id,
  6340. 'pic_task_status' => $item->pic_task_status,
  6341. 'episode_numbers' => [],
  6342. ];
  6343. }
  6344. // 添加 episode_number(去重)
  6345. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6346. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6347. }
  6348. }
  6349. // 将查询到的剧本资产合并到extra_products中
  6350. // 先构建extra_products的索引(以product_id为key,用于去重)
  6351. $extraProductsMap = [];
  6352. foreach ($extra_products as $item) {
  6353. $key = getProp($item, 'product_id');
  6354. if ($key) {
  6355. $extraProductsMap[$key] = $item;
  6356. }
  6357. }
  6358. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6359. foreach ($productMap as $product) {
  6360. $product_id = $product['product_id'];
  6361. // 如果不存在则添加(不带episode_number信息)
  6362. if (!isset($extraProductsMap[$product_id])) {
  6363. $extraProductsMap[$product_id] = [
  6364. 'product_id' => $product['product_id'],
  6365. 'product_name' => $product['product_name'],
  6366. 'type' => $product['type'],
  6367. 'product' => $product['product'],
  6368. 'pic_prompt' => $product['pic_prompt'],
  6369. 'url' => $product['url'],
  6370. 'pic_task_id' => $product['pic_task_id'],
  6371. 'pic_task_status' => $product['pic_task_status'],
  6372. ];
  6373. }
  6374. }
  6375. // 重新赋值给extra_products
  6376. $extra_products = array_values($extraProductsMap);
  6377. }
  6378. $user_anime_name = getProp($anime, 'anime_name');
  6379. $prompt = getProp($data, 'prompt');
  6380. // 处理提示词
  6381. if ($prompt && $extra_products) {
  6382. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6383. foreach($extra_products as $item) {
  6384. $product_name = getProp($item, 'product_name');
  6385. if ($product_name) {
  6386. // 替换 {product_name} 为 product_name
  6387. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6388. }
  6389. }
  6390. }
  6391. // 处理文本模型
  6392. $model = getProp($data, 'model');
  6393. if (!$model) {
  6394. // 用户没有输入,从anime表获取
  6395. $model = getProp($anime, 'model');
  6396. if (!$model) {
  6397. // anime表也没有,使用默认值
  6398. $model = 'deepseek-v4-pro';
  6399. }
  6400. }
  6401. // 验证模型是否在可用模型表中
  6402. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6403. $model = 'deepseek-v4-pro';
  6404. }
  6405. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  6406. if ($is_single) {
  6407. $episode_exists = DB::table('mp_anime_episodes')
  6408. ->where('anime_id', $anime_id)
  6409. ->where('sequence', 1)
  6410. ->exists();
  6411. if ($episode_exists) {
  6412. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  6413. }
  6414. }
  6415. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6416. if ($prompt) {
  6417. $question .= "本次修改要求如下:\n{$prompt}";
  6418. }
  6419. // 提取文件内容
  6420. if ($file) {
  6421. $content = $this->extractFileContent($file);
  6422. if (!$content) {
  6423. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6424. }
  6425. } elseif ($script_id) {
  6426. $content = $this->getContentByScriptId($script_id);
  6427. if (!$content) {
  6428. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6429. }
  6430. } elseif ($bid) {
  6431. $content = $this->getContentByBid($bid);
  6432. if (!$content) {
  6433. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6434. }
  6435. } elseif ($content) {
  6436. $content = filterContent($content);
  6437. }else {
  6438. $content = filterContent(getProp($anime, 'content'));
  6439. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6440. $need_generate_content = true;
  6441. }
  6442. }
  6443. // 判断是否需要生成原文内容
  6444. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6445. // 如果需要生成原文内容,添加额外的要求
  6446. $content_generation_requirement = $need_generate_content
  6447. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6448. : "";
  6449. // 美术风格
  6450. $input_art_style = getProp($data, 'art_style');
  6451. if (!$input_art_style) {
  6452. $mappedArtStyle = getProp($anime, 'art_style');
  6453. }else {
  6454. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6455. }
  6456. if (!$mappedArtStyle) {
  6457. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6458. }else {
  6459. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6460. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6461. }else {
  6462. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6463. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6464. }
  6465. }
  6466. // 构建主体、场景和道具提示词
  6467. $extra_role_prompt = "\n";
  6468. $extra_scene_prompt = "\n";
  6469. $extra_prop_prompt = "\n";
  6470. $ref_products = []; // 参考资产
  6471. if ($extra_products) {
  6472. foreach($extra_products as $item) {
  6473. $product = getProp($item, 'product');
  6474. $product_name = getProp($item, 'product_name');
  6475. if ($product_name == '旁白') continue;
  6476. $ref_products[$product_name] = $item;
  6477. $pic_prompt = getProp($item, 'pic_prompt');
  6478. if ((int)$product === 1) {
  6479. // 拼接角色信息
  6480. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6481. } elseif ((int)$product === 2) {
  6482. // 拼接场景信息
  6483. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6484. } elseif ((int)$product === 3) {
  6485. // 拼接道具信息
  6486. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6487. }
  6488. }
  6489. // 优化提示词,融入剧本
  6490. if (!empty(trim($extra_role_prompt))) {
  6491. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6492. }
  6493. if (!empty(trim($extra_scene_prompt))) {
  6494. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6495. }
  6496. if (!empty(trim($extra_prop_prompt))) {
  6497. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6498. }
  6499. }
  6500. if ($anime_script_id && $is_single) {
  6501. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6502. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6503. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6504. }else {
  6505. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6506. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6507. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6508. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6509. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6510. {$extra_role_prompt}";
  6511. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6512. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6513. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6514. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6515. {$extra_scene_prompt}";
  6516. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6517. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6518. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6519. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6520. {$extra_prop_prompt}";
  6521. }
  6522. $system_message = ['role'=>'system', 'content'=>$is_single
  6523. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6524. 强制要求:
  6525. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6526. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6527. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6528. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6529. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6530. 普通要求:
  6531. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6532. $role_demo
  6533. $scene_demo
  6534. $prop_demo
  6535. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6536. 5.1片段分割逻辑(优先级从高到低):
  6537. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6538. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6539. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6540. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6541. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6542. - 片段数量格式为: 片段数量:8
  6543. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6544. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6545. 5.3分镜结构:每个分镜包含以下字段:
  6546. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6547. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6548. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6549. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6550. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6551. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6552. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6553. - 运镜:场景+画面描述+运镜
  6554. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6555. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6556. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6557. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6558. 6.{$mappedArtStyle_prompt}\n\n
  6559. 示例如下:\n
  6560. ###剧本名:西昆仑
  6561. ###故事梗概
  6562. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6563. ###剧本亮点
  6564. 亮点1:绝境奇药,生死一线
  6565. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6566. 亮点2:结拜兄妹,化解尴尬
  6567. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6568. 亮点3:纤发夺命,情愫暗涌
  6569. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6570. ###人物关系
  6571. 阿雪与梁萧之间存在兄妹之情。
  6572. ###核心矛盾
  6573. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6574. ###主体列表
  6575. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6576. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6577. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6578. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6579. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6580. 全景,正面拍摄,青年女性,亚洲人。
  6581. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6582. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6583. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6584. ###美术风格
  6585. 基础画风风格词:厚涂古风
  6586. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6587. ###场景列表
  6588. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6589. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6590. 无人物。}
  6591. ###分段剧本
  6592. 片段数量:8
  6593. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6594. ##片段1
  6595. 时长:12s
  6596. 分镜1
  6597. 出场角色:刀疤脸
  6598. 场景:边境小镇街道
  6599. 出场道具:酒杯-高脚杯
  6600. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6601. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6602. 配音台词:
  6603. 背景音效:
  6604. 分镜2
  6605. 出场角色:刀疤脸
  6606. 场景:悦来酒馆
  6607. 出场道具:酒杯-高脚杯
  6608. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6609. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6610. 配音台词:
  6611. 背景音效:
  6612. 分镜3
  6613. 出场角色:刀疤脸
  6614. 场景:悦来酒馆
  6615. 出场道具:酒杯-高脚杯
  6616. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6617. 运镜:从中景推向令牌特写。
  6618. 配音台词:
  6619. 背景音效:
  6620. 分镜4
  6621. 出场角色:刀疤脸
  6622. 场景:悦来酒馆
  6623. 出场道具:酒杯-高脚杯
  6624. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6625. 运镜:极速推向酒水溅起的瞬间。
  6626. 配音台词:
  6627. 背景音效:
  6628. 分镜5
  6629. 出场角色:刀疤脸
  6630. 场景:悦来酒馆
  6631. 出场道具:酒杯-高脚杯
  6632. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6633. 运镜:固定机位,利用倾斜构图制造压迫感。
  6634. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6635. 背景音效:
  6636. \n\n"
  6637. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6638. 强制要求:\n
  6639. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6640. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6641. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6642. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6643. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6644. 普通要求:\n
  6645. 1.剧本名(必须生成)必须与文档内容高度相关
  6646. $role_demo
  6647. $scene_demo
  6648. $prop_demo
  6649. 5.{$mappedArtStyle_prompt}\n\n
  6650. 示例如下:\n
  6651. ###剧本名:西昆仑
  6652. ###故事梗概
  6653. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6654. ###剧本亮点
  6655. 亮点1:绝境奇药,生死一线
  6656. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6657. 亮点2:结拜兄妹,化解尴尬
  6658. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6659. 亮点3:纤发夺命,情愫暗涌
  6660. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6661. ###人物关系
  6662. 阿雪与梁萧之间存在兄妹之情。
  6663. ###核心矛盾
  6664. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6665. ###主体列表
  6666. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6667. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6668. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6669. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6670. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6671. 全景,正面拍摄,青年女性,亚洲人。
  6672. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6673. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6674. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6675. ###美术风格
  6676. 基础画风风格词:厚涂古风
  6677. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6678. ###场景列表
  6679. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6680. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6681. 无人物。}
  6682. ###道具列表
  6683. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  6684. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6685. $episode_count = $this->extractEpisodeNumber($prompt);
  6686. if ((int)getProp($anime, 'is_multi') !== 1) {
  6687. yield [
  6688. 'type' => 'done',
  6689. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6690. 'reasoning' => '',
  6691. 'usage' => []
  6692. ];
  6693. return;
  6694. }
  6695. if ($episode_count) {
  6696. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6697. $system_message = [
  6698. 'role' => 'system',
  6699. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6700. 强制要求:\n
  6701. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6702. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6703. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6704. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6705. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6706. 普通要求:\n
  6707. 1.<故事梗概>控制在200-300字左右
  6708. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6709. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6710. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6711. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6712. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6713. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6714. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6715. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6716. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6717. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6718. 示例如下:\n
  6719. ###剧本名:西昆仑
  6720. ###故事梗概
  6721. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6722. ###剧本亮点
  6723. 亮点1:绝境奇药,生死一线
  6724. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6725. 亮点2:结拜兄妹,化解尴尬
  6726. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6727. 亮点3:纤发夺命,情愫暗涌
  6728. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6729. ###人物关系
  6730. 阿雪与梁萧之间存在兄妹之情。
  6731. ###核心矛盾
  6732. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6733. ###主体列表
  6734. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6735. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6736. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6737. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6738. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6739. 全景,正面拍摄,青年女性,亚洲人。
  6740. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6741. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6742. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6743. ###美术风格
  6744. 基础画风风格词:厚涂古风
  6745. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6746. ###场景列表
  6747. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6748. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6749. 无人物。}
  6750. ###分集详细内容
  6751. ##第1章 重生
  6752. 我重生了。
  6753. 源于一个男人偏执的暗恋。
  6754. ##第2章 相救
  6755. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6756. 我眼睛扫向站在锅炉后的卞大伟。"
  6757. ];
  6758. // 构建消息
  6759. $messages = [
  6760. $system_message,
  6761. [
  6762. 'role' => 'user',
  6763. 'content' => "以下是文档内容:
  6764. {$content}
  6765. 用户问题:
  6766. {$question}"
  6767. ]
  6768. ];
  6769. }else {
  6770. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6771. // 构建消息
  6772. $messages = [
  6773. $system_message,
  6774. [
  6775. 'role' => 'user',
  6776. 'content' => "以下是文档内容:
  6777. {$content}
  6778. 用户问题:
  6779. {$question}"
  6780. ]
  6781. ];
  6782. }else {
  6783. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6784. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6785. return (array)$value;
  6786. })->toArray();
  6787. array_unshift($messages, $system_message);
  6788. $messages[] = [
  6789. 'role' => 'user',
  6790. 'content' => $prompt
  6791. ];
  6792. }
  6793. }
  6794. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6795. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6796. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6797. if ($model === 'deepseek-chat') {
  6798. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6799. $model = 'deepseek-v4-flash';
  6800. $thinkingMode = 'disabled';
  6801. } elseif ($model === 'deepseek-reasoner') {
  6802. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6803. $model = 'deepseek-v4-flash';
  6804. $thinkingMode = 'enabled';
  6805. }
  6806. $post_data = [
  6807. 'model' => $model,
  6808. 'messages' => $messages,
  6809. // 'max_tokens' => 8192,
  6810. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  6811. 'frequency_penalty' => 0,
  6812. 'presence_penalty' => 0,
  6813. 'response_format' => ['type' => 'text'],
  6814. 'thinking' => ['type' => $thinkingMode],
  6815. 'stream' => true // 启用流式输出
  6816. ];
  6817. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6818. // 根据模型类型选择调用方法
  6819. $fullContent = '';
  6820. $fullReasoningContent = '';
  6821. $usage = [];
  6822. // dd($post_data);
  6823. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6824. try {
  6825. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6826. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6827. } else if (in_array($model, $this->gpt_text_models)) {
  6828. // GPT-5.4 模型使用 TokenRouter API
  6829. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6830. } else {
  6831. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6832. }
  6833. // 验证返回值类型
  6834. if (!is_iterable($streamGenerator)) {
  6835. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6836. dLog('deepseek')->error('方法名流式生成器无效', [
  6837. 'generator_type' => $errorType,
  6838. 'model' => $model,
  6839. // 添加其他上下文信息
  6840. ]);
  6841. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6842. 'type' => $errorType,
  6843. 'model' => $model
  6844. ]);
  6845. yield [
  6846. 'type' => 'error',
  6847. // 根据方法返回相应的空数据结构
  6848. 'answer' => '',
  6849. 'reasoning' => '',
  6850. 'usage' => [],
  6851. 'error' => '接口返回数据异常,请重新请求'
  6852. ];
  6853. return;
  6854. }
  6855. // 处理流式输出
  6856. foreach ($streamGenerator as $chunk) {
  6857. if (isset($chunk['type'])) {
  6858. if ($chunk['type'] === 'done') {
  6859. $fullContent = $chunk['full_content'];
  6860. $fullReasoningContent = $chunk['full_reasoning'];
  6861. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6862. } else {
  6863. yield $chunk;
  6864. }
  6865. }
  6866. }
  6867. } catch (\Exception $e) {
  6868. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6869. 'model' => $model,
  6870. 'trace' => $e->getTraceAsString()
  6871. ]);
  6872. logDB('deepseek', 'error', '方法名流式处理失败', [
  6873. 'error' => $e->getMessage(),
  6874. 'model' => $model
  6875. ]);
  6876. yield [
  6877. 'type' => 'error',
  6878. // 根据方法返回相应的空数据结构
  6879. 'answer' => '',
  6880. 'reasoning' => '',
  6881. 'usage' => [],
  6882. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6883. ];
  6884. return;
  6885. }
  6886. dLog('deepseek')->info('完整内容: '.$fullContent);
  6887. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6888. // 处理完整内容并返回最终结果
  6889. $script_arr = [];
  6890. if ($fullContent) {
  6891. $script_arr = handleScriptContentForAce($fullContent);
  6892. dLog('deepseek')->info('解析内容', $script_arr);
  6893. logDB('deepseek', 'info', '解析内容', $script_arr);
  6894. }
  6895. if (empty($script_arr['roles'])) {
  6896. // 未生成剧本相关内容,保存对话记录并返回提示
  6897. dLog('deepseek')->info('未生成剧本相关的内容');
  6898. try {
  6899. $now = date('Y-m-d H:i:s');
  6900. // 保存对话记录
  6901. $records = [
  6902. [
  6903. 'uid' => $uid,
  6904. 'anime_id' => $anime_id,
  6905. 'sequence' => 0,
  6906. 'role' => 'user',
  6907. 'content' => $prompt,
  6908. 'created_at' => $now,
  6909. 'updated_at' => $now
  6910. ],
  6911. [
  6912. 'uid' => $uid,
  6913. 'anime_id' => $anime_id,
  6914. 'sequence' => 0,
  6915. 'role' => 'assistant',
  6916. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6917. 'created_at' => $now,
  6918. 'updated_at' => $now
  6919. ]
  6920. ];
  6921. DB::table('mp_anime_records')->insert($records);
  6922. } catch (\Exception $e) {
  6923. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6924. }
  6925. yield [
  6926. 'type' => 'done',
  6927. 'script' => [],
  6928. 'episode' => [],
  6929. 'answer' => $fullContent,
  6930. 'reasoning' => $fullReasoningContent,
  6931. 'usage' => $usage,
  6932. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6933. ];
  6934. return;
  6935. }
  6936. // 替换美术风格
  6937. if ($mappedArtStyle !== '') {
  6938. $script_arr['art_style'] = $mappedArtStyle;
  6939. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6940. }
  6941. if ($user_anime_name != '新剧本策划') {
  6942. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  6943. // 确认对话名称唯一性
  6944. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6945. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6946. }
  6947. }else {
  6948. $anime_name = $user_anime_name;
  6949. }
  6950. $table_data = [
  6951. 'user_id' => $uid,
  6952. 'model' => $model,
  6953. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6954. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6955. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6956. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6957. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6958. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6959. 'art_style_type' => $input_art_style,
  6960. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6961. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6962. 'status' => '解析完成',
  6963. 'generate_status' => '待执行',
  6964. 'updated_at' => date('Y-m-d H:i:s')
  6965. ];
  6966. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6967. // 如果是修改集数,则将content内容更新(会改变原文)
  6968. if (isset($episode_count) && $episode_count > 0) {
  6969. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6970. $table_data['start_episode_sequence'] = 1;
  6971. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6972. }else {
  6973. // 如果需要生成原文内容,从script_arr中提取
  6974. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6975. $table_data['content'] = $script_arr['content'];
  6976. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6977. if (!$table_data['content']) {
  6978. yield [
  6979. 'type' => 'done',
  6980. 'script' => [],
  6981. 'episode' => [],
  6982. 'answer' => $fullContent,
  6983. 'reasoning' => $fullReasoningContent,
  6984. 'usage' => $usage,
  6985. 'error' => '未生成剧本内容,请调整提示词再试'
  6986. ];
  6987. return;
  6988. }
  6989. }
  6990. if (isset($table_data['content']) && $table_data['content']) {
  6991. $chapters = splitContent($table_data['content']);
  6992. $chapter_count = count($chapters);
  6993. if ($chapter_count > 0) {
  6994. $table_data['start_episode_sequence'] = 1;
  6995. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6996. }
  6997. }
  6998. }
  6999. if ($extra_products) {
  7000. $table_data['extra_products'] = json_encode($extra_products, 256);
  7001. }
  7002. $single_episode = [];
  7003. try {
  7004. DB::beginTransaction();
  7005. $now = date('Y-m-d H:i:s');
  7006. // 更新动漫大纲
  7007. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7008. if (!$boolen) {
  7009. dLog('deepseek')->info('对话修改失败', $table_data);
  7010. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  7011. Utils::throwError('20003:对话修改失败');
  7012. }
  7013. // 保存对话记录
  7014. $records = [
  7015. [
  7016. 'uid' => $uid,
  7017. 'anime_id' => $anime_id,
  7018. 'sequence' => 0,
  7019. 'role' => 'user',
  7020. 'content' => $prompt,
  7021. 'created_at' => $now,
  7022. 'updated_at' => $now
  7023. ],
  7024. [
  7025. 'uid' => $uid,
  7026. 'anime_id' => $anime_id,
  7027. 'sequence' => 0,
  7028. 'role' => 'assistant',
  7029. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7030. 'content' => $fullContent,
  7031. 'created_at' => $now,
  7032. 'updated_at' => $now
  7033. ]
  7034. ];
  7035. // 保存对话记录
  7036. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7037. if (!$boolen3) {
  7038. Utils::throwError('20003:对话记录保存失败');
  7039. }
  7040. // 单剧集模式:生成并保存剧集信息
  7041. if ($is_single) {
  7042. $anime_name = getProp($anime, 'anime_name', '未命名');
  7043. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7044. if (empty($episode_arr['acts'])) {
  7045. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7046. }
  7047. $saveResult = $this->saveEpisodeVersionData(
  7048. $anime_id,
  7049. 1,
  7050. $episode_arr,
  7051. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7052. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7053. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7054. null,
  7055. null,
  7056. false,
  7057. $content,
  7058. $now,
  7059. $ref_products
  7060. );
  7061. $single_episode = $saveResult['episode'];
  7062. $episode_id = $saveResult['episode_id'];
  7063. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7064. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7065. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7066. 'props' => json_encode($saveResult['merged_props'], 256),
  7067. 'updated_at' => $now
  7068. ]);
  7069. if ($boolen5 === false) {
  7070. Utils::throwError('20003:单剧集主表资源同步失败');
  7071. }
  7072. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7073. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7074. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7075. $episode_record_content = '确认分镜大纲';
  7076. if ($content !== '') {
  7077. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7078. }
  7079. $episode_records = [
  7080. [
  7081. 'uid' => $uid,
  7082. 'anime_id' => $anime_id,
  7083. 'role' => 'user',
  7084. 'content' => $episode_record_content,
  7085. 'sequence' => 1,
  7086. 'episode_id' => $episode_id,
  7087. 'created_at' => $now,
  7088. 'updated_at' => $now
  7089. ],
  7090. [
  7091. 'uid' => $uid,
  7092. 'anime_id' => $anime_id,
  7093. 'role' => 'assistant',
  7094. 'content' => $fullContent,
  7095. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7096. 'sequence' => 1,
  7097. 'episode_id' => $episode_id,
  7098. 'created_at' => $now,
  7099. 'updated_at' => $now
  7100. ]
  7101. ];
  7102. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7103. if (!$boolen4) {
  7104. Utils::throwError('20003:单剧集分镜记录保存失败');
  7105. }
  7106. }
  7107. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7108. if ($is_single && !empty($single_episode)) {
  7109. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7110. 'anime_id' => $anime_id,
  7111. 'episode_id' => $episode_id ?? 0,
  7112. ]);
  7113. }
  7114. }catch (\Exception $e) {
  7115. DB::rollBack();
  7116. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  7117. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  7118. yield [
  7119. 'type' => 'done',
  7120. 'answer' => $fullContent,
  7121. 'reasoning' => $fullReasoningContent,
  7122. 'usage' => $usage,
  7123. 'error' => $e->getMessage(),
  7124. ];
  7125. return;
  7126. }
  7127. DB::commit();
  7128. dLog('deepseek')->info('保存完毕');
  7129. if ($is_single && !empty($single_episode)) {
  7130. // $this->batchSetGlobalRoleImg([
  7131. // 'anime_id' => $anime_id,
  7132. // ]);
  7133. // $this->batchSetGlobalSceneImg([
  7134. // 'anime_id' => $anime_id,
  7135. // ]);
  7136. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7137. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7138. }
  7139. $table_data['anime_id'] = $anime_id;
  7140. $table_data['roles'] = json_decode($table_data['roles'], true);
  7141. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7142. $table_data['props'] = json_decode($table_data['props'], true);
  7143. unset($table_data['updated_at']);
  7144. unset($table_data['status']);
  7145. yield [
  7146. 'type' => 'done',
  7147. 'script' => $table_data,
  7148. 'episode' => $single_episode,
  7149. 'answer' => $fullContent,
  7150. 'reasoning' => $fullReasoningContent,
  7151. 'usage' => $usage
  7152. ];
  7153. }
  7154. public function chatForAce($data) {
  7155. $uid = Site::getUid();
  7156. // 积分余额预检(不足直接报错)
  7157. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  7158. $anime_id = getProp($data, 'anime_id');
  7159. $file = getProp($data, 'file');
  7160. $content = getProp($data, 'content', '');
  7161. $bid = getProp($data, 'bid', 0);
  7162. $script_id = getProp($data, 'script_id', 0);
  7163. $episode_number = getProp($data, 'episode_number', 1);
  7164. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7165. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7166. if (!$anime) Utils::throwError('20003:该对话不存在!');
  7167. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  7168. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  7169. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  7170. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  7171. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  7172. $roles = is_array($roles) ? $roles : [];
  7173. $scenes = is_array($scenes) ? $scenes : [];
  7174. $extra_products = getProp($data, 'products', []);
  7175. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7176. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7177. $anime_script_id = getProp($anime, 'script_id');
  7178. if ($anime_script_id) {
  7179. $cpid = Site::getCpid();
  7180. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7181. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7182. ->where('mapping.script_id', $anime_script_id)
  7183. ->where('product.cpid', $cpid)
  7184. ->where('product.is_deleted', 0);
  7185. // 如果提供了 episode_number,则过滤指定集数
  7186. if ($episode_number !== null && $episode_number !== '') {
  7187. $script_products_mappings->where('mapping.episode_number', $episode_number);
  7188. }
  7189. $mappings = $script_products_mappings->select(
  7190. 'mapping.product_id',
  7191. 'mapping.episode_number',
  7192. 'product.product_name',
  7193. 'product.type',
  7194. 'product.product',
  7195. 'product.pic_prompt',
  7196. 'product.url',
  7197. 'product.pic_task_id',
  7198. 'product.pic_task_status',
  7199. 'product.three_view_image_url'
  7200. )
  7201. ->get();
  7202. // 按 product_id 分组,合并 episode_number
  7203. $productMap = [];
  7204. foreach ($mappings as $item) {
  7205. $product_id = $item->product_id;
  7206. $product_name = $item->product_name;
  7207. // 处理product_name两边的符号
  7208. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7209. if (!isset($productMap[$product_id])) {
  7210. $productMap[$product_id] = [
  7211. 'product_id' => $product_id,
  7212. 'product_name' => $product_name,
  7213. 'type' => (int)$item->type,
  7214. 'product' => (int)$item->product,
  7215. 'pic_prompt' => $item->pic_prompt,
  7216. 'url' => $item->url,
  7217. 'pic_task_id' => $item->pic_task_id,
  7218. 'pic_task_status' => $item->pic_task_status,
  7219. 'episode_numbers' => [],
  7220. ];
  7221. }
  7222. // 添加 episode_number(去重)
  7223. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7224. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7225. }
  7226. }
  7227. // 将查询到的剧本资产合并到extra_products中
  7228. // 先构建extra_products的索引(以product_id+episode_number为key)
  7229. $extraProductsMap = [];
  7230. foreach ($extra_products as $item) {
  7231. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  7232. $extraProductsMap[$key] = $item;
  7233. }
  7234. // 合并剧本资产(去重:product_id+episode_number)
  7235. foreach ($productMap as $product) {
  7236. foreach ($product['episode_numbers'] as $ep_num) {
  7237. $key = $product['product_id'] . '_' . $ep_num;
  7238. // 如果不存在则添加
  7239. if (!isset($extraProductsMap[$key])) {
  7240. $extraProductsMap[$key] = [
  7241. 'product_id' => $product['product_id'],
  7242. 'product_name' => $product['product_name'],
  7243. 'type' => $product['type'],
  7244. 'product' => $product['product'],
  7245. 'pic_prompt' => $product['pic_prompt'],
  7246. 'url' => $product['url'],
  7247. 'pic_task_id' => $product['pic_task_id'],
  7248. 'pic_task_status' => $product['pic_task_status'],
  7249. 'episode_number' => $ep_num,
  7250. ];
  7251. }
  7252. }
  7253. }
  7254. // 重新赋值给extra_products
  7255. $extra_products = array_values($extraProductsMap);
  7256. }
  7257. // 处理提示词
  7258. if ($prompt && $extra_products) {
  7259. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7260. foreach($extra_products as $item) {
  7261. $product_name = getProp($item, 'product_name');
  7262. if ($product_name) {
  7263. // 替换 {product_name} 为 product_name
  7264. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7265. }
  7266. }
  7267. }
  7268. // 获取最后一集序号
  7269. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  7270. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  7271. // 转换主体列表和场景列表的格式
  7272. // 获取参考主体或场景
  7273. if ((int)$episode_number === 1) {
  7274. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  7275. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  7276. }else {
  7277. $prev_episode_number = $episode_number - 1;
  7278. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  7279. }
  7280. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  7281. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  7282. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  7283. // 合并anime_products和extra_products(extra_products优先,去重)
  7284. $anime_products = getProp($anime, 'extra_products');
  7285. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  7286. $ref_products = [];
  7287. foreach($anime_products as $item) {
  7288. $product_name = getProp($item, 'product_name');
  7289. $ref_products[$product_name] = $item;
  7290. }
  7291. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  7292. $extra_roles = []; // 从extra_products中提取的角色
  7293. $extra_scenes = []; // 从extra_products中提取的场景
  7294. $extra_props = []; // 从extra_products中提取的道具
  7295. if ($extra_products && is_array($extra_products)) {
  7296. foreach($extra_products as $item) {
  7297. $product = (int)getProp($item, 'product');
  7298. $product_name = getProp($item, 'product_name');
  7299. if ($product_name == '旁白') continue;
  7300. $pic_prompt = getProp($item, 'pic_prompt');
  7301. $ref_products[$product_name] = $item;
  7302. if ($product === 1) {
  7303. // 角色
  7304. $extra_roles[$product_name] = [
  7305. 'role' => $product_name,
  7306. 'pic_prompt' => $pic_prompt,
  7307. 'url' => getProp($item, 'url', ''),
  7308. ];
  7309. } elseif ($product === 2) {
  7310. // 场景
  7311. $extra_scenes[$product_name] = [
  7312. 'scene' => $product_name,
  7313. 'pic_prompt' => $pic_prompt,
  7314. 'url' => getProp($item, 'url', ''),
  7315. ];
  7316. } elseif ($product === 3) {
  7317. // 道具
  7318. $extra_props[$product_name] = [
  7319. 'prop' => $product_name,
  7320. 'pic_prompt' => $pic_prompt,
  7321. 'url' => getProp($item, 'url', ''),
  7322. ];
  7323. }
  7324. }
  7325. }
  7326. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  7327. $merged_roles = [];
  7328. foreach($ref_roles as $role) {
  7329. $role_name = getProp($role, 'role');
  7330. if (!isset($extra_roles[$role_name])) {
  7331. $merged_roles[$role_name] = $role;
  7332. }
  7333. }
  7334. // 添加extra_roles
  7335. foreach($extra_roles as $role_name => $role) {
  7336. $merged_roles[$role_name] = $role;
  7337. }
  7338. $ref_roles = array_values($merged_roles);
  7339. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  7340. $merged_scenes = [];
  7341. foreach($ref_scenes as $scene) {
  7342. $scene_name = getProp($scene, 'scene');
  7343. if (!isset($extra_scenes[$scene_name])) {
  7344. $merged_scenes[$scene_name] = $scene;
  7345. }
  7346. }
  7347. // 添加extra_scenes
  7348. foreach($extra_scenes as $scene_name => $scene) {
  7349. $merged_scenes[$scene_name] = $scene;
  7350. }
  7351. $ref_scenes = array_values($merged_scenes);
  7352. // 合并ref_props和extra_props(extra_props优先,去重)
  7353. $merged_props = [];
  7354. foreach($ref_props as $prop) {
  7355. $prop_name = getProp($prop, 'prop');
  7356. if (!isset($extra_props[$prop_name])) {
  7357. $merged_props[$prop_name] = $prop;
  7358. }
  7359. }
  7360. // 添加extra_props
  7361. foreach($extra_props as $prop_name => $prop) {
  7362. $merged_props[$prop_name] = $prop;
  7363. }
  7364. $ref_props = array_values($merged_props);
  7365. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  7366. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  7367. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  7368. // 构建强制主体、场景和道具提示词
  7369. $forced_roles_prompt = "";
  7370. $forced_scenes_prompt = "";
  7371. $forced_props_prompt = "";
  7372. if (!empty($extra_roles)) {
  7373. $forced_roles_list = "";
  7374. foreach($extra_roles as $role_name => $role) {
  7375. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  7376. }
  7377. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7378. }
  7379. if (!empty($extra_scenes)) {
  7380. $forced_scenes_list = "";
  7381. foreach($extra_scenes as $scene_name => $scene) {
  7382. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  7383. }
  7384. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7385. }
  7386. if (!empty($extra_props)) {
  7387. $forced_props_list = "";
  7388. foreach($extra_props as $prop_name => $prop) {
  7389. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  7390. }
  7391. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7392. }
  7393. if ($anime_script_id) {
  7394. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  7395. }else if ($roles_content) {
  7396. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  7397. 主体范围:\n {$roles_content}\n
  7398. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  7399. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7400. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7401. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7402. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7403. }else {
  7404. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7405. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7406. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7407. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7408. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7409. }
  7410. if ($anime_script_id) {
  7411. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  7412. }else if ($scenes_content) {
  7413. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7414. 场景范围:\n {$scenes_content}\n
  7415. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  7416. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  7417. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7418. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7419. }else {
  7420. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7421. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7422. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7423. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7424. }
  7425. if ($anime_script_id) {
  7426. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  7427. }else if ($props_content) {
  7428. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7429. 道具范围:\n {$props_content}\n
  7430. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  7431. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  7432. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7433. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7434. }else {
  7435. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7436. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  7437. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7438. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7439. }
  7440. // 提取文件内容
  7441. if ($file) {
  7442. $uploaded_content = $this->extractFileContent($file);
  7443. if (!$uploaded_content) {
  7444. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7445. }
  7446. } elseif ($script_id) {
  7447. $uploaded_content = $this->getContentByScriptId($script_id);
  7448. if (!$uploaded_content) {
  7449. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7450. }
  7451. } elseif ($bid) {
  7452. $uploaded_content = $this->getContentByBid($bid);
  7453. if (!$uploaded_content) {
  7454. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7455. }
  7456. } elseif ($content) {
  7457. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  7458. }
  7459. // elseif ($prompt) {
  7460. // $uploaded_content = filterContent($prompt);
  7461. // }
  7462. else {
  7463. $uploaded_content = '';
  7464. }
  7465. // 美术风格
  7466. $input_art_style = getProp($data, 'art_style');
  7467. if (!$input_art_style) {
  7468. $mappedArtStyle = getProp($anime, 'art_style');
  7469. }else {
  7470. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7471. }
  7472. if (!$mappedArtStyle) {
  7473. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7474. }else {
  7475. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7476. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7477. }else {
  7478. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7479. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7480. }
  7481. }
  7482. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7483. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7484. // 强制要求:
  7485. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7486. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7487. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7488. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7489. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  7490. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7491. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7492. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7493. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7494. // 10.分镜要和场景列表、人物主体保持一致\n
  7495. // 普通要求:
  7496. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7497. // {$role_demo}
  7498. // {$scene_demo}
  7499. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7500. // 4.1片段分割逻辑(优先级从高到低):
  7501. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7502. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7503. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7504. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7505. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7506. // - 片段数量格式为: 片段数量:8
  7507. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7508. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7509. // 4.3分镜结构:每个分镜包含以下字段:
  7510. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  7511. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  7512. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7513. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  7514. // - 运镜:场景+画面描述+运镜
  7515. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  7516. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7517. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7518. // 5.$mappedArtStyle_prompt\n\n
  7519. // 示例格式:\n
  7520. // 第1集:隐形的守护者
  7521. // ###故事梗概
  7522. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7523. // ###美术风格
  7524. // 基础画风风格词:胡金铨武侠
  7525. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7526. // ###主体列表
  7527. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7528. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7529. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7530. // ###场景列表
  7531. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7532. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7533. // ###分段剧本
  7534. // 片段数量:8
  7535. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7536. // ##片段1
  7537. // 时长:12s
  7538. // 分镜1
  7539. // 场景:边境小镇街道
  7540. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7541. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7542. // 配音台词:
  7543. // 背景音效:
  7544. // 分镜2
  7545. // 场景:悦来酒馆
  7546. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7547. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7548. // 配音台词:
  7549. // 背景音效:
  7550. // 分镜3
  7551. // 场景:悦来酒馆
  7552. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7553. // 运镜:从中景推向令牌特写。
  7554. // 配音台词:
  7555. // 背景音效:
  7556. // 分镜4
  7557. // 场景:悦来酒馆
  7558. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7559. // 运镜:极速推向酒水溅起的瞬间。
  7560. // 配音台词:
  7561. // 背景音效:
  7562. // 分镜5
  7563. // 镜头描述
  7564. // 场景:悦来酒馆
  7565. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7566. // 运镜:固定机位,利用倾斜构图制造压迫感。
  7567. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7568. // 背景音效:
  7569. // \n\n";
  7570. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7571. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7572. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  7573. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  7574. 普通要求:
  7575. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7576. {$role_demo}
  7577. {$scene_demo}
  7578. {$prop_demo}
  7579. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7580. 5.1片段分割逻辑(优先级从高到低):
  7581. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7582. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7583. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7584. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7585. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7586. - 片段数量格式为: 片段数量:8
  7587. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7588. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7589. 5.3分镜结构:每个分镜包含以下字段:
  7590. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7591. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7592. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7593. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7594. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7595. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7596. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7597. - 运镜:场景+画面描述+运镜
  7598. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7599. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7600. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7601. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7602. 6.《情绪-视听语言映射表》:
  7603. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7604. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7605. -----|---------|------------|----------------
  7606. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7607. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7608. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7609. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7610. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7611. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7612. -----|---------|------------|----------------
  7613. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7614. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7615. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7616. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7617. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7618. --------|---------|--------------|-------------
  7619. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7620. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7621. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7622. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7623. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7624. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7625. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7626. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7627. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7628. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7629. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7630. -----|---------|------------|------------
  7631. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7632. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7633. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7634. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7635. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7636. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7637. --------|---------|--------------|----------
  7638. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7639. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7640. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7641. 6.6 声音设计与潜意识影响 (Soundscape)
  7642. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7643. -----|---------|------------|------------------
  7644. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7645. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7646. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7647. 理论基石:
  7648. - The Five C's of Cinematography by Joseph V. Mascelli
  7649. - Film Art: An Introduction by David Bordwell
  7650. - Sight, Sound, Motion by Herbert Zettl
  7651. - Notes on the Cinematograph by Robert Bresson
  7652. \n\n
  7653. 7.{$mappedArtStyle_prompt}
  7654. 示例格式:\n
  7655. 第1集:隐形的守护者
  7656. ###故事梗概
  7657. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7658. ###美术风格
  7659. 基础画风风格词:胡金铨武侠
  7660. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7661. ###主体列表
  7662. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7663. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7664. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7665. ###场景列表
  7666. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7667. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7668. ###道具列表
  7669. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  7670. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  7671. ###分段剧本
  7672. 片段数量:8
  7673. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7674. ##片段1
  7675. 时长:12s
  7676. 分镜1
  7677. 出场角色:刀疤脸
  7678. 场景:边境小镇街道
  7679. 出场道具:酒杯-高脚杯
  7680. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7681. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7682. 配音台词:
  7683. 背景音效:
  7684. 分镜2
  7685. 出场角色:刀疤脸
  7686. 场景:悦来酒馆
  7687. 出场道具:酒杯-高脚杯
  7688. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7689. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7690. 配音台词:
  7691. 背景音效:
  7692. 分镜3
  7693. 出场角色:刀疤脸
  7694. 场景:悦来酒馆
  7695. 出场道具:酒杯-高脚杯
  7696. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7697. 运镜:从中景推向令牌特写。
  7698. 配音台词:
  7699. 背景音效:
  7700. 分镜4
  7701. 出场角色:刀疤脸
  7702. 场景:悦来酒馆
  7703. 出场道具:酒杯-高脚杯
  7704. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7705. 运镜:极速推向酒水溅起的瞬间。
  7706. 配音台词:
  7707. 背景音效:
  7708. 分镜5
  7709. 出场角色:刀疤脸
  7710. 场景:悦来酒馆
  7711. 出场道具:酒杯-高脚杯
  7712. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7713. 运镜:固定机位,利用倾斜构图制造压迫感。
  7714. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7715. 背景音效:
  7716. \n\n";
  7717. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7718. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  7719. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7720. $prompt = $origin_prompt;
  7721. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7722. // 获取章节内容
  7723. $full_content = getProp($anime, 'content');
  7724. if ($uploaded_content) {
  7725. $full_content = $uploaded_content;
  7726. }
  7727. // 根据章节内容拆分章节
  7728. $chapters = splitContent($full_content);
  7729. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7730. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7731. $messages = [];
  7732. if ($prompt == '确认分镜大纲') {
  7733. // 暂时保留
  7734. $content = $chapter_content;
  7735. if ($is_single) $content = $full_content; // 单剧集使用全文
  7736. if (!$content) {
  7737. Utils::throwError('20003:章节内容无法获取,请确认');
  7738. }
  7739. $question = $is_single
  7740. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7741. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7742. // 构建消息
  7743. $messages[] =
  7744. [
  7745. 'role' => 'user',
  7746. 'content' => $question
  7747. ];
  7748. }else if ($prompt == '继续策划下一集') {
  7749. if ($is_single) {
  7750. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7751. }
  7752. $content = $chapter_content;
  7753. if (!$content) {
  7754. Utils::throwError('20003:章节内容无法获取,请确认');
  7755. }
  7756. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7757. // 获取上一集最后记录
  7758. $prev_sequence = $episode_number - 1;
  7759. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7760. // 构建消息
  7761. $messages[] =
  7762. [
  7763. 'role' => 'user',
  7764. 'content' => $question
  7765. ];
  7766. // dd($messages);
  7767. }else {
  7768. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7769. if (!$content) {
  7770. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7771. }
  7772. if (!$content) {
  7773. Utils::throwError('20003:章节内容无法获取,请确认');
  7774. }
  7775. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7776. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7777. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7778. if ($origin_prompt) {
  7779. $question .= "本次修改要求如下:\n{$origin_prompt}";
  7780. }
  7781. $messages[] =
  7782. [
  7783. 'role' => 'user',
  7784. 'content' => $question
  7785. ];
  7786. }
  7787. // 处理文本模型
  7788. $model = getProp($data, 'model');
  7789. if (!$model) {
  7790. // 用户没有输入,从anime表获取
  7791. $model = getProp($anime, 'model');
  7792. if (!$model) {
  7793. // anime表也没有,使用默认值
  7794. $model = 'deepseek-v4-pro';
  7795. }
  7796. }
  7797. // 验证模型是否在可用模型表中
  7798. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7799. $model = 'deepseek-v4-pro';
  7800. }
  7801. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7802. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7803. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7804. if ($model === 'deepseek-chat') {
  7805. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7806. $model = 'deepseek-v4-flash';
  7807. $thinkingMode = 'disabled';
  7808. } elseif ($model === 'deepseek-reasoner') {
  7809. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7810. $model = 'deepseek-v4-flash';
  7811. $thinkingMode = 'enabled';
  7812. }
  7813. $post_data = [
  7814. 'model' => $model,
  7815. 'messages' => $messages,
  7816. // 'max_tokens' => 8192,
  7817. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7818. 'frequency_penalty' => 0,
  7819. 'presence_penalty' => 0,
  7820. 'response_format' => ['type' => 'text'],
  7821. 'thinking' => ['type' => $thinkingMode],
  7822. 'stream' => true // 启用流式输出
  7823. ];
  7824. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7825. // 根据模型类型选择调用方法
  7826. $fullContent = '';
  7827. $fullReasoningContent = '';
  7828. $usage = [];
  7829. try {
  7830. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7831. // DeepSeek 官方模型使用 DeepSeek API
  7832. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7833. } else if (in_array($model, $this->gpt_text_models)) {
  7834. // GPT-5.4 模型使用 TokenRouter API
  7835. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7836. } else {
  7837. // 其他模型使用火山引擎API
  7838. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7839. }
  7840. // 验证返回值类型
  7841. if (!is_iterable($streamGenerator)) {
  7842. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7843. dLog('deepseek')->error('chat流式生成器无效', [
  7844. 'generator_type' => $errorType,
  7845. 'model' => $model,
  7846. 'anime_id' => $anime_id,
  7847. 'episode_number' => $episode_number
  7848. ]);
  7849. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7850. 'type' => $errorType,
  7851. 'model' => $model
  7852. ]);
  7853. yield [
  7854. 'type' => 'error',
  7855. 'episode' => [],
  7856. 'answer' => '',
  7857. 'reasoning' => '',
  7858. 'usage' => [],
  7859. 'error' => '接口返回数据异常,请重新请求'
  7860. ];
  7861. return;
  7862. }
  7863. // 处理流式输出
  7864. foreach ($streamGenerator as $chunk) {
  7865. if (isset($chunk['type'])) {
  7866. if ($chunk['type'] === 'done') {
  7867. // 最终结果
  7868. $fullContent = $chunk['full_content'];
  7869. $fullReasoningContent = $chunk['full_reasoning'];
  7870. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7871. } else {
  7872. // 逐块yield数据
  7873. yield $chunk;
  7874. }
  7875. }
  7876. }
  7877. } catch (\Exception $e) {
  7878. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7879. 'model' => $model,
  7880. 'anime_id' => $anime_id,
  7881. 'episode_number' => $episode_number,
  7882. 'trace' => $e->getTraceAsString()
  7883. ]);
  7884. logDB('deepseek', 'error', 'chat流式处理失败', [
  7885. 'error' => $e->getMessage(),
  7886. 'model' => $model
  7887. ]);
  7888. yield [
  7889. 'type' => 'error',
  7890. 'episode' => [],
  7891. 'answer' => '',
  7892. 'reasoning' => '',
  7893. 'usage' => [],
  7894. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7895. ];
  7896. return;
  7897. }
  7898. dLog('deepseek')->info('完整内容: '.$fullContent);
  7899. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7900. // 处理完整内容并返回最终结果
  7901. $episode_arr = handleEpisodeContentForAce($fullContent);
  7902. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7903. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  7904. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7905. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7906. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  7907. // }
  7908. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  7909. $max_retries = 3;
  7910. $retry_count = 0;
  7911. $validation_failed = false;
  7912. $validation_error_msg = '';
  7913. // 验证生成的内容
  7914. if ($anime_script_id) {
  7915. // 检查是否有acts数据
  7916. if (empty($episode_arr['acts'])) {
  7917. $validation_failed = true;
  7918. $validation_error_msg = '未生成分镜剧本相关的内容';
  7919. } else {
  7920. // 检查主体列表是否匹配 - 只验证生成的主体名是否都在预期列表中
  7921. $generated_roles = array_column($episode_arr['roles'], 'role');
  7922. // 过滤掉"旁白"角色
  7923. $generated_roles = array_filter($generated_roles, function($role) {
  7924. return $role !== '旁白';
  7925. });
  7926. $expected_roles = array_keys($extra_roles);
  7927. // 找出生成的主体中不在预期列表中的主体
  7928. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7929. if (!empty($invalid_roles)) {
  7930. $validation_failed = true;
  7931. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7932. }
  7933. // 检查场景列表是否匹配 - 只验证生成的场景名是否都在预期列表中
  7934. if (!$validation_failed) {
  7935. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7936. $expected_scenes = array_keys($extra_scenes);
  7937. // 找出生成的场景中不在预期列表中的场景
  7938. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7939. if (!empty($invalid_scenes)) {
  7940. $validation_failed = true;
  7941. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7942. }
  7943. }
  7944. }
  7945. } else {
  7946. // 如果没有anime_script_id,只检查是否有acts数据
  7947. if (empty($episode_arr['acts'])) {
  7948. $validation_failed = true;
  7949. $validation_error_msg = '未生成分镜剧本相关的内容';
  7950. }
  7951. }
  7952. // 重试逻辑
  7953. while ($validation_failed && $retry_count < $max_retries) {
  7954. $retry_count++;
  7955. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  7956. 'reason' => $validation_error_msg,
  7957. 'anime_id' => $anime_id,
  7958. 'episode_number' => $episode_number
  7959. ]);
  7960. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  7961. 'reason' => $validation_error_msg,
  7962. 'anime_id' => $anime_id
  7963. ]);
  7964. // 发送流式重试提示
  7965. yield [
  7966. 'type' => 'retry',
  7967. 'retry_count' => $retry_count,
  7968. 'reason' => $validation_error_msg
  7969. ];
  7970. // 构建重试提示词
  7971. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  7972. if ($anime_script_id) {
  7973. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  7974. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  7975. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  7976. } else {
  7977. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  7978. }
  7979. // 添加重试消息到messages
  7980. $messages[] = [
  7981. 'role' => 'assistant',
  7982. 'content' => $fullContent
  7983. ];
  7984. $messages[] = [
  7985. 'role' => 'user',
  7986. 'content' => $retry_prompt
  7987. ];
  7988. // 更新post_data的messages
  7989. $post_data['messages'] = $messages;
  7990. // 重新调用API
  7991. try {
  7992. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7993. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7994. } else if (in_array($model, $this->gpt_text_models)) {
  7995. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7996. } else {
  7997. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7998. }
  7999. // 处理流式输出
  8000. $fullContent = '';
  8001. $fullReasoningContent = '';
  8002. foreach ($streamGenerator as $chunk) {
  8003. if (isset($chunk['type'])) {
  8004. if ($chunk['type'] === 'done') {
  8005. $fullContent = $chunk['full_content'];
  8006. $fullReasoningContent = $chunk['full_reasoning'];
  8007. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8008. } else {
  8009. yield $chunk;
  8010. }
  8011. }
  8012. }
  8013. // 重新解析内容
  8014. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  8015. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  8016. $episode_arr = handleEpisodeContentForAce($fullContent);
  8017. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  8018. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  8019. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  8020. // }
  8021. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  8022. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  8023. // 重新验证
  8024. $validation_failed = false;
  8025. $validation_error_msg = '';
  8026. if ($anime_script_id) {
  8027. if (empty($episode_arr['acts'])) {
  8028. $validation_failed = true;
  8029. $validation_error_msg = '未生成分镜剧本相关的内容';
  8030. } else {
  8031. // 检查主体列表 - 只验证生成的主体名是否都在预期列表中
  8032. $generated_roles = array_column($episode_arr['roles'], 'role');
  8033. // 过滤掉"旁白"角色
  8034. $generated_roles = array_filter($generated_roles, function($role) {
  8035. return $role !== '旁白';
  8036. });
  8037. $expected_roles = array_keys($extra_roles);
  8038. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8039. if (!empty($invalid_roles)) {
  8040. $validation_failed = true;
  8041. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8042. }
  8043. // 检查场景列表 - 只验证生成的场景名是否都在预期列表中
  8044. if (!$validation_failed) {
  8045. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  8046. $expected_scenes = array_keys($extra_scenes);
  8047. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8048. if (!empty($invalid_scenes)) {
  8049. $validation_failed = true;
  8050. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8051. }
  8052. }
  8053. }
  8054. } else {
  8055. if (empty($episode_arr['acts'])) {
  8056. $validation_failed = true;
  8057. $validation_error_msg = '未生成分镜剧本相关的内容';
  8058. }
  8059. }
  8060. } catch (\Exception $e) {
  8061. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  8062. 'trace' => $e->getTraceAsString()
  8063. ]);
  8064. break;
  8065. }
  8066. }
  8067. // 如果重试后仍然失败
  8068. if ($validation_failed) {
  8069. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  8070. 'retry_count' => $retry_count,
  8071. 'last_error' => $validation_error_msg
  8072. ]);
  8073. try {
  8074. $now = date('Y-m-d H:i:s');
  8075. $records = [
  8076. [
  8077. 'uid' => $uid,
  8078. 'anime_id' => $anime_id,
  8079. 'sequence' => $episode_number,
  8080. 'role' => 'user',
  8081. 'content' => $prompt,
  8082. 'created_at' => $now,
  8083. 'updated_at' => $now
  8084. ],
  8085. [
  8086. 'uid' => $uid,
  8087. 'anime_id' => $anime_id,
  8088. 'sequence' => $episode_number,
  8089. 'role' => 'assistant',
  8090. 'content' => $fullContent,
  8091. 'created_at' => $now,
  8092. 'updated_at' => $now
  8093. ]
  8094. ];
  8095. DB::table('mp_anime_records')->insert($records);
  8096. } catch (\Exception $e) {
  8097. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8098. }
  8099. yield [
  8100. 'type' => 'done',
  8101. 'episode' => [],
  8102. 'answer' => $fullContent,
  8103. 'reasoning' => $fullReasoningContent,
  8104. 'usage' => $usage,
  8105. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8106. ];
  8107. return;
  8108. }
  8109. // 验证成功,记录日志
  8110. if ($retry_count > 0) {
  8111. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8112. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8113. }
  8114. // 老逻辑
  8115. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  8116. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  8117. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  8118. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  8119. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  8120. $existing_props = is_array($existing_props) ? $existing_props : [];
  8121. $now = date('Y-m-d H:i:s');
  8122. try {
  8123. DB::beginTransaction();
  8124. $saveResult = $this->saveEpisodeVersionData(
  8125. $anime_id,
  8126. $episode_number,
  8127. $episode_arr,
  8128. $existing_roles,
  8129. $existing_scenes,
  8130. $existing_props,
  8131. $current_episode,
  8132. $base_episode,
  8133. $is_regenerate_version,
  8134. $content,
  8135. $now,
  8136. $ref_products
  8137. );
  8138. $episode = $saveResult['episode'];
  8139. $episode_id = $saveResult['episode_id'];
  8140. $merged_roles = $saveResult['merged_roles'];
  8141. $merged_scenes = $saveResult['merged_scenes'];
  8142. $merged_props = $saveResult['merged_props'];
  8143. $record_content = $origin_prompt;
  8144. if ($uploaded_content !== '') {
  8145. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  8146. }
  8147. $records = [
  8148. [
  8149. 'uid' => $uid,
  8150. 'anime_id' => $anime_id,
  8151. 'role' => 'user',
  8152. 'content' => $record_content,
  8153. 'sequence' => $episode_number,
  8154. 'episode_id' => $episode_id,
  8155. 'created_at' => $now,
  8156. 'updated_at' => $now
  8157. ],
  8158. [
  8159. 'uid' => $uid,
  8160. 'anime_id' => $anime_id,
  8161. 'role' => 'assistant',
  8162. 'content' => $fullContent,
  8163. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8164. 'sequence' => $episode_number,
  8165. 'episode_id' => $episode_id,
  8166. 'created_at' => $now,
  8167. 'updated_at' => $now
  8168. ]
  8169. ];
  8170. $boolen4 = DB::table('mp_anime_records')->insert($records);
  8171. if (!$boolen4) {
  8172. Utils::throwError('20003:对话记录保存失败');
  8173. }
  8174. // 保存模型到anime表
  8175. $update_anime_data = [
  8176. 'model' => $model,
  8177. 'updated_at' => $now
  8178. ];
  8179. if ($uploaded_content) {
  8180. $update_anime_data['content'] = $uploaded_content;
  8181. }
  8182. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  8183. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8184. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8185. 'anime_id' => $anime_id,
  8186. 'episode_number' => $episode_number,
  8187. 'model' => $model,
  8188. ]);
  8189. }catch (\Exception $e) {
  8190. DB::rollBack();
  8191. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8192. yield [
  8193. 'type' => 'done',
  8194. 'answer' => $fullContent,
  8195. 'reasoning' => $fullReasoningContent,
  8196. 'usage' => $usage,
  8197. 'error' => $e->getMessage(),
  8198. ];
  8199. return;
  8200. }
  8201. DB::commit();
  8202. if ($is_global_generate_pics) {
  8203. // // 批量生成全局角色图片
  8204. // $this->batchSetGlobalRoleImg([
  8205. // 'anime_id' => $anime_id,
  8206. // ], true);
  8207. // // 批量生成全局场景图片
  8208. // $this->batchSetGlobalSceneImg([
  8209. // 'anime_id' => $anime_id,
  8210. // ], true);
  8211. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8212. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8213. }
  8214. $episode['episode_id'] = $episode_id;
  8215. $episode['roles'] = $merged_roles;
  8216. $episode['scenes'] = $merged_scenes;
  8217. $episode['props'] = $merged_props;
  8218. $episode['end_episode_sequence'] = $end_episode_sequence;
  8219. // 获取mp_animes表中的视频参数
  8220. $episode['video_params'] = [
  8221. 'video_model' => getProp($anime, 'video_model'),
  8222. 'video_resolution' => getProp($anime, 'video_resolution'),
  8223. 'ratio' => getProp($anime, 'video_ratio'),
  8224. ];
  8225. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  8226. yield [
  8227. 'type' => 'done',
  8228. 'episode' => $episode,
  8229. 'answer' => $fullContent,
  8230. 'reasoning' => $fullReasoningContent,
  8231. 'usage' => $usage
  8232. ];
  8233. }
  8234. /**
  8235. * chatForAce的非流式版本 - 用于定时任务
  8236. * 只获取最终 type=done 的数据,并验证必要字段
  8237. *
  8238. * @param array $data 请求数据
  8239. * @return array 生成结果
  8240. */
  8241. public function chatForAceNonStream($data) {
  8242. $finalResult = null;
  8243. // 调用流式方法,只保存 type=done 的数据
  8244. foreach ($this->chatForAce($data) as $chunk) {
  8245. // 只关注最终结果
  8246. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  8247. $finalResult = $chunk;
  8248. break; // 找到 done 就退出循环
  8249. }
  8250. }
  8251. // 验证最终结果
  8252. if (!$finalResult) {
  8253. return ['error' => '生成失败:未获取到最终结果'];
  8254. }
  8255. // 检查是否有错误
  8256. if (isset($finalResult['error']) && $finalResult['error']) {
  8257. return $finalResult;
  8258. }
  8259. // 验证必要字段
  8260. $episode = $finalResult['episode'] ?? [];
  8261. // 验证 roles
  8262. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  8263. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  8264. }
  8265. // 验证 scenes
  8266. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  8267. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  8268. }
  8269. // 验证 props(道具可以为空,但必须存在且为数组)
  8270. if (!isset($episode['props']) || !is_array($episode['props'])) {
  8271. $episode['props'] = [];
  8272. }
  8273. // 验证 acts(分镜剧本)
  8274. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  8275. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  8276. }
  8277. // 更新验证后的 episode 数据
  8278. $finalResult['episode'] = $episode;
  8279. // 记录验证成功日志
  8280. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  8281. 'roles_count' => count($episode['roles']),
  8282. 'scenes_count' => count($episode['scenes']),
  8283. 'props_count' => count($episode['props']),
  8284. 'acts_count' => count($episode['acts'])
  8285. ]);
  8286. return $finalResult;
  8287. }
  8288. /**
  8289. * 批量生成多个分集
  8290. *
  8291. * @param array $data 请求数据
  8292. * @return array 任务信息
  8293. */
  8294. public function batchGenerateEpisodes($data) {
  8295. $uid = Site::getUid();
  8296. $cpid = Site::getCpid();
  8297. $anime_id = getProp($data, 'anime_id');
  8298. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  8299. if (!$anime_id) {
  8300. Utils::throwError('20003:anime_id参数缺失');
  8301. }
  8302. if ($generate_episode_number < 1) {
  8303. Utils::throwError('20003:生成集数必须大于0');
  8304. }
  8305. // 获取动漫信息
  8306. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8307. if (!$anime) {
  8308. Utils::throwError('20003:该剧集不存在');
  8309. }
  8310. // 检查是否是全能模式
  8311. if ((int)getProp($anime, 'ace_mode') !== 1) {
  8312. Utils::throwError('20003:只有全能模式才支持批量生成');
  8313. }
  8314. // 检查是否是多剧集模式
  8315. if ((int)getProp($anime, 'is_multi') !== 1) {
  8316. Utils::throwError('20003:单剧集不支持批量生成');
  8317. }
  8318. // 获取当前已生成的最大集数
  8319. $currentMaxEpisode = DB::table('mp_anime_episodes')
  8320. ->where('anime_id', $anime_id)
  8321. ->where('is_default', 1)
  8322. ->max('episode_number');
  8323. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  8324. // 确定起始集数
  8325. $startEpisodeNumber = $currentMaxEpisode + 1;
  8326. // 计算结束集数
  8327. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  8328. // 检查是否超过总集数限制
  8329. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  8330. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  8331. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  8332. }
  8333. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  8334. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  8335. ->where('anime_id', $anime_id)
  8336. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  8337. ->whereIn('status', ['pending', 'processing', 'completed'])
  8338. ->count();
  8339. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  8340. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  8341. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  8342. if ($needEpisodeCount > 0) {
  8343. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS * $needEpisodeCount, $uid);
  8344. }
  8345. $now = date('Y-m-d H:i:s');
  8346. $createdTasks = [];
  8347. $skippedTasks = [];
  8348. // 为每一集创建详情记录
  8349. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  8350. // 检查是否已有该集的任务记录
  8351. $existingTask = DB::table('mp_batch_episode_generation_details')
  8352. ->where('anime_id', $anime_id)
  8353. ->where('episode_number', $episodeNumber)
  8354. ->first();
  8355. if ($existingTask) {
  8356. // 如果已存在且未完成,跳过
  8357. if (in_array($existingTask->status, ['pending', 'processing'])) {
  8358. $skippedTasks[] = $episodeNumber;
  8359. continue;
  8360. }
  8361. // 如果是失败状态,可以重新创建(删除旧记录)
  8362. if ($existingTask->status === 'failed') {
  8363. DB::table('mp_batch_episode_generation_details')
  8364. ->where('id', $existingTask->id)
  8365. ->delete();
  8366. }
  8367. // 如果是已完成状态,也跳过
  8368. if ($existingTask->status === 'completed') {
  8369. $skippedTasks[] = $episodeNumber;
  8370. continue;
  8371. }
  8372. }
  8373. // 准备任务数据
  8374. $taskData = [
  8375. 'anime_id' => $anime_id,
  8376. 'uid' => $uid,
  8377. 'cpid' => $cpid,
  8378. 'episode_number' => $episodeNumber,
  8379. 'status' => 'pending',
  8380. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  8381. 'retry_count' => 0,
  8382. 'created_at' => $now,
  8383. 'updated_at' => $now
  8384. ];
  8385. // 创建任务记录
  8386. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  8387. if ($taskId) {
  8388. $createdTasks[] = $episodeNumber;
  8389. }
  8390. }
  8391. if (empty($createdTasks)) {
  8392. if (!empty($skippedTasks)) {
  8393. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  8394. } else {
  8395. Utils::throwError('20003:创建批量生成任务失败');
  8396. }
  8397. }
  8398. return [
  8399. 'anime_id' => $anime_id,
  8400. 'start_episode' => $startEpisodeNumber,
  8401. 'end_episode' => $endEpisodeNumber,
  8402. 'total_episodes' => $generate_episode_number,
  8403. 'created_episodes' => $createdTasks,
  8404. 'skipped_episodes' => $skippedTasks,
  8405. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  8406. "已创建: " . implode(',', $createdTasks) .
  8407. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  8408. ];
  8409. }
  8410. /**
  8411. * 获取批量生成任务状态
  8412. *
  8413. * @param array $data 请求数据
  8414. * @return array 任务状态信息
  8415. */
  8416. public function getBatchGenerationTaskStatus($data) {
  8417. $anime_id = getProp($data, 'anime_id');
  8418. if (!$anime_id) {
  8419. Utils::throwError('20003:anime_id参数缺失');
  8420. }
  8421. // 获取该anime的所有任务
  8422. $tasks = DB::table('mp_batch_episode_generation_details')
  8423. ->where('anime_id', $anime_id)
  8424. ->orderBy('episode_number')
  8425. ->get()
  8426. ->map(function($item) {
  8427. return [
  8428. 'id' => $item->id,
  8429. 'episode_number' => $item->episode_number,
  8430. 'status' => $item->status,
  8431. 'error_message' => $item->error_message,
  8432. 'retry_count' => $item->retry_count,
  8433. 'created_at' => $item->created_at,
  8434. 'updated_at' => $item->updated_at,
  8435. 'completed_at' => $item->completed_at
  8436. ];
  8437. })
  8438. ->toArray();
  8439. if (empty($tasks)) {
  8440. Utils::throwError('20003:该剧集没有批量生成任务');
  8441. }
  8442. // 统计各状态数量
  8443. $totalCount = count($tasks);
  8444. $pendingCount = 0;
  8445. $processingCount = 0;
  8446. $completedCount = 0;
  8447. $failedCount = 0;
  8448. foreach ($tasks as $task) {
  8449. switch ($task['status']) {
  8450. case 'pending':
  8451. $pendingCount++;
  8452. break;
  8453. case 'processing':
  8454. $processingCount++;
  8455. break;
  8456. case 'completed':
  8457. $completedCount++;
  8458. break;
  8459. case 'failed':
  8460. $failedCount++;
  8461. break;
  8462. }
  8463. }
  8464. // 计算进度百分比
  8465. $progress = 0;
  8466. if ($totalCount > 0) {
  8467. $progress = round(($completedCount / $totalCount) * 100, 2);
  8468. }
  8469. // 判断整体状态
  8470. $overallStatus = 'processing';
  8471. if ($completedCount === $totalCount) {
  8472. $overallStatus = 'completed';
  8473. } elseif ($pendingCount === $totalCount) {
  8474. $overallStatus = 'pending';
  8475. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  8476. $overallStatus = 'failed';
  8477. }
  8478. return [
  8479. 'anime_id' => $anime_id,
  8480. 'total_episodes' => $totalCount,
  8481. 'pending_count' => $pendingCount,
  8482. 'processing_count' => $processingCount,
  8483. 'completed_count' => $completedCount,
  8484. 'failed_count' => $failedCount,
  8485. 'progress' => $progress,
  8486. 'overall_status' => $overallStatus,
  8487. 'tasks' => $tasks
  8488. ];
  8489. }
  8490. /**
  8491. * 智能匹配并替换主体和场景名称
  8492. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  8493. *
  8494. * @param array $episode_arr 解析后的剧集数据
  8495. * @param array $extra_roles 强制主体设定(key为主体名称)
  8496. * @param array $extra_scenes 强制场景设定(key为场景名称)
  8497. * @return array 替换后的剧集数据
  8498. */
  8499. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  8500. $replaced_count = 0;
  8501. // 1. 处理主体列表
  8502. if (!empty($episode_arr['roles'])) {
  8503. foreach ($episode_arr['roles'] as &$role) {
  8504. $generated_role_name = $role['role'] ?? '';
  8505. // 跳过旁白
  8506. if ($generated_role_name === '旁白') {
  8507. continue;
  8508. }
  8509. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  8510. if (!isset($extra_roles[$generated_role_name])) {
  8511. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  8512. if ($matched_role) {
  8513. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  8514. $role['role'] = $matched_role;
  8515. $replaced_count++;
  8516. }
  8517. }
  8518. }
  8519. }
  8520. // 2. 处理场景列表
  8521. if (!empty($episode_arr['scenes'])) {
  8522. foreach ($episode_arr['scenes'] as &$scene) {
  8523. $generated_scene_name = $scene['scene'] ?? '';
  8524. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  8525. if (!isset($extra_scenes[$generated_scene_name])) {
  8526. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  8527. if ($matched_scene) {
  8528. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  8529. $scene['scene'] = $matched_scene;
  8530. $replaced_count++;
  8531. }
  8532. }
  8533. }
  8534. }
  8535. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  8536. if (!empty($episode_arr['acts'])) {
  8537. foreach ($episode_arr['acts'] as &$act) {
  8538. if (!empty($act['segments'])) {
  8539. foreach ($act['segments'] as &$segment) {
  8540. if (!empty($segment['segment_content'])) {
  8541. $original_content = $segment['segment_content'];
  8542. $replaced_content = $original_content;
  8543. // 替换场景名 - 在文本中查找并替换
  8544. foreach (array_keys($extra_scenes) as $full_scene_name) {
  8545. // 尝试找到可能的短名称
  8546. $potential_short_names = [];
  8547. // 提取场景名的主要部分(冒号之前)
  8548. if (mb_strpos($full_scene_name, ':') !== false) {
  8549. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8550. $potential_short_names[] = $short_name;
  8551. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  8552. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8553. $potential_short_names[] = $short_name;
  8554. }
  8555. // 替换场景字段中的短名称
  8556. foreach ($potential_short_names as $short_name) {
  8557. if ($short_name !== $full_scene_name) {
  8558. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  8559. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  8560. if ($new_content !== $replaced_content) {
  8561. $replaced_content = $new_content;
  8562. $replaced_count++;
  8563. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  8564. }
  8565. }
  8566. }
  8567. }
  8568. // 替换配音角色名(跳过旁白)
  8569. foreach (array_keys($extra_roles) as $full_role_name) {
  8570. if ($full_role_name === '旁白') {
  8571. continue;
  8572. }
  8573. // 尝试找到可能的短名称
  8574. $potential_short_names = [];
  8575. // 提取角色名的主要部分(短横线之前)
  8576. if (mb_strpos($full_role_name, '-') !== false) {
  8577. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  8578. $potential_short_names[] = $short_name;
  8579. }
  8580. // 替换配音台词中的短名称
  8581. foreach ($potential_short_names as $short_name) {
  8582. if ($short_name !== $full_role_name) {
  8583. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  8584. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  8585. if ($new_content !== $replaced_content) {
  8586. $replaced_content = $new_content;
  8587. $replaced_count++;
  8588. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  8589. }
  8590. }
  8591. }
  8592. }
  8593. // 如果有替换,更新segment_content
  8594. if ($replaced_content !== $original_content) {
  8595. $segment['segment_content'] = $replaced_content;
  8596. }
  8597. }
  8598. }
  8599. }
  8600. }
  8601. }
  8602. if ($replaced_count > 0) {
  8603. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  8604. 'replaced_count' => $replaced_count
  8605. ]);
  8606. }
  8607. return $episode_arr;
  8608. }
  8609. /**
  8610. * 查找匹配的名称
  8611. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  8612. *
  8613. * @param string $generated_name 生成的名称
  8614. * @param array $expected_names 预期的名称列表
  8615. * @return string|null 匹配到的名称,如果没有匹配则返回null
  8616. */
  8617. private function findMatchingName($generated_name, $expected_names) {
  8618. if (empty($generated_name)) {
  8619. return null;
  8620. }
  8621. // 尝试精确匹配
  8622. if (in_array($generated_name, $expected_names)) {
  8623. return $generated_name;
  8624. }
  8625. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  8626. foreach ($expected_names as $expected_name) {
  8627. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  8628. if (mb_strpos($expected_name, $generated_name) === 0) {
  8629. return $expected_name;
  8630. }
  8631. }
  8632. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  8633. // 这样可以处理一些变体,但优先级较低
  8634. foreach ($expected_names as $expected_name) {
  8635. if (mb_strpos($expected_name, $generated_name) !== false) {
  8636. return $expected_name;
  8637. }
  8638. }
  8639. return null;
  8640. }
  8641. /**
  8642. * 重新生成分段剧本
  8643. * @param array $data 包含以下字段:
  8644. * - prompt: string|null 用户修改要求(可选)
  8645. * - template_id: int|null 提示词模板ID(可选)
  8646. * - act_id: int|null 单个片段ID(与episode_id二选一)
  8647. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  8648. * @return array 返回生成结果
  8649. */
  8650. public function regenerateSegmentScript($data) {
  8651. $uid = Site::getUid();
  8652. $prompt = trim((string)getProp($data, 'prompt', ''));
  8653. $template_id = getProp($data, 'template_id', 0);
  8654. $act_id = getProp($data, 'act_id', 0);
  8655. $episode_id = getProp($data, 'episode_id', 0);
  8656. // 验证:prompt和template_id至少提供一个
  8657. if (empty($prompt) && empty($template_id)) {
  8658. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  8659. }
  8660. // 验证:act_id和episode_id二选一
  8661. if (empty($act_id) && empty($episode_id)) {
  8662. Utils::throwError('20003:请提供片段ID或剧集ID');
  8663. }
  8664. if (!empty($act_id) && !empty($episode_id)) {
  8665. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  8666. }
  8667. // 积分余额预检(仅剧集ID模式收费)
  8668. if (!empty($episode_id)) {
  8669. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  8670. }
  8671. // 如果提供了template_id,获取模板提示词
  8672. $template_prompt = '';
  8673. if ($template_id > 0) {
  8674. $template = DB::table('mp_prompt_templates')
  8675. ->where('id', $template_id)
  8676. ->where('is_deleted', 0)
  8677. ->first();
  8678. if (!$template) {
  8679. Utils::throwError('20003:提示词模板不存在或已删除');
  8680. }
  8681. $template_prompt = $template->template_prompt ?? '';
  8682. }
  8683. // 合并用户提示词和模板提示词
  8684. $final_prompt = '';
  8685. if (!empty($template_prompt)) {
  8686. $final_prompt = $template_prompt;
  8687. if (!empty($prompt)) {
  8688. $final_prompt .= "\n\n补充要求:" . $prompt;
  8689. }
  8690. } else {
  8691. $final_prompt = $prompt;
  8692. }
  8693. // 获取需要重新生成的内容参考
  8694. $reference_content = '';
  8695. $target_episode_id = 0;
  8696. $target_anime_id = 0;
  8697. $target_episode_number = 0;
  8698. if ($act_id > 0) {
  8699. // 单个片段模式:获取该片段的内容
  8700. $segment = DB::table('mp_episode_segments')
  8701. ->where('id', $act_id)
  8702. ->first();
  8703. if (!$segment) {
  8704. Utils::throwError('20003:片段不存在');
  8705. }
  8706. $target_episode_id = $segment->episode_id;
  8707. $target_anime_id = $segment->anime_id;
  8708. $target_episode_number = $segment->episode_number;
  8709. $reference_content = $segment->act_content ?? '';
  8710. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8711. } else {
  8712. // 整个剧集模式:获取所有片段的内容
  8713. $segments = DB::table('mp_episode_segments')
  8714. ->where('episode_id', $episode_id)
  8715. ->orderBy('act_number')
  8716. ->get();
  8717. if ($segments->isEmpty()) {
  8718. Utils::throwError('20003:该剧集没有片段数据');
  8719. }
  8720. $target_episode_id = $episode_id;
  8721. $target_anime_id = $segments[0]->anime_id;
  8722. $target_episode_number = $segments[0]->episode_number;
  8723. // 拼接所有片段内容,保留格式用于AI理解
  8724. $act_contents = [];
  8725. foreach ($segments as $seg) {
  8726. $act_number = $seg->act_number;
  8727. $act_content = $seg->act_content ?? '';
  8728. if (!empty($act_content)) {
  8729. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  8730. }
  8731. }
  8732. $reference_content = implode("\n\n", $act_contents);
  8733. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  8734. if ($episode_content) {
  8735. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  8736. }else {
  8737. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8738. }
  8739. }
  8740. if (empty($reference_content)) {
  8741. Utils::throwError('20003:没有可参考的片段内容');
  8742. }
  8743. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  8744. $episode = DB::table('mp_anime_episodes')
  8745. ->where('id', $target_episode_id)
  8746. ->first();
  8747. if (!$episode) {
  8748. Utils::throwError('20003:剧集不存在');
  8749. }
  8750. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  8751. $anime_script_id = getProp($anime, 'script_id');
  8752. $intro = $episode->intro ?? '';
  8753. $art_style = $episode->art_style ?? '';
  8754. $roles = json_decode($episode->roles ?? '[]', true);
  8755. $scenes = json_decode($episode->scenes ?? '[]', true);
  8756. $props = json_decode($episode->props ?? '[]', true);
  8757. // 构建提示词中的主体列表和场景列表参考
  8758. $roles_ref = '';
  8759. if (!empty($roles) && is_array($roles)) {
  8760. $roles_list = [];
  8761. foreach ($roles as $role) {
  8762. $role_name = getProp($role, 'role', '');
  8763. $role_desc = getProp($role, 'description', '');
  8764. $pic_prompt = getProp($role, 'pic_prompt', '');
  8765. $voice_prompt = getProp($role, 'voice_prompt', '');
  8766. if (!empty($role_name)) {
  8767. $role_line = $role_name;
  8768. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  8769. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  8770. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  8771. $roles_list[] = $role_line;
  8772. }
  8773. }
  8774. if (!empty($roles_list)) {
  8775. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  8776. }
  8777. }
  8778. $scenes_ref = '';
  8779. if (!empty($scenes) && is_array($scenes)) {
  8780. $scenes_list = [];
  8781. foreach ($scenes as $scene) {
  8782. $scene_name = getProp($scene, 'scene', '');
  8783. $scene_desc = getProp($scene, 'description', '');
  8784. $pic_prompt = getProp($scene, 'pic_prompt', '');
  8785. if (!empty($scene_name)) {
  8786. $scene_line = $scene_name;
  8787. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  8788. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  8789. $scenes_list[] = $scene_line;
  8790. }
  8791. }
  8792. if (!empty($scenes_list)) {
  8793. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  8794. }
  8795. }
  8796. $props_ref = '';
  8797. if (!empty($props) && is_array($props)) {
  8798. $props_list = [];
  8799. foreach ($props as $prop) {
  8800. $prop_name = getProp($prop, 'prop', '');
  8801. $prop_desc = getProp($prop, 'description', '');
  8802. $pic_prompt = getProp($prop, 'pic_prompt', '');
  8803. if (!empty($prop_name)) {
  8804. $prop_line = $prop_name;
  8805. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  8806. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  8807. $props_list[] = $prop_line;
  8808. }
  8809. }
  8810. if (!empty($props_list)) {
  8811. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  8812. }
  8813. }
  8814. // 构建美术风格参考
  8815. $art_style_ref = '';
  8816. if (!empty($art_style)) {
  8817. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  8818. }
  8819. // 构建内容简介参考
  8820. $intro_ref = '';
  8821. if (!empty($intro)) {
  8822. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  8823. }
  8824. // 构建完整的AI提示词
  8825. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  8826. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  8827. $user_prompt .= $intro_ref;
  8828. $user_prompt .= $art_style_ref;
  8829. $user_prompt .= $reference_content;
  8830. // $user_prompt .= $roles_ref;
  8831. // $user_prompt .= $scenes_ref;
  8832. $system_prompt = "\n\n【强制要求】\n";
  8833. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  8834. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  8835. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  8836. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  8837. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  8838. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  8839. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  8840. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  8841. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  8842. ###分段剧本
  8843. 片段数量:8
  8844. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8845. ##片段1
  8846. 时长:12s
  8847. 分镜1
  8848. 出场角色:刀疤脸
  8849. 场景:边境小镇街道
  8850. 出场道具:酒杯-高脚杯
  8851. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8852. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8853. 配音台词:
  8854. 背景音效:
  8855. 分镜2
  8856. 出场角色:刀疤脸
  8857. 场景:悦来酒馆
  8858. 出场道具:酒杯-高脚杯
  8859. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8860. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8861. 配音台词:
  8862. 背景音效:
  8863. 分镜3
  8864. 出场角色:刀疤脸
  8865. 场景:悦来酒馆
  8866. 出场道具:酒杯-高脚杯
  8867. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8868. 运镜:从中景推向令牌特写。
  8869. 配音台词:
  8870. 背景音效:
  8871. 分镜4
  8872. 出场角色:刀疤脸
  8873. 场景:悦来酒馆
  8874. 出场道具:酒杯-高脚杯
  8875. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8876. 运镜:极速推向酒水溅起的瞬间。
  8877. 配音台词:
  8878. 背景音效:
  8879. 分镜5
  8880. 出场角色:刀疤脸
  8881. 场景:悦来酒馆
  8882. 出场道具:酒杯-高脚杯
  8883. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8884. 运镜:固定机位,利用倾斜构图制造压迫感。
  8885. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8886. 背景音效:";
  8887. // 获取模型配置
  8888. $model = getProp($data, 'model');
  8889. if (!$model) {
  8890. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  8891. }
  8892. // 验证模型是否在可用模型表中
  8893. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8894. $model = 'deepseek-v4-pro';
  8895. }
  8896. // 模型兼容性处理
  8897. $thinkingMode = 'disabled';
  8898. $reasoningEffort = 'high';
  8899. if ($model === 'deepseek-chat') {
  8900. $model = 'deepseek-v4-flash';
  8901. $thinkingMode = 'disabled';
  8902. } elseif ($model === 'deepseek-reasoner') {
  8903. $model = 'deepseek-v4-flash';
  8904. $thinkingMode = 'enabled';
  8905. }
  8906. // 构建消息
  8907. $messages = [
  8908. [
  8909. 'role' => 'system',
  8910. 'content' => $system_prompt
  8911. ],
  8912. [
  8913. 'role' => 'user',
  8914. 'content' => $user_prompt
  8915. ]
  8916. ];
  8917. // dd($messages);
  8918. // 构建请求参数
  8919. $post_data = [
  8920. 'model' => $model,
  8921. 'messages' => $messages,
  8922. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8923. 'frequency_penalty' => 0,
  8924. 'presence_penalty' => 0,
  8925. 'response_format' => ['type' => 'text'],
  8926. 'thinking' => ['type' => $thinkingMode],
  8927. 'stream' => false // 非流式输出
  8928. ];
  8929. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8930. // 调用AI生成新的分段剧本
  8931. try {
  8932. $fullContent = '';
  8933. $usage = [];
  8934. // 根据模型类型选择调用方法
  8935. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8936. // DeepSeek 官方模型使用 DeepSeek API
  8937. $chatResult = $this->chatOnly($post_data);
  8938. } else if (in_array($model, $this->gpt_text_models)) {
  8939. // GPT 模型使用 TokenRouter API
  8940. $chatResult = $this->gpt54ChatOnly($post_data);
  8941. } else {
  8942. // 其他模型使用火山引擎API
  8943. $chatResult = $this->volcEngineChatCompletion($post_data);
  8944. }
  8945. if (is_array($chatResult)) {
  8946. $fullContent = $chatResult['fullContent'] ?? '';
  8947. $usage = $chatResult['usage'] ?? [];
  8948. }
  8949. $generated_content = $fullContent;
  8950. if (empty($generated_content)) {
  8951. Utils::throwError('20003:AI生成内容为空,请重试');
  8952. }
  8953. // 解析生成的内容 - 按片段分割
  8954. $parsed_segments = [];
  8955. // 先在开头添加换行符,确保第1片段也能被正确分割
  8956. $normalizedText = "\n" . $generated_content;
  8957. $parts = preg_split('/\n\s*##/', $normalizedText);
  8958. foreach ($parts as $part) {
  8959. $part = trim($part);
  8960. if (empty($part)) continue;
  8961. // 匹配"片段X"格式
  8962. if (!preg_match('/^片段\d+/', $part)) {
  8963. continue;
  8964. }
  8965. // 分离标题和内容
  8966. $lines = explode("\n", $part, 2);
  8967. $actTitle = trim($lines[0]);
  8968. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  8969. // 解析标题,提取序号
  8970. $actNumber = 0;
  8971. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  8972. $actNumber = intval($segmentTitleMatch[1]);
  8973. } else {
  8974. $actNumber = count($parsed_segments) + 1;
  8975. }
  8976. // 提取时长(仅保留数字)
  8977. $actDuration = 0;
  8978. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  8979. $actDurationStr = trim($actDurationMatch[1]);
  8980. // 提取数字部分(支持整数和小数)
  8981. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  8982. $actDuration = (float)$numMatch[1];
  8983. }
  8984. }
  8985. // 清理act_content:去除时长、旁白音色等非分镜内容行
  8986. // 只保留分镜内容,并确保分镜标记使用【】格式
  8987. $cleaned_content = '';
  8988. $content_lines = explode("\n", $actContent);
  8989. $is_capturing = false; // 标记是否开始捕获分镜内容
  8990. $count = 0;
  8991. foreach ($content_lines as $line) {
  8992. $trimmed_line = trim($line);
  8993. // 跳过时长和旁白音色行
  8994. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  8995. continue;
  8996. }
  8997. // 检测是否是分镜开始
  8998. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  8999. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  9000. $count++;
  9001. $is_capturing = true;
  9002. // 如果没有【】,则添加
  9003. if (!preg_match('/^【/u', $trimmed_line)) {
  9004. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  9005. }
  9006. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  9007. }
  9008. // 如果已经开始捕获,则添加该行
  9009. if ($is_capturing && !empty($trimmed_line)) {
  9010. $cleaned_content .= $trimmed_line."\n";
  9011. }
  9012. }
  9013. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  9014. $parsed_segments[] = [
  9015. 'act_number' => $actNumber,
  9016. 'act_title' => $actTitle,
  9017. 'act_duration' => $actDuration,
  9018. 'act_content' => $cleaned_content,
  9019. ];
  9020. }
  9021. if (empty($parsed_segments)) {
  9022. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  9023. }
  9024. // 收集所有资产名称(角色、场景、道具)
  9025. $product_names = [];
  9026. // 收集角色名称
  9027. if (!empty($roles) && is_array($roles)) {
  9028. foreach ($roles as $role) {
  9029. $role_name = getProp($role, 'role', '');
  9030. if (!empty($role_name)) {
  9031. $product_names[] = $role_name;
  9032. }
  9033. }
  9034. }
  9035. // 收集场景名称
  9036. if (!empty($scenes) && is_array($scenes)) {
  9037. foreach ($scenes as $scene) {
  9038. $scene_name = getProp($scene, 'scene', '');
  9039. if (!empty($scene_name)) {
  9040. $product_names[] = $scene_name;
  9041. }
  9042. }
  9043. }
  9044. // 收集道具名称
  9045. if (!empty($props) && is_array($props)) {
  9046. foreach ($props as $prop) {
  9047. $prop_name = getProp($prop, 'prop', '');
  9048. if (!empty($prop_name)) {
  9049. $product_names[] = $prop_name;
  9050. }
  9051. }
  9052. }
  9053. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  9054. $product_names = array_unique($product_names);
  9055. usort($product_names, function($a, $b) {
  9056. return mb_strlen($b) - mb_strlen($a);
  9057. });
  9058. // 处理每个片段的 act_show_content
  9059. foreach ($parsed_segments as &$segment) {
  9060. $act_content = getProp($segment, 'act_content', '');
  9061. if (empty($act_content)) {
  9062. $segment['act_show_content'] = '';
  9063. continue;
  9064. }
  9065. $processed_content = $act_content;
  9066. // 统一替换所有资产名称为 {资产名} 格式
  9067. // 使用占位符避免嵌套替换问题
  9068. $placeholder_map = [];
  9069. $placeholder_index = 0;
  9070. foreach ($product_names as $product_name) {
  9071. // 转义特殊字符
  9072. $escaped_product = preg_quote($product_name, '/');
  9073. // 检查是否匹配且未被 {} 包裹
  9074. $processed_content = preg_replace_callback(
  9075. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  9076. function($matches) use (&$placeholder_map, &$placeholder_index) {
  9077. // 使用唯一占位符
  9078. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  9079. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  9080. $placeholder_index++;
  9081. return $placeholder;
  9082. },
  9083. $processed_content
  9084. );
  9085. }
  9086. // 将所有占位符替换回实际内容
  9087. foreach ($placeholder_map as $placeholder => $replacement) {
  9088. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  9089. }
  9090. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  9091. $shot_counter = 0;
  9092. $processed_content = preg_replace_callback(
  9093. '/【(?:镜头|分镜)(\d+)】/u',
  9094. function($matches) use (&$shot_counter) {
  9095. $shot_counter++;
  9096. return '【镜头' . $shot_counter . '】';
  9097. },
  9098. $processed_content
  9099. );
  9100. $segment['act_show_content'] = $processed_content;
  9101. }
  9102. unset($segment); // 解除引用
  9103. // 保存到数据库
  9104. $now = date('Y-m-d H:i:s');
  9105. $saved_acts = []; // 用于记录保存后的片段信息
  9106. if ($act_id > 0) {
  9107. // 单个片段模式:更新单条记录
  9108. if (count($parsed_segments) > 0) {
  9109. $new_segment = $parsed_segments[0];
  9110. $update_data = [
  9111. 'act_content' => getProp($new_segment, 'act_content', ''),
  9112. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  9113. 'act_title' => getProp($new_segment, 'act_title', ''),
  9114. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  9115. 'updated_at' => $now,
  9116. ];
  9117. DB::table('mp_episode_segments')
  9118. ->where('id', $act_id)
  9119. ->update($update_data);
  9120. // 获取更新后的记录
  9121. $updated_act = DB::table('mp_episode_segments')
  9122. ->where('id', $act_id)
  9123. ->first();
  9124. if ($updated_act) {
  9125. $saved_acts[] = [
  9126. 'act_id' => $updated_act->id,
  9127. 'act_number' => $updated_act->act_number,
  9128. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  9129. 'act_content' => $updated_act->act_content,
  9130. 'act_show_content' => $updated_act->act_show_content,
  9131. 'video_url' => $updated_act->video_url ?? '',
  9132. 'video_duration' => $updated_act->video_duration ?? 0,
  9133. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  9134. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  9135. ];
  9136. }
  9137. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  9138. }
  9139. } else {
  9140. // 整个剧集模式:删除原有记录并批量保存新记录
  9141. DB::beginTransaction();
  9142. try {
  9143. // 删除原有的所有片段记录
  9144. DB::table('mp_episode_segments')
  9145. ->where('episode_id', $target_episode_id)
  9146. ->delete();
  9147. // 批量插入新的片段记录
  9148. $segments_to_insert = [];
  9149. foreach ($parsed_segments as $index => $segment) {
  9150. $act_number = $index + 1;
  9151. $segments_to_insert[] = [
  9152. 'anime_id' => $target_anime_id,
  9153. 'episode_id' => $target_episode_id,
  9154. 'episode_number' => $target_episode_number,
  9155. 'act_number' => $act_number,
  9156. 'act_title' => getProp($segment, 'act_title', ''),
  9157. 'act_duration' => getProp($segment, 'act_duration', 0),
  9158. 'act_content' => getProp($segment, 'act_content', ''),
  9159. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  9160. 'created_at' => $now,
  9161. 'updated_at' => $now,
  9162. ];
  9163. }
  9164. if (!empty($segments_to_insert)) {
  9165. DB::table('mp_episode_segments')->insert($segments_to_insert);
  9166. }
  9167. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  9168. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  9169. 'anime_id' => $target_anime_id,
  9170. 'episode_id' => $target_episode_id,
  9171. ]);
  9172. DB::commit();
  9173. // 查询保存后的所有片段记录
  9174. $saved_segments = DB::table('mp_episode_segments')
  9175. ->where('episode_id', $target_episode_id)
  9176. ->orderBy('act_number')
  9177. ->get();
  9178. foreach ($saved_segments as $saved_segment) {
  9179. $saved_acts[] = [
  9180. 'act_id' => $saved_segment->id,
  9181. 'act_number' => $saved_segment->act_number,
  9182. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  9183. 'act_content' => $saved_segment->act_content,
  9184. 'act_show_content' => $saved_segment->act_show_content,
  9185. 'video_url' => $saved_segment->video_url ?? '',
  9186. 'video_duration' => $saved_segment->video_duration ?? 0,
  9187. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  9188. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  9189. ];
  9190. }
  9191. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  9192. 'episode_id' => $target_episode_id,
  9193. 'segments_count' => count($segments_to_insert)
  9194. ]);
  9195. } catch (\Exception $e) {
  9196. DB::rollBack();
  9197. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  9198. Utils::throwError('20003:保存失败,请重试');
  9199. }
  9200. }
  9201. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  9202. return [
  9203. 'anime_id' => $target_anime_id,
  9204. 'episode_id' => $target_episode_id,
  9205. 'title' => getProp($episode, 'title', ''),
  9206. 'episode_number' => $target_episode_number,
  9207. 'is_generated' => getProp($episode, 'is_generated', 0),
  9208. 'acts' => $saved_acts,
  9209. ];
  9210. } catch (\Exception $e) {
  9211. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  9212. throw $e;
  9213. }
  9214. }
  9215. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  9216. {
  9217. $episode_arr = [
  9218. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  9219. 'intro' => getProp($script_arr, 'intro'),
  9220. 'art_style' => getProp($script_arr, 'art_style'),
  9221. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  9222. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  9223. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  9224. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  9225. ];
  9226. if (empty($episode_arr['acts'])) {
  9227. $fallback_episode_arr = handleEpisodeContent($fullContent);
  9228. if (!empty($fallback_episode_arr['acts'])) {
  9229. $episode_arr = array_merge($fallback_episode_arr, [
  9230. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  9231. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  9232. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  9233. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  9234. ]);
  9235. }
  9236. }
  9237. // if (!getProp($episode_arr, 'episode_title')) {
  9238. // $episode_title = '';
  9239. // $episodes = getProp($script_arr, 'episodes', []);
  9240. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  9241. // $episode_title = '第1集:' . $episodes[0]['title'];
  9242. // }
  9243. // if (!$episode_title) {
  9244. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  9245. // }
  9246. // $episode_arr['episode_title'] = $episode_title;
  9247. // }
  9248. return $episode_arr;
  9249. }
  9250. private function saveEpisodeVersionData(
  9251. int $anime_id,
  9252. int $episode_number,
  9253. array $episode_arr,
  9254. array $existing_roles,
  9255. array $existing_scenes,
  9256. array $existing_props,
  9257. $current_episode,
  9258. $base_episode,
  9259. bool $is_regenerate_version,
  9260. string $content,
  9261. string $now,
  9262. array $ref_products = []
  9263. ): array {
  9264. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  9265. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  9266. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  9267. // 过滤掉关键字段为空的条目
  9268. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  9269. return !empty($item['role'] ?? null);
  9270. }));
  9271. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  9272. return !empty($item['scene'] ?? null);
  9273. }));
  9274. $merged_props = array_values(array_filter($generated_props, function ($item) {
  9275. return !empty($item['prop'] ?? null);
  9276. }));
  9277. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  9278. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  9279. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  9280. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9281. $ace_mode = getProp($anime, 'ace_mode');
  9282. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  9283. $global_roles = json_decode(getProp($anime, 'roles'), true);
  9284. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  9285. $global_roles = is_array($global_roles) ? $global_roles : [];
  9286. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  9287. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  9288. $art_style_type = getProp($anime, 'art_style_type');
  9289. // 检查并创建 roles 的图片生成任务
  9290. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  9291. // 检查并创建 scenes 的图片生成任务
  9292. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  9293. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  9294. if ($arr && is_array($arr)) {
  9295. $merged_roles = $arr['roles'];
  9296. $merged_scenes = $arr['scenes'];
  9297. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  9298. }
  9299. // 确保数据是数组类型
  9300. if (!is_array($merged_roles)) {
  9301. dLog('deepseek')->error('merged_roles不是数组类型', [
  9302. 'type' => gettype($merged_roles),
  9303. 'value' => $merged_roles
  9304. ]);
  9305. $merged_roles = [];
  9306. }
  9307. if (!is_array($merged_scenes)) {
  9308. dLog('deepseek')->error('merged_scenes不是数组类型', [
  9309. 'type' => gettype($merged_scenes),
  9310. 'value' => $merged_scenes
  9311. ]);
  9312. $merged_scenes = [];
  9313. }
  9314. if (!is_array($merged_props)) {
  9315. dLog('deepseek')->error('merged_props不是数组类型', [
  9316. 'type' => gettype($merged_props),
  9317. 'value' => $merged_props
  9318. ]);
  9319. $merged_props = [];
  9320. }
  9321. // 同步新出现的主体和场景到全局
  9322. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  9323. $role_arr = [];
  9324. foreach ($merged_roles as $item) {
  9325. $role_arr[$item['role']] = $item;
  9326. }
  9327. $version_count = DB::table('mp_anime_episodes')
  9328. ->where('anime_id', $anime_id)
  9329. ->where('episode_number', $episode_number)
  9330. ->count('id');
  9331. $episode = [
  9332. 'anime_id' => $anime_id,
  9333. 'episode_number' => $episode_number,
  9334. 'title' => getProp($episode_arr, 'episode_title'),
  9335. 'content' => $content,
  9336. 'intro' => getProp($episode_arr, 'intro'),
  9337. 'art_style' => getProp($episode_arr, 'art_style'),
  9338. 'roles' => json_encode($merged_roles, 256),
  9339. 'scenes' => json_encode($merged_scenes, 256),
  9340. 'props' => json_encode($merged_props, 256),
  9341. 'generate_status' => '待执行',
  9342. 'generate_at' => $now,
  9343. 'is_default' => 1,
  9344. 'updated_at' => $now,
  9345. ];
  9346. $del_flag = false;
  9347. if ($is_regenerate_version) {
  9348. DB::table('mp_anime_episodes')
  9349. ->where('anime_id', $anime_id)
  9350. ->where('episode_number', $episode_number)
  9351. ->update(['is_default' => 0, 'updated_at' => $now]);
  9352. $episode['sequence'] = $version_count + 1;
  9353. $episode['created_at'] = $now;
  9354. $episode['cpid'] = Site::getCpid();
  9355. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9356. if (!$episode_id) {
  9357. Utils::throwError('20003:创建剧集版本失败');
  9358. }
  9359. } else {
  9360. $target_episode = $current_episode ?: $base_episode;
  9361. if ($target_episode) {
  9362. $episode_id = getProp($target_episode, 'id');
  9363. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  9364. DB::table('mp_anime_episodes')
  9365. ->where('anime_id', $anime_id)
  9366. ->where('episode_number', $episode_number)
  9367. ->where('id', '<>', $episode_id)
  9368. ->update(['is_default' => 0, 'updated_at' => $now]);
  9369. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  9370. if ($boolen === false) {
  9371. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  9372. Utils::throwError('20003:分集内容保存失败');
  9373. }
  9374. $del_flag = true;
  9375. } else {
  9376. DB::table('mp_anime_episodes')
  9377. ->where('anime_id', $anime_id)
  9378. ->where('episode_number', $episode_number)
  9379. ->update(['is_default' => 0, 'updated_at' => $now]);
  9380. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  9381. $episode['created_at'] = $now;
  9382. $episode['cpid'] = Site::getCpid();
  9383. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9384. if (!$episode_id) {
  9385. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  9386. Utils::throwError('20003:分集内容保存失败');
  9387. }
  9388. }
  9389. }
  9390. $segments = [];
  9391. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9392. // 如果是第2集及以后,获取上一集的主体音色数据
  9393. $previous_roles_voice = [];
  9394. if ($episode_number >= 2) {
  9395. $previous_episode = DB::table('mp_anime_episodes')
  9396. ->where('anime_id', $anime_id)
  9397. ->where('episode_number', $episode_number - 1)
  9398. ->where('is_default', 1)
  9399. ->first();
  9400. if ($previous_episode) {
  9401. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  9402. if (is_array($previous_roles)) {
  9403. foreach ($previous_roles as $prev_role) {
  9404. $role_name = getProp($prev_role, 'role');
  9405. if ($role_name) {
  9406. $previous_roles_voice[$role_name] = [
  9407. 'voice_name' => getProp($prev_role, 'voice_name'),
  9408. 'voice_type' => getProp($prev_role, 'voice_type'),
  9409. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  9410. ];
  9411. $voice_prompt = getProp($prev_role, 'voice_prompt');
  9412. if ($voice_prompt) {
  9413. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  9414. }
  9415. }
  9416. }
  9417. }
  9418. }
  9419. }
  9420. // 将继承的音色数据同步到当前集的主体列表
  9421. if (!empty($previous_roles_voice)) {
  9422. foreach ($merged_roles as &$role) {
  9423. $role_name = getProp($role, 'role');
  9424. if ($role_name && isset($previous_roles_voice[$role_name])) {
  9425. // 强制继承上一集的音色数据
  9426. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  9427. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  9428. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  9429. // 如果上一集有 voice_prompt 则继承,否则跳过
  9430. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  9431. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  9432. }
  9433. }
  9434. }
  9435. unset($role); // 解除引用
  9436. // 更新 role_arr 以便后续使用
  9437. $role_arr = [];
  9438. foreach ($merged_roles as $item) {
  9439. $role_arr[$item['role']] = $item;
  9440. }
  9441. }
  9442. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  9443. $emotion_list = array_flip($emotion_list);
  9444. foreach ($acts as $act) {
  9445. $act_segments = getProp($act, 'segments', []);
  9446. if (!is_array($act_segments)) {
  9447. continue;
  9448. }
  9449. if ((int)$ace_mode === 1) {
  9450. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  9451. $merged_parts = [];
  9452. foreach ($act_segments as $seg) {
  9453. $seg_num = getProp($seg, 'segment_number');
  9454. $seg_content = getProp($seg, 'segment_content');
  9455. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  9456. }
  9457. $act_content = implode("\n", $merged_parts);
  9458. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9459. $segments[] = [
  9460. 'anime_id' => $anime_id,
  9461. 'episode_id' => $episode_id,
  9462. 'episode_number' => $episode_number,
  9463. 'act_number' => getProp($act, 'act_number'),
  9464. 'act_title' => getProp($act, 'act_title'),
  9465. 'act_duration' => getProp($act, 'act_duration'),
  9466. 'act_content' => $act_content,
  9467. 'created_at' => $now,
  9468. 'updated_at' => $now
  9469. ];
  9470. } else {
  9471. foreach ($act_segments as $segment) {
  9472. $voice_actor = getProp($segment, 'voice_actor');
  9473. // 优先从上一集继承音色数据
  9474. $timbre_info = [];
  9475. if (isset($previous_roles_voice[$voice_actor])) {
  9476. // 从上一集继承音色数据
  9477. $timbre_info = $previous_roles_voice[$voice_actor];
  9478. } elseif (isset($role_arr[$voice_actor])) {
  9479. // 使用当前集的主体音色数据
  9480. $timbre_info = $role_arr[$voice_actor];
  9481. }
  9482. $voice_type = getProp($timbre_info, 'voice_type');
  9483. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  9484. if ($timbre_emotion) {
  9485. $timbre_emotion = explode(',', $timbre_emotion);
  9486. } else {
  9487. $timbre_emotion = [];
  9488. }
  9489. $emotion = getProp($segment, 'emotion', '中性');
  9490. if (!in_array($emotion, $timbre_emotion)) {
  9491. $emotion = '中性';
  9492. }
  9493. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  9494. $segments[] = [
  9495. 'anime_id' => $anime_id,
  9496. 'episode_id' => $episode_id,
  9497. 'episode_number' => $episode_number,
  9498. 'act_number' => getProp($act, 'act_number'),
  9499. 'act_title' => getProp($act, 'act_title'),
  9500. 'act_duration' => getProp($act, 'act_duration'),
  9501. 'segment_id' => getProp($segment, 'segment_id'),
  9502. 'segment_number' => getProp($segment, 'segment_number'),
  9503. 'segment_content' => getProp($segment, 'segment_content'),
  9504. 'description' => getProp($segment, 'description'),
  9505. 'composition' => getProp($segment, 'composition'),
  9506. 'camera_movement' => getProp($segment, 'camera_movement'),
  9507. 'voice_actor' => $voice_actor,
  9508. 'dialogue' => getProp($segment, 'dialogue'),
  9509. 'frame_type' => getProp($segment, 'frame_type'),
  9510. 'scene' => getProp($segment, 'scene'),
  9511. 'characters' => getProp($segment, 'characters'),
  9512. 'tail_frame' => getProp($segment, 'tail_frame'),
  9513. 'voice_name' => getProp($timbre_info, 'voice_name'),
  9514. 'voice_type' => $voice_type,
  9515. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  9516. 'emotion' => $emotion,
  9517. 'emotion_type' => $emotion_type,
  9518. 'gender' => getProp($segment, 'gender', '0'),
  9519. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  9520. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  9521. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  9522. 'pitch' => getProp($segment, 'pitch', 0),
  9523. 'created_at' => $now,
  9524. 'updated_at' => $now
  9525. ];
  9526. }
  9527. }
  9528. }
  9529. if ($segments) {
  9530. if ($del_flag) {
  9531. DB::table('mp_episode_segments')
  9532. ->where('anime_id', $anime_id)
  9533. ->where('episode_id', $episode_id)
  9534. ->delete();
  9535. }
  9536. $boolen = DB::table('mp_episode_segments')->insert($segments);
  9537. if (!$boolen) {
  9538. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  9539. Utils::throwError('20003:分镜内容保存失败');
  9540. }
  9541. }
  9542. dLog('deepseek')->info('segments', $segments);
  9543. // ace_mode=1: acts 返回值按合并格式调整
  9544. if ((int)$ace_mode === 1) {
  9545. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  9546. $act_map = [];
  9547. foreach ($table_act_data as $item) {
  9548. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  9549. }
  9550. $restructured_acts = [];
  9551. foreach ($acts as $act) {
  9552. $act_segments = getProp($act, 'segments', []);
  9553. if (!is_array($act_segments)) {
  9554. continue;
  9555. }
  9556. $merged_parts = [];
  9557. foreach ($act_segments as $seg) {
  9558. $seg_num = getProp($seg, 'segment_number');
  9559. $seg_content = getProp($seg, 'segment_content');
  9560. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  9561. }
  9562. $act_content = implode("\n", $merged_parts);
  9563. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9564. $restructured_acts[] = [
  9565. 'anime_id' => $anime_id,
  9566. 'episode_id' => $episode_id,
  9567. 'episode_number' => $episode_number,
  9568. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  9569. 'act_number' => getProp($act, 'act_number'),
  9570. 'act_title' => getProp($act, 'act_title'),
  9571. 'act_duration' => getProp($act, 'act_duration'),
  9572. 'act_content' => $act_content,
  9573. 'created_at' => $now,
  9574. 'updated_at' => $now,
  9575. ];
  9576. }
  9577. $acts = $restructured_acts;
  9578. }
  9579. $episode['episode_id'] = $episode_id;
  9580. $episode['roles'] = $merged_roles;
  9581. $episode['scenes'] = $merged_scenes;
  9582. $episode['props'] = $merged_props;
  9583. $episode['acts'] = $acts;
  9584. return [
  9585. 'episode' => $episode,
  9586. 'episode_id' => $episode_id,
  9587. 'merged_roles' => $merged_roles,
  9588. 'merged_scenes' => $merged_scenes,
  9589. 'merged_props' => $merged_props,
  9590. ];
  9591. }
  9592. private function buildEpisodeItemContent(array $items, string $nameKey): string
  9593. {
  9594. $content = '';
  9595. foreach ($items as $item) {
  9596. $name = trim((string)getProp($item, $nameKey));
  9597. if ($name === '' || $name === '旁白') {
  9598. continue;
  9599. }
  9600. $description = trim((string)getProp($item, 'description'));
  9601. $content .= $name . ': ' . $description;
  9602. if ($nameKey == 'role') {
  9603. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9604. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9605. $voice_name = trim(getProp($item, 'voice_name'));
  9606. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9607. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  9608. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9609. }else {
  9610. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9611. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9612. }
  9613. $content .= "\n";
  9614. }
  9615. return trim($content);
  9616. }
  9617. private function getEpisodeChatContent($animeId, $sequence, $content) {
  9618. if ((int)$sequence <= 0) {
  9619. return [];
  9620. }
  9621. $origin_content = '';
  9622. if ($content) {
  9623. $origin_content = '本集剧情内容:'.$content;
  9624. }else {
  9625. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  9626. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  9627. }
  9628. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  9629. // 获取分集信息
  9630. $episode = DB::table('mp_anime_episodes')
  9631. ->where('anime_id', $animeId)
  9632. ->where('episode_number', $sequence)
  9633. ->where('is_default', 1)
  9634. ->first();
  9635. if (!$episode) {
  9636. return [];
  9637. }
  9638. $episode_id = getProp($episode, 'id');
  9639. $episode_number = getProp($episode, 'episode_number');
  9640. $title = getProp($episode, 'title');
  9641. $intro = getProp($episode, 'intro');
  9642. $art_style = getProp($episode, 'art_style');
  9643. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9644. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9645. // 组装纯文本内容
  9646. $content = '';
  9647. // 添加分集标题和梗概
  9648. $content .= "###第{$episode_number}集:{$title}\n\n";
  9649. $content .= "###故事梗概\n";
  9650. $content .= trim($intro) . "\n\n";
  9651. // 添加美术风格
  9652. $content .= "###美术风格\n";
  9653. $content .= trim($art_style) . "\n\n";
  9654. // 添加主体列表
  9655. $content .= "###主体列表\n";
  9656. $pangbai_voice_prompt = "";
  9657. foreach ($roles as $role) {
  9658. $name = getProp($role, 'role');
  9659. $description = getProp($role, 'description');
  9660. $pic_prompt = getProp($role, 'pic_prompt');
  9661. $voice_prompt = getProp($role, 'voice_prompt');
  9662. $voice_name = getProp($role, 'voice_name');
  9663. $content .= "{$name}: {$description}";
  9664. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9665. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9666. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9667. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  9668. $content .= "\n";
  9669. }
  9670. $content .= "\n";
  9671. // 添加场景列表
  9672. $content .= "###场景列表\n";
  9673. foreach ($scenes as $scene) {
  9674. $name = getProp($scene, 'scene');
  9675. $description = getProp($scene, 'description');
  9676. $pic_prompt = getProp($scene, 'pic_prompt');
  9677. $content .= "{$name}: {$description}";
  9678. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9679. $content .= "\n";
  9680. }
  9681. $content .= "\n";
  9682. // 获取分镜信息
  9683. $segments = DB::table('mp_episode_segments')
  9684. ->where('anime_id', $animeId)
  9685. ->where('episode_id', $episode_id)
  9686. ->orderBy('segment_number')
  9687. ->get();
  9688. if ($segments && count($segments) > 0) {
  9689. if ((int)$ace_mode === 1) {
  9690. $content .= "###分段剧本\n";
  9691. // 获取片段数量
  9692. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  9693. $content .= "片段数量:{$act_count}\n";
  9694. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  9695. $content .= "\n";
  9696. }else {
  9697. $content .= "###分镜剧本\n";
  9698. }
  9699. // 按幕分组
  9700. $currentAct = null;
  9701. foreach ($segments as $segment) {
  9702. $act_number = getProp($segment, 'act_number');
  9703. $act_title = getProp($segment, 'act_title');
  9704. $act_duration = getProp($segment, 'act_duration');
  9705. $segment_number = getProp($segment, 'segment_number');
  9706. $segment_content = getProp($segment, 'segment_content');
  9707. $scene_description = getProp($segment, 'scene_description');
  9708. $scene_name = getProp($segment, 'scene_name');
  9709. $composition = getProp($segment, 'composition');
  9710. $camera_movement = getProp($segment, 'camera_movement');
  9711. $voice_type = getProp($segment, 'voice_type');
  9712. $characters = getProp($segment, 'characters');
  9713. $dialogue = getProp($segment, 'dialogue');
  9714. $frame_type = getProp($segment, 'frame_type');
  9715. $tail_frame_description = getProp($segment, 'tail_frame_description');
  9716. // 判断是否是全能模式
  9717. if ((int)$ace_mode === 1) { // 全能模式
  9718. // 如果是新的分段,添加分段标题
  9719. if ($act_number !== $currentAct) {
  9720. $currentAct = $act_number;
  9721. $content .= "##{$act_title}\n";
  9722. $content .= "时长:{$act_duration}s\n";
  9723. }
  9724. }else {
  9725. // 如果是新的幕,添加幕标题
  9726. if ($act_number !== $currentAct) {
  9727. $currentAct = $act_number;
  9728. $content .= "##第{$act_number}幕:{$scene_name}\n";
  9729. }
  9730. }
  9731. // 添加分镜信息
  9732. $content .= "分镜{$segment_number}\n";
  9733. $content .= "分镜内容:\n{$segment_content}\n";
  9734. // $content .= "画面描述:{$scene_description}\n";
  9735. // $content .= "场景:{$scene_name}\n";
  9736. // $content .= "构图设计:{$composition}\n";
  9737. // $content .= "运镜调度:{$camera_movement}\n";
  9738. // if (!empty($voice_type)) {
  9739. // $content .= "配音角色:{$voice_type}\n";
  9740. // }
  9741. // if (!empty($characters)) {
  9742. // $content .= "出镜角色:{$characters}\n";
  9743. // }
  9744. // if (!empty($dialogue)) {
  9745. // $content .= "台词内容:\"{$dialogue}\"\n";
  9746. // }
  9747. // $content .= "画面类型:{$frame_type}\n";
  9748. // $content .= "尾帧描述:{$tail_frame_description}\n";
  9749. $content .= "\n";
  9750. }
  9751. }
  9752. $content = trim($content);
  9753. if($content) $content = "上集剧本内容:\n{$content}";
  9754. return [
  9755. [
  9756. 'role' => 'user',
  9757. 'content' => $origin_content
  9758. ],
  9759. [
  9760. 'role' => 'assistant',
  9761. 'content' => $content
  9762. ]
  9763. ];
  9764. }
  9765. private function getEpisodeChatMessages($animeId, $sequence): array
  9766. {
  9767. if ((int)$sequence <= 0) {
  9768. return [];
  9769. }
  9770. return DB::table('mp_anime_records')
  9771. ->where('anime_id', $animeId)
  9772. ->where('sequence', $sequence)
  9773. ->where('episode_id', '>', 0)
  9774. ->select('role', 'content')
  9775. ->orderBy('created_at')
  9776. ->orderBy('id')
  9777. ->get()
  9778. ->map(function ($value) {
  9779. return (array)$value;
  9780. })
  9781. ->toArray();
  9782. }
  9783. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  9784. {
  9785. $existingMap = [];
  9786. foreach ($existingItems as $item) {
  9787. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9788. if ($itemKey === '') {
  9789. continue;
  9790. }
  9791. $existingMap[$itemKey] = $item;
  9792. }
  9793. if (!$generatedItems) {
  9794. return array_values($existingItems);
  9795. }
  9796. $merged = [];
  9797. foreach ($generatedItems as $item) {
  9798. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9799. if ($itemKey === '') {
  9800. continue;
  9801. }
  9802. if (isset($existingMap[$itemKey])) {
  9803. if (trim((string)getProp($item, 'description')) === '') {
  9804. $merged[] = $existingMap[$itemKey];
  9805. continue;
  9806. }
  9807. // 检查内容是否发生变化
  9808. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  9809. if (!$isChanged) {
  9810. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  9811. $mergedItem = [
  9812. $nameKey => trim((string)getProp($item, $nameKey)),
  9813. 'description' => trim((string)getProp($item, 'description')),
  9814. ];
  9815. // 如果有 pic_prompt,添加到合并项中
  9816. $picPrompt = getProp($item, 'pic_prompt');
  9817. if (!empty($picPrompt)) {
  9818. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9819. }
  9820. // 继承现有项的 URL
  9821. $existingUrl = getProp($existingMap[$itemKey], 'url');
  9822. if (!empty($existingUrl)) {
  9823. $mergedItem['url'] = $existingUrl;
  9824. }
  9825. // 继承现有项的 task_id
  9826. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  9827. if (!empty($existingTaskId)) {
  9828. $mergedItem['task_id'] = $existingTaskId;
  9829. }
  9830. // 继承现有项的 task_status
  9831. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  9832. if (!empty($existingTaskStatus)) {
  9833. $mergedItem['task_status'] = $existingTaskStatus;
  9834. }
  9835. // 保留生成项的音色字段
  9836. $voiceName = getProp($item, 'voice_name');
  9837. if (!empty($voiceName)) {
  9838. $mergedItem['voice_name'] = $voiceName;
  9839. }
  9840. $voiceType = getProp($item, 'voice_type');
  9841. if (!empty($voiceType)) {
  9842. $mergedItem['voice_type'] = $voiceType;
  9843. }
  9844. $audioUrl = getProp($item, 'voice_audio_url');
  9845. if (!empty($audioUrl)) {
  9846. $mergedItem['voice_audio_url'] = $audioUrl;
  9847. }
  9848. $merged[] = $mergedItem;
  9849. } else {
  9850. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  9851. $mergedItem = [
  9852. $nameKey => trim((string)getProp($item, $nameKey)),
  9853. 'description' => trim((string)getProp($item, 'description')),
  9854. ];
  9855. // 如果有 pic_prompt,添加到合并项中
  9856. $picPrompt = getProp($item, 'pic_prompt');
  9857. if (!empty($picPrompt)) {
  9858. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9859. }
  9860. // 保留生成项的音色字段
  9861. $voiceName = getProp($item, 'voice_name');
  9862. if (!empty($voiceName)) {
  9863. $mergedItem['voice_name'] = $voiceName;
  9864. }
  9865. $voiceType = getProp($item, 'voice_type');
  9866. if (!empty($voiceType)) {
  9867. $mergedItem['voice_type'] = $voiceType;
  9868. }
  9869. $audioUrl = getProp($item, 'voice_audio_url');
  9870. if (!empty($audioUrl)) {
  9871. $mergedItem['voice_audio_url'] = $audioUrl;
  9872. }
  9873. // 不继承 URL、task_id 和 task_status(重置状态)
  9874. $merged[] = $mergedItem;
  9875. }
  9876. } else {
  9877. // 新增项,保留生成项的所有字段
  9878. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  9879. }
  9880. }
  9881. return $merged ?: array_values($existingItems);
  9882. }
  9883. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  9884. {
  9885. $resetItem = [
  9886. $nameKey => trim((string)getProp($item, $nameKey)),
  9887. 'description' => trim((string)getProp($item, 'description')),
  9888. ];
  9889. // 保留指定的字段
  9890. foreach ($preserveFields as $field) {
  9891. $value = getProp($item, $field);
  9892. if (!empty($value)) {
  9893. $resetItem[$field] = $value;
  9894. }
  9895. }
  9896. return $resetItem;
  9897. }
  9898. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  9899. {
  9900. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  9901. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  9902. if ($existingKey !== $generatedKey) {
  9903. return true;
  9904. }
  9905. // 比较 description 是否变化
  9906. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  9907. return true;
  9908. }
  9909. // 比较 pic_prompt 是否变化
  9910. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  9911. }
  9912. private function normalizeEpisodeResourceKey($value): string
  9913. {
  9914. $value = trim((string)$value);
  9915. if ($value === '') {
  9916. return '';
  9917. }
  9918. return strtolower((string)preg_replace('/\s+/u', '', $value));
  9919. }
  9920. // 生成全局角色图片
  9921. private function batchSetGlobalRoleImg($data, $is_force=false) {
  9922. $anime_id = getProp($data, 'anime_id');
  9923. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9924. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9925. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9926. $art_style = getProp($anime, 'art_style');
  9927. $update_flag = false;
  9928. foreach ($roles as &$role) {
  9929. $role_name = getProp($role, 'role');
  9930. if ($role_name == '旁白') continue;
  9931. // 优先使用 pic_prompt,如果没有则使用 description
  9932. $pic_prompt = getProp($role, 'pic_prompt');
  9933. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9934. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9935. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9936. // 参考图地址
  9937. $ref_img_url = getProp($role, 'url');
  9938. if (!$is_force && $ref_img_url) continue;
  9939. $update_flag = true;
  9940. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9941. try {
  9942. $params = [
  9943. 'prompt' => $description,
  9944. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  9945. 'ref_img_urls' => []
  9946. ];
  9947. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9948. $task_id = $task->id;
  9949. if (!$task_id) {
  9950. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  9951. }
  9952. $role['task_id'] = $task_id;
  9953. $role['task_status'] = 'processing';
  9954. } catch (\Exception $e) {
  9955. Utils::throwError("20003:" . $e->getMessage());
  9956. }
  9957. }
  9958. if (!$update_flag) return true;
  9959. // 保存角色信息
  9960. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9961. 'roles' => json_encode($roles, 256),
  9962. 'generate_status' => '执行中',
  9963. 'generate_at' => date('Y-m-d H:i:s'),
  9964. 'updated_at' => date('Y-m-d H:i:s')
  9965. ]);
  9966. if (!$boolen) {
  9967. Utils::throwError('20003:保存角色信息失败');
  9968. }
  9969. return $boolen;
  9970. }
  9971. // 生成全局场景图片
  9972. private function batchSetGlobalSceneImg($data, $is_force=false) {
  9973. $anime_id = getProp($data, 'anime_id');
  9974. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9975. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9976. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9977. $art_style = getProp($anime, 'art_style');
  9978. $update_flag = false;
  9979. foreach ($scenes as &$scene) {
  9980. $scene_name = getProp($scene, 'scene');
  9981. // 优先使用 pic_prompt,如果没有则使用 description
  9982. $pic_prompt = getProp($scene, 'pic_prompt');
  9983. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  9984. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  9985. // 参考图地址
  9986. $ref_img_url = getProp($scene, 'url');
  9987. if (!$is_force && $ref_img_url) continue;
  9988. $update_flag = true;
  9989. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9990. try {
  9991. $params = [
  9992. 'prompt' => $description,
  9993. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  9994. 'ref_img_urls' => []
  9995. ];
  9996. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9997. $task_id = $task->id;
  9998. if (!$task_id) {
  9999. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  10000. }
  10001. $scene['task_id'] = $task_id;
  10002. $scene['task_status'] = 'processing';
  10003. } catch (\Exception $e) {
  10004. Utils::throwError("20003:" . $e->getMessage());
  10005. }
  10006. }
  10007. if (!$update_flag) return true;
  10008. // 保存角色信息
  10009. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  10010. 'scenes' => json_encode($scenes, 256),
  10011. 'generate_status' => '执行中',
  10012. 'generate_at' => date('Y-m-d H:i:s'),
  10013. 'updated_at' => date('Y-m-d H:i:s')
  10014. ]);
  10015. if (!$boolen) {
  10016. Utils::throwError('20003:保存角色信息失败');
  10017. }
  10018. return $boolen;
  10019. }
  10020. // 生成分镜主体、场景和道具图片
  10021. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  10022. $character_prefix = '';
  10023. $scene_prefix = '';
  10024. $prop_prefix = '';
  10025. if ($art_style_type) {
  10026. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  10027. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  10028. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  10029. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  10030. }
  10031. $update_flag = false;
  10032. // 获取上一集的roles、scenes和props数据
  10033. $prev_roles = [];
  10034. $prev_scenes = [];
  10035. $prev_props = [];
  10036. if ($episode_number > 1) {
  10037. $prev_episode = DB::table('mp_anime_episodes')
  10038. ->where('anime_id', $anime_id)
  10039. ->where('episode_number', $episode_number - 1)
  10040. ->where('is_default', 1)
  10041. ->first();
  10042. if ($prev_episode) {
  10043. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  10044. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  10045. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  10046. dLog('deepseek')->info("获取上一集数据成功", [
  10047. 'anime_id' => $anime_id,
  10048. 'prev_episode_number' => $episode_number - 1,
  10049. 'prev_roles_count' => count($prev_roles),
  10050. 'prev_scenes_count' => count($prev_scenes),
  10051. 'prev_props_count' => count($prev_props)
  10052. ]);
  10053. }
  10054. }
  10055. // 处理角色图片生成
  10056. foreach ($roles as &$role) {
  10057. $role_name = getProp($role, 'role');
  10058. if ($role_name == '旁白') continue;
  10059. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  10060. if (isset($ref_products[$role_name])) {
  10061. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  10062. if ($role['url']) continue;
  10063. }
  10064. $role_description = getProp($role, 'description');
  10065. $role_pic_prompt = getProp($role, 'pic_prompt');
  10066. $role_url = getProp($role, 'url');
  10067. // 检查是否可以从上一集继承
  10068. $inherited = false;
  10069. if (!$is_force && !empty($prev_roles)) {
  10070. foreach ($prev_roles as $prev_role) {
  10071. $prev_role_name = getProp($prev_role, 'role');
  10072. $prev_description = getProp($prev_role, 'description');
  10073. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  10074. $prev_url = getProp($prev_role, 'url');
  10075. $prev_task_id = getProp($prev_role, 'task_id');
  10076. $prev_task_status = getProp($prev_role, 'task_status');
  10077. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  10078. if ($role_name == $prev_role_name
  10079. && $role_description == $prev_description
  10080. && $role_pic_prompt == $prev_pic_prompt
  10081. && !empty($prev_url)) {
  10082. $role['task_id'] = $prev_task_id;
  10083. $role['task_status'] = $prev_task_status;
  10084. $role['url'] = $prev_url;
  10085. $inherited = true;
  10086. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  10087. 'anime_id' => $anime_id,
  10088. 'episode_number' => $episode_number,
  10089. 'task_id' => $prev_task_id,
  10090. 'url' => $prev_url
  10091. ]);
  10092. break;
  10093. }
  10094. }
  10095. }
  10096. // 如果已继承或已有url,跳过生成
  10097. if ($inherited || (!$is_force && $role_url)) {
  10098. continue;
  10099. }
  10100. // 优先使用 pic_prompt,如果没有则使用 description
  10101. $pic_prompt = getProp($role, 'pic_prompt');
  10102. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  10103. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10104. $update_flag = true;
  10105. // 调用AIImageGenerationService的生成图片任务接口
  10106. try {
  10107. $params = [
  10108. 'prompt' => $description,
  10109. 'ref_img_urls' => []
  10110. ];
  10111. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10112. $task_id = $task->id;
  10113. if (!$task_id) {
  10114. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  10115. continue; // 不中断,继续处理其他角色
  10116. }
  10117. $role['task_id'] = $task_id;
  10118. $role['task_status'] = 'processing';
  10119. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  10120. 'anime_id' => $anime_id,
  10121. 'episode_number' => $episode_number,
  10122. 'task_id' => $task_id
  10123. ]);
  10124. } catch (\Exception $e) {
  10125. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  10126. // 不抛出异常,继续处理其他角色
  10127. }
  10128. }
  10129. // 处理场景图片生成
  10130. foreach ($scenes as &$scene) {
  10131. $scene_name = getProp($scene, 'scene');
  10132. $scene_description = getProp($scene, 'description');
  10133. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  10134. $scene_url = getProp($scene, 'url');
  10135. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  10136. if (isset($ref_products[$scene_name])) {
  10137. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  10138. if ($scene['url']) continue;
  10139. }
  10140. // 检查是否可以从上一集继承
  10141. $inherited = false;
  10142. if (!$is_force && !empty($prev_scenes)) {
  10143. foreach ($prev_scenes as $prev_scene) {
  10144. $prev_scene_name = getProp($prev_scene, 'scene');
  10145. $prev_description = getProp($prev_scene, 'description');
  10146. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  10147. $prev_url = getProp($prev_scene, 'url');
  10148. $prev_task_id = getProp($prev_scene, 'task_id');
  10149. $prev_task_status = getProp($prev_scene, 'task_status');
  10150. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  10151. if ($scene_name == $prev_scene_name
  10152. && $scene_description == $prev_description
  10153. && $scene_pic_prompt == $prev_pic_prompt
  10154. && !empty($prev_url)) {
  10155. $scene['task_id'] = $prev_task_id;
  10156. $scene['task_status'] = $prev_task_status;
  10157. $scene['url'] = $prev_url;
  10158. $inherited = true;
  10159. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  10160. 'anime_id' => $anime_id,
  10161. 'episode_number' => $episode_number,
  10162. 'task_id' => $prev_task_id,
  10163. 'url' => $prev_url
  10164. ]);
  10165. break;
  10166. }
  10167. }
  10168. }
  10169. // 如果已继承或已有url,跳过生成
  10170. if ($inherited || (!$is_force && $scene_url)) {
  10171. continue;
  10172. }
  10173. // 优先使用 pic_prompt,如果没有则使用 description
  10174. $pic_prompt = getProp($scene, 'pic_prompt');
  10175. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  10176. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10177. $update_flag = true;
  10178. // 调用AIImageGenerationService的生成图片任务接口
  10179. try {
  10180. $params = [
  10181. 'prompt' => $description,
  10182. 'ref_img_urls' => []
  10183. ];
  10184. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10185. $task_id = $task->id;
  10186. if (!$task_id) {
  10187. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  10188. continue; // 不中断,继续处理其他场景
  10189. }
  10190. $scene['task_id'] = $task_id;
  10191. $scene['task_status'] = 'processing';
  10192. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  10193. 'anime_id' => $anime_id,
  10194. 'episode_number' => $episode_number,
  10195. 'task_id' => $task_id
  10196. ]);
  10197. } catch (\Exception $e) {
  10198. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  10199. // 不抛出异常,继续处理其他场景
  10200. }
  10201. }
  10202. // 处理道具图片生成(逻辑与场景一致)
  10203. foreach ($props as &$prop) {
  10204. $prop_name = getProp($prop, 'prop');
  10205. $prop_description = getProp($prop, 'description');
  10206. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  10207. $prop_url = getProp($prop, 'url');
  10208. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  10209. if (isset($ref_products[$prop_name])) {
  10210. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  10211. if ($prop['url']) continue;
  10212. }
  10213. // 检查是否可以从上一集继承
  10214. $inherited = false;
  10215. if (!$is_force && !empty($prev_props)) {
  10216. foreach ($prev_props as $prev_prop) {
  10217. $prev_prop_name = getProp($prev_prop, 'prop');
  10218. $prev_description = getProp($prev_prop, 'description');
  10219. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  10220. $prev_url = getProp($prev_prop, 'url');
  10221. $prev_task_id = getProp($prev_prop, 'task_id');
  10222. $prev_task_status = getProp($prev_prop, 'task_status');
  10223. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  10224. if ($prop_name == $prev_prop_name
  10225. && $prop_description == $prev_description
  10226. && $prop_pic_prompt == $prev_pic_prompt
  10227. && !empty($prev_url)) {
  10228. $prop['task_id'] = $prev_task_id;
  10229. $prop['task_status'] = $prev_task_status;
  10230. $prop['url'] = $prev_url;
  10231. $inherited = true;
  10232. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  10233. 'anime_id' => $anime_id,
  10234. 'episode_number' => $episode_number,
  10235. 'task_id' => $prev_task_id,
  10236. 'url' => $prev_url
  10237. ]);
  10238. break;
  10239. }
  10240. }
  10241. }
  10242. // 如果已继承或已有url,跳过生成
  10243. if ($inherited || (!$is_force && $prop_url)) {
  10244. continue;
  10245. }
  10246. // 优先使用 pic_prompt,如果没有则使用 description
  10247. $pic_prompt = getProp($prop, 'pic_prompt');
  10248. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  10249. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10250. $update_flag = true;
  10251. // 调用AIImageGenerationService的生成图片任务接口
  10252. try {
  10253. $params = [
  10254. 'prompt' => $description,
  10255. 'ref_img_urls' => []
  10256. ];
  10257. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10258. $task_id = $task->id;
  10259. if (!$task_id) {
  10260. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  10261. continue; // 不中断,继续处理其他道具
  10262. }
  10263. $prop['task_id'] = $task_id;
  10264. $prop['task_status'] = 'processing';
  10265. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  10266. 'anime_id' => $anime_id,
  10267. 'episode_number' => $episode_number,
  10268. 'task_id' => $task_id
  10269. ]);
  10270. } catch (\Exception $e) {
  10271. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  10272. // 不抛出异常,继续处理其他道具
  10273. }
  10274. }
  10275. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10276. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  10277. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  10278. // // 保存剧集的角色和场景信息
  10279. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10280. // 'roles' => json_encode($roles, 256),
  10281. // 'scenes' => json_encode($scenes, 256),
  10282. // 'generate_status' => '执行中',
  10283. // 'generate_at' => date('Y-m-d H:i:s'),
  10284. // 'updated_at' => date('Y-m-d H:i:s')
  10285. // ]);
  10286. // if (!$boolen) {
  10287. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  10288. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  10289. // }
  10290. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  10291. // 'episode_id' => $episode_id,
  10292. 'roles_count' => count($roles),
  10293. 'scenes_count' => count($scenes),
  10294. 'props_count' => count($props)
  10295. ]);
  10296. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10297. }
  10298. /**
  10299. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  10300. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  10301. *
  10302. * @param int $anime_id 动漫对话ID
  10303. * @param array $episode_roles 剧集角色数据
  10304. * @param array $episode_scenes 剧集场景数据
  10305. * @param array $episode_props 剧集道具数据
  10306. * @return bool
  10307. */
  10308. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  10309. // 获取全局数据
  10310. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10311. if (!$anime) {
  10312. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10313. return false;
  10314. }
  10315. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10316. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10317. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  10318. $roles_added = false;
  10319. $roles_updated = false;
  10320. $scenes_added = false;
  10321. $props_added = false;
  10322. // 处理角色同步
  10323. foreach ($episode_roles as $episode_role) {
  10324. $episode_role_name = getProp($episode_role, 'role');
  10325. $episode_description = getProp($episode_role, 'description');
  10326. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10327. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  10328. // 跳过旁白
  10329. if ($episode_role_name == '旁白') {
  10330. continue;
  10331. }
  10332. // 检查全局中是否已存在相同的角色
  10333. $exists = false;
  10334. $global_role_index = -1;
  10335. foreach ($global_roles as $index => $global_role) {
  10336. $global_role_name = getProp($global_role, 'role');
  10337. $global_description = getProp($global_role, 'description');
  10338. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10339. // 如果role、description、pic_prompt三项都一致,则认为已存在
  10340. if ($episode_role_name == $global_role_name
  10341. && $episode_description == $global_description
  10342. && $episode_pic_prompt == $global_pic_prompt) {
  10343. $exists = true;
  10344. $global_role_index = $index;
  10345. break;
  10346. }
  10347. }
  10348. // 如果不存在,则添加到全局
  10349. if (!$exists) {
  10350. $global_roles[] = $episode_role;
  10351. $roles_added = true;
  10352. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  10353. 'anime_id' => $anime_id,
  10354. 'role' => $episode_role_name
  10355. ]);
  10356. } else {
  10357. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  10358. if (!empty($episode_voice_prompt)) {
  10359. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  10360. // 如果全局没有voice_prompt或与剧集不一致,则更新
  10361. if ($global_voice_prompt !== $episode_voice_prompt) {
  10362. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  10363. $roles_updated = true;
  10364. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  10365. 'anime_id' => $anime_id,
  10366. 'role' => $episode_role_name,
  10367. 'voice_prompt' => $episode_voice_prompt
  10368. ]);
  10369. }
  10370. }
  10371. }
  10372. }
  10373. // 处理场景同步
  10374. foreach ($episode_scenes as $episode_scene) {
  10375. $episode_scene_name = getProp($episode_scene, 'scene');
  10376. $episode_description = getProp($episode_scene, 'description');
  10377. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10378. // 检查全局中是否已存在相同的场景
  10379. $exists = false;
  10380. foreach ($global_scenes as $global_scene) {
  10381. $global_scene_name = getProp($global_scene, 'scene');
  10382. $global_description = getProp($global_scene, 'description');
  10383. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10384. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  10385. if ($episode_scene_name == $global_scene_name
  10386. && $episode_description == $global_description
  10387. && $episode_pic_prompt == $global_pic_prompt) {
  10388. $exists = true;
  10389. break;
  10390. }
  10391. }
  10392. // 如果不存在,则添加到全局
  10393. if (!$exists) {
  10394. $global_scenes[] = $episode_scene;
  10395. $scenes_added = true;
  10396. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  10397. 'anime_id' => $anime_id,
  10398. 'scene' => $episode_scene_name
  10399. ]);
  10400. }
  10401. }
  10402. // 处理道具同步(逻辑与场景一致)
  10403. foreach ($episode_props as $episode_prop) {
  10404. $episode_prop_name = getProp($episode_prop, 'prop');
  10405. $episode_description = getProp($episode_prop, 'description');
  10406. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  10407. // 检查全局中是否已存在相同的道具
  10408. $exists = false;
  10409. foreach ($global_props as $global_prop) {
  10410. $global_prop_name = getProp($global_prop, 'prop');
  10411. $global_description = getProp($global_prop, 'description');
  10412. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  10413. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  10414. if ($episode_prop_name == $global_prop_name
  10415. && $episode_description == $global_description
  10416. && $episode_pic_prompt == $global_pic_prompt) {
  10417. $exists = true;
  10418. break;
  10419. }
  10420. }
  10421. // 如果不存在,则添加到全局
  10422. if (!$exists) {
  10423. $global_props[] = $episode_prop;
  10424. $props_added = true;
  10425. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  10426. 'anime_id' => $anime_id,
  10427. 'prop' => $episode_prop_name
  10428. ]);
  10429. }
  10430. }
  10431. // 如果有新增或更新,则更新全局数据
  10432. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  10433. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10434. if ($roles_added || $roles_updated) {
  10435. $update_data['roles'] = json_encode($global_roles, 256);
  10436. }
  10437. if ($scenes_added) {
  10438. $update_data['scenes'] = json_encode($global_scenes, 256);
  10439. }
  10440. if ($props_added) {
  10441. $update_data['props'] = json_encode($global_props, 256);
  10442. }
  10443. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  10444. dLog('deepseek')->info('剧集数据同步到全局完成', [
  10445. 'anime_id' => $anime_id,
  10446. 'roles_added' => $roles_added,
  10447. 'roles_updated' => $roles_updated,
  10448. 'scenes_added' => $scenes_added,
  10449. 'props_added' => $props_added,
  10450. 'global_roles_count' => count($global_roles),
  10451. 'global_scenes_count' => count($global_scenes),
  10452. 'global_props_count' => count($global_props)
  10453. ]);
  10454. }
  10455. return true;
  10456. }
  10457. /**
  10458. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  10459. *
  10460. * @param int $anime_id 动漫对话ID
  10461. * @param int $episode_id 分集ID
  10462. * @return bool
  10463. */
  10464. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  10465. // 获取全局角色和场景数据
  10466. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10467. if (!$anime) {
  10468. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10469. return false;
  10470. }
  10471. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10472. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10473. // 获取指定的分集
  10474. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  10475. if (!$episode) {
  10476. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10477. return false;
  10478. }
  10479. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10480. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10481. $roles_updated = false;
  10482. $scenes_updated = false;
  10483. // 继承角色的task_id、task_status和url
  10484. foreach ($episode_roles as &$episode_role) {
  10485. $episode_role_name = getProp($episode_role, 'role');
  10486. $episode_description = getProp($episode_role, 'description');
  10487. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10488. $episode_url = getProp($episode_role, 'url');
  10489. // 跳过旁白角色
  10490. if ($episode_role_name == '旁白') {
  10491. continue;
  10492. }
  10493. // 如果剧集中已有URL,跳过
  10494. if (!empty($episode_url)) {
  10495. continue;
  10496. }
  10497. // 遍历全局角色数据,查找匹配的角色
  10498. foreach ($global_roles as $global_role) {
  10499. $global_role_name = getProp($global_role, 'role');
  10500. $global_description = getProp($global_role, 'description');
  10501. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10502. $global_url = getProp($global_role, 'url');
  10503. $global_task_id = getProp($global_role, 'task_id');
  10504. $global_task_status = getProp($global_role, 'task_status');
  10505. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10506. if ($episode_role_name == $global_role_name
  10507. && $episode_description == $global_description
  10508. && $episode_pic_prompt == $global_pic_prompt) {
  10509. // 继承 task_id、task_status 和 url
  10510. if (!empty($global_task_id)) {
  10511. $episode_role['task_id'] = $global_task_id;
  10512. $episode_role['task_status'] = $global_task_status;
  10513. $roles_updated = true;
  10514. dLog('deepseek')->info('剧集角色继承全局task_id', [
  10515. 'episode_id' => $episode_id,
  10516. 'role' => $episode_role_name,
  10517. 'task_id' => $global_task_id,
  10518. 'task_status' => $global_task_status
  10519. ]);
  10520. }
  10521. if (!empty($global_url)) {
  10522. $episode_role['url'] = $global_url;
  10523. $roles_updated = true;
  10524. dLog('deepseek')->info('剧集角色继承全局url', [
  10525. 'episode_id' => $episode_id,
  10526. 'role' => $episode_role_name,
  10527. 'url' => $global_url
  10528. ]);
  10529. }
  10530. break;
  10531. }
  10532. }
  10533. }
  10534. // 继承场景的task_id、task_status和url
  10535. foreach ($episode_scenes as &$episode_scene) {
  10536. $episode_scene_name = getProp($episode_scene, 'scene');
  10537. $episode_description = getProp($episode_scene, 'description');
  10538. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10539. $episode_url = getProp($episode_scene, 'url');
  10540. // 如果剧集中已有URL,跳过
  10541. if (!empty($episode_url)) {
  10542. continue;
  10543. }
  10544. // 遍历全局场景数据,查找匹配的场景
  10545. foreach ($global_scenes as $global_scene) {
  10546. $global_scene_name = getProp($global_scene, 'scene');
  10547. $global_description = getProp($global_scene, 'description');
  10548. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10549. $global_url = getProp($global_scene, 'url');
  10550. $global_task_id = getProp($global_scene, 'task_id');
  10551. $global_task_status = getProp($global_scene, 'task_status');
  10552. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10553. if ($episode_scene_name == $global_scene_name
  10554. && $episode_description == $global_description
  10555. && $episode_pic_prompt == $global_pic_prompt) {
  10556. // 继承 task_id、task_status 和 url
  10557. if (!empty($global_task_id)) {
  10558. $episode_scene['task_id'] = $global_task_id;
  10559. $episode_scene['task_status'] = $global_task_status;
  10560. $scenes_updated = true;
  10561. dLog('deepseek')->info('剧集场景继承全局task_id', [
  10562. 'episode_id' => $episode_id,
  10563. 'scene' => $episode_scene_name,
  10564. 'task_id' => $global_task_id,
  10565. 'task_status' => $global_task_status
  10566. ]);
  10567. }
  10568. if (!empty($global_url)) {
  10569. $episode_scene['url'] = $global_url;
  10570. $scenes_updated = true;
  10571. dLog('deepseek')->info('剧集场景继承全局url', [
  10572. 'episode_id' => $episode_id,
  10573. 'scene' => $episode_scene_name,
  10574. 'url' => $global_url
  10575. ]);
  10576. }
  10577. break;
  10578. }
  10579. }
  10580. }
  10581. // 如果有更新,则保存到数据库
  10582. if ($roles_updated || $scenes_updated) {
  10583. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10584. if ($roles_updated) {
  10585. $update_data['roles'] = json_encode($episode_roles, 256);
  10586. }
  10587. if ($scenes_updated) {
  10588. $update_data['scenes'] = json_encode($episode_scenes, 256);
  10589. }
  10590. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  10591. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  10592. 'episode_id' => $episode_id,
  10593. 'roles_updated' => $roles_updated,
  10594. 'scenes_updated' => $scenes_updated
  10595. ]);
  10596. }
  10597. return true;
  10598. }
  10599. public function chatChangeImg($data) {
  10600. $segment = getProp($data, 'segment');
  10601. $segment_content = getProp($segment, 'segment_content');
  10602. $prompt = getProp($data, 'prompt');
  10603. $ref_img = getProp($data, 'ref_img');
  10604. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  10605. // 处理文本模型
  10606. $model = getProp($data, 'model');
  10607. if (!$model) {
  10608. // 用户没有输入,从anime表获取
  10609. $segment_id = getProp($segment, 'segment_id');
  10610. if ($segment_id) {
  10611. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  10612. if ($episode_id) {
  10613. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  10614. if ($anime_id) {
  10615. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  10616. }
  10617. }
  10618. }
  10619. if (!$model) {
  10620. // anime表也没有,使用默认值
  10621. $model = 'doubao-seed-2-0-mini-260215';
  10622. }
  10623. }
  10624. // 验证模型是否在可用模型表中
  10625. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10626. $model = 'doubao-seed-2-0-mini-260215';
  10627. }
  10628. $messages[] =
  10629. [
  10630. 'role' => 'user',
  10631. 'content' => $question
  10632. ];
  10633. $post_data = [
  10634. 'model' => $model,
  10635. 'messages' => $messages,
  10636. // 'max_tokens' => 8192,
  10637. 'temperature' => 0.7,
  10638. 'frequency_penalty' => 0,
  10639. 'presence_penalty' => 0,
  10640. 'response_format' => ['type' => 'text'],
  10641. 'stream' => false // 是否启用流式输出
  10642. ];
  10643. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10644. // DeepSeek 官方模型使用 DeepSeek API
  10645. $chatResult = $this->chatOnly($post_data);
  10646. } else if (in_array($model, $this->gpt_text_models)) {
  10647. // GPT-5.4 模型使用 TokenRouter API
  10648. $chatResult = $this->gpt54ChatOnly($post_data);
  10649. } else {
  10650. // 其他模型使用火山引擎API
  10651. $chatResult = $this->volcEngineChatCompletion($post_data);
  10652. }
  10653. if (is_array($chatResult)) {
  10654. extract($chatResult);
  10655. }else {
  10656. Utils::throwError('20003: 接口调用失败!');
  10657. }
  10658. return [
  10659. 'type' => 'done',
  10660. // 'episode' => $episode,
  10661. 'answer' => $fullContent,
  10662. 'reasoning' => $fullReasoningContent,
  10663. 'usage' => $usage
  10664. ];
  10665. }
  10666. // 仅调用deepseek对话接口
  10667. private function chatOnly($post_data) {
  10668. $post_data['max_tokens'] = 300000;
  10669. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10670. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  10671. $response = $result->getBody()->getContents();
  10672. $response_arr = json_decode($response, true);
  10673. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  10674. $fullContent = '';
  10675. $fullReasoningContent = [];
  10676. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10677. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10678. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10679. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  10680. }
  10681. return [
  10682. 'fullContent' => $fullContent,
  10683. 'fullReasoningContent' => $fullReasoningContent,
  10684. 'usage' => $usage
  10685. ];
  10686. }
  10687. // 仅调用 GPT-5.4 对话接口(非流式)
  10688. private function gpt54ChatOnly($post_data) {
  10689. $apiKey = env('GPT_54_API_KEY');
  10690. if (empty($apiKey)) {
  10691. Utils::throwError('20003:GPT-5.4 API Key未配置');
  10692. }
  10693. // 先探活,服务不可用时自动重试
  10694. $this->ensureGptServiceAvailable();
  10695. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10696. $headers = [
  10697. 'Authorization' => 'Bearer ' . $apiKey,
  10698. 'Content-Type' => 'application/json'
  10699. ];
  10700. // 移除 thinking 参数,GPT-5.4 不支持
  10701. if (isset($post_data['thinking'])) {
  10702. unset($post_data['thinking']);
  10703. }
  10704. if (isset($post_data['reasoning_effort'])) {
  10705. unset($post_data['reasoning_effort']);
  10706. }
  10707. $post_data['max_completion_tokens'] = 100000;
  10708. // 确保 stream 为 false
  10709. $post_data['stream'] = false;
  10710. $maxRetries = $this->gptRetryTimes();
  10711. $interval = $this->gptRetryInterval();
  10712. $attempt = 0;
  10713. while (true) {
  10714. try {
  10715. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  10716. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  10717. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  10718. 'json' => $post_data,
  10719. 'headers' => $headers
  10720. ]);
  10721. $response = $result->getBody()->getContents();
  10722. $response_arr = json_decode($response, true);
  10723. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  10724. $fullContent = '';
  10725. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10726. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10727. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10728. }
  10729. return [
  10730. 'fullContent' => $fullContent,
  10731. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  10732. 'usage' => $usage
  10733. ];
  10734. } catch (\Exception $e) {
  10735. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  10736. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  10737. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  10738. throw $e;
  10739. }
  10740. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  10741. 'retry' => $attempt + 1,
  10742. 'max_retries' => $maxRetries,
  10743. 'error' => $e->getMessage()
  10744. ]);
  10745. sleep($interval);
  10746. $attempt++;
  10747. }
  10748. }
  10749. }
  10750. private function splitContent($content) {
  10751. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  10752. $chapters = [];
  10753. // 匹配章节标题格式:
  10754. // 1. 标题可能独占一行,也可能在正文末尾或中间
  10755. // 2. 格式支持:
  10756. // - **第一集**
  10757. // - 第一集:
  10758. // - ###第1章 重生
  10759. // - ##第2章 相救
  10760. // - 第三章 共处一室
  10761. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  10762. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  10763. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  10764. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  10765. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  10766. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  10767. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  10768. // 先在每个标题前插入换行符(如果前面不是换行的话)
  10769. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  10770. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  10771. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  10772. // 用正则找出所有章节标题的位置
  10773. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  10774. $titleCount = count($matches[0]);
  10775. for ($i = 0; $i < $titleCount; $i++) {
  10776. // 获取当前章节标题
  10777. $titleLine = trim($matches[0][$i][0]);
  10778. // 去除标题开头的特殊符号
  10779. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  10780. // 去除标题结尾的冒号和特殊符号
  10781. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  10782. $cleanTitle = trim($cleanTitle);
  10783. // 获取当前标题的结束位置
  10784. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  10785. // 获取下一个章节标题的开始位置(如果存在)
  10786. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  10787. // 提取章节内容(从标题结束到下一个标题开始)
  10788. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  10789. // 清理内容:去除前后空白和分隔线
  10790. $chapterContent = trim($chapterContent);
  10791. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  10792. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  10793. if (!empty($cleanTitle) && !empty($chapterContent)) {
  10794. $chapters[] = [
  10795. 'title' => $cleanTitle,
  10796. 'content' => $chapterContent
  10797. ];
  10798. }
  10799. }
  10800. } else {
  10801. // 如果没有匹配到章节,返回整个内容
  10802. $chapters[] = [
  10803. 'title' => '',
  10804. 'content' => $content
  10805. ];
  10806. }
  10807. return $chapters;
  10808. }
  10809. public function getContentByBid($bid) {
  10810. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  10811. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  10812. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  10813. $content = '';
  10814. foreach ($chapters as $chapter) {
  10815. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  10816. }
  10817. return $content;
  10818. }
  10819. public function getContentByScriptId($script_id) {
  10820. $content = '';
  10821. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  10822. if ($contents) {
  10823. $content = implode(PHP_EOL, $contents);
  10824. }else {
  10825. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  10826. }
  10827. return $content;
  10828. }
  10829. /**
  10830. * 根据文件类型提取文本内容
  10831. *
  10832. * @param mixed $file 文件对象或文件路径
  10833. * @return string
  10834. */
  10835. public function extractFileContent($file) {
  10836. // 获取文件路径和扩展名
  10837. if (is_string($file)) {
  10838. $filePath = $file;
  10839. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  10840. } else {
  10841. // Laravel UploadedFile 对象
  10842. $filePath = $file->getRealPath();
  10843. $extension = strtolower($file->getClientOriginalExtension());
  10844. }
  10845. $content = '';
  10846. switch ($extension) {
  10847. case 'txt':
  10848. $content = $this->extractTxtContent($filePath);
  10849. break;
  10850. case 'pdf':
  10851. $content = $this->extractPdfContent($filePath);
  10852. break;
  10853. case 'doc':
  10854. case 'docx':
  10855. $content = $this->extractWordContent($filePath);
  10856. break;
  10857. // case 'jpg':
  10858. // case 'jpeg':
  10859. // case 'png':
  10860. // case 'gif':
  10861. // case 'bmp':
  10862. // case 'webp':
  10863. // $content = $this->extractImageContent($filePath);
  10864. // break;
  10865. default:
  10866. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  10867. }
  10868. return $content;
  10869. }
  10870. /**
  10871. * 提取 TXT 文件内容
  10872. */
  10873. private function extractTxtContent($filePath) {
  10874. if (!file_exists($filePath)) {
  10875. Utils::throwError('20003:文件不存在');
  10876. }
  10877. $content = file_get_contents($filePath);
  10878. // 尝试检测并转换编码
  10879. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  10880. if ($encoding && $encoding !== 'UTF-8') {
  10881. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  10882. }
  10883. return trim($content);
  10884. }
  10885. /**
  10886. * 提取 PDF 文件内容
  10887. */
  10888. private function extractPdfContent($filePath) {
  10889. if (!file_exists($filePath)) {
  10890. Utils::throwError('20003:文件不存在');
  10891. }
  10892. try {
  10893. $parser = new PdfParser();
  10894. $pdf = $parser->parseFile($filePath);
  10895. $content = $pdf->getText();
  10896. return trim($content);
  10897. } catch (\Exception $e) {
  10898. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  10899. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  10900. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  10901. }
  10902. }
  10903. /**
  10904. * 提取 Word 文件内容(支持 doc 和 docx)
  10905. */
  10906. private function extractWordContent($filePath) {
  10907. if (!file_exists($filePath)) {
  10908. Utils::throwError('20003:文件不存在');
  10909. }
  10910. try {
  10911. $phpWord = WordIOFactory::load($filePath);
  10912. $content = '';
  10913. foreach ($phpWord->getSections() as $section) {
  10914. foreach ($section->getElements() as $element) {
  10915. $content .= $this->extractWordElementText($element);
  10916. }
  10917. }
  10918. return trim($content);
  10919. } catch (\Exception $e) {
  10920. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  10921. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  10922. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  10923. }
  10924. }
  10925. /**
  10926. * 递归提取 Word 元素中的文本
  10927. */
  10928. private function extractWordElementText($element) {
  10929. $text = '';
  10930. if (method_exists($element, 'getText')) {
  10931. $text .= $element->getText() . "\n";
  10932. } elseif (method_exists($element, 'getElements')) {
  10933. foreach ($element->getElements() as $childElement) {
  10934. $text .= $this->extractWordElementText($childElement);
  10935. }
  10936. }
  10937. return $text;
  10938. }
  10939. /**
  10940. * 提取图片内容(使用火山引擎 OCR)
  10941. */
  10942. private function extractImageContent($filePath) {
  10943. if (!file_exists($filePath)) {
  10944. Utils::throwError('20003:文件不存在');
  10945. }
  10946. try {
  10947. // 读取图片并转换为 base64
  10948. $imageData = file_get_contents($filePath);
  10949. $base64Image = base64_encode($imageData);
  10950. // 调用火山引擎 OCR 服务
  10951. $content = $this->callVolcEngineOCR($base64Image);
  10952. return trim($content);
  10953. } catch (\Exception $e) {
  10954. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  10955. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  10956. Utils::throwError('20003:图片识别失败');
  10957. }
  10958. }
  10959. /**
  10960. * 调用火山引擎 OCR 服务识别图片文字
  10961. *
  10962. * @param string $base64Image base64 编码的图片数据
  10963. * @return string 识别的文字内容
  10964. */
  10965. private function callVolcEngineOCR($base64Image) {
  10966. $method = 'POST';
  10967. $service = 'cv';
  10968. $host = 'visual.volcengineapi.com';
  10969. $region = env('VOLC_REGION', 'cn-north-1');
  10970. $access_key = env('VOLC_AK');
  10971. $secret_key = env('VOLC_SK');
  10972. $action = 'OCRNormal';
  10973. $version = '2020-08-26';
  10974. if (!$access_key || !$secret_key) {
  10975. Utils::throwError('20003:请配置火山引擎 AK/SK');
  10976. }
  10977. // 请求体
  10978. $body = json_encode([
  10979. 'image_base64' => $base64Image
  10980. ]);
  10981. // 生成签名
  10982. $headers = $this->getVolcEngineSignHeaders(
  10983. $method, $service, $host, $region,
  10984. "Action={$action}&Version={$version}",
  10985. $access_key, $secret_key, $body
  10986. );
  10987. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10988. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  10989. 'headers' => $headers,
  10990. 'body' => $body
  10991. ]);
  10992. $response_arr = json_decode($response->getBody()->getContents(), true);
  10993. // 提取识别的文字
  10994. $textLines = [];
  10995. if (isset($response_arr['data']['line_texts'])) {
  10996. $textLines = $response_arr['data']['line_texts'];
  10997. } elseif (isset($response_arr['data']['ocr_infos'])) {
  10998. foreach ($response_arr['data']['ocr_infos'] as $info) {
  10999. if (isset($info['text'])) {
  11000. $textLines[] = $info['text'];
  11001. }
  11002. }
  11003. }
  11004. if (empty($textLines)) {
  11005. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  11006. return '';
  11007. }
  11008. return implode("\n", $textLines);
  11009. }
  11010. /**
  11011. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  11012. */
  11013. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  11014. $contentType = 'application/json';
  11015. $accept = 'application/json';
  11016. // 获取当前UTC时间
  11017. $t = new DateTime('now', new DateTimeZone('UTC'));
  11018. $xDate = $t->format('Ymd\THis\Z');
  11019. $dateStamp = $t->format('Ymd');
  11020. // 计算 body 的 sha256 哈希
  11021. $payloadHash = hash('sha256', $body);
  11022. // 1. 拼接规范请求串
  11023. $canonicalUri = '/';
  11024. $canonicalQueryString = $queryString;
  11025. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  11026. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  11027. $canonicalRequest = implode("\n", [
  11028. $method,
  11029. $canonicalUri,
  11030. $canonicalQueryString,
  11031. $canonicalHeaders,
  11032. $signedHeaders,
  11033. $payloadHash
  11034. ]);
  11035. // 2. 拼接待签名字符串
  11036. $algorithm = 'HMAC-SHA256';
  11037. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  11038. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  11039. $stringToSign = implode("\n", [
  11040. $algorithm,
  11041. $xDate,
  11042. $credentialScope,
  11043. $hashedCanonicalRequest
  11044. ]);
  11045. // 3. 计算签名
  11046. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  11047. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  11048. // 4. 添加签名到请求头
  11049. $authorizationHeader = sprintf(
  11050. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  11051. $algorithm,
  11052. $access_key,
  11053. $credentialScope,
  11054. $signedHeaders,
  11055. $signature
  11056. );
  11057. return [
  11058. 'Accept' => $accept,
  11059. 'Content-Type' => $contentType,
  11060. 'Host' => $host,
  11061. 'X-Date' => $xDate,
  11062. 'X-Content-Sha256'=> $payloadHash,
  11063. 'Authorization' => $authorizationHeader
  11064. ];
  11065. }
  11066. public function generateScriptWords($cid, $model = 'r1') {
  11067. ini_set('max_execution_time', 0);
  11068. if (!$cid) Utils::throwError('20003: 请选择章节!');
  11069. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  11070. // 模型兼容性处理和思考模式设置
  11071. $thinkingMode = 'disabled';
  11072. $reasoningEffort = 'high';
  11073. if ($model == 'r1') {
  11074. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  11075. $thinkingMode = 'enabled';
  11076. } else {
  11077. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  11078. $thinkingMode = 'disabled';
  11079. }
  11080. $messages = [
  11081. [
  11082. 'role' => 'system',
  11083. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  11084. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  11085. 2.非对话部分请全部用旁白角色代替
  11086. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  11087. ],
  11088. [
  11089. 'role' => 'user',
  11090. 'content' => $content
  11091. ]
  11092. ];
  11093. $post_data = [
  11094. 'model' => $model,
  11095. 'messages' => $messages,
  11096. // 'max_tokens' => 8192,
  11097. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  11098. 'frequency_penalty' => 0,
  11099. 'presence_penalty' => 0,
  11100. 'thinking' => ['type' => $thinkingMode],
  11101. 'response_format' => [
  11102. 'type' => 'text'
  11103. ],
  11104. 'stream' => false
  11105. ];
  11106. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  11107. // 根据模型类型选择调用方法
  11108. $fullContent = '';
  11109. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11110. // DeepSeek 官方模型使用 DeepSeek API
  11111. $chatResult = $this->chatOnly($post_data);
  11112. } else if (in_array($model, $this->gpt_text_models)) {
  11113. // GPT-5.4 模型使用 TokenRouter API
  11114. $chatResult = $this->gpt54ChatOnly($post_data);
  11115. } else {
  11116. // 其他模型使用火山引擎API
  11117. $chatResult = $this->volcEngineChatCompletion($post_data);
  11118. }
  11119. if (is_array($chatResult)) {
  11120. $fullContent = $chatResult['fullContent'];
  11121. }
  11122. return $fullContent;
  11123. }
  11124. /**
  11125. * 智能化解析集数信息
  11126. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  11127. *
  11128. * @param string $prompt 用户输入的提示词
  11129. * @return int|null 解析出的集数,如果没有找到则返回null
  11130. */
  11131. private function extractEpisodeNumber($prompt)
  11132. {
  11133. if (empty($prompt)) {
  11134. return null;
  11135. }
  11136. // 定义各种可能的表达模式
  11137. $patterns = [
  11138. // 基本模式:改成N集、调整成N集、修改成N集
  11139. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  11140. // 扩展模式:分成N集、拆分成N集、分割成N集
  11141. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  11142. // 数量模式:N集、共N集、总共N集
  11143. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  11144. // 制作模式:制作N集、生成N集、创建N集
  11145. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  11146. // 计划模式:计划N集、预计N集、打算N集
  11147. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  11148. // 需要模式:需要N集、要N集
  11149. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  11150. // 中文数字模式:改成三集、调整成五集等
  11151. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  11152. // 英文数字模式
  11153. '/(?: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',
  11154. ];
  11155. // 中文数字转阿拉伯数字的映射
  11156. $chineseNumbers = [
  11157. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  11158. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  11159. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  11160. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  11161. ];
  11162. // 逐个尝试匹配模式
  11163. foreach ($patterns as $pattern) {
  11164. if (preg_match($pattern, $prompt, $matches)) {
  11165. $number = trim($matches[1]);
  11166. // 如果是中文数字,转换为阿拉伯数字
  11167. if (isset($chineseNumbers[$number])) {
  11168. return $chineseNumbers[$number];
  11169. }
  11170. // 如果是阿拉伯数字,直接返回
  11171. if (is_numeric($number)) {
  11172. $episodeNum = intval($number);
  11173. // 合理性检查:集数应该在1-100之间
  11174. if ($episodeNum >= 1 && $episodeNum <= 100) {
  11175. return $episodeNum;
  11176. }
  11177. }
  11178. }
  11179. }
  11180. return null;
  11181. }
  11182. /**
  11183. * 调用火山引擎对话(Chat) API
  11184. *
  11185. * @param array $params 包含以下参数:
  11186. * - model: 模型ID(必填)
  11187. * - messages: 消息列表(必填)
  11188. * - stream: 是否流式输出(可选,默认false)
  11189. * - max_tokens: 最大输出token数(可选)
  11190. * - temperature: 采样温度(可选,默认1)
  11191. * - top_p: 核采样概率(可选,默认0.7)
  11192. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  11193. * - presence_penalty: 存在惩罚系数(可选,默认0)
  11194. * - stop: 停止词(可选)
  11195. * - tools: 工具列表(可选)
  11196. * @return array|Generator 非流式返回数组,流式返回生成器
  11197. */
  11198. public function volcEngineChatCompletion(array $params)
  11199. {
  11200. $apiKey = env('VOLC_AI_API_KEY');
  11201. if (empty($apiKey)) {
  11202. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  11203. }
  11204. // 构建请求参数
  11205. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  11206. $requestData = [
  11207. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  11208. 'messages' => $params['messages'] ?? [],
  11209. ];
  11210. if (!in_array($originalModel, $this->valid_text_models)) {
  11211. Utils::throwError('20003:该模型不支持!');
  11212. }
  11213. // 添加可选参数
  11214. if (isset($params['stream'])) {
  11215. $requestData['stream'] = $params['stream'];
  11216. }
  11217. if (isset($params['stream_options'])) {
  11218. $requestData['stream_options'] = $params['stream_options'];
  11219. }
  11220. if (isset($params['max_tokens'])) {
  11221. $requestData['max_tokens'] = $params['max_tokens'];
  11222. }else if (isset($params['max_completion_tokens'])) {
  11223. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  11224. }else {
  11225. $requestData['max_completion_tokens'] = 100000;
  11226. }
  11227. if (isset($params['temperature'])) {
  11228. $requestData['temperature'] = $params['temperature'];
  11229. }
  11230. if (isset($params['top_p'])) {
  11231. $requestData['top_p'] = $params['top_p'];
  11232. }
  11233. if (isset($params['frequency_penalty'])) {
  11234. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  11235. }
  11236. if (isset($params['presence_penalty'])) {
  11237. $requestData['presence_penalty'] = $params['presence_penalty'];
  11238. }
  11239. if (isset($params['stop'])) {
  11240. $requestData['stop'] = $params['stop'];
  11241. }
  11242. if (isset($params['tools'])) {
  11243. $requestData['tools'] = $params['tools'];
  11244. }
  11245. if (isset($params['tool_choice'])) {
  11246. $requestData['tool_choice'] = $params['tool_choice'];
  11247. }
  11248. if (isset($params['response_format'])) {
  11249. $requestData['response_format'] = $params['response_format'];
  11250. }
  11251. if (isset($params['thinking'])) {
  11252. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  11253. if (is_array($params['thinking'])) {
  11254. $requestData['thinking'] = $params['thinking'];
  11255. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  11256. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11257. }
  11258. } else {
  11259. $requestData['thinking'] = ['type' => $params['thinking']];
  11260. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  11261. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11262. }
  11263. }
  11264. } else {
  11265. $requestData['thinking'] = ['type' => 'disabled'];
  11266. }
  11267. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  11268. $client = new Client(['verify' => false, 'timeout' => 1800]);
  11269. try {
  11270. // 判断是否为流式输出
  11271. $isStream = isset($params['stream']) && $params['stream'] === true;
  11272. if ($isStream) {
  11273. // 流式输出
  11274. // 流式请求默认声明返回 usage(未显式传参时)
  11275. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  11276. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  11277. } else {
  11278. // 非流式输出
  11279. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11280. 'headers' => [
  11281. 'Authorization' => 'Bearer ' . $apiKey,
  11282. 'Content-Type' => 'application/json',
  11283. ],
  11284. 'json' => $requestData
  11285. ]);
  11286. $responseData = json_decode($response->getBody(), true);
  11287. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  11288. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  11289. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  11290. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  11291. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  11292. }
  11293. return [
  11294. 'fullContent' => $fullContent,
  11295. 'fullReasoningContent' => $fullReasoningContent,
  11296. 'usage' => $usage
  11297. ];
  11298. }
  11299. } catch (\Exception $e) {
  11300. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  11301. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  11302. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  11303. }
  11304. }
  11305. /**
  11306. * 火山引擎对话API流式输出
  11307. *
  11308. * @param Client $client HTTP客户端
  11309. * @param string $apiKey API密钥
  11310. * @param array $requestData 请求数据
  11311. * @return Generator
  11312. */
  11313. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  11314. {
  11315. try {
  11316. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11317. 'headers' => [
  11318. 'Authorization' => 'Bearer ' . $apiKey,
  11319. 'Content-Type' => 'application/json',
  11320. ],
  11321. 'json' => $requestData,
  11322. 'stream' => true
  11323. ]);
  11324. $body = $response->getBody();
  11325. $buffer = '';
  11326. $fullContent = '';
  11327. $fullReasoningContent = '';
  11328. $usage = [];
  11329. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  11330. // 逐行读取流式响应
  11331. while (!$body->eof()) {
  11332. $chunk = $body->read(1024);
  11333. $buffer .= $chunk;
  11334. // 按行分割
  11335. $lines = explode("\n", $buffer);
  11336. $buffer = array_pop($lines);
  11337. foreach ($lines as $line) {
  11338. $line = trim($line);
  11339. if (empty($line)) {
  11340. continue;
  11341. }
  11342. // 检查是否是SSE数据行
  11343. if (strpos($line, 'data: ') !== 0) {
  11344. continue;
  11345. }
  11346. $data = substr($line, 6);
  11347. if ($data === '[DONE]') {
  11348. dLog('deepseek')->info('收到结束标记');
  11349. break 2;
  11350. }
  11351. try {
  11352. $json = json_decode($data, true);
  11353. if (json_last_error() !== JSON_ERROR_NONE) {
  11354. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  11355. continue;
  11356. }
  11357. if (isset($json['choices'][0]['delta'])) {
  11358. $delta = $json['choices'][0]['delta'];
  11359. // 处理思维链内容
  11360. if (isset($delta['reasoning_content'])) {
  11361. $fullReasoningContent .= $delta['reasoning_content'];
  11362. yield [
  11363. 'type' => 'reasoning',
  11364. 'content' => $delta['reasoning_content'],
  11365. 'full_reasoning' => $fullReasoningContent
  11366. ];
  11367. }
  11368. // 处理回答内容
  11369. if (isset($delta['content'])) {
  11370. $fullContent .= $delta['content'];
  11371. yield [
  11372. 'type' => 'content',
  11373. 'content' => $delta['content'],
  11374. ];
  11375. }
  11376. }
  11377. // 获取使用统计信息
  11378. if (isset($json['usage'])) {
  11379. $usage = $json['usage'];
  11380. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  11381. }
  11382. } catch (\Exception $e) {
  11383. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  11384. continue;
  11385. }
  11386. }
  11387. }
  11388. dLog('deepseek')->info('流式读取完成', [
  11389. 'content_length' => strlen($fullContent),
  11390. 'reasoning_length' => strlen($fullReasoningContent)
  11391. ]);
  11392. yield [
  11393. 'type' => 'done',
  11394. 'full_content' => $fullContent,
  11395. 'full_reasoning' => $fullReasoningContent,
  11396. 'usage' => $usage
  11397. ];
  11398. } catch (\Exception $e) {
  11399. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  11400. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  11401. throw $e;
  11402. }
  11403. }
  11404. /**
  11405. * 检查并创建图片生成任务
  11406. *
  11407. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  11408. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  11409. * @param string $nameKey 资源名称字段('role' 或 'scene')
  11410. * @param string $art_style 美术风格
  11411. * @return array 更新后的资源列表
  11412. */
  11413. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  11414. {
  11415. // 确保参数为数组
  11416. $merged_items = is_array($merged_items) ? $merged_items : [];
  11417. $global_items = is_array($global_items) ? $global_items : [];
  11418. // 构建全局资源映射表,用于快速查找
  11419. $global_map = [];
  11420. foreach ($global_items as $item) {
  11421. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11422. if ($itemKey === '') {
  11423. continue;
  11424. }
  11425. $global_map[$itemKey] = $item;
  11426. }
  11427. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  11428. foreach ($merged_items as &$item) {
  11429. $item_name = getProp($item, $nameKey);
  11430. $item_description = getProp($item, 'description');
  11431. // $item_url = getProp($item, 'url');
  11432. // // 如果已有图片URL,跳过
  11433. // if (!empty($item_url)) {
  11434. // continue;
  11435. // }
  11436. // 如果是旁白角色,跳过
  11437. if ($nameKey === 'role' && $item_name === '旁白') {
  11438. continue;
  11439. }
  11440. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  11441. if ($itemKey === '') {
  11442. continue;
  11443. }
  11444. $need_create_task = false;
  11445. // 条件1:在全局资源中找不到匹配的名称
  11446. if (!isset($global_map[$itemKey])) {
  11447. $need_create_task = true;
  11448. } else {
  11449. // 条件2:名称匹配但描述或 pic_prompt 不一致
  11450. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  11451. $current_description = trim((string)$item_description);
  11452. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  11453. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  11454. // 如果 description 或 pic_prompt 有变化,需要重新生成
  11455. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  11456. $need_create_task = true;
  11457. }
  11458. }
  11459. // 如果需要创建任务,调用图片生成服务
  11460. if ($need_create_task) {
  11461. try {
  11462. // 优先使用 pic_prompt,如果没有则使用 description
  11463. $pic_prompt = getProp($item, 'pic_prompt');
  11464. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  11465. // 添加美术风格前缀
  11466. if ($art_style) {
  11467. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  11468. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  11469. $description = "{$prefix}:{$description}";
  11470. }
  11471. $params = [
  11472. 'prompt' => $description,
  11473. 'ref_img_urls' => []
  11474. ];
  11475. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11476. $task_id = $task->id;
  11477. if ($task_id) {
  11478. $item['task_id'] = $task_id;
  11479. $item['task_status'] = 'processing';
  11480. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11481. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  11482. }
  11483. } catch (\Exception $e) {
  11484. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11485. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  11486. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  11487. // 不抛出异常,继续处理其他资源
  11488. }
  11489. }
  11490. }
  11491. return $merged_items;
  11492. }
  11493. /**
  11494. * 同步新出现的主体和场景到全局
  11495. *
  11496. * @param int $anime_id 动漫ID
  11497. * @param array $merged_roles 合并后的角色列表
  11498. * @param array $merged_scenes 合并后的场景列表
  11499. * @param array $global_roles 全局角色列表
  11500. * @param array $global_scenes 全局场景列表
  11501. * @return void
  11502. */
  11503. private function syncNewResourcesToGlobal(
  11504. int $anime_id,
  11505. array $merged_roles,
  11506. array $merged_scenes,
  11507. array $global_roles,
  11508. array $global_scenes
  11509. ): void {
  11510. // 构建全局角色映射表
  11511. $global_role_map = [];
  11512. foreach ($global_roles as $role) {
  11513. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  11514. if ($roleKey !== '') {
  11515. $global_role_map[$roleKey] = $role;
  11516. }
  11517. }
  11518. // 构建全局场景映射表
  11519. $global_scene_map = [];
  11520. foreach ($global_scenes as $scene) {
  11521. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  11522. if ($sceneKey !== '') {
  11523. $global_scene_map[$sceneKey] = $scene;
  11524. }
  11525. }
  11526. $need_update = false;
  11527. $new_global_roles = $global_roles;
  11528. $new_global_scenes = $global_scenes;
  11529. // 检查并添加新角色到全局
  11530. foreach ($merged_roles as $role) {
  11531. $role_name = getProp($role, 'role');
  11532. // 跳过旁白
  11533. if ($role_name === '旁白') {
  11534. continue;
  11535. }
  11536. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  11537. if ($roleKey === '') {
  11538. continue;
  11539. }
  11540. // 如果全局中不存在该角色,添加到全局
  11541. if (!isset($global_role_map[$roleKey])) {
  11542. $new_global_roles[] = [
  11543. 'role' => $role_name,
  11544. 'description' => getProp($role, 'description', ''),
  11545. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  11546. 'voice_name' => getProp($role, 'voice_name', ''),
  11547. 'voice_type' => getProp($role, 'voice_type', ''),
  11548. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  11549. 'url' => getProp($role, 'url', ''),
  11550. 'task_id' => getProp($role, 'task_id', ''),
  11551. 'task_status' => getProp($role, 'task_status', ''),
  11552. ];
  11553. $global_role_map[$roleKey] = true; // 标记已添加
  11554. $need_update = true;
  11555. dLog('deepseek')->info("新角色同步到全局", [
  11556. 'anime_id' => $anime_id,
  11557. 'role' => $role_name,
  11558. 'task_id' => getProp($role, 'task_id', ''),
  11559. ]);
  11560. }
  11561. // else {
  11562. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11563. // $global_role = $global_role_map[$roleKey];
  11564. // if (is_array($global_role)) {
  11565. // $updated = false;
  11566. // $update_fields = [];
  11567. // // 检查描述是否更新
  11568. // $current_description = trim((string)getProp($role, 'description'));
  11569. // $global_description = trim((string)getProp($global_role, 'description'));
  11570. // if ($current_description !== '' && $current_description !== $global_description) {
  11571. // $updated = true;
  11572. // $update_fields[] = 'description';
  11573. // }
  11574. // // 检查pic_prompt是否更新
  11575. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  11576. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  11577. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11578. // $updated = true;
  11579. // $update_fields[] = 'pic_prompt';
  11580. // }
  11581. // // 检查图片任务信息是否更新
  11582. // $current_task_id = getProp($role, 'task_id');
  11583. // $global_task_id = getProp($global_role, 'task_id');
  11584. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11585. // $updated = true;
  11586. // $update_fields[] = 'task_id';
  11587. // }
  11588. // // 如果有更新,同步到全局
  11589. // if ($updated) {
  11590. // foreach ($new_global_roles as &$global_role_item) {
  11591. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  11592. // if ($global_role_key === $roleKey) {
  11593. // if (in_array('description', $update_fields)) {
  11594. // $global_role_item['description'] = $current_description;
  11595. // }
  11596. // if (in_array('pic_prompt', $update_fields)) {
  11597. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  11598. // }
  11599. // if (in_array('task_id', $update_fields)) {
  11600. // $global_role_item['task_id'] = $current_task_id;
  11601. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  11602. // $global_role_item['url'] = getProp($role, 'url', '');
  11603. // }
  11604. // break;
  11605. // }
  11606. // }
  11607. // $need_update = true;
  11608. // dLog('deepseek')->info("角色信息更新到全局", [
  11609. // 'anime_id' => $anime_id,
  11610. // 'role' => $role_name,
  11611. // 'update_fields' => implode(',', $update_fields),
  11612. // ]);
  11613. // }
  11614. // }
  11615. // }
  11616. }
  11617. // 检查并添加新场景到全局
  11618. foreach ($merged_scenes as $scene) {
  11619. $scene_name = getProp($scene, 'scene');
  11620. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  11621. if ($sceneKey === '') {
  11622. continue;
  11623. }
  11624. // 如果全局中不存在该场景,添加到全局
  11625. if (!isset($global_scene_map[$sceneKey])) {
  11626. $new_global_scenes[] = [
  11627. 'scene' => $scene_name,
  11628. 'description' => getProp($scene, 'description', ''),
  11629. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  11630. 'url' => getProp($scene, 'url', ''),
  11631. 'task_id' => getProp($scene, 'task_id', ''),
  11632. 'task_status' => getProp($scene, 'task_status', ''),
  11633. ];
  11634. $global_scene_map[$sceneKey] = true; // 标记已添加
  11635. $need_update = true;
  11636. dLog('deepseek')->info("新场景同步到全局", [
  11637. 'anime_id' => $anime_id,
  11638. 'scene' => $scene_name,
  11639. 'task_id' => getProp($scene, 'task_id', ''),
  11640. ]);
  11641. }
  11642. // else {
  11643. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11644. // $global_scene = $global_scene_map[$sceneKey];
  11645. // if (is_array($global_scene)) {
  11646. // $updated = false;
  11647. // $update_fields = [];
  11648. // // 检查描述是否更新
  11649. // $current_description = trim((string)getProp($scene, 'description'));
  11650. // $global_description = trim((string)getProp($global_scene, 'description'));
  11651. // if ($current_description !== '' && $current_description !== $global_description) {
  11652. // $updated = true;
  11653. // $update_fields[] = 'description';
  11654. // }
  11655. // // 检查pic_prompt是否更新
  11656. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  11657. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  11658. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11659. // $updated = true;
  11660. // $update_fields[] = 'pic_prompt';
  11661. // }
  11662. // // 检查图片任务信息是否更新
  11663. // $current_task_id = getProp($scene, 'task_id');
  11664. // $global_task_id = getProp($global_scene, 'task_id');
  11665. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11666. // $updated = true;
  11667. // $update_fields[] = 'task_id';
  11668. // }
  11669. // // 如果有更新,同步到全局
  11670. // if ($updated) {
  11671. // foreach ($new_global_scenes as &$global_scene_item) {
  11672. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  11673. // if ($global_scene_key === $sceneKey) {
  11674. // if (in_array('description', $update_fields)) {
  11675. // $global_scene_item['description'] = $current_description;
  11676. // }
  11677. // if (in_array('pic_prompt', $update_fields)) {
  11678. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  11679. // }
  11680. // if (in_array('task_id', $update_fields)) {
  11681. // $global_scene_item['task_id'] = $current_task_id;
  11682. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  11683. // $global_scene_item['url'] = getProp($scene, 'url', '');
  11684. // }
  11685. // break;
  11686. // }
  11687. // }
  11688. // $need_update = true;
  11689. // dLog('deepseek')->info("场景信息更新到全局", [
  11690. // 'anime_id' => $anime_id,
  11691. // 'scene' => $scene_name,
  11692. // 'update_fields' => implode(',', $update_fields),
  11693. // ]);
  11694. // }
  11695. // }
  11696. // }
  11697. }
  11698. // 如果有新增或更新,更新数据库
  11699. if ($need_update) {
  11700. $update_data = [
  11701. 'roles' => json_encode($new_global_roles, 256),
  11702. 'scenes' => json_encode($new_global_scenes, 256),
  11703. 'updated_at' => date('Y-m-d H:i:s'),
  11704. ];
  11705. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11706. if ($result !== false) {
  11707. dLog('deepseek')->info("全局角色和场景更新成功", [
  11708. 'anime_id' => $anime_id,
  11709. 'roles_count' => count($new_global_roles),
  11710. 'scenes_count' => count($new_global_scenes),
  11711. ]);
  11712. } else {
  11713. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  11714. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  11715. }
  11716. }
  11717. }
  11718. }