DeepSeekService.php 822 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002
  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. private $gemini_text_models;
  30. protected $aiImageGenerationService;
  31. protected $pointsService;
  32. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  33. $this->aiImageGenerationService = $aiImageGenerationService;
  34. $this->pointsService = $pointsService;
  35. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  36. $this->api_key = env('DEEPSEEK_API_KEY');
  37. $this->headers = [
  38. 'Authorization' => 'Bearer '.$this->api_key,
  39. 'Content-Type' => 'application/json; charset=UTF-8'
  40. ];
  41. // 火山引擎模型列表
  42. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  43. // GPT文本模型列表
  44. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  45. // Gemini文本模型列表
  46. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  47. $this->sys_message = [
  48. 'role' => 'system',
  49. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  50. 强制要求:\n
  51. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  52. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  53. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  54. 普通要求:\n
  55. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  56. 2.<分集剧本>的要求如下:
  57.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  58.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  59.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  60.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  61. \n\n
  62. 示例如下:\n
  63. ###剧本名:西昆仑
  64. ###故事梗概
  65. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  66. ###剧本亮点
  67. 亮点1:绝境奇药,生死一线
  68. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  69. 亮点2:结拜兄妹,化解尴尬
  70. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  71. 亮点3:纤发夺命,情愫暗涌
  72. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  73. ###人物关系
  74. 阿雪与梁萧之间存在兄妹之情。
  75. ###核心矛盾
  76. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  77. ###主体列表
  78. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  79. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  80. 阴阳球:天地异宝,能化生精气,救人于危难。
  81. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  82. ###美术风格
  83. 基础画风风格词:厚涂古风
  84. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  85. ###场景列表
  86. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  87. ###分集剧本
  88. ##分集01
  89. 第1集: 第一集的标题
  90. 场景描述:地点、时间、场景
  91. 运镜:固定近距离
  92. 出场角色:男主、女主
  93. 台词内容:
  94. 女主: 女主对话
  95. 男主:男主对话
  96. 女主: 女主对话
  97. 男主: 男主对话
  98. ##分集02
  99. 第2集: 第二集的标题
  100. 场景描述:地点、时间、场景
  101. 运镜:固定近距离
  102. 出场角色:男主、女主
  103. 台词内容:
  104. 女主: 女主对话
  105. 男主:男主对话
  106. 女主: 女主对话
  107. 男主: 男主对话"
  108. ];
  109. }
  110. /**
  111. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  112. *
  113. * @param array $data 请求参数
  114. * @return \Generator 返回生成器,用于流式输出
  115. */
  116. public function generateText($data) {
  117. // 获取请求参数
  118. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  119. $messages = getProp($data, 'messages', []);
  120. $systemPrompt = getProp($data, 'system_prompt', '');
  121. $prompt = getProp($data, 'prompt', '');
  122. $images = getProp($data, 'images', []); // 支持多张图片
  123. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  124. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  125. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  126. $isGeminiModel = in_array($model, $this->gemini_text_models);
  127. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  128. Utils::throwError('20003:仅Gemini模型支持视频输入');
  129. }
  130. // Gemini 多模态(图片/视频 -> 文本)按模型预检积分;纯文本不扣费
  131. $uid = Site::getUid();
  132. $chargeModality = '';
  133. $chargePoints = 0;
  134. $hasImageMedia = !empty($images) || !empty($imageUrls)
  135. || $this->messagesContainMedia($messages, ['image_url', 'image']);
  136. $hasVideoMedia = !empty($videos) || !empty($videoUrls)
  137. || $this->messagesContainMedia($messages, ['video_url', 'video']);
  138. if ($isGeminiModel && ($hasImageMedia || $hasVideoMedia)) {
  139. $chargeModality = $hasVideoMedia ? 'video' : 'image';
  140. $pricingModel = $this->geminiMultimodalPricingModel($model);
  141. if ($pricingModel !== '') {
  142. $chargePoints = $this->pointsService->getVideoChargePoints(['model' => $pricingModel]);
  143. if ($chargePoints > 0) {
  144. $this->pointsService->checkUserPointsEnough($chargePoints, $uid);
  145. }
  146. }
  147. }
  148. // 如果没有提供messages,则根据system_prompt、content和images构建
  149. if (empty($messages)) {
  150. $messages = [];
  151. // 添加系统提示词
  152. if (!empty($systemPrompt)) {
  153. $messages[] = [
  154. 'role' => 'system',
  155. 'content' => $systemPrompt
  156. ];
  157. }
  158. // 构建用户消息内容(支持文本+图片)
  159. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  160. $userMessage = [
  161. 'role' => 'user',
  162. 'content' => []
  163. ];
  164. // 添加文本内容
  165. if (!empty($prompt)) {
  166. $userMessage['content'][] = [
  167. 'type' => 'text',
  168. 'text' => $prompt
  169. ];
  170. }
  171. // 处理上传的图片文件
  172. if (!empty($images)) {
  173. if (!is_array($images)) {
  174. $images = [$images];
  175. }
  176. foreach ($images as $image) {
  177. $imageBase64 = $this->processImageToBase64($image);
  178. if ($imageBase64) {
  179. $userMessage['content'][] = [
  180. 'type' => 'image_url',
  181. 'image_url' => [
  182. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  183. ]
  184. ];
  185. }
  186. }
  187. }
  188. // 处理图片URL
  189. if (!empty($imageUrls)) {
  190. if (!is_array($imageUrls)) {
  191. $imageUrls = [$imageUrls];
  192. }
  193. foreach ($imageUrls as $url) {
  194. if (!empty($url)) {
  195. $userMessage['content'][] = [
  196. 'type' => 'image_url',
  197. 'image_url' => [
  198. 'url' => $url
  199. ]
  200. ];
  201. }
  202. }
  203. }
  204. // 处理上传的视频文件(仅 Gemini)
  205. if (!empty($videos) && $isGeminiModel) {
  206. if (!is_array($videos)) {
  207. $videos = [$videos];
  208. }
  209. foreach ($videos as $video) {
  210. $inlineData = $this->processMediaToInlineData($video);
  211. if ($inlineData) {
  212. $userMessage['content'][] = [
  213. 'type' => 'video',
  214. 'inline_data' => $inlineData
  215. ];
  216. }
  217. }
  218. }
  219. // 处理视频URL(仅 Gemini)
  220. if (!empty($videoUrls) && $isGeminiModel) {
  221. if (!is_array($videoUrls)) {
  222. $videoUrls = [$videoUrls];
  223. }
  224. foreach ($videoUrls as $url) {
  225. if (!empty($url)) {
  226. $userMessage['content'][] = [
  227. 'type' => 'video_url',
  228. 'video_url' => ['url' => $url]
  229. ];
  230. }
  231. }
  232. }
  233. // 如果只有文本内容,简化为字符串格式
  234. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  235. $userMessage['content'] = $userMessage['content'][0]['text'];
  236. }
  237. $messages[] = $userMessage;
  238. }
  239. }
  240. // 验证messages不为空
  241. if (empty($messages)) {
  242. Utils::throwError('20003:请提供有效的对话内容');
  243. }
  244. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  245. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  246. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  247. if ($model === 'deepseek-chat') {
  248. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  249. $model = 'deepseek-v4-flash';
  250. $thinkingMode = 'disabled';
  251. } elseif ($model === 'deepseek-reasoner') {
  252. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  253. $model = 'deepseek-v4-flash';
  254. $thinkingMode = 'enabled';
  255. }
  256. // 构建请求参数
  257. $post_data = [
  258. 'model' => $model,
  259. 'messages' => $messages,
  260. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  261. 'temperature' => getProp($data, 'temperature', 1),
  262. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  263. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  264. 'thinking' => ['type' => $thinkingMode],
  265. 'stream' => true // 启用流式输出
  266. ];
  267. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  268. // 添加可选参数
  269. if (isset($data['top_p'])) {
  270. $post_data['top_p'] = $data['top_p'];
  271. }
  272. if (isset($data['response_format'])) {
  273. $post_data['response_format'] = $data['response_format'];
  274. }
  275. // 根据模型类型选择调用方法
  276. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  277. // DeepSeek 官方模型使用 DeepSeek API
  278. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  279. } else if (in_array($model, $this->gpt_text_models)) {
  280. // GPT 模型使用 TokenRouter API
  281. $streamGenerator = $this->gpt54StreamResponse($post_data);
  282. } else if (in_array($model, $this->gemini_text_models)) {
  283. // Gemini 模型使用 Gemini API
  284. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  285. } else if (in_array($model, $this->valid_text_models)) {
  286. // 火山引擎支持的模型使用火山引擎 API
  287. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  288. } else {
  289. Utils::throwError('20003:不支持的模型: ' . $model);
  290. }
  291. if ($chargePoints > 0) {
  292. return $this->wrapGenerateTextCharge($streamGenerator, $uid, $model, $chargePoints, $chargeModality);
  293. }
  294. return $streamGenerator;
  295. }
  296. /**
  297. * 流式生成成功后再按 Gemini 多模态规则扣费
  298. *
  299. * @param \Generator $generator
  300. * @param int $uid
  301. * @param string $model
  302. * @param int $points
  303. * @param string $modality
  304. * @return \Generator
  305. */
  306. private function wrapGenerateTextCharge(\Generator $generator, int $uid, string $model, int $points, string $modality): \Generator
  307. {
  308. $charged = false;
  309. foreach ($generator as $chunk) {
  310. if (!$charged && isset($chunk['type']) && $chunk['type'] === 'done') {
  311. $fullContent = (string)getProp($chunk, 'full_content', getProp($chunk, 'answer', ''));
  312. if ($fullContent !== '') {
  313. $this->chargeGeminiMultimodal($uid, $model, $points, $modality, getProp($chunk, 'usage', []));
  314. $charged = true;
  315. }
  316. }
  317. yield $chunk;
  318. }
  319. }
  320. /**
  321. * Gemini 多模态(图片/视频 -> 文本)成功后扣费并记录 token 明细
  322. *
  323. * @param int $uid
  324. * @param string $model
  325. * @param int $points
  326. * @param string $modality
  327. * @param mixed $usage
  328. * @return void
  329. */
  330. private function chargeGeminiMultimodal(int $uid, string $model, int $points, string $modality, $usage): void
  331. {
  332. $result = $this->pointsService->recordChatCharge(
  333. $uid,
  334. $points,
  335. $this->pointsService->getTokensFromUsage($usage),
  336. [
  337. 'model' => $model,
  338. 'modality' => $modality,
  339. 'source' => 'generateText',
  340. ],
  341. '',
  342. $model
  343. );
  344. if (empty($result['charged'])) {
  345. throw new \Exception('Gemini多模态计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  346. }
  347. }
  348. /**
  349. * Gemini 文本模型 ID 转 mp_video_models 中的按次计费模型 ID
  350. *
  351. * @param string $model
  352. * @return string
  353. */
  354. private function geminiMultimodalPricingModel(string $model): string
  355. {
  356. $map = [
  357. 'gemini-3.1-flash-image-preview-t' => 'gemini-3.1-flash',
  358. 'gemini-3.1-pro-preview' => 'gemini-3.1-pro',
  359. 'gemini-3-flash-preview' => 'gemini-3.0-flash',
  360. 'gemini-3-pro-preview' => 'gemini-3.0-pro',
  361. 'gemini-3.6-flash' => 'gemini-3.6-flash',
  362. ];
  363. return $map[$model] ?? '';
  364. }
  365. /**
  366. * 检查 OpenAI 风格消息中是否包含指定媒体类型
  367. *
  368. * @param array $messages
  369. * @param array $mediaTypes
  370. * @return bool
  371. */
  372. private function messagesContainMedia(array $messages, array $mediaTypes): bool
  373. {
  374. foreach ($messages as $message) {
  375. $content = getProp($message, 'content', '');
  376. if (!is_array($content)) {
  377. continue;
  378. }
  379. foreach ($content as $part) {
  380. if (is_array($part) && in_array(getProp($part, 'type', ''), $mediaTypes, true)) {
  381. return true;
  382. }
  383. }
  384. }
  385. return false;
  386. }
  387. public function createGenerateText($data) {
  388. $file = getProp($data, 'file');
  389. $episode_num = getProp($data, 'episode_num');
  390. $uid = Site::getUid();
  391. $cpid = Site::getCpid();
  392. if (!$file) {
  393. Utils::throwError('20003:请上传文件');
  394. }
  395. // 提取文件内容
  396. $content = $this->extractFileContent($file);
  397. if (!$content) {
  398. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  399. }
  400. // 拆分章节并校验章节总数、标题连续性
  401. if ($episode_num) {
  402. $this->validateGenerateTextChapters($content, (int)$episode_num);
  403. }
  404. // 获取原始文件名(不含扩展名)作为script_name
  405. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  406. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  407. // 字节安全剥离,不依赖服务器locale设置
  408. $originalName = $file->getClientOriginalName();
  409. $extension = $file->getClientOriginalExtension();
  410. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  411. ? substr($originalName, 0, -strlen($extension) - 1)
  412. : $originalName;
  413. if ($script_name === '') {
  414. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  415. }
  416. // 如果同一用户的剧本名存在则提示
  417. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  418. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  419. }
  420. // 插入数据到mp_scripts表
  421. $script_id = DB::table('mp_scripts')->insertGetId([
  422. 'script_name' => $script_name,
  423. 'user_id' => $uid,
  424. 'cpid' => $cpid,
  425. 'content' => $content,
  426. 'created_at' => date('Y-m-d H:i:s'),
  427. 'updated_at' => date('Y-m-d H:i:s')
  428. ]);
  429. return [
  430. 'script_id' => $script_id,
  431. 'script_name' => $script_name
  432. ];
  433. }
  434. /**
  435. * AI对话调用成功后的积分扣费(返回结果前调用)
  436. *
  437. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  438. *
  439. * @param int $uid
  440. * @param int $tokens
  441. * @param array $chargeInfo
  442. * @return void
  443. */
  444. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo): void
  445. {
  446. $result = $this->pointsService->recordChatCharge(
  447. $uid,
  448. PointsService::CHAT_CHARGE_POINTS,
  449. $tokens,
  450. $chargeInfo
  451. );
  452. if (empty($result['charged'])) {
  453. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  454. }
  455. }
  456. /**
  457. * 拆分剧本内容并校验章节总数与标题连续性
  458. *
  459. * @param string $content
  460. * @param int $episodeNum
  461. * @return void
  462. */
  463. private function validateGenerateTextChapters($content, $episodeNum)
  464. {
  465. $chapters = splitContent($content);
  466. if (count($chapters) !== $episodeNum) {
  467. Utils::throwError('20003:章节总数与集数不一致,请检查上传内容');
  468. }
  469. if (empty($chapters)) {
  470. return;
  471. }
  472. // 先尝试从标题正则中解析序号,确认是否从1开始连续递增
  473. $numbers = [];
  474. $unparsedIndex = null;
  475. foreach ($chapters as $index => $chapter) {
  476. $num = $this->parseChapterNumber($chapter['title']);
  477. if ($num === null) {
  478. $unparsedIndex = $index;
  479. break;
  480. }
  481. $numbers[] = $num;
  482. }
  483. if ($unparsedIndex === null) {
  484. $expected = 1;
  485. foreach ($numbers as $index => $num) {
  486. if ($num !== $expected) {
  487. $title = mb_substr(trim((string)$chapters[$index]['title']), 0, 40);
  488. Utils::throwError('20003:章节序号不连续:第' . ($index + 1) . '个章节“' . $title . '”序号为' . $num . ',预期为' . $expected);
  489. }
  490. $expected++;
  491. }
  492. return;
  493. }
  494. // 标题格式无法用正则确认时,交给模型分析
  495. $titles = array_column($chapters, 'title');
  496. $aiResult = $this->validateChapterSequenceByAI($titles);
  497. if ($aiResult['valid'] === false) {
  498. $badIndex = $aiResult['invalid_index'] ?: $unparsedIndex + 1;
  499. if (isset($chapters[$badIndex - 1])) {
  500. $title = mb_substr(trim((string)$chapters[$badIndex - 1]['title']), 0, 40);
  501. Utils::throwError('20003:章节序号不连续:第' . $badIndex . '个章节“' . $title . '”序号异常,请检查');
  502. }
  503. Utils::throwError('20003:章节序号不连续,请检查章节标题格式');
  504. }
  505. if ($aiResult['valid'] === null) {
  506. if (isset($chapters[$unparsedIndex])) {
  507. $title = mb_substr(trim((string)$chapters[$unparsedIndex]['title']), 0, 40);
  508. Utils::throwError('20003:无法确认第' . ($unparsedIndex + 1) . '个章节“' . $title . '”的章节序号,请检查标题格式');
  509. }
  510. Utils::throwError('20003:无法确认章节标题连续性,请检查章节标题格式');
  511. }
  512. }
  513. /**
  514. * 从章节标题中解析序号,支持阿拉伯数字和中文数字
  515. *
  516. * @param string $title
  517. * @return int|null
  518. */
  519. private function parseChapterNumber($title)
  520. {
  521. if (!preg_match('/第\s*([一二两三四五六七八九十百千万0-9]+)\s*[章节集幕场回话]/u', $title, $match)) {
  522. return null;
  523. }
  524. return $this->convertChineseNumber($match[1]);
  525. }
  526. /**
  527. * 中文数字转阿拉伯数字(支持到千)
  528. *
  529. * @param string $numStr
  530. * @return int
  531. */
  532. private function convertChineseNumber($numStr)
  533. {
  534. if (preg_match('/^\d+$/', $numStr)) {
  535. return (int)$numStr;
  536. }
  537. $map = [
  538. '零' => 0,
  539. '一' => 1,
  540. '二' => 2,
  541. '两' => 2,
  542. '三' => 3,
  543. '四' => 4,
  544. '五' => 5,
  545. '六' => 6,
  546. '七' => 7,
  547. '八' => 8,
  548. '九' => 9
  549. ];
  550. $total = 0;
  551. $section = 0;
  552. $length = mb_strlen($numStr);
  553. for ($i = 0; $i < $length; $i++) {
  554. $char = mb_substr($numStr, $i, 1);
  555. if (isset($map[$char])) {
  556. $section = $map[$char];
  557. } elseif ($char === '十') {
  558. $total += $section === 0 ? 10 : $section * 10;
  559. $section = 0;
  560. } elseif ($char === '百') {
  561. $total += $section === 0 ? 100 : $section * 100;
  562. $section = 0;
  563. } elseif ($char === '千') {
  564. $total += $section === 0 ? 1000 : $section * 1000;
  565. $section = 0;
  566. }
  567. }
  568. return $total + $section;
  569. }
  570. /**
  571. * 用 deepseek-v4-flash 非流式判断章节标题是否从1开始连续编号
  572. *
  573. * @param array $titles
  574. * @return array{valid: bool|null, invalid_index: int|null}
  575. */
  576. private function validateChapterSequenceByAI($titles)
  577. {
  578. $titleLines = [];
  579. foreach (array_slice($titles, 0, 200) as $index => $title) {
  580. $titleLines[] = ($index + 1) . '. ' . mb_substr(trim((string)$title), 0, 80);
  581. }
  582. $result = [
  583. 'valid' => null,
  584. 'invalid_index' => null
  585. ];
  586. $post_data = [
  587. 'model' => 'deepseek-v4-flash',
  588. 'messages' => [
  589. [
  590. 'role' => 'system',
  591. 'content' => '你是剧本章节校验助手。用户会给出章节标题列表,请判断这些标题中的编号是否从第1章/第1集开始连续递增,支持阿拉伯数字和中文数字。只输出 JSON,格式为 {"valid":true};若不连续则输出 {"valid":false,"invalid_index":N},其中 N 是第一个序号异常的章节序号(从1开始),不要输出其他内容。',
  592. ],
  593. [
  594. 'role' => 'user',
  595. 'content' => implode("\n", $titleLines),
  596. ],
  597. ],
  598. 'temperature' => 0,
  599. 'frequency_penalty' => 0,
  600. 'presence_penalty' => 0,
  601. 'stream' => false,
  602. ];
  603. try {
  604. $result = $this->chatOnly($post_data, 8);
  605. $content = trim((string)($result['fullContent'] ?? ''));
  606. if (preg_match('/"valid"\s*:\s*(true|false)/i', $content, $match)) {
  607. $result['valid'] = strtolower($match[1]) === 'true';
  608. }
  609. if (preg_match('/"invalid_index"\s*:\s*(\d+)/i', $content, $match)) {
  610. $result['invalid_index'] = (int)$match[1];
  611. }
  612. } catch (\Exception $e) {
  613. dLog('deepseek')->error('章节连续性AI校验失败: ' . $e->getMessage());
  614. }
  615. return $result;
  616. }
  617. /**
  618. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  619. *
  620. * @param array $data 请求参数
  621. * @return array 返回结果数组
  622. */
  623. public function newGenerateText($data) {
  624. // 获取请求参数
  625. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  626. $messages = getProp($data, 'messages', []);
  627. $systemPrompt = getProp($data, 'system_prompt', '');
  628. $prompt = getProp($data, 'prompt', '');
  629. $images = getProp($data, 'images', []); // 支持多张图片
  630. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  631. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  632. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  633. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  634. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  635. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  636. $generateTaskId = 0;
  637. $uid = Site::getUid();
  638. if ($script_id > 0) {
  639. $existingTask = DB::table('mp_script_generate_tasks')
  640. ->where('uid', $uid)
  641. ->where('script_id', $script_id)
  642. ->orderByDesc('id')
  643. ->first();
  644. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  645. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  646. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  647. }
  648. }
  649. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  650. $originalContent = '';
  651. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  652. if ($script_id > 0) {
  653. $script = DB::table('mp_scripts')
  654. ->where('id', $script_id)
  655. ->where('is_deleted', 0)
  656. ->first();
  657. if (!$script) {
  658. Utils::throwError('20003:剧本不存在或已删除');
  659. }
  660. $originalContent = $script->content ?? '';
  661. if (empty($originalContent)) {
  662. Utils::throwError('20003:剧本内容为空');
  663. }
  664. $hasValidScript = true;
  665. // 将剧本内容添加到提示词前面
  666. if (!empty($originalContent)) {
  667. if (!empty($prompt)) {
  668. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  669. } else {
  670. $prompt = "原文内容:\n" . $originalContent;
  671. }
  672. }
  673. }
  674. // 新增: 如果提供了template_id,从数据库获取template_prompt
  675. if ($templateId > 0) {
  676. $template = DB::table('mp_prompt_templates')
  677. ->where('id', $templateId)
  678. ->where('is_deleted', 0)
  679. ->first();
  680. if (!$template) {
  681. Utils::throwError('20003:模板不存在或已删除');
  682. }
  683. $templatePrompt = $template->template_prompt ?? '';
  684. // 将模板提示词和用户输入的prompt组合
  685. // 模板为准,用户输入作为补充要求
  686. if (!empty($templatePrompt)) {
  687. if (!empty($prompt)) {
  688. $prompt = $templatePrompt . "\n\n" . $prompt;
  689. } else {
  690. $prompt = $templatePrompt;
  691. }
  692. }
  693. }
  694. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  695. if (empty($messages)) {
  696. $messages = [];
  697. // 添加系统提示词
  698. if (!empty($systemPrompt)) {
  699. $messages[] = [
  700. 'role' => 'system',
  701. 'content' => $systemPrompt
  702. ];
  703. }
  704. // 构建用户消息内容(支持文本+图片)
  705. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  706. $userMessage = [
  707. 'role' => 'user',
  708. 'content' => []
  709. ];
  710. // 添加文本内容
  711. if (!empty($prompt)) {
  712. $userMessage['content'][] = [
  713. 'type' => 'text',
  714. 'text' => $prompt
  715. ];
  716. }
  717. // 处理上传的图片文件
  718. if (!empty($images)) {
  719. if (!is_array($images)) {
  720. $images = [$images];
  721. }
  722. foreach ($images as $image) {
  723. $imageBase64 = $this->processImageToBase64($image);
  724. if ($imageBase64) {
  725. $userMessage['content'][] = [
  726. 'type' => 'image_url',
  727. 'image_url' => [
  728. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  729. ]
  730. ];
  731. }
  732. }
  733. }
  734. // 处理图片URL
  735. if (!empty($imageUrls)) {
  736. if (!is_array($imageUrls)) {
  737. $imageUrls = [$imageUrls];
  738. }
  739. foreach ($imageUrls as $url) {
  740. if (!empty($url)) {
  741. $userMessage['content'][] = [
  742. 'type' => 'image_url',
  743. 'image_url' => [
  744. 'url' => $url
  745. ]
  746. ];
  747. }
  748. }
  749. }
  750. // 如果只有文本内容,简化为字符串格式
  751. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  752. $userMessage['content'] = $userMessage['content'][0]['text'];
  753. }
  754. $messages[] = $userMessage;
  755. }
  756. }
  757. // 验证messages不为空
  758. if (empty($messages)) {
  759. Utils::throwError('20003:请提供有效的对话内容');
  760. }
  761. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  762. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  763. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  764. if ($model === 'deepseek-chat') {
  765. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  766. $model = 'deepseek-v4-flash';
  767. $thinkingMode = 'disabled';
  768. } elseif ($model === 'deepseek-reasoner') {
  769. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  770. $model = 'deepseek-v4-flash';
  771. $thinkingMode = 'enabled';
  772. }
  773. // 构建请求参数(非流式)
  774. $post_data = [
  775. 'model' => $model,
  776. 'messages' => $messages,
  777. 'temperature' => getProp($data, 'temperature', 1),
  778. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  779. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  780. 'thinking' => ['type' => $thinkingMode],
  781. 'stream' => false // 非流式输出
  782. ];
  783. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  784. // 添加可选参数
  785. if (isset($data['top_p'])) {
  786. $post_data['top_p'] = $data['top_p'];
  787. }
  788. // 新增: 根据response_format设置响应格式
  789. if ($responseFormat === 'json') {
  790. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  791. $hasJsonKeyword = false;
  792. foreach ($post_data['messages'] as $message) {
  793. if (isset($message['content'])) {
  794. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  795. if (stripos($content, 'json') !== false) {
  796. $hasJsonKeyword = true;
  797. break;
  798. }
  799. }
  800. }
  801. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  802. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  803. if (!$hasJsonKeyword) {
  804. $lastMessageIndex = count($post_data['messages']) - 1;
  805. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  806. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  807. // 如果content是字符串,直接追加
  808. if (is_string($lastContent)) {
  809. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  810. }
  811. // 如果content是数组(包含文本和图片),在文本部分追加
  812. else if (is_array($lastContent)) {
  813. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  814. if ($contentPart['type'] === 'text') {
  815. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  816. break;
  817. }
  818. }
  819. }
  820. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  821. }
  822. }
  823. // 设置response_format参数(所有支持的模型)
  824. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  825. // DeepSeek模型
  826. $post_data['response_format'] = ['type' => 'json_object'];
  827. } else if (in_array($model, $this->gpt_text_models)) {
  828. // GPT模型
  829. $post_data['response_format'] = ['type' => 'json_object'];
  830. } else if (in_array($model, $this->valid_text_models)) {
  831. // 火山引擎模型
  832. $post_data['response_format'] = ['type' => 'json_object'];
  833. }
  834. }
  835. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  836. if ($script_id > 0) {
  837. $uid = Site::getUid();
  838. // 创建新的生成任务
  839. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  840. 'uid' => $uid,
  841. 'script_id' => $script_id,
  842. 'sequence' => $sequence,
  843. 'status' => 'processing',
  844. 'prompt' => getProp($data, 'prompt', ''),
  845. 'started_at' => date('Y-m-d H:i:s'),
  846. 'created_at' => date('Y-m-d H:i:s'),
  847. 'updated_at' => date('Y-m-d H:i:s')
  848. ]);
  849. }
  850. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  851. if ($hasValidScript) {
  852. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  853. }
  854. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  855. try {
  856. $aiResult = null;
  857. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  858. // DeepSeek 官方模型使用现有的 chatOnly 方法
  859. $result = $this->chatOnly($post_data);
  860. // 记录实际使用的模型
  861. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  862. $aiResult = [
  863. 'content' => $result['fullContent'],
  864. 'reasoning_content' => $result['fullReasoningContent'],
  865. 'usage' => $result['usage'],
  866. 'model' => $model,
  867. 'finish_reason' => 'stop'
  868. ];
  869. } else if (in_array($model, $this->gpt_text_models)) {
  870. // GPT 模型使用现有的 gpt54ChatOnly 方法
  871. $result = $this->gpt54ChatOnly($post_data);
  872. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  873. $aiResult = [
  874. 'content' => $result['fullContent'],
  875. 'reasoning_content' => '',
  876. 'usage' => $result['usage'],
  877. 'model' => $model,
  878. 'finish_reason' => 'stop'
  879. ];
  880. } else if (in_array($model, $this->gemini_text_models)) {
  881. // Gemini 模型使用 Gemini API(非流式)
  882. $result = $this->geminiChatOnly($post_data, $model);
  883. dLog('deepseek')->info('newGenerateText使用Gemini模型', ['requested_model' => $model]);
  884. $aiResult = [
  885. 'content' => $result['fullContent'],
  886. 'reasoning_content' => $result['fullReasoningContent'] ?? '',
  887. 'usage' => $result['usage'],
  888. 'model' => $model,
  889. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  890. ];
  891. } else if (in_array($model, $this->valid_text_models)) {
  892. // 火山引擎支持的模型使用火山引擎 API(非流式)
  893. $post_data['stream'] = false;
  894. $result = $this->volcEngineChatCompletion($post_data);
  895. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  896. 'requested_model' => $model,
  897. 'result_keys' => array_keys($result),
  898. 'has_fullContent' => isset($result['fullContent']),
  899. 'has_content' => isset($result['content'])
  900. ]);
  901. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  902. $aiResult = [
  903. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  904. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  905. 'usage' => $result['usage'] ?? [],
  906. 'model' => $model,
  907. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  908. ];
  909. } else {
  910. Utils::throwError('20003:不支持的模型: ' . $model);
  911. }
  912. } catch (\Exception $e) {
  913. // 生成失败,更新任务状态
  914. if ($generateTaskId) {
  915. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  916. 'status' => 'failed',
  917. 'error_message' => $e->getMessage(),
  918. 'completed_at' => date('Y-m-d H:i:s'),
  919. 'updated_at' => date('Y-m-d H:i:s')
  920. ]);
  921. }
  922. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  923. }
  924. // 生成成功,更新任务状态
  925. if ($generateTaskId && $aiResult) {
  926. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  927. 'status' => 'success',
  928. 'result' => getProp($aiResult, 'content', ''),
  929. 'completed_at' => date('Y-m-d H:i:s'),
  930. 'updated_at' => date('Y-m-d H:i:s')
  931. ]);
  932. $aiResult['generate_task_id'] = $generateTaskId;
  933. }
  934. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  935. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  936. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  937. 'model' => $model,
  938. 'script_id' => $script_id,
  939. 'sequence' => $sequence,
  940. 'source' => 'newGenerateText',
  941. ]);
  942. }
  943. // 新增: 如果提供了script_id,保存对话记录
  944. if ($script_id > 0 && $aiResult) {
  945. try {
  946. $uid = Site::getUid();
  947. $now = now();
  948. // 获取用户原始的prompt(不包含剧本内容)
  949. $originalPrompt = getProp($data, 'prompt', '');
  950. $recordsToInsert = [
  951. [
  952. 'uid' => $uid,
  953. 'script_id' => $script_id,
  954. 'sequence' => $sequence,
  955. 'role' => 'user',
  956. 'content' => $originalPrompt,
  957. 'created_at' => $now,
  958. 'updated_at' => $now,
  959. ],
  960. [
  961. 'uid' => $uid,
  962. 'script_id' => $script_id,
  963. 'sequence' => $sequence,
  964. 'role' => 'assistant',
  965. 'content' => $aiResult['content'],
  966. 'created_at' => $now,
  967. 'updated_at' => $now,
  968. ]
  969. ];
  970. DB::table('mp_script_records')->insert($recordsToInsert);
  971. // 获取刚插入的记录ID(假设按插入顺序返回)
  972. $insertedRecords = DB::table('mp_script_records')
  973. ->where('uid', $uid)
  974. ->where('script_id', $script_id)
  975. ->where('sequence', $sequence)
  976. ->orderBy('id', 'desc')
  977. ->limit(2)
  978. ->get()
  979. ->map(function ($record) {
  980. return [
  981. 'rid' => $record->id,
  982. 'script_id' => $record->script_id,
  983. 'sequence' => $record->sequence,
  984. 'role' => $record->role,
  985. 'content' => $record->content,
  986. 'created_at' => $record->created_at,
  987. ];
  988. })
  989. ->reverse()
  990. ->values()
  991. ->toArray();
  992. // 将记录信息添加到返回结果中
  993. $aiResult['records'] = $insertedRecords;
  994. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  995. } catch (\Exception $e) {
  996. // 记录错误但不影响主流程
  997. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  998. }
  999. }
  1000. return $aiResult;
  1001. }
  1002. /**
  1003. * 通用 Gemini 文生文方法(支持流式和非流式)
  1004. *
  1005. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  1006. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  1007. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  1008. * system_prompt 系统提示词(可选)
  1009. * prompt 用户提示词(可选)
  1010. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  1011. * image_urls 图片/视频URL列表(可选,同上)
  1012. * temperature 温度(可选,默认 1)
  1013. * top_p 核采样(可选)
  1014. * max_tokens 最大输出 token(可选,默认 8192)
  1015. * response_format text/json(可选)
  1016. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  1017. * thinking_budget 思考预算(可选,默认 20)
  1018. * stream 是否流式(可选,默认 false)
  1019. *
  1020. * @param array $data 请求参数
  1021. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  1022. */
  1023. public function geminiGenerateText($data) {
  1024. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  1025. $isStream = (bool)getProp($data, 'stream', false);
  1026. if (!in_array($model, $this->gemini_text_models)) {
  1027. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  1028. }
  1029. $requestData = $this->buildGeminiRequestBody($data, $model);
  1030. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  1031. if ($isStream) {
  1032. // 流式返回生成器
  1033. return $this->geminiStreamResponse($requestData, $model);
  1034. }
  1035. // 非流式
  1036. return $this->geminiChatOnly($requestData, $model);
  1037. }
  1038. /**
  1039. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  1040. */
  1041. private function geminiMediaMaxBytes() {
  1042. return 14 * 1024 * 1024;
  1043. }
  1044. /**
  1045. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  1046. */
  1047. private function buildGeminiRequestBody($data, $model) {
  1048. $messages = getProp($data, 'messages', []);
  1049. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  1050. if (empty($messages)) {
  1051. $systemPrompt = getProp($data, 'system_prompt', '');
  1052. $prompt = getProp($data, 'prompt', '');
  1053. $images = getProp($data, 'images', []);
  1054. $imageUrls = getProp($data, 'image_urls', []);
  1055. $messages = [];
  1056. if (!empty($systemPrompt)) {
  1057. $messages[] = [
  1058. 'role' => 'system',
  1059. 'content' => $systemPrompt
  1060. ];
  1061. }
  1062. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1063. $userMessage = ['role' => 'user', 'content' => []];
  1064. if (!empty($prompt)) {
  1065. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  1066. }
  1067. if (!empty($images)) {
  1068. if (!is_array($images)) {
  1069. $images = [$images];
  1070. }
  1071. foreach ($images as $image) {
  1072. $inlineData = $this->processMediaToInlineData($image);
  1073. if ($inlineData) {
  1074. $userMessage['content'][] = [
  1075. 'type' => 'image',
  1076. 'inline_data' => $inlineData
  1077. ];
  1078. }
  1079. }
  1080. }
  1081. if (!empty($imageUrls)) {
  1082. if (!is_array($imageUrls)) {
  1083. $imageUrls = [$imageUrls];
  1084. }
  1085. foreach ($imageUrls as $url) {
  1086. if (!empty($url)) {
  1087. $inlineData = $this->processMediaToInlineData($url);
  1088. if ($inlineData) {
  1089. $userMessage['content'][] = [
  1090. 'type' => 'image',
  1091. 'inline_data' => $inlineData
  1092. ];
  1093. }
  1094. }
  1095. }
  1096. }
  1097. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  1098. $userMessage['content'] = $userMessage['content'][0]['text'];
  1099. }
  1100. $messages[] = $userMessage;
  1101. }
  1102. }
  1103. if (empty($messages)) {
  1104. Utils::throwError('20003:请提供有效的对话内容');
  1105. }
  1106. // 转换为 Gemini contents 格式
  1107. $systemInstruction = '';
  1108. $contents = [];
  1109. foreach ($messages as $message) {
  1110. $role = getProp($message, 'role', 'user');
  1111. $content = getProp($message, 'content', '');
  1112. if ($role === 'system') {
  1113. if (is_array($content)) {
  1114. $systemInstruction = $this->extractGeminiTextFromParts($content);
  1115. } else {
  1116. $systemInstruction = (string)$content;
  1117. }
  1118. continue;
  1119. }
  1120. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  1121. $parts = [];
  1122. if (is_array($content)) {
  1123. foreach ($content as $part) {
  1124. $partType = getProp($part, 'type', 'text');
  1125. if ($partType === 'text') {
  1126. $text = (string)getProp($part, 'text', '');
  1127. if ($text !== '') {
  1128. $parts[] = ['text' => $text];
  1129. }
  1130. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  1131. if (in_array($partType, ['image_url', 'video_url'])) {
  1132. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  1133. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  1134. } elseif (isset($part['inline_data'])) {
  1135. // 已处理过的 inline_data 直接使用
  1136. $parts[] = ['inline_data' => $part['inline_data']];
  1137. continue;
  1138. } else {
  1139. $url = '';
  1140. }
  1141. $inlineData = $this->processMediaToInlineData($url);
  1142. if ($inlineData) {
  1143. $parts[] = ['inline_data' => $inlineData];
  1144. }
  1145. }
  1146. }
  1147. } else {
  1148. $text = (string)$content;
  1149. if ($text !== '') {
  1150. $parts[] = ['text' => $text];
  1151. }
  1152. }
  1153. if (!empty($parts)) {
  1154. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  1155. }
  1156. }
  1157. if (empty($contents)) {
  1158. Utils::throwError('20003:请提供有效的对话内容');
  1159. }
  1160. // 构建生成配置
  1161. $generationConfig = [];
  1162. if (getProp($data, 'temperature', null) !== null) {
  1163. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  1164. }
  1165. if (getProp($data, 'top_p', null) !== null) {
  1166. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1167. }
  1168. if (getProp($data, 'frequency_penalty', null) !== null) {
  1169. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1170. }
  1171. if (getProp($data, 'presence_penalty', null) !== null) {
  1172. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1173. }
  1174. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1175. if ($maxOutputTokens <= 0) {
  1176. $maxOutputTokens = 8192;
  1177. }
  1178. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1179. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1180. $maxOutputTokens = 32768;
  1181. }
  1182. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1183. // response_format 映射:text -> text/plain,json -> application/json
  1184. $responseFormat = getProp($data, 'response_format', 'text');
  1185. if (is_array($responseFormat)) {
  1186. $responseFormat = getProp($responseFormat, 'type', 'text');
  1187. }
  1188. if (in_array($responseFormat, ['json', 'json_object'])) {
  1189. $generationConfig['responseMimeType'] = 'application/json';
  1190. } else {
  1191. $generationConfig['responseMimeType'] = 'text/plain';
  1192. }
  1193. $requestData = [
  1194. 'contents' => $contents,
  1195. 'generationConfig' => $generationConfig,
  1196. ];
  1197. if ($systemInstruction !== '') {
  1198. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1199. }
  1200. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1201. $thinkingMode = getProp($data, 'thinking', null);
  1202. if (is_array($thinkingMode)) {
  1203. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1204. }
  1205. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1206. if ($thinkingMode === null) {
  1207. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1208. }
  1209. if ($thinkingMode === 'enabled') {
  1210. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1211. if ($thinkingBudget <= 0) {
  1212. $thinkingBudget = 20;
  1213. }
  1214. $requestData['generationConfig']['thinkingConfig'] = [
  1215. 'thinkingBudget' => $thinkingBudget
  1216. ];
  1217. } elseif ($defaultThinking) {
  1218. // 该模型仅支持思考模式,传 0 会返回 400
  1219. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1220. } else {
  1221. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1222. }
  1223. return $requestData;
  1224. }
  1225. /**
  1226. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1227. *
  1228. * 模型名 -> env 变量名映射:
  1229. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1230. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1231. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1232. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1233. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1234. */
  1235. private function getGeminiApiKey($model) {
  1236. $map = [
  1237. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1238. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1239. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1240. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1241. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1242. ];
  1243. if (isset($map[$model])) {
  1244. $key = env($map[$model]);
  1245. if (!empty($key)) {
  1246. return $key;
  1247. }
  1248. }
  1249. return env('GEMINI_API_KEY', '');
  1250. }
  1251. /**
  1252. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1253. */
  1254. private function geminiChatOnly($requestData, $model) {
  1255. $apiKey = $this->getGeminiApiKey($model);
  1256. if (empty($apiKey)) {
  1257. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1258. }
  1259. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1260. if (isset($requestData['messages'])) {
  1261. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1262. }
  1263. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1264. . '/models/' . $model . ':generateContent';
  1265. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1266. $headers = [
  1267. 'Authorization' => 'Bearer ' . $apiKey,
  1268. 'Content-Type' => 'application/json'
  1269. ];
  1270. $maxRetries = $this->gptRetryTimes();
  1271. $interval = $this->gptRetryInterval();
  1272. $attempt = 0;
  1273. while (true) {
  1274. try {
  1275. $response = $client->post($url, [
  1276. 'json' => $requestData,
  1277. 'headers' => $headers
  1278. ]);
  1279. $responseArr = json_decode($response->getBody()->getContents(), true);
  1280. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1281. $fullContent = $this->extractGeminiContent($responseArr);
  1282. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1283. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1284. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1285. ? $responseArr['candidates'][0]['finishReason']
  1286. : '';
  1287. return [
  1288. 'fullContent' => $fullContent,
  1289. 'fullReasoningContent' => $fullReasoningContent,
  1290. 'usage' => $usage,
  1291. 'finish_reason' => $finishReason
  1292. ];
  1293. } catch (\Exception $e) {
  1294. $retryable = true;
  1295. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1296. $status = $e->getResponse()->getStatusCode();
  1297. $retryable = $status >= 500 || $status == 429;
  1298. }
  1299. if (!$retryable || $attempt >= $maxRetries) {
  1300. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1301. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1302. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1303. }
  1304. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1305. 'retry' => $attempt + 1,
  1306. 'max_retries' => $maxRetries,
  1307. 'error' => $e->getMessage()
  1308. ]);
  1309. sleep($interval);
  1310. $attempt++;
  1311. }
  1312. }
  1313. }
  1314. /**
  1315. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1316. */
  1317. private function geminiStreamResponse($requestData, $model) {
  1318. $apiKey = $this->getGeminiApiKey($model);
  1319. if (empty($apiKey)) {
  1320. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1321. }
  1322. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1323. if (isset($requestData['messages'])) {
  1324. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1325. }
  1326. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1327. . '/models/' . $model . ':generateContent?alt=sse';
  1328. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1329. $headers = [
  1330. 'Authorization' => 'Bearer ' . $apiKey,
  1331. 'Content-Type' => 'application/json'
  1332. ];
  1333. try {
  1334. $response = $client->post($url, [
  1335. 'json' => $requestData,
  1336. 'headers' => $headers,
  1337. 'stream' => true
  1338. ]);
  1339. $body = $response->getBody();
  1340. $fullContent = '';
  1341. $fullReasoningContent = '';
  1342. $usage = [];
  1343. $buffer = '';
  1344. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1345. while (!$body->eof()) {
  1346. $chunk = $body->read(1024);
  1347. $buffer .= $chunk;
  1348. $lines = explode("\n", $buffer);
  1349. $buffer = array_pop($lines);
  1350. foreach ($lines as $line) {
  1351. $line = trim($line);
  1352. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1353. continue;
  1354. }
  1355. $data = substr($line, 6);
  1356. if ($data === '[DONE]') {
  1357. break 2;
  1358. }
  1359. try {
  1360. $json = json_decode($data, true);
  1361. if (json_last_error() !== JSON_ERROR_NONE) {
  1362. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1363. continue;
  1364. }
  1365. // 思考内容(thoughts)
  1366. $thoughts = $this->extractGeminiThoughts($json);
  1367. if ($thoughts !== '') {
  1368. $fullReasoningContent .= $thoughts;
  1369. yield [
  1370. 'type' => 'reasoning',
  1371. 'content' => $thoughts,
  1372. 'full_reasoning' => $fullReasoningContent
  1373. ];
  1374. }
  1375. // 回答内容
  1376. $partText = $this->extractGeminiContent($json);
  1377. if ($partText !== '') {
  1378. $fullContent .= $partText;
  1379. yield [
  1380. 'type' => 'content',
  1381. 'content' => $partText,
  1382. ];
  1383. }
  1384. // 使用统计
  1385. if (isset($json['usageMetadata'])) {
  1386. $usage = $json['usageMetadata'];
  1387. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  1388. }
  1389. } catch (\Exception $e) {
  1390. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1391. continue;
  1392. }
  1393. }
  1394. }
  1395. dLog('deepseek')->info('Gemini流式读取完成', [
  1396. 'content_length' => strlen($fullContent),
  1397. 'reasoning_length' => strlen($fullReasoningContent)
  1398. ]);
  1399. yield [
  1400. 'type' => 'done',
  1401. 'full_content' => $fullContent,
  1402. 'full_reasoning' => $fullReasoningContent,
  1403. 'usage' => $usage
  1404. ];
  1405. } catch (\Exception $e) {
  1406. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  1407. yield [
  1408. 'type' => 'error',
  1409. 'msg' => $e->getMessage(),
  1410. 'code' => $e->getCode()
  1411. ];
  1412. }
  1413. }
  1414. /**
  1415. * 从 Gemini 响应中提取回答文本
  1416. */
  1417. private function extractGeminiContent($responseArr) {
  1418. $text = '';
  1419. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  1420. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  1421. if (isset($part['text'])) {
  1422. $text .= $part['text'];
  1423. }
  1424. }
  1425. }
  1426. return $text;
  1427. }
  1428. /**
  1429. * 从 Gemini 响应中提取思考内容
  1430. */
  1431. private function extractGeminiReasoningContent($responseArr) {
  1432. $reasoning = '';
  1433. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1434. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1435. if (isset($thought['text'])) {
  1436. $reasoning .= $thought['text'];
  1437. }
  1438. }
  1439. }
  1440. return $reasoning;
  1441. }
  1442. /**
  1443. * 从 Gemini 流式响应中提取本次增量思考内容
  1444. */
  1445. private function extractGeminiThoughts($responseArr) {
  1446. $thoughts = '';
  1447. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1448. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1449. if (isset($thought['text'])) {
  1450. $thoughts .= $thought['text'];
  1451. }
  1452. }
  1453. }
  1454. return $thoughts;
  1455. }
  1456. /**
  1457. * 提取消息数组中的纯文本
  1458. */
  1459. private function extractGeminiTextFromParts($parts) {
  1460. $text = '';
  1461. if (is_array($parts)) {
  1462. foreach ($parts as $part) {
  1463. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  1464. $text .= (string)getProp($part, 'text', '');
  1465. }
  1466. }
  1467. }
  1468. return $text;
  1469. }
  1470. /**
  1471. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  1472. *
  1473. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  1474. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  1475. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  1476. *
  1477. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  1478. * @return array|null ['mime_type' => string, 'data' => string]
  1479. */
  1480. private function processMediaToInlineData($media) {
  1481. if (empty($media)) {
  1482. return null;
  1483. }
  1484. $localPath = null;
  1485. $isTempFile = false;
  1486. try {
  1487. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  1488. if (is_string($media) && strpos($media, 'data:') === 0) {
  1489. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  1490. return [
  1491. 'mime_type' => $matches[1],
  1492. 'data' => $matches[2]
  1493. ];
  1494. }
  1495. return null;
  1496. }
  1497. // 2. 获取本地文件路径
  1498. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  1499. $localPath = $this->downloadMediaToTemp($media);
  1500. $isTempFile = true;
  1501. } elseif (is_string($media)) {
  1502. $localPath = $media;
  1503. } else {
  1504. // Laravel UploadedFile 对象
  1505. $localPath = $media->getRealPath();
  1506. }
  1507. if (!$localPath || !file_exists($localPath)) {
  1508. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  1509. return null;
  1510. }
  1511. $fileSize = filesize($localPath);
  1512. $maxBytes = $this->geminiMediaMaxBytes();
  1513. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  1514. $mimeType = $this->detectMediaMime($localPath);
  1515. $isVideo = strpos($mimeType, 'video/') === 0;
  1516. $needCompress = $fileSize > $maxBytes;
  1517. $duration = 0;
  1518. if ($isVideo) {
  1519. $duration = $this->getMediaDuration($localPath);
  1520. if ($duration > 300) {
  1521. $needCompress = true;
  1522. }
  1523. }
  1524. $finalPath = $localPath;
  1525. $compressedPath = null;
  1526. if ($needCompress && $this->ffmpegAvailable()) {
  1527. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  1528. if ($compressed && file_exists($compressed)) {
  1529. $compressedPath = $compressed;
  1530. if (filesize($compressed) < $fileSize || $isVideo) {
  1531. $finalPath = $compressed;
  1532. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  1533. } else {
  1534. @unlink($compressed);
  1535. $compressedPath = null;
  1536. }
  1537. }
  1538. }
  1539. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  1540. $finalSize = filesize($finalPath);
  1541. if ($finalSize > $maxBytes) {
  1542. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  1543. 'path' => $localPath,
  1544. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  1545. 'limit_mb' => 14
  1546. ]);
  1547. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  1548. }
  1549. // 兜底校验:视频时长超过5分钟且未能压缩成功
  1550. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  1551. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  1552. }
  1553. $data = base64_encode(file_get_contents($finalPath));
  1554. return [
  1555. 'mime_type' => $mimeType,
  1556. 'data' => $data
  1557. ];
  1558. } catch (\App\Exceptions\ApiException $e) {
  1559. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  1560. throw $e;
  1561. } catch (\Exception $e) {
  1562. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  1563. return null;
  1564. } finally {
  1565. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  1566. @unlink($compressedPath);
  1567. }
  1568. if ($isTempFile && $localPath && file_exists($localPath)) {
  1569. @unlink($localPath);
  1570. }
  1571. }
  1572. }
  1573. /**
  1574. * 下载远程多媒体到临时目录
  1575. *
  1576. * @return string|null 本地临时文件路径
  1577. */
  1578. private function downloadMediaToTemp($url) {
  1579. try {
  1580. $tempDir = storage_path('app/temp/gemini');
  1581. if (!is_dir($tempDir)) {
  1582. mkdir($tempDir, 0775, true);
  1583. }
  1584. $extension = 'tmp';
  1585. $pathInfo = parse_url($url, PHP_URL_PATH);
  1586. if ($pathInfo) {
  1587. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  1588. if ($ext && strlen($ext) <= 10) {
  1589. $extension = strtolower($ext);
  1590. }
  1591. }
  1592. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  1593. $client = new Client(['timeout' => 300, 'verify' => false]);
  1594. $response = $client->get($url, ['sink' => $tmpFile]);
  1595. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  1596. @unlink($tmpFile);
  1597. return null;
  1598. }
  1599. return $tmpFile;
  1600. } catch (\Exception $e) {
  1601. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  1602. return null;
  1603. }
  1604. }
  1605. /**
  1606. * 检测多媒体文件 MIME 类型
  1607. */
  1608. private function detectMediaMime($filePath) {
  1609. $imageInfo = @getimagesize($filePath);
  1610. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  1611. return $imageInfo['mime'];
  1612. }
  1613. // 视频按扩展名粗略判断
  1614. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  1615. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  1616. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  1617. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  1618. if (isset($videoExts[$ext])) {
  1619. return $videoExts[$ext];
  1620. }
  1621. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  1622. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  1623. if (isset($imageExts[$ext])) {
  1624. return $imageExts[$ext];
  1625. }
  1626. return 'application/octet-stream';
  1627. }
  1628. /**
  1629. * 获取多媒体时长(秒),非视频或失败返回 0
  1630. */
  1631. private function getMediaDuration($filePath) {
  1632. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  1633. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  1634. $output = trim((string)shell_exec($cmd));
  1635. $duration = (float)$output;
  1636. return $duration > 0 ? $duration : 0;
  1637. }
  1638. /**
  1639. * 检查 ffmpeg 是否可用
  1640. */
  1641. private function ffmpegAvailable() {
  1642. static $available = null;
  1643. if ($available !== null) {
  1644. return $available;
  1645. }
  1646. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1647. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  1648. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  1649. $available = false;
  1650. return $available;
  1651. }
  1652. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  1653. $output = shell_exec($cmd);
  1654. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  1655. return $available;
  1656. }
  1657. /**
  1658. * 使用 ffmpeg 压缩多媒体文件
  1659. *
  1660. * @param string $inputFile 输入文件路径
  1661. * @param bool $isVideo 是否为视频
  1662. * @param float $duration 视频时长(秒),非视频传 0
  1663. * @return string|null 压缩后的文件路径,失败返回 null
  1664. */
  1665. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  1666. try {
  1667. $tempDir = storage_path('app/temp/gemini');
  1668. if (!is_dir($tempDir)) {
  1669. mkdir($tempDir, 0775, true);
  1670. }
  1671. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1672. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  1673. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  1674. if ($isVideo) {
  1675. // 视频:时长超过5分钟则加速压缩到5分钟以内
  1676. $speedFactor = 1.0;
  1677. if ($duration > 300) {
  1678. $speedFactor = $duration / 300;
  1679. }
  1680. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  1681. $finalDuration = $duration / max(1.0, $speedFactor);
  1682. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  1683. $targetBitrate = max(300, min(6000, $targetBitrate));
  1684. $filters = [];
  1685. $filters[] = 'scale=min(1280,iw):-2';
  1686. $filters[] = 'fps=24';
  1687. if ($speedFactor > 1.0) {
  1688. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  1689. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  1690. $fullCount = (int)ceil($speedFactor / 2.0);
  1691. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1692. if ($lastTempo < 0.5) {
  1693. $fullCount++;
  1694. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1695. }
  1696. for ($i = 0; $i < $fullCount; $i++) {
  1697. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  1698. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  1699. }
  1700. }
  1701. $filterStr = implode(',', $filters);
  1702. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  1703. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  1704. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  1705. } else {
  1706. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  1707. $imageInfo = @getimagesize($inputFile);
  1708. $scaleW = 2048;
  1709. $scaleH = 2048;
  1710. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  1711. if ($imageInfo[0] >= $imageInfo[1]) {
  1712. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  1713. $scaleW = 2048;
  1714. } else {
  1715. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  1716. $scaleH = 2048;
  1717. }
  1718. }
  1719. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  1720. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  1721. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  1722. }
  1723. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  1724. $output = shell_exec($cmd);
  1725. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  1726. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  1727. 'input' => $inputFile,
  1728. 'output' => $output
  1729. ]);
  1730. @unlink($outputFile);
  1731. return null;
  1732. }
  1733. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  1734. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  1735. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  1736. ]);
  1737. return $outputFile;
  1738. } catch (\Exception $e) {
  1739. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  1740. return null;
  1741. }
  1742. }
  1743. /**
  1744. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  1745. *
  1746. * @param array $data
  1747. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1748. */
  1749. public function getScriptGenerateTasks($data) {
  1750. $uid = Site::getUid();
  1751. return DB::table('mp_script_generate_tasks as t')
  1752. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  1753. ->where('t.uid', $uid)
  1754. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  1755. ->orderByDesc('t.id')
  1756. ->paginate(15);
  1757. }
  1758. public function saveScriptChatHistory($data) {
  1759. $uid = Site::getUid();
  1760. $rid = getProp($data, 'rid');
  1761. $script_id = getProp($data, 'script_id');
  1762. $sequence = getProp($data, 'sequence', 0);
  1763. $content = getProp($data, 'content');
  1764. if (!$rid) {
  1765. Utils::throwError('20003:请选择对话记录ID');
  1766. }
  1767. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  1768. if (!$record) {
  1769. Utils::throwError('20003:对话记录不存在');
  1770. }
  1771. if (!$script_id) {
  1772. Utils::throwError('20003:请选择剧本');
  1773. }
  1774. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  1775. if (!$script) {
  1776. Utils::throwError('20003:剧本不存在');
  1777. }
  1778. // 批量插入数据
  1779. return DB::table('mp_script_records')->where('id', $rid)->update([
  1780. 'content' => $content,
  1781. 'updated_at' => date('Y-m-d H:i:s')
  1782. ]);
  1783. }
  1784. /**
  1785. * 获取剧本的历史对话记录
  1786. *
  1787. * @param array $data 请求参数
  1788. * @return array 返回历史记录数组
  1789. */
  1790. public function getScriptChatHistory($data) {
  1791. $uid = Site::getUid();
  1792. $script_id = getProp($data, 'script_id');
  1793. $rid = getProp($data, 'rid');
  1794. $sequence = getProp($data, 'sequence', null);
  1795. if (!$script_id) {
  1796. Utils::throwError('20003:请提供剧本ID');
  1797. }
  1798. // 验证剧本是否存在
  1799. $script = DB::table('mp_scripts')
  1800. ->where('id', $script_id)
  1801. ->where('is_deleted', 0)
  1802. ->first();
  1803. if (!$script) {
  1804. Utils::throwError('20003:剧本不存在');
  1805. }
  1806. // 构建查询
  1807. $query = DB::table('mp_script_records')
  1808. ->where('script_id', $script_id);
  1809. // ->where('uid', $uid);
  1810. // 如果提供了 sequence,则过滤指定剧集
  1811. if ($sequence !== null) {
  1812. $query->where('sequence', $sequence);
  1813. }
  1814. // 记录ID筛选
  1815. if ($rid) {
  1816. $query->where('id', $rid);
  1817. }
  1818. // 查询记录并按 id 正序排序
  1819. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  1820. ->orderBy('created_at', 'asc')
  1821. ->orderBy('id', 'asc')
  1822. ->get()
  1823. ->map(function ($record) {
  1824. return [
  1825. 'rid' => $record->id,
  1826. 'script_id' => $record->script_id,
  1827. 'sequence' => $record->sequence,
  1828. 'role' => $record->role,
  1829. 'content' => $record->content,
  1830. 'products' => $record->products ? json_decode($record->products) : [],
  1831. 'created_at' => $record->created_at,
  1832. ];
  1833. })
  1834. ->toArray();
  1835. return $records;
  1836. }
  1837. /**
  1838. * 处理图片转换为base64
  1839. *
  1840. * @param mixed $image 图片文件对象或文件路径
  1841. * @return string|null base64编码的图片数据
  1842. */
  1843. private function processImageToBase64($image) {
  1844. try {
  1845. // 获取文件路径
  1846. if (is_string($image)) {
  1847. $filePath = $image;
  1848. } else {
  1849. // Laravel UploadedFile 对象
  1850. $filePath = $image->getRealPath();
  1851. }
  1852. if (!file_exists($filePath)) {
  1853. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  1854. return null;
  1855. }
  1856. // 验证是否为图片文件
  1857. $imageInfo = @getimagesize($filePath);
  1858. if ($imageInfo === false) {
  1859. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  1860. return null;
  1861. }
  1862. // 读取图片并转换为base64
  1863. $imageData = file_get_contents($filePath);
  1864. $base64Image = base64_encode($imageData);
  1865. dLog('deepseek')->info('图片转换成功', [
  1866. 'size' => strlen($imageData),
  1867. 'type' => $imageInfo['mime']
  1868. ]);
  1869. return $base64Image;
  1870. } catch (\Exception $e) {
  1871. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  1872. return null;
  1873. }
  1874. }
  1875. private function getArtStylePromptMappings($art_style='')
  1876. {
  1877. $arr = [
  1878. '唯美真人风格' => [
  1879. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1880. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  1881. ],
  1882. '真人古风风格' => [
  1883. 'aliases' => ['真人古风风格', '真人古风'],
  1884. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  1885. ],
  1886. '日系动漫风格' => [
  1887. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1888. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  1889. ],
  1890. '国漫风格' => [
  1891. 'aliases' => ['国漫风格', '国漫'],
  1892. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  1893. ],
  1894. 'Q版卡通风格' => [
  1895. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1896. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  1897. ],
  1898. '简约扁平风格' => [
  1899. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1900. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  1901. ],
  1902. '武侠风格' => [
  1903. 'aliases' => ['武侠风格', '武侠'],
  1904. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  1905. ],
  1906. '古风仙侠风格' => [
  1907. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1908. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  1909. ],
  1910. '新中式水墨风格' => [
  1911. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  1912. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  1913. ],
  1914. '写实插画风格' => [
  1915. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  1916. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  1917. ],
  1918. '3D卡通风格' => [
  1919. 'aliases' => ['3D卡通风格', '3D卡通'],
  1920. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  1921. ],
  1922. '条漫风格' => [
  1923. 'aliases' => ['条漫风格', '条漫'],
  1924. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  1925. ],
  1926. '赛博朋克风格' => [
  1927. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1928. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  1929. ],
  1930. '暗黑悬疑风格' => [
  1931. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1932. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  1933. ],
  1934. '治愈清新风格' => [
  1935. 'aliases' => ['治愈清新风格', '治愈清新'],
  1936. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  1937. ],
  1938. '3D真人风格' => [
  1939. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  1940. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  1941. ],
  1942. ];
  1943. if($art_style) {
  1944. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  1945. }
  1946. return $arr;
  1947. $arr = [
  1948. '唯美真人风格' => [
  1949. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1950. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  1951. 2. 色彩色调
  1952. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  1953. 3. 画质精度
  1954. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  1955. 4. 画面观感
  1956. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  1957. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  1958. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  1959. ],
  1960. '真人古风风格' => [
  1961. 'aliases' => ['真人古风风格', '真人古风'],
  1962. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  1963. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  1964. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  1965. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  1966. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  1967. ],
  1968. '日系动漫风格' => [
  1969. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1970. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  1971. 正向提示词(中文)
  1972. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  1973. 必须遵守规则
  1974. • 全程保持日系动漫风格,不混入其他画风
  1975. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  1976. • 画面适配所选画面比例,构图居中,主体突出
  1977. • 线条干净、色彩统一,不杂乱、不突兀
  1978. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  1979. ],
  1980. '国漫风格' => [
  1981. 'aliases' => ['国漫风格', '国漫'],
  1982. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  1983. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  1984. 必须遵守规则
  1985. • 严格保持国漫画风,不串风格、不混画风
  1986. • 角色形象统一,不随意改变五官、身材、服饰
  1987. • 画面构图稳定,适合漫剧叙事展示
  1988. • 色调统一,不出现脏色、杂色
  1989. 禁止/避免词汇
  1990. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  1991. ],
  1992. 'Q版卡通风格' => [
  1993. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1994. 'prompt' => "风格说明
  1995. 头大身小,造型可爱圆润,简约干净
  1996. 正向提示词(中文)
  1997. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  1998. 必须遵守规则
  1999. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  2000. • 角色造型统一,表情可爱,不诡异
  2001. • 画面简洁清爽,无多余复杂元素
  2002. • 色彩明亮柔和,不刺眼
  2003. 禁止/避免词汇
  2004. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  2005. ],
  2006. '简约扁平风格' => [
  2007. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2008. 'prompt' => "风格说明
  2009. 色块简洁、无复杂渐变,现代极简风
  2010. 正向提示词(中文)
  2011. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  2012. 必须遵守规则
  2013. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  2014. • 构图简洁,主体突出,无多余装饰
  2015. • 色彩统一、干净,不杂乱
  2016. 禁止/避免词汇
  2017. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  2018. ],
  2019. '武侠风格' => [
  2020. 'aliases' => ['武侠风格', '武侠'],
  2021. 'prompt' => "风格说明
  2022. 江湖气息,线条硬朗,动作感强
  2023. 正向提示词(中文)
  2024. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  2025. 必须遵守规则
  2026. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  2027. • 角色形象、服饰、身材比例统一
  2028. • 画面动作自然,不扭曲、不畸形
  2029. 禁止/避免词汇
  2030. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  2031. ],
  2032. '古风仙侠风格' => [
  2033. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2034. 'prompt' => "风格说明
  2035. 飘逸汉服、云雾仙气、唯美空灵
  2036. 正向提示词(中文)
  2037. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  2038. 必须遵守规则
  2039. • 保持古风仙侠统一画风,不混入现代、科幻元素
  2040. • 角色服饰、发型、形象前后一致
  2041. • 场景仙气飘逸,色调清雅统一
  2042. • 画面唯美柔和,不阴暗、不诡异
  2043. 禁止/避免词汇
  2044. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  2045. ],
  2046. '新中式水墨风格' => [
  2047. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2048. 'prompt' => "风格说明
  2049. 淡墨渲染,毛笔笔触,留白意境
  2050. 正向提示词(中文)
  2051. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  2052. 必须遵守规则
  2053. • 严格保持水墨质感,不混入厚涂、写实、卡通
  2054. • 色调淡雅统一,不浓艳杂乱
  2055. • 画面干净有意境,不堆砌元素
  2056. 禁止/避免词汇
  2057. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  2058. ],
  2059. '写实插画风格' => [
  2060. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2061. 'prompt' => "风格说明
  2062. 接近真人比例,光影真实,质感细腻
  2063. 正向提示词(中文)
  2064. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  2065. 必须遵守规则
  2066. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  2067. • 角色五官、身材、服饰高度统一
  2068. • 画面清晰、光影自然、不扭曲
  2069. 禁止/避免词汇
  2070. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  2071. ],
  2072. '3D卡通风格' => [
  2073. 'aliases' => ['3D卡通风格', '3D卡通'],
  2074. 'prompt' => "风格说明
  2075. 3D建模质感,柔和渲染,圆润可爱
  2076. 正向提示词(中文)
  2077. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  2078. 必须遵守规则
  2079. • 保持3D卡通统一质感,不出现2D杂乱线条
  2080. • 角色模型、比例、形象前后一致
  2081. • 画面干净,不模糊、不穿模
  2082. 禁止/避免词汇
  2083. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  2084. ],
  2085. '条漫风格' => [
  2086. 'aliases' => ['条漫风格', '条漫'],
  2087. 'prompt' => "风格说明
  2088. 纵向分镜,上下滑动阅读,轻量化
  2089. 正向提示词(中文)
  2090. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  2091. 必须遵守规则
  2092. • 保持条漫纵向阅读逻辑,构图简洁
  2093. • 画风统一,不混写实、3D、水墨
  2094. • 画面干净,不杂乱
  2095. 禁止/避免词汇
  2096. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  2097. ],
  2098. '赛博朋克风格' => [
  2099. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2100. 'prompt' => "风格说明
  2101. 霓虹灯光、未来都市、暗色调、科技机械
  2102. 正向提示词(中文)
  2103. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  2104. 必须遵守规则
  2105. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  2106. • 色调以暗调+霓虹为主,色彩统一
  2107. • 画面科技感强,不杂乱
  2108. 禁止/避免词汇
  2109. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  2110. ],
  2111. '暗黑悬疑风格' => [
  2112. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2113. 'prompt' => "风格说明
  2114. 低饱和、冷色调、阴影重、神秘压抑
  2115. 正向提示词(中文)
  2116. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  2117. 必须遵守规则
  2118. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  2119. • 画面氛围压抑神秘,但不低俗、不血腥
  2120. • 角色形象统一,不崩坏
  2121. 禁止/避免词汇
  2122. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  2123. ],
  2124. '治愈清新风格' => [
  2125. 'aliases' => ['治愈清新风格', '治愈清新'],
  2126. 'prompt' => "风格说明
  2127. 马卡龙色系、柔光、温暖干净
  2128. 正向提示词(中文)
  2129. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  2130. 必须遵守规则
  2131. • 保持治愈清新统一色调,不阴暗、不诡异
  2132. • 画面柔和干净,无杂乱元素
  2133. • 角色形象柔和可爱,不狰狞
  2134. 禁止/避免词汇
  2135. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  2136. ],
  2137. ];
  2138. return $arr;
  2139. }
  2140. public function getArtStylePromptByInput($inputArtStyle): string
  2141. {
  2142. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2143. if ($normalizedInput === '') {
  2144. return '';
  2145. }
  2146. return $this->getArtStylePromptMappings($normalizedInput);
  2147. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  2148. // foreach ($mapping['aliases'] as $alias) {
  2149. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  2150. // if ($normalizedAlias === '') {
  2151. // continue;
  2152. // }
  2153. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  2154. // return $mapping['prompt'];
  2155. // }
  2156. // }
  2157. // }
  2158. return '';
  2159. }
  2160. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2161. $stylePrefixes = [
  2162. '唯美真人风格' => [
  2163. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2164. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  2165. ],
  2166. '真人古风风格' => [
  2167. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2168. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  2169. ],
  2170. '日系动漫风格' => [
  2171. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2172. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  2173. ],
  2174. '国漫风格' => [
  2175. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2176. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  2177. ],
  2178. 'Q版卡通风格' => [
  2179. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2180. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  2181. ],
  2182. '简约扁平风格' => [
  2183. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2184. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  2185. ],
  2186. '武侠风格' => [
  2187. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2188. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  2189. ],
  2190. '古风仙侠风格' => [
  2191. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2192. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  2193. ],
  2194. '新中式水墨风格' => [
  2195. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2196. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  2197. ],
  2198. '写实插画风格' => [
  2199. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2200. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  2201. ],
  2202. '3D卡通风格' => [
  2203. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2204. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  2205. ],
  2206. '条漫风格' => [
  2207. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2208. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  2209. ],
  2210. '赛博朋克风格' => [
  2211. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2212. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  2213. ],
  2214. '暗黑悬疑风格' => [
  2215. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2216. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  2217. ],
  2218. '治愈清新风格' => [
  2219. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2220. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  2221. ]
  2222. ];
  2223. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  2224. }
  2225. private function normalizeArtStyleInput($value): string
  2226. {
  2227. $value = trim((string)$value);
  2228. if ($value === '') {
  2229. return '';
  2230. }
  2231. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2232. return mb_strtolower($value, 'UTF-8');
  2233. }
  2234. private function replaceArtStyleSection(string $content, string $artStyle): string
  2235. {
  2236. if ($content === '' || $artStyle === '') {
  2237. return $content;
  2238. }
  2239. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2240. if (!preg_match($pattern, $content)) {
  2241. return $content;
  2242. }
  2243. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2244. }
  2245. /**
  2246. * DeepSeek流式输出处理方法
  2247. *
  2248. * @param array $post_data DeepSeek API请求参数
  2249. * @return \Generator 返回生成器,用于流式输出
  2250. */
  2251. private function unwrapJsonWrappedContent($content) {
  2252. $trimmed = ltrim((string)$content);
  2253. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2254. return $content;
  2255. }
  2256. $decoded = json_decode($trimmed, true);
  2257. if (!is_array($decoded)) {
  2258. return $content;
  2259. }
  2260. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2261. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2262. return $decoded[$key];
  2263. }
  2264. }
  2265. return $content;
  2266. }
  2267. private function deepSeekStreamResponse($post_data) {
  2268. // 设置最大输出tokens
  2269. $post_data['max_tokens'] = 300000;
  2270. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2271. $post_data['stream_options'] = ['include_usage' => true];
  2272. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2273. $response = $client->post($this->url, [
  2274. 'json' => $post_data,
  2275. 'headers' => $this->headers,
  2276. 'stream' => true // 启用流式响应
  2277. ]);
  2278. $body = $response->getBody();
  2279. $fullContent = '';
  2280. $fullReasoningContent = '';
  2281. $usage = [];
  2282. $buffer = '';
  2283. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2284. // 逐行读取流式响应
  2285. while (!$body->eof()) {
  2286. $chunk = $body->read(1024); // 每次读取 1KB
  2287. $buffer .= $chunk;
  2288. // 按行分割
  2289. $lines = explode("\n", $buffer);
  2290. // 保留最后一个不完整的行
  2291. $buffer = array_pop($lines);
  2292. foreach ($lines as $line) {
  2293. $line = trim($line);
  2294. // 跳过空行
  2295. if (empty($line)) {
  2296. continue;
  2297. }
  2298. // 检查是否是 SSE 数据行
  2299. if (strpos($line, 'data: ') !== 0) {
  2300. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2301. continue;
  2302. }
  2303. $data = substr($line, 6); // 移除 "data: " 前缀
  2304. if ($data === '[DONE]') {
  2305. dLog('deepseek')->info('收到结束标记');
  2306. break 2; // 跳出两层循环
  2307. }
  2308. try {
  2309. $json = json_decode($data, true);
  2310. if (json_last_error() !== JSON_ERROR_NONE) {
  2311. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2312. continue;
  2313. }
  2314. if (isset($json['choices'][0]['delta'])) {
  2315. $delta = $json['choices'][0]['delta'];
  2316. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2317. if (isset($delta['reasoning_content'])) {
  2318. $fullReasoningContent .= $delta['reasoning_content'];
  2319. yield [
  2320. 'type' => 'reasoning',
  2321. 'content' => $delta['reasoning_content'],
  2322. 'full_reasoning' => $fullReasoningContent
  2323. ];
  2324. }
  2325. // 处理最终回答内容
  2326. if (isset($delta['content'])) {
  2327. $fullContent .= $delta['content'];
  2328. yield [
  2329. 'type' => 'content',
  2330. 'content' => $delta['content'],
  2331. ];
  2332. }
  2333. }
  2334. // 获取使用统计信息
  2335. if (isset($json['usage'])) {
  2336. $usage = $json['usage'];
  2337. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2338. }
  2339. } catch (\Exception $e) {
  2340. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2341. continue;
  2342. }
  2343. }
  2344. }
  2345. dLog('deepseek')->info('流式读取完成', [
  2346. 'content_length' => strlen($fullContent),
  2347. 'reasoning_length' => strlen($fullReasoningContent)
  2348. ]);
  2349. yield [
  2350. 'type' => 'done',
  2351. 'full_content' => $fullContent,
  2352. 'full_reasoning' => $fullReasoningContent,
  2353. 'usage' => $usage
  2354. ];
  2355. }
  2356. /**
  2357. * GPT 重试次数(env 可配置,默认 5 次)
  2358. */
  2359. private function gptRetryTimes()
  2360. {
  2361. return (int)env('GPT_RETRY_TIMES', 5);
  2362. }
  2363. /**
  2364. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  2365. */
  2366. private function gptRetryInterval()
  2367. {
  2368. return (int)env('GPT_RETRY_INTERVAL', 10);
  2369. }
  2370. /**
  2371. * 判断 GPT 请求异常是否可重试
  2372. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  2373. */
  2374. private function isGptRetryableException(\Exception $e)
  2375. {
  2376. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  2377. return false;
  2378. }
  2379. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  2380. $status = $e->getResponse()->getStatusCode();
  2381. return $status >= 500 || $status == 429;
  2382. }
  2383. return true;
  2384. }
  2385. /**
  2386. * GPT 中转站探活:GET /v1/models,5 秒短超时
  2387. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  2388. */
  2389. private function checkGptServiceAvailable()
  2390. {
  2391. $apiKey = env('GPT_54_API_KEY');
  2392. if (empty($apiKey)) {
  2393. return false;
  2394. }
  2395. try {
  2396. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  2397. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  2398. 'headers' => [
  2399. 'Authorization' => 'Bearer ' . $apiKey,
  2400. 'Content-Type' => 'application/json'
  2401. ]
  2402. ]);
  2403. $status = $response->getStatusCode();
  2404. return $status < 500 && $status != 429;
  2405. } catch (\Exception $e) {
  2406. return false;
  2407. }
  2408. }
  2409. /**
  2410. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  2411. * 全部失败抛出友好错误
  2412. */
  2413. private function ensureGptServiceAvailable()
  2414. {
  2415. $maxRetries = $this->gptRetryTimes();
  2416. $interval = $this->gptRetryInterval();
  2417. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  2418. if ($this->checkGptServiceAvailable()) {
  2419. return;
  2420. }
  2421. if ($attempt < $maxRetries) {
  2422. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  2423. 'retry' => $attempt + 1,
  2424. 'max_retries' => $maxRetries
  2425. ]);
  2426. sleep($interval);
  2427. }
  2428. }
  2429. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  2430. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  2431. 'max_retries' => $maxRetries,
  2432. 'interval' => $interval
  2433. ]);
  2434. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  2435. }
  2436. /**
  2437. * GPT 流式输出处理方法
  2438. *
  2439. * @param array $post_data GPT API请求参数
  2440. * @return \Generator 返回生成器,用于流式输出
  2441. */
  2442. private function gpt54StreamResponse($post_data) {
  2443. $apiKey = env('GPT_54_API_KEY');
  2444. if (empty($apiKey)) {
  2445. Utils::throwError('20003:GPT API Key未配置');
  2446. }
  2447. // 先探活,服务不可用时自动重试
  2448. $this->ensureGptServiceAvailable();
  2449. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2450. $headers = [
  2451. 'Authorization' => 'Bearer ' . $apiKey,
  2452. 'Content-Type' => 'application/json',
  2453. 'Accept' => 'text/event-stream'
  2454. ];
  2455. // 移除 thinking 参数,GPT-5.4 不支持
  2456. if (isset($post_data['thinking'])) {
  2457. unset($post_data['thinking']);
  2458. }
  2459. if (isset($post_data['reasoning_effort'])) {
  2460. unset($post_data['reasoning_effort']);
  2461. }
  2462. // 中转站不识别 response_format,可能被误转成 JSON 输出模式
  2463. if (isset($post_data['response_format'])) {
  2464. unset($post_data['response_format']);
  2465. }
  2466. $post_data['max_completion_tokens'] = 100000;
  2467. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2468. $post_data['stream_options'] = ['include_usage' => true];
  2469. $maxRetries = $this->gptRetryTimes();
  2470. $interval = $this->gptRetryInterval();
  2471. $attempt = 0;
  2472. while (true) {
  2473. $fullContent = '';
  2474. $usage = [];
  2475. $buffer = '';
  2476. $suspectJsonWrap = false;
  2477. $pendingContent = '';
  2478. try {
  2479. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  2480. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  2481. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  2482. 'json' => $post_data,
  2483. 'headers' => $headers,
  2484. 'stream' => true // 启用流式响应
  2485. ]);
  2486. $body = $response->getBody();
  2487. dLog('deepseek')->info('开始读取 GPT 流式响应');
  2488. // 逐行读取流式响应
  2489. while (!$body->eof()) {
  2490. $chunk = $body->read(1024); // 每次读取 1KB
  2491. $buffer .= $chunk;
  2492. // 按行分割
  2493. $lines = explode("\n", $buffer);
  2494. // 保留最后一个不完整的行
  2495. $buffer = array_pop($lines);
  2496. foreach ($lines as $line) {
  2497. $line = trim($line);
  2498. // 跳过空行
  2499. if (empty($line)) {
  2500. continue;
  2501. }
  2502. // 检查是否是 SSE 数据行
  2503. if (strpos($line, 'data: ') !== 0) {
  2504. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2505. continue;
  2506. }
  2507. $data = substr($line, 6); // 移除 "data: " 前缀
  2508. if ($data === '[DONE]') {
  2509. dLog('deepseek')->info('收到结束标记');
  2510. break 2; // 跳出 foreach 和流读取循环
  2511. }
  2512. try {
  2513. $json = json_decode($data, true);
  2514. if (json_last_error() !== JSON_ERROR_NONE) {
  2515. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2516. continue;
  2517. }
  2518. if (isset($json['choices'][0]['delta'])) {
  2519. $delta = $json['choices'][0]['delta'];
  2520. // 处理回答内容
  2521. if (isset($delta['content'])) {
  2522. $fullContent .= $delta['content'];
  2523. $trimmed = ltrim($fullContent);
  2524. if (!$suspectJsonWrap && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  2525. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  2526. $suspectJsonWrap = true;
  2527. }
  2528. if (!$suspectJsonWrap) {
  2529. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  2530. $chunkSize = 256;
  2531. $chunkLength = mb_strlen($delta['content']);
  2532. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  2533. yield [
  2534. 'type' => 'content',
  2535. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  2536. ];
  2537. }
  2538. } else {
  2539. $pendingContent .= $delta['content'];
  2540. }
  2541. }
  2542. }
  2543. // 获取使用统计信息
  2544. if (isset($json['usage'])) {
  2545. $usage = $json['usage'];
  2546. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2547. }
  2548. } catch (\Exception $e) {
  2549. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2550. continue;
  2551. }
  2552. }
  2553. }
  2554. dLog('deepseek')->info('流式读取完成', [
  2555. 'content_length' => strlen($fullContent)
  2556. ]);
  2557. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  2558. if ($suspectJsonWrap) {
  2559. $decoded = json_decode(trim($fullContent), true);
  2560. $unwrapped = null;
  2561. if (is_array($decoded)) {
  2562. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2563. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2564. $unwrapped = $decoded[$key];
  2565. break;
  2566. }
  2567. }
  2568. }
  2569. if ($unwrapped !== null) {
  2570. $fullContent = $unwrapped;
  2571. $chunkSize = 256;
  2572. $contentLength = mb_strlen($fullContent);
  2573. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  2574. yield [
  2575. 'type' => 'content',
  2576. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  2577. ];
  2578. }
  2579. } elseif ($pendingContent !== '') {
  2580. // 误判:补发暂缓内容,避免内容丢失
  2581. yield [
  2582. 'type' => 'content',
  2583. 'content' => $pendingContent,
  2584. ];
  2585. }
  2586. }
  2587. yield [
  2588. 'type' => 'done',
  2589. 'full_content' => $fullContent,
  2590. 'full_reasoning' => '',
  2591. 'usage' => $usage
  2592. ];
  2593. return;
  2594. } catch (\Exception $e) {
  2595. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  2596. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  2597. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  2598. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  2599. throw $e;
  2600. }
  2601. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  2602. 'retry' => $attempt + 1,
  2603. 'max_retries' => $maxRetries,
  2604. 'error' => $e->getMessage()
  2605. ]);
  2606. sleep($interval);
  2607. $attempt++;
  2608. }
  2609. }
  2610. }
  2611. // 与推理模型对话
  2612. public function chatWithReasoner($data) {
  2613. $content = getProp($data, 'content');
  2614. $model = getProp($data, 'model', 'r1');
  2615. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2616. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2617. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2618. if ($model == 'r1') {
  2619. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  2620. $thinkingMode = 'disabled';
  2621. } else {
  2622. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  2623. $thinkingMode = 'disabled';
  2624. }
  2625. // 获取可选情感(根据音色可支持情感选)
  2626. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  2627. $emotion_list = [];
  2628. foreach ($timbre_emotion as $emotion) {
  2629. $tmp = explode(',', $emotion);
  2630. $emotion_list = array_merge($emotion_list, $tmp);
  2631. }
  2632. $emotion_list = array_unique($emotion_list);
  2633. $emotion_str = implode('、', $emotion_list);
  2634. // // 获取可选情感
  2635. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  2636. // $emotion_str = implode('、', $emotion_list);
  2637. // 是否启用情感
  2638. $enable_emotion = getProp($data, 'enable_emotion', 0);
  2639. if ($enable_emotion) {
  2640. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  2641. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2642. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  2643. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  2644. }else {
  2645. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  2646. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2647. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  2648. }
  2649. $messages = [
  2650. [
  2651. 'role' => 'system',
  2652. 'content' => $sys_content
  2653. ],
  2654. [
  2655. 'role' => 'user',
  2656. 'content' => $content
  2657. ]
  2658. ];
  2659. $post_data = [
  2660. 'model' => $model,
  2661. 'messages' => $messages,
  2662. // 'max_tokens' => 8192,
  2663. 'temperature' => 1,
  2664. 'frequency_penalty' => 0,
  2665. 'presence_penalty' => 0,
  2666. 'thinking' => ['type' => $thinkingMode],
  2667. 'response_format' => [
  2668. 'type' => 'text'
  2669. ],
  2670. 'stream' => false
  2671. ];
  2672. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2673. // 根据模型类型选择调用方法
  2674. $fullContent = '';
  2675. $usage = [];
  2676. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2677. // DeepSeek 官方模型使用 DeepSeek API
  2678. $chatResult = $this->chatOnly($post_data);
  2679. } else if (in_array($model, $this->gpt_text_models)) {
  2680. // GPT-5.4 模型使用 TokenRouter API
  2681. $chatResult = $this->gpt54ChatOnly($post_data);
  2682. } else {
  2683. // 其他模型使用火山引擎API
  2684. $chatResult = $this->volcEngineChatCompletion($post_data);
  2685. }
  2686. if (is_array($chatResult)) {
  2687. $fullContent = $chatResult['fullContent'];
  2688. $usage = $chatResult['usage'];
  2689. }
  2690. // 处理获取到的剧本数据
  2691. $script_content = handleScriptWords($fullContent, $enable_emotion);
  2692. $result = [
  2693. 'origin_content' => $fullContent,
  2694. 'roles' => getProp($script_content, 'roles'),
  2695. 'words' => getProp($script_content, 'words'),
  2696. ];
  2697. return $result;
  2698. }
  2699. public function resetParagraphAudio($data) {
  2700. $bid = getProp($data, 'bid');
  2701. $cid = getProp($data, 'cid');
  2702. $version_id = getProp($data, 'version_id');
  2703. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  2704. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  2705. 'generate_status' => '待制作',
  2706. 'updated_at' => date('Y-m-d H:i:s')
  2707. ]);
  2708. }
  2709. public function saveParagraphAudio($data) {
  2710. $bid = getProp($data, 'bid');
  2711. $cid = getProp($data, 'cid');
  2712. $version_id = getProp($data, 'version_id');
  2713. $sequence = getProp($data, 'sequence');
  2714. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  2715. // 获取所有情感
  2716. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2717. $emotion_list = array_flip($emotion_list);
  2718. // 获取音色支持情感
  2719. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  2720. $timbre_emotion = explode(',', $timbre_emotion);
  2721. $emotion = getProp($data, 'emotion');
  2722. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  2723. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  2724. $list = [
  2725. 'bid' => $bid,
  2726. 'cid' => $cid,
  2727. 'version_id' => $version_id,
  2728. 'sequence' => $sequence,
  2729. 'role' => getProp($data, 'role'),
  2730. 'gender' => getProp($data, 'gender'),
  2731. 'text' => trim(getProp($data, 'text')),
  2732. 'emotion' => $emotion,
  2733. 'emotion_type' => $emotion_type,
  2734. 'voice_type' => getProp($data, 'voice_type'),
  2735. 'voice_name' => getProp($data, 'voice_name'),
  2736. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  2737. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  2738. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  2739. 'pitch' => getProp($data, 'pitch', 0),
  2740. // 'paragraph_audio_url' => '',
  2741. 'generate_status' => '制作中',
  2742. 'error_msg' => '',
  2743. 'updated_at' => date('Y-m-d H:i:s')
  2744. ];
  2745. $continue = false;
  2746. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  2747. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  2748. $list['generate_status'] = '制作成功';
  2749. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2750. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  2751. $continue = true;
  2752. }
  2753. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  2754. if ($id) {
  2755. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  2756. }else {
  2757. $list['created_at'] = date('Y-m-d H:i:s');
  2758. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  2759. $boolen = $id ? true : false;
  2760. }
  2761. // 如果更新成功则加入查询队列
  2762. if ($boolen) {
  2763. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  2764. Redis::sadd($redis_key, $id);
  2765. }
  2766. if ($boolen && !$continue) {
  2767. $boolen = false;
  2768. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2769. // 根据ID通过API通知合成音频
  2770. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  2771. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  2772. $response = $result->getBody()->getContents();
  2773. $response_arr = json_decode($response, true);
  2774. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2775. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2776. Log::info('通知火山生成段落音频失败: '.$error_msg);
  2777. Utils::throwError('20003:通知火山生成段落音频失败');
  2778. }
  2779. $boolen = true;
  2780. }
  2781. return $boolen;
  2782. }
  2783. public function insertAudioEffect($data) {
  2784. $audio_id = getProp($data, 'audio_id');
  2785. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2786. $bid = getProp($chapter_audio, 'bid');
  2787. $version_id = getProp($chapter_audio, 'version_id');
  2788. $cid = getProp($chapter_audio, 'cid');
  2789. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2790. $audio_effect_json = getProp($data, 'audio_effect_json');
  2791. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  2792. try {
  2793. DB::beginTransaction();
  2794. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2795. if (!$count) {
  2796. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2797. }else {
  2798. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2799. }
  2800. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2801. 'audio_effect_status' => '添加中',
  2802. 'audio_effect_json' => $audio_effect_json,
  2803. 'updated_at' => date('Y-m-d H:i:s')
  2804. ]);
  2805. if (!$boolen1) {
  2806. DB::rollBack();
  2807. Utils::throwError('20003:更新生成数据失败');
  2808. }
  2809. $id = DB::table('mp_audio_tasks')->insertGetId([
  2810. 'audio_id' => $audio_id,
  2811. 'generate_status' => '执行中',
  2812. 'generate_json' => json_encode([], 256),
  2813. 'bid' => $bid,
  2814. 'book_name' => getProp($chapter_audio, 'book_name'),
  2815. 'version_id' => $version_id,
  2816. 'version_name' => getProp($chapter_audio, 'version_name'),
  2817. 'cid' => $cid,
  2818. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2819. 'task_name' => $task_name,
  2820. 'created_at' => date('Y-m-d H:i:s'),
  2821. 'updated_at' => date('Y-m-d H:i:s')
  2822. ]);
  2823. if (!$id) {
  2824. DB::rollBack();
  2825. Utils::throwError('20003:创建任务失败');
  2826. }
  2827. }catch (\Exception $e) {
  2828. DB::rollBack();
  2829. Utils::throwError('20003:'.$e->getMessage());
  2830. }
  2831. DB::commit();
  2832. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2833. // 根据ID通过API通知合成音频
  2834. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2835. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2836. $response = $result->getBody()->getContents();
  2837. $response_arr = json_decode($response, true);
  2838. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2839. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2840. Log::info('通知火山插入音效失败: '.$error_msg);
  2841. Utils::throwError('20003:通知火山插入音效失败');
  2842. }
  2843. return true;
  2844. }
  2845. public function insertBgm($data) {
  2846. $audio_id = getProp($data, 'audio_id');
  2847. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2848. $bid = getProp($chapter_audio, 'bid');
  2849. $version_id = getProp($chapter_audio, 'version_id');
  2850. $cid = getProp($chapter_audio, 'cid');
  2851. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2852. $bgm_json = getProp($data, 'bgm_json');
  2853. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2854. if (!$bgm_json) {
  2855. $bgm_json = getProp($data, 'audio_effect_json');
  2856. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2857. }
  2858. try {
  2859. DB::beginTransaction();
  2860. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2861. if (!$count) {
  2862. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2863. }else {
  2864. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2865. }
  2866. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2867. 'bgm_status' => '添加中',
  2868. 'bgm_json' => $bgm_json,
  2869. 'updated_at' => date('Y-m-d H:i:s')
  2870. ]);
  2871. if (!$boolen1) {
  2872. DB::rollBack();
  2873. Utils::throwError('20003:更新生成数据失败');
  2874. }
  2875. $id = DB::table('mp_audio_tasks')->insertGetId([
  2876. 'audio_id' => $audio_id,
  2877. 'generate_status' => '执行中',
  2878. 'generate_json' => json_encode([], 256),
  2879. 'bid' => $bid,
  2880. 'book_name' => getProp($chapter_audio, 'book_name'),
  2881. 'version_id' => $version_id,
  2882. 'version_name' => getProp($chapter_audio, 'version_name'),
  2883. 'cid' => $cid,
  2884. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2885. 'task_name' => $task_name,
  2886. 'created_at' => date('Y-m-d H:i:s'),
  2887. 'updated_at' => date('Y-m-d H:i:s')
  2888. ]);
  2889. if (!$id) {
  2890. DB::rollBack();
  2891. Utils::throwError('20003:创建任务失败');
  2892. }
  2893. }catch (\Exception $e) {
  2894. DB::rollBack();
  2895. Utils::throwError('20003:'.$e->getMessage());
  2896. }
  2897. DB::commit();
  2898. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2899. // 根据ID通过API通知合成音频
  2900. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2901. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2902. $response = $result->getBody()->getContents();
  2903. $response_arr = json_decode($response, true);
  2904. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2905. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2906. Log::info('通知火山插入bgm失败: '.$error_msg);
  2907. Utils::throwError('20003:通知火山插入bgm失败');
  2908. }
  2909. return true;
  2910. }
  2911. public function getParagraphAudios($data) {
  2912. $bid = getProp($data, 'bid');
  2913. $cid = getProp($data, 'cid');
  2914. $version_id = getProp($data, 'version_id');
  2915. $sequence = getProp($data, 'sequence');
  2916. // 获取已生成的音频
  2917. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  2918. if ($sequence) $query->where('sequence', $sequence);
  2919. $paragraph_audios = $query->orderBy('sequence')->get();
  2920. $result = [];
  2921. foreach($paragraph_audios as $item) {
  2922. $result[] = [
  2923. 'sequence' => getProp($item, 'sequence'),
  2924. 'role' => getProp($item, 'role'),
  2925. 'gender' => getProp($item, 'gender'),
  2926. 'text' => trim(getProp($item, 'text')),
  2927. 'emotion' => getProp($item, 'emotion'),
  2928. 'emotion_type' => getProp($item, 'emotion_type'),
  2929. 'voice_type' => getProp($item, 'voice_type'),
  2930. 'voice_name' => getProp($item, 'voice_name'),
  2931. 'speed_ratio' => getProp($item, 'speed_ratio'),
  2932. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  2933. 'emotion_scale' => getProp($item, 'emotion_scale'),
  2934. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  2935. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  2936. ];
  2937. }
  2938. return $result;
  2939. }
  2940. // 新增合成任务
  2941. public function addGenerateTask($data) {
  2942. $bid = getProp($data, 'bid');
  2943. $cid = getProp($data, 'cid');
  2944. $version_id = getProp($data, 'version_id');
  2945. $generate_json = getProp($data, 'generate_json');
  2946. // 获取已生成的音频
  2947. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  2948. $paragraph_list = [];
  2949. foreach($paragraph_audios as $item) {
  2950. $paragraph_list[getProp($item, 'sequence')] = [
  2951. 'role' => getProp($item, 'role'),
  2952. 'gender' => getProp($item, 'gender'),
  2953. 'text' => trim(getProp($item, 'text')),
  2954. 'emotion' => getProp($item, 'emotion'),
  2955. 'emotion_type' => getProp($item, 'emotion_type'),
  2956. 'voice_type' => getProp($item, 'voice_type'),
  2957. 'voice_name' => getProp($item, 'voice_name'),
  2958. 'speed_ratio' => getProp($item, 'speed_ratio'),
  2959. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  2960. 'emotion_scale' => getProp($item, 'emotion_scale'),
  2961. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  2962. ];
  2963. }
  2964. // 更新角色-音色信息
  2965. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  2966. $existed_role_info = json_decode($existed_role_info, true);
  2967. if (!$existed_role_info) $existed_role_info = [];
  2968. // 获取情感信息
  2969. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2970. $emotion_list = array_flip($emotion_list);
  2971. // 获取音色对应情感组
  2972. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  2973. $timbre_emotion_list = [];
  2974. foreach($timbre_emotions as $item) {
  2975. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  2976. }
  2977. // 构造生成音频的json
  2978. $words = json_decode($generate_json, true);
  2979. // 最终合成前的参数组
  2980. $mp_chapter_paragraph_audios = [];
  2981. $sequence = 1;
  2982. $complete_paragraph_sequences = [];
  2983. foreach($words as &$word) {
  2984. 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:参数格式有误');
  2985. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  2986. $role = getProp($word, 'role');
  2987. $word['gender'] = (int)$word['gender'];
  2988. // 判断音色对应情感是否支持,不支持则调整为中性
  2989. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  2990. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  2991. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  2992. if (isset($emotion_list[getProp($word, 'emotion')])) {
  2993. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  2994. }else {
  2995. $word['emotion'] = '中性';
  2996. $word['emotion_type'] = 'neutral';
  2997. }
  2998. $existed_role_info[$role] = [
  2999. 'timbre_type' => $word['voice_type'],
  3000. 'timbre_name' => $word['voice_name'],
  3001. 'emotion' => $word['emotion'],
  3002. 'emotion_type' => $word['emotion_type'],
  3003. 'speed_ratio' => $word['speed_ratio'],
  3004. 'loudness_ratio'=> $word['loudness_ratio'],
  3005. 'emotion_scale' => $word['emotion_scale'],
  3006. 'pitch' => $word['pitch']
  3007. ];
  3008. $word['paragraph_audio_url'] = '';
  3009. // 判断生成参数是否相同,相同则直接使用已生成的音频
  3010. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  3011. // 如果音频存在并且参数都未改变则使用已生成的音频
  3012. if (getProp($paragraph, 'paragraph_audio_url')) {
  3013. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  3014. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  3015. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  3016. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  3017. // {
  3018. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3019. // }
  3020. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3021. }
  3022. $tmp = $word;
  3023. // 组装章节分句音频数据
  3024. // $tmp['sequence'] = getProp($word, 'sequence');
  3025. // $tmp['text'] = getProp($word, 'text');
  3026. // $tmp['emotion'] = getProp($word, 'emotion');
  3027. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  3028. // $tmp['voice_name'] = getProp($word, 'voice_name');
  3029. // $tmp['voice_type'] = getProp($word, 'voice_type');
  3030. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  3031. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  3032. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  3033. $tmp['bid'] = $bid;
  3034. $tmp['version_id'] = $version_id;
  3035. $tmp['cid'] = $cid;
  3036. $tmp['sequence'] = $sequence;
  3037. $tmp['created_at'] = date('Y-m-d H:i:s');
  3038. $tmp['updated_at'] = date('Y-m-d H:i:s');
  3039. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  3040. $mp_chapter_paragraph_audios[] = $tmp;
  3041. $complete_paragraph_sequences[] = $sequence;
  3042. $sequence++;
  3043. }
  3044. $generate_json = json_encode($words, 256);
  3045. // 判断是否有未生成字幕的段落
  3046. $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();
  3047. if ($no_subtitle_sequences) {
  3048. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  3049. }
  3050. try {
  3051. DB::beginTransaction();
  3052. $role_info = json_encode($existed_role_info, 256);
  3053. $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')]);
  3054. if (!$boolen) {
  3055. DB::rollBack();
  3056. Utils::throwError('20003:更新角色信息失败');
  3057. }
  3058. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  3059. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  3060. if (!$count) {
  3061. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3062. }else {
  3063. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3064. }
  3065. $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')]);
  3066. if (!$boolen1) {
  3067. DB::rollBack();
  3068. Utils::throwError('20003:更新生成数据失败');
  3069. }
  3070. $id = DB::table('mp_audio_tasks')->insertGetId([
  3071. 'audio_id' => getProp($chapter_audio, 'id'),
  3072. 'generate_status' => '执行中',
  3073. 'generate_json' => $generate_json,
  3074. 'bid' => $bid,
  3075. 'book_name' => getProp($chapter_audio, 'book_name'),
  3076. 'version_id' => $version_id,
  3077. 'version_name' => getProp($chapter_audio, 'version_name'),
  3078. 'cid' => $cid,
  3079. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3080. 'task_name' => $task_name,
  3081. 'created_at' => date('Y-m-d H:i:s'),
  3082. 'updated_at' => date('Y-m-d H:i:s')
  3083. ]);
  3084. if (!$id) {
  3085. DB::rollBack();
  3086. Utils::throwError('20003:创建任务失败');
  3087. }
  3088. // 删除不在段落序号范围内的其他数据
  3089. if ($complete_paragraph_sequences) {
  3090. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  3091. }
  3092. // // 删除章节分句音频数据并重新插入
  3093. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  3094. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  3095. // if (!$boolen3) {
  3096. // DB::rollBack();
  3097. // Utils::throwError('20003:更新章节分句音频失败');
  3098. // }
  3099. } catch (\Exception $e) {
  3100. DB::rollBack();
  3101. Utils::throwError('20003:'.$e->getMessage());
  3102. }
  3103. DB::commit();
  3104. // 通知火山生成音频
  3105. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3106. // 根据ID通过API通知合成音频
  3107. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  3108. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  3109. $response = $result->getBody()->getContents();
  3110. $response_arr = json_decode($response, true);
  3111. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3112. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3113. Log::info('通知火山生成音频失败: '.$error_msg);
  3114. Utils::throwError('20003:通知火山生成音频失败');
  3115. }
  3116. return true;
  3117. }
  3118. public function timbreList($data) {
  3119. $gender = getProp($data, 'gender');
  3120. $timbre_name = getProp($data, 'voice_name');
  3121. $category_id = getProp($data, 'category_id');
  3122. $age_stage = getProp($data, 'age_stage');
  3123. $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');
  3124. if ($gender) {
  3125. $query->where('gender', $gender);
  3126. }
  3127. if ($timbre_name) {
  3128. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  3129. }
  3130. if ($category_id) {
  3131. $query->where(function ($query) use ($category_id) {
  3132. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  3133. });
  3134. }
  3135. if ($age_stage) {
  3136. $query->where('age_stage', $age_stage);
  3137. }
  3138. $list = $query->get()->map(function ($value) {
  3139. $value = (array)$value;
  3140. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  3141. return $value;
  3142. })->toArray();
  3143. return $list;
  3144. }
  3145. // 生成火山临时token
  3146. public function setStsToken() {
  3147. // ************* 配置参数 *************
  3148. $method = 'GET';
  3149. $service = 'sts';
  3150. $host = 'open.volcengineapi.com';
  3151. $region = env('VOLC_REGION');
  3152. $endpoint = 'https://open.volcengineapi.com';
  3153. // $endpoint = 'https://tos-cn-beijing.volces.com';
  3154. $access_key = env('VOLC_AK');
  3155. $secret_key = env('VOLC_SK');
  3156. // 获取缓存中的token,如果没有则请求接口
  3157. $token = Redis::get('volc_sts_token');
  3158. if (!$token) {
  3159. // 查询参数
  3160. $query_parameters = [
  3161. 'Action' => 'AssumeRole',
  3162. 'RoleSessionName' => 'user@zw',
  3163. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  3164. 'Version' => '2018-01-01'
  3165. ];
  3166. // 生成URL编码的查询字符串
  3167. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  3168. // 获取签名头信息
  3169. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  3170. // 构建完整URL
  3171. $request_url = $endpoint . '?' . $request_parameters;
  3172. $client = new Client(['verify' => false]);
  3173. $response = $client->get($request_url, ['headers' => $headers]);
  3174. $response_arr = json_decode($response->getBody()->getContents(), true);
  3175. $result = [
  3176. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  3177. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  3178. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  3179. 'Region' => env('VOLC_REGION'),
  3180. 'Endpoint' => env('VOLC_END_POINT'),
  3181. 'Bucket' => env('VOLC_BUCKET'),
  3182. ];
  3183. // 缓存token
  3184. Redis::setex('volc_sts_token', 3000, json_encode($result));
  3185. return $result;
  3186. } else {
  3187. return json_decode($token, true);
  3188. }
  3189. // $response = $response['Response'];
  3190. // $access_key = $response['Credentials']['AccessKeyId'];
  3191. // $secret_key = $response['Credentials']['AccessKeySecret'];
  3192. // $security_token = $response['Credentials']['SecurityToken'];
  3193. // $expiration = $response['Credentials']['Expiration'];
  3194. // dd($response_arr);
  3195. }
  3196. public function emotionGroups($data) {
  3197. $id = getProp($data, 'group_id');
  3198. $group_name = getProp($data, 'group_name');
  3199. $voice_type = getProp($data, 'voice_type');
  3200. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  3201. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  3202. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  3203. if ($group_name) {
  3204. $query->where('group_name', 'like', "%{$group_name}%");
  3205. }
  3206. if ($id) {
  3207. $query->where('id', $id);
  3208. }
  3209. if ($voice_type) {
  3210. $query->where('voice_type', $voice_type);
  3211. }
  3212. return $query->orderBy('id')->get()->map(function ($value) {
  3213. return (array)$value;
  3214. })->toArray();
  3215. }
  3216. private function sign($key, $msg) {
  3217. return hash_hmac('sha256', $msg, $key, true);
  3218. }
  3219. // 生成签名密钥
  3220. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  3221. $kDate = $this->sign($key, $dateStamp);
  3222. $kRegion = $this->sign($kDate, $regionName);
  3223. $kService = $this->sign($kRegion, $serviceName);
  3224. $kSigning = $this->sign($kService, 'request');
  3225. return $kSigning;
  3226. }
  3227. // 获取签名头信息
  3228. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  3229. $contenttype = 'application/x-www-form-urlencoded';
  3230. $accept = 'application/json';
  3231. // 获取当前UTC时间
  3232. $t = new DateTime('now', new DateTimeZone('UTC'));
  3233. $xdate = $t->format('Ymd\THis\Z');
  3234. $datestamp = $t->format('Ymd');
  3235. // 1. 拼接规范请求串
  3236. $canonical_uri = '/';
  3237. $canonical_querystring = $request_parameters;
  3238. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  3239. $signed_headers = 'content-type;host;x-date';
  3240. // 空请求体的SHA256哈希
  3241. $payload_hash = hash('sha256', '');
  3242. $canonical_request = implode("\n", [
  3243. $method,
  3244. $canonical_uri,
  3245. $canonical_querystring,
  3246. $canonical_headers,
  3247. $signed_headers,
  3248. $payload_hash
  3249. ]);
  3250. // 2. 拼接待签名字符串
  3251. $algorithm = 'HMAC-SHA256';
  3252. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  3253. $hashed_canonical_request = hash('sha256', $canonical_request);
  3254. $string_to_sign = implode("\n", [
  3255. $algorithm,
  3256. $xdate,
  3257. $credential_scope,
  3258. $hashed_canonical_request
  3259. ]);
  3260. // 3. 计算签名
  3261. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  3262. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  3263. // 4. 添加签名到请求头
  3264. $authorization_header = sprintf(
  3265. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  3266. $algorithm,
  3267. $access_key,
  3268. $credential_scope,
  3269. $signed_headers,
  3270. $signature
  3271. );
  3272. return [
  3273. 'Accept' => $accept,
  3274. 'Content-Type' => $contenttype,
  3275. 'X-Date' => $xdate,
  3276. 'Authorization' => $authorization_header
  3277. ];
  3278. }
  3279. // 文字合成语音(火山引擎)
  3280. public function tts($data) {
  3281. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  3282. $headers = [
  3283. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  3284. 'Content-Type' => 'application/json; charset=UTF-8'
  3285. ];
  3286. $post_data = [
  3287. 'app' => [
  3288. 'appid' => env('VOLC_APPID'),
  3289. 'token' => env('VOLC_TOKEN'),
  3290. 'cluster' => 'volcano_tts'
  3291. ],
  3292. 'user' => [
  3293. 'uid' => 'mp_audio'
  3294. ],
  3295. // 'audio' => [
  3296. // 'voice_type' =>
  3297. // ],
  3298. ];
  3299. }
  3300. public function scriptList($data) {
  3301. $uid = Site::getUid();
  3302. $script_id = getProp($data, 'script_id');
  3303. $script_name = getProp($data, 'script_name');
  3304. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  3305. if ($script_id) {
  3306. $query->where('id', $script_id);
  3307. }
  3308. if ($script_name) {
  3309. $query->where('script_name', 'like', "%{$script_name}%");
  3310. }
  3311. return $query->orderBy('created_at', 'desc')->paginate(12);
  3312. }
  3313. public function scripts($data) {
  3314. $uid = Site::getUid();
  3315. $script_id = getProp($data, 'script_id');
  3316. $script_name = getProp($data, 'script_name');
  3317. $is_products = getProp($data, 'is_products');
  3318. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  3319. if ($script_id) {
  3320. $query->where('id', $script_id);
  3321. }
  3322. if ($is_products !== '') {
  3323. $query->where('is_products', $is_products);
  3324. }
  3325. if ($script_name) {
  3326. $query->where('script_name', 'like', "%{$script_name}%");
  3327. }
  3328. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  3329. return (array)$value;
  3330. })->toArray();
  3331. }
  3332. public function scriptInfo($data) {
  3333. $uid = Site::getUid();
  3334. $script_id = getProp($data, 'script_id');
  3335. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  3336. // ->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();
  3337. ->selectRaw('id as script_id, script_name')->first();
  3338. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3339. $script = (array)$script;
  3340. // 获取分集组信息
  3341. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  3342. ->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')
  3343. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  3344. $value = (array)$value;
  3345. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  3346. return (array)$value;
  3347. })->toArray();
  3348. $script['group'] = $groups;
  3349. return $script;
  3350. }
  3351. public function createScript($data) {
  3352. $script_name = getProp($data, 'script_name');
  3353. $uid = Site::getUid(); // 获取当前用户ID
  3354. $cpid = Site::getCpid(); // 获取当前公司组ID
  3355. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  3356. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  3357. $script_name .= '_'.date('YmdHis');
  3358. }
  3359. return DB::table('mp_scripts')->insertGetId([
  3360. 'script_name' => $script_name,
  3361. 'user_id' => $uid,
  3362. 'cpid' => $cpid,
  3363. 'created_at' => date('Y-m-d H:i:s'),
  3364. 'updated_at' => date('Y-m-d H:i:s')
  3365. ]);
  3366. }
  3367. public function editScript($data) {
  3368. $script_id = getProp($data, 'script_id');
  3369. $script_name = getProp($data, 'script_name');
  3370. $uid = Site::getUid(); // 获取当前用户ID
  3371. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  3372. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  3373. if ($id && (int)$id !== (int)$script_id) {
  3374. $script_name .= '_'.date('YmdHis');
  3375. }
  3376. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3377. 'script_name' => $script_name,
  3378. 'updated_at' => date('Y-m-d H:i:s')
  3379. ]);
  3380. }
  3381. public function delScript($data) {
  3382. $script_id = getProp($data, 'script_id');
  3383. $uid = Site::getUid(); // 获取当前用户ID
  3384. if (!$script_id) Utils::throwError('20003:请选择剧本');
  3385. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3386. 'is_deleted' => 1,
  3387. 'updated_at' => date('Y-m-d H:i:s')
  3388. ]);
  3389. }
  3390. public function createEpisode($data) {
  3391. $script_id = getProp($data, 'script_id');
  3392. $group_name = getProp($data, 'group_name');
  3393. $remark = getProp($data, 'remark');
  3394. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  3395. $uid = Site::getUid(); // 获取当前用户ID
  3396. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  3397. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  3398. $group_name .= '_'.date('YmdHis');
  3399. }
  3400. return DB::table('mp_script_episode_group')->insertGetId([
  3401. 'script_id' => $script_id,
  3402. 'group_name' => $group_name,
  3403. 'user_id' => $uid,
  3404. 'remark' => $remark,
  3405. 'created_at' => date('Y-m-d H:i:s'),
  3406. 'updated_at' => date('Y-m-d H:i:s')
  3407. ]);
  3408. }
  3409. public function editEpisode($data) {
  3410. $group_id = getProp($data, 'group_id');
  3411. $start_episode_number = getProp($data, 'start_episode_number');
  3412. $end_episode_number = getProp($data, 'end_episode_number');
  3413. $group_name = getProp($data, 'group_name');
  3414. $uid = Site::getUid(); // 获取当前用户ID
  3415. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  3416. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  3417. if ($id && (int)$id !== (int)$group_id) {
  3418. $group_name .= '_'.date('YmdHis');
  3419. }
  3420. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3421. 'group_name' => $group_name,
  3422. 'start_episode_number' => $start_episode_number,
  3423. 'end_episode_number' => $end_episode_number,
  3424. 'updated_at' => date('Y-m-d H:i:s')
  3425. ]);
  3426. }
  3427. public function delEpisode($data) {
  3428. $group_id = getProp($data, 'group_id');
  3429. $uid = Site::getUid(); // 获取当前用户ID
  3430. if (!$group_id) Utils::throwError('20003:请选择分集');
  3431. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3432. 'is_deleted' => 1,
  3433. 'updated_at' => date('Y-m-d H:i:s')
  3434. ]);
  3435. }
  3436. /**
  3437. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3438. *
  3439. * @param array $data 包含以下参数:
  3440. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3441. * - question: 用户问题(可选)
  3442. * - model: 使用的模型(r1 或 v3,默认 v3)
  3443. * @return \Generator 返回生成器,用于流式输出
  3444. */
  3445. public function generateEpisodes($data) {
  3446. $script_id = getProp($data, 'script_id');
  3447. $group_id = getProp($data, 'group_id');
  3448. // $file = getProp($data, 'file');
  3449. $file = '';
  3450. $content = getProp($data, 'content', '');
  3451. // $bid = getProp($data, 'bid', 0);
  3452. $bid = 0;
  3453. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3454. if (!$group) {
  3455. Utils::throwError('20003:剧本分集不存在');
  3456. }
  3457. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  3458. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  3459. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  3460. $prompt = getProp($data, 'prompt');
  3461. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  3462. $model = getProp($data, 'model');
  3463. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3464. Utils::throwError('20003:该模型不存在!');
  3465. }
  3466. // 检查是否存在重叠的剧集序号范围
  3467. $exists_groups = DB::table('mp_script_episode_group')
  3468. ->where('script_id', $script_id)
  3469. ->where('id', '<>', $group_id) // 排除当前组
  3470. ->where('is_deleted', 0)
  3471. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3472. // 检查新范围是否与现有范围重叠
  3473. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3474. // 新范围的开始在现有范围内
  3475. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3476. ->where('end_episode_number', '>=', $start_episode_sequence);
  3477. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3478. // 新范围的结束在现有范围内
  3479. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3480. ->where('end_episode_number', '>=', $end_episode_sequence);
  3481. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3482. // 新范围完全包含现有范围
  3483. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3484. ->where('end_episode_number', '<=', $end_episode_sequence);
  3485. });
  3486. })
  3487. ->select('start_episode_number', 'end_episode_number')
  3488. ->get();
  3489. if ($exists_groups->isNotEmpty()) {
  3490. $conflict_ranges = [];
  3491. foreach ($exists_groups as $group) {
  3492. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3493. }
  3494. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3495. }
  3496. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3497. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3498. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3499. if ($model === 'deepseek-chat') {
  3500. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3501. $model = 'deepseek-v4-flash';
  3502. $thinkingMode = 'disabled';
  3503. } elseif ($model === 'deepseek-reasoner') {
  3504. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3505. $model = 'deepseek-v4-flash';
  3506. $thinkingMode = 'enabled';
  3507. }
  3508. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3509. if (!$script) {
  3510. Utils::throwError('20003:剧本不存在');
  3511. }
  3512. $content = getProp($group, 'content');
  3513. if (!$file && !$content && !$bid) {
  3514. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3515. }
  3516. // 提取文件内容
  3517. if ($file) {
  3518. $content = $this->extractFileContent($file);
  3519. if (!$content) {
  3520. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3521. }
  3522. } elseif ($bid) {
  3523. $content = $this->getContentByBid($bid);
  3524. if (!$content) {
  3525. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3526. }
  3527. } elseif ($content) {
  3528. $content = filterContent($content);
  3529. } elseif ($prompt) {
  3530. $content = filterContent($prompt);
  3531. } else {
  3532. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3533. }
  3534. // 构建消息
  3535. $messages = [
  3536. $this->sys_message,
  3537. [
  3538. 'role' => 'user',
  3539. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3540. ]
  3541. ];
  3542. $post_data = [
  3543. 'model' => $model,
  3544. 'messages' => $messages,
  3545. // 'max_tokens' => 8192,
  3546. 'temperature' => 0.7,
  3547. 'frequency_penalty' => 0,
  3548. 'presence_penalty' => 0,
  3549. 'thinking' => ['type' => $thinkingMode],
  3550. 'response_format' => ['type' => 'text'],
  3551. 'stream' => true
  3552. ];
  3553. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3554. // 根据模型类型选择调用方法
  3555. $fullContent = '';
  3556. $fullReasoningContent = '';
  3557. $usage = [];
  3558. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3559. // DeepSeek 官方模型使用 DeepSeek API
  3560. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3561. } else if (in_array($model, $this->gpt_text_models)) {
  3562. // GPT-5.4 模型使用 TokenRouter API
  3563. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3564. } else if (in_array($model, $this->gemini_text_models)) {
  3565. // Gemini 模型使用 Gemini API
  3566. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3567. } else {
  3568. // 其他模型使用火山引擎API
  3569. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3570. }
  3571. // 处理流式输出
  3572. foreach ($streamGenerator as $chunk) {
  3573. if (isset($chunk['type'])) {
  3574. if ($chunk['type'] === 'done') {
  3575. // 最终结果
  3576. $fullContent = $chunk['full_content'];
  3577. $fullReasoningContent = $chunk['full_reasoning'];
  3578. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3579. } else {
  3580. // 逐块yield数据
  3581. yield $chunk;
  3582. }
  3583. }
  3584. }
  3585. dLog('deepseek')->info('完整内容: '.$fullContent);
  3586. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3587. // 处理完整内容并返回最终结果
  3588. $script_arr = [];
  3589. if ($fullContent) {
  3590. $script_arr = extractScriptContent($fullContent);
  3591. }
  3592. logDB('deepseek', 'info', '解析内容', $script_arr);
  3593. if (!$script_arr['episodes']) {
  3594. Utils::throwError('20003:未生成剧本相关信息');
  3595. // yield [
  3596. // 'type' => 'done',
  3597. // 'script' => $script_arr,
  3598. // 'msg' => '未生成剧本相关信息',
  3599. // 'answer' => $fullContent,
  3600. // 'reasoning' => $fullReasoningContent,
  3601. // 'usage' => $usage
  3602. // ];
  3603. // return ;
  3604. }
  3605. try {
  3606. DB::beginTransaction();
  3607. // // 返回前保存剧本内容
  3608. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3609. // 'content' => $content,
  3610. // 'updated_at' => date('Y-m-d H:i:s')
  3611. // ]);
  3612. // if (!$boolen) {
  3613. // Utils::throwError('20003:保存剧本内容失败');
  3614. // }
  3615. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3616. // 'start_episode_number' => $start_episode_sequence,
  3617. // 'end_episode_number' => $end_episode_sequence,
  3618. // 'updated_at' => date('Y-m-d H:i:s')
  3619. // ]);
  3620. // if (!$boolen1) {
  3621. // Utils::throwError('20003:保存分集失败');
  3622. // }
  3623. $episode_content = '';
  3624. $episodes = [];
  3625. foreach ($script_arr['episodes'] as $item) {
  3626. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  3627. // $episodes[] = [
  3628. // 'script_id' => $script_id,
  3629. // 'episode_number' => $item['episode_number'],
  3630. // 'episode_name' => $item['episode_name'],
  3631. // 'episode_content' => $item['episode_content'],
  3632. // 'created_at' => date('Y-m-d H:i:s'),
  3633. // 'updated_at' => date('Y-m-d H:i:s'),
  3634. // ];
  3635. }
  3636. if ($episode_content) {
  3637. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3638. 'episode_content' => $episode_content,
  3639. 'updated_at' => date('Y-m-d H:i:s')
  3640. ]);
  3641. if (!$boolen2) {
  3642. Utils::throwError('20003:保存分集内容失败');
  3643. }
  3644. }else {
  3645. Utils::throwError('20003:分集剧本解析失败');
  3646. }
  3647. }catch (\Exception $e) {
  3648. DB::rollBack();
  3649. Utils::throwError('20003:'.$e->getMessage());
  3650. }
  3651. DB::commit();
  3652. yield [
  3653. 'type' => 'done',
  3654. 'script' => $script_arr,
  3655. 'episode_content' => $episode_content,
  3656. 'answer' => $fullContent,
  3657. 'reasoning' => $fullReasoningContent,
  3658. 'usage' => $usage
  3659. ];
  3660. }
  3661. public function chatWithFileStream($data) {
  3662. $script_id = getProp($data, 'script_id');
  3663. $group_id = getProp($data, 'group_id');
  3664. $file = getProp($data, 'file');
  3665. $content = getProp($data, 'content', '');
  3666. $bid = getProp($data, 'bid', 0);
  3667. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3668. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3669. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  3670. $prompt = getProp($data, 'prompt');
  3671. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3672. if (!empty($prompt)) {
  3673. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3674. }
  3675. $question = getProp($data, 'question', $baseQuestion);
  3676. $model = getProp($data, 'model');
  3677. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3678. Utils::throwError('20003:该模型不存在!');
  3679. }
  3680. // 检查是否存在重叠的剧集序号范围
  3681. $exists_groups = DB::table('mp_script_episode_group')
  3682. ->where('script_id', $script_id)
  3683. ->where('id', '<>', $group_id)
  3684. ->where('is_deleted', 0)
  3685. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3686. // 检查新范围是否与现有范围重叠
  3687. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3688. // 新范围的开始在现有范围内
  3689. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3690. ->where('end_episode_number', '>=', $start_episode_sequence);
  3691. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3692. // 新范围的结束在现有范围内
  3693. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3694. ->where('end_episode_number', '>=', $end_episode_sequence);
  3695. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3696. // 新范围完全包含现有范围
  3697. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3698. ->where('end_episode_number', '<=', $end_episode_sequence);
  3699. });
  3700. })
  3701. ->select('start_episode_number', 'end_episode_number')
  3702. ->get();
  3703. if ($exists_groups->isNotEmpty()) {
  3704. $conflict_ranges = [];
  3705. foreach ($exists_groups as $group) {
  3706. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3707. }
  3708. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3709. }
  3710. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3711. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3712. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3713. if ($model === 'deepseek-chat') {
  3714. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3715. $model = 'deepseek-v4-flash';
  3716. $thinkingMode = 'disabled';
  3717. } elseif ($model === 'deepseek-reasoner') {
  3718. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3719. $model = 'deepseek-v4-flash';
  3720. $thinkingMode = 'enabled';
  3721. }
  3722. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3723. if (!$script) {
  3724. Utils::throwError('20003:剧本不存在');
  3725. }
  3726. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3727. if (!$group) {
  3728. Utils::throwError('20003:剧本分集不存在');
  3729. }
  3730. if (!$file && !$content && !$bid) {
  3731. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3732. }
  3733. // 提取文件内容
  3734. if ($file) {
  3735. $content = $this->extractFileContent($file);
  3736. if (!$content) {
  3737. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3738. }
  3739. } elseif ($bid) {
  3740. $content = $this->getContentByBid($bid);
  3741. if (!$content) {
  3742. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3743. }
  3744. } elseif ($content) {
  3745. $content = filterContent($content);
  3746. } elseif ($prompt) {
  3747. $content = filterContent($prompt);
  3748. } else {
  3749. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3750. }
  3751. // 构建消息
  3752. $messages = [
  3753. [
  3754. 'role' => 'system',
  3755. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3756. 强制要求:\n
  3757. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3758. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  3759. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  3760. 普通要求:\n
  3761. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  3762. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  3763. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  3764. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  3765. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  3766. 示例如下:\n
  3767. ###剧本名:西昆仑
  3768. ###故事梗概
  3769. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3770. ###剧本亮点
  3771. 亮点1:绝境奇药,生死一线
  3772. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3773. 亮点2:结拜兄妹,化解尴尬
  3774. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3775. 亮点3:纤发夺命,情愫暗涌
  3776. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3777. ###人物关系
  3778. 阿雪与梁萧之间存在兄妹之情。
  3779. ###核心矛盾
  3780. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3781. ###主体列表
  3782. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3783. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3784. 阴阳球:天地异宝,能化生精气,救人于危难。
  3785. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3786. ###美术风格
  3787. 基础画风风格词:厚涂古风
  3788. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3789. ###场景列表
  3790. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  3791. [
  3792. 'role' => 'user',
  3793. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3794. ]
  3795. ];
  3796. $post_data = [
  3797. 'model' => $model,
  3798. 'messages' => $messages,
  3799. // 'max_tokens' => 8192,
  3800. 'temperature' => 0.7,
  3801. 'frequency_penalty' => 0,
  3802. 'presence_penalty' => 0,
  3803. 'thinking' => ['type' => $thinkingMode],
  3804. 'response_format' => ['type' => 'text'],
  3805. 'stream' => true
  3806. ];
  3807. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3808. // 根据模型类型选择调用方法
  3809. $fullContent = '';
  3810. $fullReasoningContent = '';
  3811. $usage = [];
  3812. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3813. // DeepSeek 官方模型使用 DeepSeek API
  3814. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3815. } else if (in_array($model, $this->gpt_text_models)) {
  3816. // GPT-5.4 模型使用 TokenRouter API
  3817. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3818. } else if (in_array($model, $this->gemini_text_models)) {
  3819. // Gemini 模型使用 Gemini API
  3820. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3821. } else {
  3822. // 其他模型使用火山引擎API
  3823. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3824. }
  3825. // 处理流式输出
  3826. foreach ($streamGenerator as $chunk) {
  3827. if (isset($chunk['type'])) {
  3828. if ($chunk['type'] === 'done') {
  3829. // 最终结果
  3830. $fullContent = $chunk['full_content'];
  3831. $fullReasoningContent = $chunk['full_reasoning'];
  3832. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3833. } else {
  3834. // 逐块yield数据
  3835. yield $chunk;
  3836. }
  3837. }
  3838. }
  3839. dLog('deepseek')->info('完整内容: '.$fullContent);
  3840. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3841. // 处理完整内容并返回最终结果
  3842. $script_arr = [];
  3843. if ($fullContent) {
  3844. $script_arr = extractScriptContent($fullContent);
  3845. }
  3846. logDB('deepseek', 'info', '解析内容', $script_arr);
  3847. if (!$script_arr['roles']) {
  3848. Utils::throwError('20003:未生成剧本相关信息');
  3849. // yield [
  3850. // 'type' => 'done',
  3851. // 'script' => $script_arr,
  3852. // 'msg' => '未生成剧本相关信息',
  3853. // 'answer' => $fullContent,
  3854. // 'reasoning' => $fullReasoningContent,
  3855. // 'usage' => $usage
  3856. // ];
  3857. }
  3858. try {
  3859. DB::beginTransaction();
  3860. // // 返回前保存剧本内容
  3861. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3862. // 'content' => $content,
  3863. // 'status' => '解析完成',
  3864. // 'updated_at' => date('Y-m-d H:i:s')
  3865. // ]);
  3866. // if (!$boolen) {
  3867. // Utils::throwError('20003:保存剧本内容失败');
  3868. // }
  3869. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3870. 'start_episode_number' => $start_episode_sequence,
  3871. 'end_episode_number' => $end_episode_sequence,
  3872. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3873. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3874. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3875. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3876. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3877. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3878. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3879. 'status' => '解析完成',
  3880. 'content' => $content,
  3881. 'updated_at' => date('Y-m-d H:i:s')
  3882. ]);
  3883. if (!$boolen1) {
  3884. Utils::throwError('20003:保存分集失败');
  3885. }
  3886. // $episodes = [];
  3887. // foreach ($script_arr['episodes'] as $item) {
  3888. // $episodes[] = [
  3889. // 'script_id' => $script_id,
  3890. // 'episode_number' => $item['episode_number'],
  3891. // 'episode_name' => $item['episode_name'],
  3892. // 'episode_content' => $item['episode_content'],
  3893. // 'created_at' => date('Y-m-d H:i:s'),
  3894. // 'updated_at' => date('Y-m-d H:i:s'),
  3895. // ];
  3896. // }
  3897. // if ($episodes) {
  3898. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  3899. // if (!$boolen2) {
  3900. // Utils::throwError('20003:保存分集内容失败');
  3901. // }
  3902. // }else {
  3903. // Utils::throwError('20003:分集剧本解析失败');
  3904. // }
  3905. }catch (\Exception $e) {
  3906. DB::rollBack();
  3907. Utils::throwError('20003:'.$e->getMessage());
  3908. }
  3909. DB::commit();
  3910. yield [
  3911. 'type' => 'done',
  3912. 'script' => $script_arr,
  3913. 'answer' => $fullContent,
  3914. 'reasoning' => $fullReasoningContent,
  3915. 'usage' => $usage
  3916. ];
  3917. }
  3918. /**
  3919. * 上传文件识别文字内容并与 DeepSeek 进行对话
  3920. *
  3921. * @param array $data 包含以下参数:
  3922. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3923. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  3924. * - model: 使用的模型(r1 或 v3,默认 v3)
  3925. * @return array
  3926. */
  3927. public function chatWithFile($data) {
  3928. $script_id = getProp($data, 'script_id');
  3929. $file = getProp($data, 'file');
  3930. $content = getProp($data, 'content', '');
  3931. $bid = getProp($data, 'bid', 0);
  3932. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3933. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3934. $prompt = getProp($data, 'prompt');
  3935. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3936. if (!empty($prompt)) {
  3937. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3938. }
  3939. $question = getProp($data, 'question', $baseQuestion);
  3940. // 处理文本模型
  3941. $model = getProp($data, 'model');
  3942. if (!$model) {
  3943. // 用户没有输入,使用默认值
  3944. $model = 'doubao-seed-2-0-mini-260215';
  3945. }
  3946. // 验证模型是否在可用模型表中
  3947. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3948. $model = 'doubao-seed-2-0-mini-260215';
  3949. }
  3950. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3951. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3952. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3953. if ($model === 'deepseek-chat') {
  3954. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3955. $model = 'deepseek-v4-flash';
  3956. $thinkingMode = 'disabled';
  3957. } elseif ($model === 'deepseek-reasoner') {
  3958. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3959. $model = 'deepseek-v4-flash';
  3960. $thinkingMode = 'enabled';
  3961. }
  3962. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3963. if (!$script) {
  3964. Utils::throwError('20003:剧本不存在');
  3965. }
  3966. if (!$file && !$content && !$bid) {
  3967. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3968. }
  3969. // 提取文件内容
  3970. if ($file) {
  3971. $content = $this->extractFileContent($file);
  3972. if (!$content) {
  3973. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3974. }
  3975. } elseif ($bid) {
  3976. $content = $this->getContentByBid($bid);
  3977. if (!$content) {
  3978. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3979. }
  3980. } elseif ($content) {
  3981. $content = filterContent($content);
  3982. } elseif ($prompt) {
  3983. $content = filterContent($prompt);
  3984. } else {
  3985. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3986. }
  3987. // 构建消息
  3988. $messages = [
  3989. $this->sys_message,
  3990. [
  3991. 'role' => 'user',
  3992. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3993. ]
  3994. ];
  3995. $post_data = [
  3996. 'model' => $model,
  3997. 'messages' => $messages,
  3998. // 'max_tokens' => 8192,
  3999. 'temperature' => 0.7,
  4000. 'frequency_penalty' => 0,
  4001. 'presence_penalty' => 0,
  4002. 'thinking' => ['type' => $thinkingMode],
  4003. 'response_format' => ['type' => 'text'],
  4004. 'stream' => false
  4005. ];
  4006. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4007. // 根据模型类型选择调用方法
  4008. $fullContent = '';
  4009. $usage = [];
  4010. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4011. // DeepSeek 官方模型使用 DeepSeek API
  4012. $chatResult = $this->chatOnly($post_data);
  4013. } else if (in_array($model, $this->gpt_text_models)) {
  4014. // GPT-5.4 模型使用 TokenRouter API
  4015. $chatResult = $this->gpt54ChatOnly($post_data);
  4016. } else {
  4017. // 其他模型使用火山引擎API
  4018. $chatResult = $this->volcEngineChatCompletion($post_data);
  4019. }
  4020. if (is_array($chatResult)) {
  4021. $fullContent = $chatResult['fullContent'];
  4022. $usage = $chatResult['usage'];
  4023. }
  4024. $script_arr = [];
  4025. // 处理结果
  4026. if ($fullContent) {
  4027. $script_arr = extractScriptContent($fullContent);
  4028. }
  4029. // 返回前保存剧本内容
  4030. DB::table('mp_scripts')->where('id', $script_id)->update([
  4031. 'content' => $content,
  4032. 'updated_at' => date('Y-m-d H:i:s')
  4033. ]);
  4034. return [
  4035. 'script' => $script_arr,
  4036. 'answer' => $fullContent,
  4037. 'usage' => $usage
  4038. ];
  4039. }
  4040. public function getEpisodeContent($data) {
  4041. $group_id = getProp($data, 'group_id');
  4042. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  4043. }
  4044. public function saveEpisodeContent($data) {
  4045. $script_id = getProp($data, 'script_id');
  4046. $group_id = getProp($data, 'group_id');
  4047. $start_episode_sequence = getProp($data, 'start_episode_number');
  4048. $end_episode_sequence = getProp($data, 'end_episode_number');
  4049. // 检查是否存在重叠的剧集序号范围
  4050. $exists_groups = DB::table('mp_script_episode_group')
  4051. ->where('script_id', $script_id)
  4052. ->where('id', '<>', $group_id) // 排除当前组
  4053. ->where('is_deleted', 0)
  4054. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4055. // 检查新范围是否与现有范围重叠
  4056. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4057. // 新范围的开始在现有范围内
  4058. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4059. ->where('end_episode_number', '>=', $start_episode_sequence);
  4060. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4061. // 新范围的结束在现有范围内
  4062. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4063. ->where('end_episode_number', '>=', $end_episode_sequence);
  4064. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4065. // 新范围完全包含现有范围
  4066. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4067. ->where('end_episode_number', '<=', $end_episode_sequence);
  4068. });
  4069. })
  4070. ->select('start_episode_number', 'end_episode_number')
  4071. ->get();
  4072. if ($exists_groups->isNotEmpty()) {
  4073. $conflict_ranges = [];
  4074. foreach ($exists_groups as $group) {
  4075. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4076. }
  4077. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4078. }
  4079. $episode_content = getProp($data, 'episode_content');
  4080. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  4081. 'content' => $episode_content,
  4082. 'start_episode_number' => $start_episode_sequence,
  4083. 'end_episode_number' => $end_episode_sequence,
  4084. 'updated_at' => date('Y-m-d H:i:s')
  4085. ]);
  4086. $script_arr =getProp($data, 'script', []);
  4087. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  4088. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4089. $script_id = getProp($data, 'script_id');
  4090. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  4091. try {
  4092. DB::beginTransaction();
  4093. $update_data = [
  4094. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4095. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4096. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4097. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4098. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4099. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4100. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4101. 'status' => 3,
  4102. 'start_episode_sequence' => $start_episode_sequence,
  4103. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  4104. 'episode_num' => count($script_arr['episodes']),
  4105. 'updated_at' => date('Y-m-d H:i:s')
  4106. ];
  4107. // 保存剧本内容
  4108. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  4109. if (!$boolen) {
  4110. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  4111. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  4112. Utils::throwError('20003:剧本内容保存失败');
  4113. }
  4114. // 保存分集内容
  4115. // 删除历史分集内容
  4116. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  4117. $episodes = [];
  4118. $sequence = 1;
  4119. foreach ($script_arr['episodes'] as $episode) {
  4120. $segment_number = 1;
  4121. foreach($episode['segments'] as $segment) {
  4122. $episodes[] = [
  4123. 'script_id' => $script_id,
  4124. 'episode_number' => $episode['episode_number'],
  4125. 'title' => $episode['title'],
  4126. // 'content' => $episode['content'],
  4127. 'content' => '',
  4128. 'segment_number' => $segment_number,
  4129. 'segment_content' => $segment['segment_content'],
  4130. 'sequence' => $sequence,
  4131. 'created_at' => date('Y-m-d H:i:s'),
  4132. 'updated_at' => date('Y-m-d H:i:s')
  4133. ];
  4134. $sequence++;
  4135. $segment_number++;
  4136. }
  4137. }
  4138. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4139. if (!$boolen2) {
  4140. dLog('deepseek')->info('分集内容保存失败', $episodes);
  4141. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  4142. Utils::throwError('20003:分集内容保存失败');
  4143. }
  4144. } catch (\Exception $e) {
  4145. DB::rollBack();
  4146. Utils::throwError('20003:'.$e->getMessage());
  4147. }
  4148. DB::commit();
  4149. return true;
  4150. }
  4151. public function getBookContent($data) {
  4152. $bid = getProp($data, 'bid');
  4153. $start_sequence = getProp($data, 'start_sequence');
  4154. $end_sequence = getProp($data, 'end_sequence');
  4155. $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])
  4156. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  4157. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  4158. return $return_content;
  4159. }
  4160. public function exportScript($data) {
  4161. $filename = getProp($data, 'filename');
  4162. $script_id = getProp($data, 'script_id');
  4163. $group_id = getProp($data, 'group_id');
  4164. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  4165. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  4166. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4167. $script = (array)$script;
  4168. // 获取分集组信息
  4169. if ($group_id) {
  4170. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4171. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4172. ->get()->map(function($value) {
  4173. return (array)$value;
  4174. })->toArray();
  4175. }else {
  4176. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4177. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4178. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  4179. return (array)$value;
  4180. })->toArray();
  4181. }
  4182. if (!$groups) Utils::throwError('20003:分集不存在');
  4183. $script['group'] = $groups;
  4184. $export_type = getProp($data, 'export_type', 'txt');
  4185. // 生成文件名
  4186. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  4187. // 根据导出类型生成不同格式的文件
  4188. switch ($export_type) {
  4189. case 'txt':
  4190. return $this->exportScriptAsTxt($script, $filename);
  4191. case 'pdf':
  4192. return $this->exportScriptAsPdf($script, $filename);
  4193. default:
  4194. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  4195. }
  4196. }
  4197. /**
  4198. * 导出剧本为TXT格式
  4199. */
  4200. private function exportScriptAsTxt($script, $filename) {
  4201. // 构建TXT内容
  4202. $content = $this->buildScriptContent($script);
  4203. // 设置响应头,直接下载
  4204. header('Content-Type: text/plain; charset=utf-8');
  4205. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  4206. header('Content-Length: ' . strlen($content));
  4207. // 输出内容并结束
  4208. echo $content;
  4209. exit();
  4210. }
  4211. /**
  4212. * 导出剧本为PDF格式
  4213. */
  4214. private function exportScriptAsPdf($script, $filename) {
  4215. // 使用HTML转PDF的方式来更好地支持中文
  4216. $htmlContent = $this->buildScriptHtmlForPdf($script);
  4217. // 创建PDF实例
  4218. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  4219. // 设置文档信息
  4220. $pdf->SetCreator('剧本导出系统');
  4221. $pdf->SetAuthor('系统');
  4222. $pdf->SetTitle($script['script_name']);
  4223. $pdf->SetSubject('剧本导出');
  4224. // 设置边距
  4225. $pdf->SetMargins(15, 15, 15);
  4226. $pdf->SetAutoPageBreak(TRUE, 15);
  4227. // 添加页面
  4228. $pdf->AddPage();
  4229. // 注册并使用 simsun.ttf 字体
  4230. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  4231. // 使用HTML内容生成PDF
  4232. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  4233. // 直接输出PDF文件供下载
  4234. header('Content-Type: application/pdf');
  4235. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  4236. // 直接输出PDF内容
  4237. $pdf->Output($filename . '.pdf', 'D');
  4238. exit();
  4239. }
  4240. /**
  4241. * 构建用于PDF的HTML内容
  4242. */
  4243. private function buildScriptHtmlForPdf($script) {
  4244. $html = '<style>
  4245. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  4246. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  4247. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  4248. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  4249. .info { margin-bottom: 8px; }
  4250. .group { margin-bottom: 30px; page-break-inside: avoid; }
  4251. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  4252. .segment { margin-bottom: 10px; margin-left: 20px; }
  4253. .episode-content { white-space: pre-wrap; }
  4254. </style>';
  4255. // 标题
  4256. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  4257. // 处理分组数据
  4258. if (!empty($script['group']) && is_array($script['group'])) {
  4259. $groups = (array)$script['group'];
  4260. foreach ($groups as $group) {
  4261. $html .= '<div class="group">';
  4262. // 分组标题
  4263. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  4264. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  4265. // 故事梗概
  4266. if (!empty($group['intro'])) {
  4267. $html .= '<h3>故事梗概</h3>';
  4268. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  4269. }
  4270. // 剧本亮点
  4271. if (!empty($group['highlights'])) {
  4272. $html .= '<h3>剧本亮点</h3>';
  4273. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  4274. }
  4275. // 人物关系
  4276. if (!empty($group['role_relationship'])) {
  4277. $html .= '<h3>人物关系</h3>';
  4278. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  4279. }
  4280. // 核心矛盾
  4281. if (!empty($group['core_contradiction'])) {
  4282. $html .= '<h3>核心矛盾</h3>';
  4283. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  4284. }
  4285. // 主体列表
  4286. if (!empty($group['roles']) && is_array($group['roles'])) {
  4287. $html .= '<h3>主体列表</h3>';
  4288. $html .= '<ul>';
  4289. foreach ($group['roles'] as $role) {
  4290. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  4291. }
  4292. $html .= '</ul>';
  4293. }
  4294. // 美术风格
  4295. if (!empty($group['art_style'])) {
  4296. $html .= '<h3>美术风格</h3>';
  4297. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  4298. }
  4299. // 场景列表
  4300. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4301. $html .= '<h3>场景列表</h3>';
  4302. $html .= '<ul>';
  4303. foreach ($group['scenes'] as $scene) {
  4304. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  4305. }
  4306. $html .= '</ul>';
  4307. }
  4308. // 分集剧本
  4309. if (!empty($group['episode_content'])) {
  4310. $html .= '<h3>分集剧本</h3>';
  4311. // 去除零宽字符和其他不可见字符
  4312. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  4313. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  4314. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  4315. }
  4316. $html .= '</div>';
  4317. }
  4318. }
  4319. return $html;
  4320. }
  4321. /**
  4322. * 构建PDF内容
  4323. */
  4324. private function buildPdfContent($pdf, $script) {
  4325. // 标题
  4326. $pdf->SetFont('dejavusans', 'B', 18);
  4327. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  4328. $pdf->Ln(5);
  4329. // 基本信息
  4330. $pdf->SetFont('dejavusans', '', 12);
  4331. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  4332. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  4333. $pdf->Ln(5);
  4334. // 剧本简介
  4335. if (!empty($script['intro'])) {
  4336. $pdf->SetFont('dejavusans', 'B', 14);
  4337. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  4338. $pdf->SetFont('dejavusans', '', 12);
  4339. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  4340. $pdf->Ln(3);
  4341. }
  4342. // 亮点
  4343. if (!empty($script['highlights'])) {
  4344. $pdf->SetFont('dejavusans', 'B', 14);
  4345. $pdf->Cell(0, 10, '亮点', 0, 1);
  4346. $pdf->SetFont('dejavusans', '', 12);
  4347. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  4348. $pdf->Ln(3);
  4349. }
  4350. // 核心矛盾
  4351. if (!empty($script['core_contradiction'])) {
  4352. $pdf->SetFont('dejavusans', 'B', 14);
  4353. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  4354. $pdf->SetFont('dejavusans', '', 12);
  4355. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  4356. $pdf->Ln(3);
  4357. }
  4358. // 艺术风格
  4359. if (!empty($script['art_style'])) {
  4360. $pdf->SetFont('dejavusans', 'B', 14);
  4361. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  4362. $pdf->SetFont('dejavusans', '', 12);
  4363. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  4364. $pdf->Ln(3);
  4365. }
  4366. // 备注
  4367. if (!empty($script['remark'])) {
  4368. $pdf->SetFont('dejavusans', 'B', 14);
  4369. $pdf->Cell(0, 10, '备注', 0, 1);
  4370. $pdf->SetFont('dejavusans', '', 12);
  4371. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  4372. $pdf->Ln(3);
  4373. }
  4374. // 角色列表
  4375. if (!empty($script['roles']) && is_array($script['roles'])) {
  4376. $pdf->SetFont('dejavusans', 'B', 14);
  4377. $pdf->Cell(0, 10, '角色列表', 0, 1);
  4378. $pdf->SetFont('dejavusans', '', 12);
  4379. foreach ($script['roles'] as $index => $role) {
  4380. if (is_array($role) || is_object($role)) {
  4381. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  4382. } else {
  4383. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  4384. }
  4385. }
  4386. $pdf->Ln(3);
  4387. }
  4388. // 角色关系
  4389. if (!empty($script['role_relationship'])) {
  4390. $pdf->SetFont('dejavusans', 'B', 14);
  4391. $pdf->Cell(0, 10, '角色关系', 0, 1);
  4392. $pdf->SetFont('dejavusans', '', 12);
  4393. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  4394. $pdf->Ln(3);
  4395. }
  4396. // 场景列表
  4397. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  4398. $pdf->SetFont('dejavusans', 'B', 14);
  4399. $pdf->Cell(0, 10, '场景列表', 0, 1);
  4400. $pdf->SetFont('dejavusans', '', 12);
  4401. foreach ($script['scenes'] as $index => $scene) {
  4402. if (is_array($scene) || is_object($scene)) {
  4403. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  4404. } else {
  4405. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  4406. }
  4407. }
  4408. $pdf->Ln(5);
  4409. }
  4410. // 分集内容
  4411. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  4412. $pdf->SetFont('dejavusans', 'B', 16);
  4413. $pdf->Cell(0, 12, '分集内容', 0, 1);
  4414. $pdf->Ln(3);
  4415. foreach ($script['episodes'] as $episode) {
  4416. // 检查是否需要新页面
  4417. if ($pdf->GetY() > 250) {
  4418. $pdf->AddPage();
  4419. }
  4420. $pdf->SetFont('dejavusans', 'B', 14);
  4421. $episodeTitle = '第' . $episode['episode_number'] . '集';
  4422. if (!empty($episode['title'])) {
  4423. $episodeTitle .= ':' . $episode['title'];
  4424. }
  4425. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  4426. // 处理分段内容
  4427. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  4428. $pdf->SetFont('dejavusans', '', 12);
  4429. foreach ($episode['segments'] as $segment) {
  4430. if (!empty($segment['segment_content'])) {
  4431. // 如果有分段编号,显示分段标题
  4432. if (!empty($segment['segment_number'])) {
  4433. $pdf->SetFont('dejavusans', 'B', 12);
  4434. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  4435. $pdf->SetFont('dejavusans', '', 12);
  4436. }
  4437. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  4438. $pdf->Ln(2);
  4439. }
  4440. }
  4441. }
  4442. $pdf->Ln(5);
  4443. }
  4444. }
  4445. }
  4446. /**
  4447. * 构建剧本文本内容
  4448. */
  4449. private function buildScriptContent($script) {
  4450. $content = '';
  4451. $groups = $script['group'];
  4452. $groups = (array)$groups;
  4453. foreach ($groups as $group) {
  4454. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  4455. // 剧本基本信息
  4456. if (!empty($group['intro'])) {
  4457. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  4458. }
  4459. if (!empty($group['highlights'])) {
  4460. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  4461. }
  4462. if (!empty($group['role_relationship'])) {
  4463. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  4464. }
  4465. if (!empty($group['core_contradiction'])) {
  4466. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  4467. }
  4468. if (!empty($group['roles']) && is_array($group['roles'])) {
  4469. $content .= "###主体列表\n";
  4470. foreach ($group['roles'] as $role) {
  4471. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  4472. }
  4473. $content .= "\n\n";
  4474. }
  4475. if (!empty($group['art_style'])) {
  4476. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  4477. }
  4478. // 场景信息
  4479. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4480. $content .= "###场景列表\n";
  4481. foreach ($group['scenes'] as $scene) {
  4482. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  4483. }
  4484. $content .= "\n\n";
  4485. }
  4486. // 分集内容
  4487. if (!empty($group['episode_content'])) {
  4488. $content .= "###分集剧本\n";
  4489. $content .= $group['episode_content'];
  4490. // foreach ($script['episodes'] as $episode) {
  4491. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  4492. // // if (!empty($episode['episode_name'])) {
  4493. // // $content .= ":" . $episode['episode_name'];
  4494. // // }
  4495. // // $content .= "\n";
  4496. // $content .= $episode['episode_content'] . "\n\n";
  4497. // }
  4498. }
  4499. }
  4500. return $content;
  4501. }
  4502. /**
  4503. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4504. *
  4505. * @param array $data 包含以下参数:
  4506. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4507. * - question: 用户问题(可选)
  4508. * - model: 使用的模型(r1 或 v3,默认 v3)
  4509. * @return \Generator 返回生成器,用于流式输出
  4510. */
  4511. public function addChat($data) {
  4512. $uid = Site::getUid();
  4513. $anime_id = getProp($data, 'anime_id');
  4514. if (!$anime_id) Utils::throwError('20003:请选择对话');
  4515. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4516. if (!$anime) Utils::throwError('20003:对话不存在');
  4517. $file = getProp($data, 'file');
  4518. $content = getProp($data, 'content', '');
  4519. $bid = getProp($data, 'bid', 0);
  4520. $script_id = getProp($data, 'script_id', 0);
  4521. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  4522. $prompt = getProp($data, 'prompt');
  4523. $user_anime_name = getProp($anime, 'anime_name');
  4524. // 处理文本模型
  4525. $model = getProp($data, 'model');
  4526. if (!$model) {
  4527. // 用户没有输入,从anime表获取
  4528. $model = getProp($anime, 'model');
  4529. if (!$model) {
  4530. // anime表也没有,使用默认值
  4531. $model = 'doubao-seed-2-0-mini-260215';
  4532. }
  4533. }
  4534. // 验证模型是否在可用模型表中
  4535. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4536. $model = 'doubao-seed-2-0-mini-260215';
  4537. }
  4538. $is_multi = getProp($anime, 'is_multi');
  4539. $is_single = (int)$is_multi !== 1;
  4540. // 积分余额预检(仅单剧集模式收费)
  4541. if ($is_single) {
  4542. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  4543. }
  4544. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4545. if ($prompt) {
  4546. $question .= "本次修改要求如下:\n{$prompt}";
  4547. }
  4548. // if (!$file && !$content && !$bid) {
  4549. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4550. // }
  4551. // 提取文件内容
  4552. if ($file) {
  4553. $content = $this->extractFileContent($file);
  4554. if (!$content) {
  4555. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4556. }
  4557. } elseif ($script_id) {
  4558. $content = $this->getContentByScriptId($script_id);
  4559. if (!$content) {
  4560. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4561. }
  4562. } elseif ($bid) {
  4563. $content = $this->getContentByBid($bid);
  4564. if (!$content) {
  4565. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4566. }
  4567. } elseif ($content) {
  4568. $content = filterContent($content);
  4569. } else {
  4570. $content = getProp($anime, 'content');
  4571. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4572. $need_generate_content = true;
  4573. }
  4574. }
  4575. // 美术风格
  4576. $input_art_style = getProp($data, 'art_style');
  4577. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4578. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4579. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4580. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4581. 中年女:邻居阿姨
  4582. 老年男:幽默大爷
  4583. 老年女:婆婆
  4584. 萌娃:奶气萌娃";
  4585. // 判断是否需要生成原文内容
  4586. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4587. // 如果需要生成原文内容,添加额外的要求
  4588. $content_generation_requirement = $need_generate_content
  4589. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4590. : "";
  4591. // 美术风格
  4592. if (!$mappedArtStyle) {
  4593. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4594. }else {
  4595. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4596. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4597. }else {
  4598. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4599. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4600. }
  4601. }
  4602. $systemPrompt = $is_single
  4603. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4604. 强制要求:
  4605. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4606. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4607. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4608. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4609. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4610. 普通要求:
  4611. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4612. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4613. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  4614. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4615. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4616. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4617. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4618. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4619. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4620. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4621. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4622. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4623. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4624. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4625. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4626. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4627. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4628. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4629. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4630. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4631. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4632. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4633. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4634. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4635. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4636. 5.{$mappedArtStyle_prompt}\n\n
  4637. 示例如下:\n
  4638. ###剧本名:西昆仑
  4639. ###故事梗概
  4640. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4641. ###剧本亮点
  4642. 亮点1:绝境奇药,生死一线
  4643. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4644. 亮点2:结拜兄妹,化解尴尬
  4645. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4646. 亮点3:纤发夺命,情愫暗涌
  4647. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4648. ###人物关系
  4649. 阿雪与梁萧之间存在兄妹之情。
  4650. ###核心矛盾
  4651. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4652. ###主体列表
  4653. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4654. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4655. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4656. 姿态:站立。}{{甜心小美}}
  4657. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4658. 全景,正面拍摄,青年女性,亚洲人。
  4659. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4660. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4661. 姿态:站立。}{{阳光青年}}
  4662. ###美术风格
  4663. 基础画风风格词:厚涂古风
  4664. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4665. ###场景列表
  4666. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4667. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4668. 无人物。}
  4669. ###分镜剧本
  4670. ##第1幕:徐家老旧厨房 白天 室内
  4671. 分镜1
  4672. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4673. 场景:徐家老旧厨房
  4674. 构图设计:全景,低角度仰视
  4675. 运镜调度:手持拍摄
  4676. 配音角色:旁白
  4677. 出镜角色:许芸-校服装、徐母
  4678. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4679. 画面类型:普通画面
  4680. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4681. 分镜2
  4682. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4683. 场景:徐家老旧厨房
  4684. 构图设计:近景,徐母面部特写
  4685. 运镜调度:固定镜头
  4686. 配音角色:徐母
  4687. 出镜角色:徐母
  4688. 台词内容:问我夜不归宿死哪儿去了。
  4689. 画面类型:对口型
  4690. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4691. ##第2幕:徐家简陋客厅 黄昏 室内
  4692. 分镜3
  4693. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4694. 场景:徐家简陋客厅
  4695. 构图设计:全景,景深虚化
  4696. 运镜调度:固定镜头
  4697. 配音角色:旁白
  4698. 出镜角色:无
  4699. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4700. 画面类型:普通画面
  4701. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4702. 分镜4
  4703. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4704. 场景:徐家简陋客厅
  4705. 构图设计:特写,火车票
  4706. 运镜调度:固定镜头
  4707. 配音角色:旁白
  4708. 出镜角色:无
  4709. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4710. 画面类型:普通画面
  4711. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4712. "
  4713. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4714. 强制要求:\n
  4715. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4716. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4717. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4718. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4719. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4720. 普通要求:\n
  4721. 1.剧本名(必须生成)必须与文档内容高度相关
  4722. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4723. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4724. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4725. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4726. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4727. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4728. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4729. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4730. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4731. 4.{$mappedArtStyle_prompt}\n\n
  4732. 示例如下:\n
  4733. ###剧本名:西昆仑
  4734. ###故事梗概
  4735. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4736. ###剧本亮点
  4737. 亮点1:绝境奇药,生死一线
  4738. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4739. 亮点2:结拜兄妹,化解尴尬
  4740. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4741. 亮点3:纤发夺命,情愫暗涌
  4742. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4743. ###人物关系
  4744. 阿雪与梁萧之间存在兄妹之情。
  4745. ###核心矛盾
  4746. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4747. ###主体列表
  4748. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4749. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4750. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4751. 姿态:站立。}{{甜心小美}}
  4752. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4753. 全景,正面拍摄,青年女性,亚洲人。
  4754. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4755. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4756. 姿态:站立。}{{阳光青年}}
  4757. ###美术风格
  4758. 基础画风风格词:厚涂古风
  4759. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4760. ###场景列表
  4761. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4762. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4763. 无人物。}";
  4764. // 构建消息
  4765. $messages = [
  4766. [
  4767. 'role' => 'system',
  4768. 'content' => $systemPrompt
  4769. ],
  4770. [
  4771. 'role' => 'user',
  4772. 'content' => "以下是文档内容:
  4773. {$content}
  4774. 用户问题:
  4775. {$question}"
  4776. ]
  4777. ];
  4778. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4779. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4780. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4781. if ($model === 'deepseek-chat') {
  4782. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4783. $model = 'deepseek-v4-flash';
  4784. $thinkingMode = 'disabled';
  4785. } elseif ($model === 'deepseek-reasoner') {
  4786. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4787. $model = 'deepseek-v4-flash';
  4788. $thinkingMode = 'enabled';
  4789. }
  4790. $post_data = [
  4791. 'model' => $model,
  4792. 'messages' => $messages,
  4793. // 'max_tokens' => 8192,
  4794. 'temperature' => 0.7,
  4795. 'frequency_penalty' => 0,
  4796. 'presence_penalty' => 0,
  4797. 'response_format' => ['type' => 'text'],
  4798. 'thinking' => ['type'=>$thinkingMode],
  4799. 'stream' => true // 启用流式输出
  4800. ];
  4801. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4802. // 根据模型类型选择调用方法
  4803. $fullContent = '';
  4804. $fullReasoningContent = '';
  4805. $usage = [];
  4806. try {
  4807. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4808. // DeepSeek 官方模型使用 DeepSeek API
  4809. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4810. } else if (in_array($model, $this->gpt_text_models)) {
  4811. // GPT-5.4 模型使用 TokenRouter API
  4812. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4813. } else if (in_array($model, $this->gemini_text_models)) {
  4814. // Gemini 模型使用 Gemini API
  4815. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4816. } else {
  4817. // 其他模型使用火山引擎API
  4818. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4819. }
  4820. // 验证返回值类型
  4821. if (!is_iterable($streamGenerator)) {
  4822. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4823. dLog('deepseek')->error('addChat流式生成器无效', [
  4824. 'generator_type' => $errorType,
  4825. 'model' => $model,
  4826. 'anime_id' => $anime_id
  4827. ]);
  4828. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  4829. 'type' => $errorType,
  4830. 'model' => $model
  4831. ]);
  4832. yield [
  4833. 'type' => 'error',
  4834. 'script' => [],
  4835. 'episode' => [],
  4836. 'answer' => '',
  4837. 'reasoning' => '',
  4838. 'usage' => [],
  4839. 'error' => '接口返回数据异常,请重新请求'
  4840. ];
  4841. return;
  4842. }
  4843. // 处理流式输出
  4844. foreach ($streamGenerator as $chunk) {
  4845. if (isset($chunk['type'])) {
  4846. if ($chunk['type'] === 'done') {
  4847. // 最终结果
  4848. $fullContent = $chunk['full_content'];
  4849. $fullReasoningContent = $chunk['full_reasoning'];
  4850. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4851. } else {
  4852. // 逐块yield数据
  4853. yield $chunk;
  4854. }
  4855. }
  4856. }
  4857. } catch (\Exception $e) {
  4858. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  4859. 'model' => $model,
  4860. 'anime_id' => $anime_id,
  4861. 'trace' => $e->getTraceAsString()
  4862. ]);
  4863. logDB('deepseek', 'error', 'addChat流式处理失败', [
  4864. 'error' => $e->getMessage(),
  4865. 'model' => $model
  4866. ]);
  4867. yield [
  4868. 'type' => 'error',
  4869. 'script' => [],
  4870. 'episode' => [],
  4871. 'answer' => '',
  4872. 'reasoning' => '',
  4873. 'usage' => [],
  4874. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4875. ];
  4876. return;
  4877. }
  4878. dLog('deepseek')->info('完整内容: '.$fullContent);
  4879. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4880. // 处理完整内容并返回最终结果
  4881. $script_arr = [];
  4882. if ($fullContent) {
  4883. $script_arr = handleScriptContent($fullContent);
  4884. dLog('deepseek')->info('解析内容', $script_arr);
  4885. logDB('deepseek', 'info', '解析内容', $script_arr);
  4886. }
  4887. if (empty($script_arr['roles'])) {
  4888. // 未生成剧本相关内容,保存对话记录并返回提示
  4889. dLog('deepseek')->info('未生成剧本相关的内容');
  4890. try {
  4891. DB::beginTransaction();
  4892. $now = date('Y-m-d H:i:s');
  4893. // 保存对话记录
  4894. $records = [
  4895. [
  4896. 'uid' => $uid,
  4897. 'anime_id' => $anime_id,
  4898. 'sequence' => 0,
  4899. 'role' => 'user',
  4900. 'content' => $prompt,
  4901. 'created_at' => $now,
  4902. 'updated_at' => $now
  4903. ],
  4904. [
  4905. 'uid' => $uid,
  4906. 'anime_id' => $anime_id,
  4907. 'sequence' => 0,
  4908. 'role' => 'assistant',
  4909. // 'content' => $fullContent,
  4910. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  4911. 'created_at' => $now,
  4912. 'updated_at' => $now
  4913. ]
  4914. ];
  4915. DB::table('mp_anime_records')->insert($records);
  4916. DB::commit();
  4917. } catch (\Exception $e) {
  4918. DB::rollBack();
  4919. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4920. }
  4921. yield [
  4922. 'type' => 'done',
  4923. 'script' => [],
  4924. 'episode' => [],
  4925. 'answer' => $fullContent,
  4926. 'reasoning' => $fullReasoningContent,
  4927. 'usage' => $usage,
  4928. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4929. ];
  4930. return;
  4931. }
  4932. // 如果需要生成原文内容,从script_arr中提取
  4933. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4934. $content = $script_arr['content'];
  4935. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  4936. if (!$content) {
  4937. yield [
  4938. 'type' => 'done',
  4939. 'script' => [],
  4940. 'episode' => [],
  4941. 'answer' => $fullContent,
  4942. 'reasoning' => $fullReasoningContent,
  4943. 'usage' => $usage,
  4944. 'error' => '未生成剧本内容,请调整提示词再试'
  4945. ];
  4946. return;
  4947. }
  4948. }
  4949. // 替换美术风格
  4950. if ($mappedArtStyle !== '') {
  4951. $script_arr['art_style'] = $mappedArtStyle;
  4952. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4953. }
  4954. // 新建动漫
  4955. if ($user_anime_name == '新剧本策划') {
  4956. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  4957. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  4958. // if (!$anime_name) {
  4959. // // 未识别到剧本名,保存对话记录并返回提示
  4960. // dLog('deepseek')->info('未能识别到剧本名称');
  4961. // try {
  4962. // DB::beginTransaction();
  4963. // $now = date('Y-m-d H:i:s');
  4964. // // 保存对话记录
  4965. // $records = [
  4966. // [
  4967. // 'uid' => $uid,
  4968. // 'anime_id' => $anime_id,
  4969. // 'sequence' => 0,
  4970. // 'role' => 'user',
  4971. // 'content' => $prompt,
  4972. // 'created_at' => $now,
  4973. // 'updated_at' => $now
  4974. // ],
  4975. // [
  4976. // 'uid' => $uid,
  4977. // 'anime_id' => $anime_id,
  4978. // 'sequence' => 0,
  4979. // 'role' => 'assistant',
  4980. // 'content' => '未能生成剧本名称,请重试',
  4981. // 'created_at' => $now,
  4982. // 'updated_at' => $now
  4983. // ]
  4984. // ];
  4985. // DB::table('mp_anime_records')->insert($records);
  4986. // DB::commit();
  4987. // } catch (\Exception $e) {
  4988. // DB::rollBack();
  4989. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4990. // }
  4991. // yield [
  4992. // 'type' => 'done',
  4993. // 'script' => [],
  4994. // 'episode' => [],
  4995. // 'answer' => $fullContent,
  4996. // 'reasoning' => $fullReasoningContent,
  4997. // 'usage' => $usage,
  4998. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  4999. // ];
  5000. // return;
  5001. // }
  5002. // 确认对话名称唯一性
  5003. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5004. $anime_name = $anime_name . '_' . date('YmdHis');
  5005. }
  5006. }else {
  5007. $anime_name = $user_anime_name;
  5008. }
  5009. $table_data = [
  5010. 'user_id' => $uid,
  5011. 'anime_name' => $anime_name,
  5012. 'model' => $model,
  5013. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5014. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5015. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5016. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5017. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5018. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5019. 'art_style_type' => $input_art_style,
  5020. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5021. 'status' => '解析完成',
  5022. 'content' => $content,
  5023. 'is_multi' => $is_multi,
  5024. 'ace_mode' => $ace_mode,
  5025. 'generate_status' => '待执行',
  5026. 'updated_at' => date('Y-m-d H:i:s')
  5027. ];
  5028. if ($table_data['content']) {
  5029. $chapters = splitContent($table_data['content']);
  5030. $chapter_count = count($chapters);
  5031. if ($chapter_count > 0) {
  5032. $table_data['start_episode_sequence'] = 1;
  5033. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5034. }
  5035. }
  5036. // 如果有剧本ID则进行绑定
  5037. if ($script_id) {
  5038. $table_data['script_id'] = $script_id;
  5039. }
  5040. $single_episode = [];
  5041. try {
  5042. DB::beginTransaction();
  5043. $now = date('Y-m-d H:i:s');
  5044. // 更新动漫大纲
  5045. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5046. if (!$boolen) {
  5047. dLog('deepseek')->info('动漫保存失败', $table_data);
  5048. Utils::throwError('20003:动漫保存失败');
  5049. }
  5050. // 保存对话记录
  5051. $records = [
  5052. [
  5053. 'uid' => $uid,
  5054. 'anime_id' => $anime_id,
  5055. 'sequence' => 0,
  5056. 'role' => 'user',
  5057. 'content' => $prompt,
  5058. 'created_at' => date('Y-m-d H:i:s'),
  5059. 'updated_at' => date('Y-m-d H:i:s')
  5060. ],
  5061. [
  5062. 'uid' => $uid,
  5063. 'anime_id' => $anime_id,
  5064. 'sequence' => 0,
  5065. 'role' => 'assistant',
  5066. 'content' => $fullContent,
  5067. 'created_at' => date('Y-m-d H:i:s'),
  5068. 'updated_at' => date('Y-m-d H:i:s')
  5069. ]
  5070. ];
  5071. // 保存对话记录
  5072. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5073. if (!$boolen3) {
  5074. Utils::throwError('20003:对话记录保存失败');
  5075. }
  5076. if ($is_single) {
  5077. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5078. if (empty($episode_arr['acts'])) {
  5079. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5080. }
  5081. $saveResult = $this->saveEpisodeVersionData(
  5082. $anime_id,
  5083. 1,
  5084. $episode_arr,
  5085. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5086. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5087. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5088. null,
  5089. null,
  5090. false,
  5091. $content,
  5092. $now
  5093. );
  5094. $single_episode = $saveResult['episode'];
  5095. $episode_id = $saveResult['episode_id'];
  5096. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5097. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5098. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5099. 'props' => json_encode($saveResult['merged_props'], 256),
  5100. 'updated_at' => $now
  5101. ]);
  5102. if ($boolen5 === false) {
  5103. Utils::throwError('20003:单剧集主表资源同步失败');
  5104. }
  5105. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5106. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5107. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5108. $episode_record_content = '确认分镜大纲';
  5109. if ($content !== '') {
  5110. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5111. }
  5112. $episode_records = [
  5113. [
  5114. 'uid' => $uid,
  5115. 'anime_id' => $anime_id,
  5116. 'role' => 'user',
  5117. 'content' => $episode_record_content,
  5118. 'sequence' => 1,
  5119. 'episode_id' => $episode_id,
  5120. 'created_at' => $now,
  5121. 'updated_at' => $now
  5122. ],
  5123. [
  5124. 'uid' => $uid,
  5125. 'anime_id' => $anime_id,
  5126. 'role' => 'assistant',
  5127. 'content' => $fullContent,
  5128. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5129. 'sequence' => 1,
  5130. 'episode_id' => $episode_id,
  5131. 'created_at' => $now,
  5132. 'updated_at' => $now
  5133. ]
  5134. ];
  5135. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5136. if (!$boolen4) {
  5137. Utils::throwError('20003:单剧集分镜记录保存失败');
  5138. }
  5139. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  5140. if ($is_single && !empty($single_episode)) {
  5141. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5142. 'anime_id' => $anime_id,
  5143. 'episode_id' => $episode_id ?? 0,
  5144. ]);
  5145. }
  5146. }
  5147. }catch (\Exception $e) {
  5148. DB::rollBack();
  5149. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5150. yield [
  5151. 'type' => 'done',
  5152. 'answer' => $fullContent,
  5153. 'reasoning' => $fullReasoningContent,
  5154. 'usage' => $usage,
  5155. 'error' => $e->getMessage(),
  5156. ];
  5157. return;
  5158. }
  5159. DB::commit();
  5160. dLog('deepseek')->info('保存完毕');
  5161. if ($is_single && !empty($single_episode)) {
  5162. // $this->batchSetGlobalRoleImg([
  5163. // 'anime_id' => $anime_id,
  5164. // ]);
  5165. // $this->batchSetGlobalSceneImg([
  5166. // 'anime_id' => $anime_id,
  5167. // ]);
  5168. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5169. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5170. }
  5171. $table_data['anime_id'] = $anime_id;
  5172. $table_data['roles'] = json_decode($table_data['roles'], true);
  5173. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5174. // $table_data['episodes'] = $script_arr['episodes'];
  5175. unset($table_data['created_at']);
  5176. unset($table_data['updated_at']);
  5177. unset($table_data['status']);
  5178. dLog('deepseek')->info('开始返回');
  5179. yield [
  5180. 'type' => 'done',
  5181. 'script' => $table_data,
  5182. 'episode' => $single_episode,
  5183. 'answer' => $fullContent,
  5184. 'reasoning' => $fullReasoningContent,
  5185. 'usage' => $usage
  5186. ];
  5187. }
  5188. public function reGenerateAnime($data) {
  5189. $uid = Site::getUid();
  5190. $file = getProp($data, 'file');
  5191. $content = getProp($data, 'content', '');
  5192. $bid = getProp($data, 'bid', 0);
  5193. $script_id = getProp($data, 'script_id', 0);
  5194. $anime_id = getProp($data, 'anime_id');
  5195. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5196. if (!$anime) {
  5197. Utils::throwError('20003:该对话不存在');
  5198. }
  5199. $user_anime_name = getProp($anime, 'anime_name');
  5200. $prompt = getProp($data, 'prompt');
  5201. // 处理文本模型
  5202. $model = getProp($data, 'model');
  5203. if (!$model) {
  5204. // 用户没有输入,从anime表获取
  5205. $model = getProp($anime, 'model');
  5206. if (!$model) {
  5207. // anime表也没有,使用默认值
  5208. $model = 'doubao-seed-2-0-mini-260215';
  5209. }
  5210. }
  5211. // 验证模型是否在可用模型表中
  5212. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5213. $model = 'doubao-seed-2-0-mini-260215';
  5214. }
  5215. $is_multi = getProp($anime, 'is_multi', 1);
  5216. $is_single = (int)$is_multi !== 1;
  5217. // 积分余额预检(仅单剧集模式收费)
  5218. if ($is_single) {
  5219. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  5220. }
  5221. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  5222. if ($is_single) {
  5223. $episode_exists = DB::table('mp_anime_episodes')
  5224. ->where('anime_id', $anime_id)
  5225. ->where('sequence', 1)
  5226. ->exists();
  5227. if ($episode_exists) {
  5228. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  5229. }
  5230. }
  5231. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5232. if ($prompt) {
  5233. $question .= "本次修改要求如下:\n{$prompt}";
  5234. }
  5235. // 提取文件内容
  5236. if ($file) {
  5237. $content = $this->extractFileContent($file);
  5238. if (!$content) {
  5239. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5240. }
  5241. } elseif ($script_id) {
  5242. $content = $this->getContentByScriptId($script_id);
  5243. if (!$content) {
  5244. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5245. }
  5246. } elseif ($bid) {
  5247. $content = $this->getContentByBid($bid);
  5248. if (!$content) {
  5249. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5250. }
  5251. } elseif ($content) {
  5252. $content = filterContent($content);
  5253. }else {
  5254. $content = filterContent(getProp($anime, 'content'));
  5255. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5256. $need_generate_content = true;
  5257. }
  5258. }
  5259. // 判断是否需要生成原文内容
  5260. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5261. // 如果需要生成原文内容,添加额外的要求
  5262. $content_generation_requirement = $need_generate_content
  5263. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5264. : "";
  5265. // 美术风格
  5266. $input_art_style = getProp($anime, 'art_style');
  5267. if (!$input_art_style) {
  5268. $input_art_style = getProp($data, 'art_style');
  5269. }
  5270. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5271. // 美术风格
  5272. if (!$mappedArtStyle) {
  5273. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5274. }else {
  5275. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5276. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5277. }else {
  5278. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5279. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5280. }
  5281. }
  5282. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5283. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5284. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5285. 中年女:邻居阿姨
  5286. 老年男:幽默大爷
  5287. 老年女:婆婆
  5288. 萌娃:奶气萌娃";
  5289. $system_message = ['role'=>'system', 'content'=>$is_single
  5290. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5291. 强制要求:
  5292. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5293. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5294. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5295. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5296. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5297. 普通要求:
  5298. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5299. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5300. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5301. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5302. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5303. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5304. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5305. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5306. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5307. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5308. 3.$mappedArtStyle_prompt\n\n
  5309. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5310. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5311. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5312. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5313. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5314. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5315. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5316. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5317. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5318. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5319. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5320. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5321. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5322. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5323. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5324. 示例如下:\n
  5325. ###剧本名:西昆仑
  5326. ###故事梗概
  5327. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5328. ###剧本亮点
  5329. 亮点1:绝境奇药,生死一线
  5330. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5331. 亮点2:结拜兄妹,化解尴尬
  5332. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5333. 亮点3:纤发夺命,情愫暗涌
  5334. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5335. ###人物关系
  5336. 阿雪与梁萧之间存在兄妹之情。
  5337. ###核心矛盾
  5338. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5339. ###主体列表
  5340. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5341. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5342. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5343. 姿态:站立。}{{甜心小美}}
  5344. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5345. 全景,正面拍摄,青年女性,亚洲人。
  5346. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5347. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5348. 姿态:站立。}{{阳光青年}}
  5349. ###美术风格
  5350. 基础画风风格词:厚涂古风
  5351. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5352. ###场景列表
  5353. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5354. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5355. 无人物。}
  5356. ###分镜剧本
  5357. ##第1幕:徐家老旧厨房 白天 室内
  5358. 分镜1
  5359. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5360. 场景:徐家老旧厨房
  5361. 构图设计:全景,低角度仰视
  5362. 运镜调度:手持拍摄
  5363. 配音角色:旁白
  5364. 出镜角色:许芸-校服装、徐母
  5365. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5366. 画面类型:普通画面
  5367. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5368. 分镜2
  5369. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5370. 场景:徐家老旧厨房
  5371. 构图设计:近景,徐母面部特写
  5372. 运镜调度:固定镜头
  5373. 配音角色:徐母
  5374. 出镜角色:徐母
  5375. 台词内容:问我夜不归宿死哪儿去了。
  5376. 画面类型:对口型
  5377. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5378. ##第2幕:徐家简陋客厅 黄昏 室内
  5379. 分镜3
  5380. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5381. 场景:徐家简陋客厅
  5382. 构图设计:全景,景深虚化
  5383. 运镜调度:固定镜头
  5384. 配音角色:旁白
  5385. 出镜角色:无
  5386. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5387. 画面类型:普通画面
  5388. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5389. 分镜4
  5390. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5391. 场景:徐家简陋客厅
  5392. 构图设计:特写,火车票
  5393. 运镜调度:固定镜头
  5394. 配音角色:旁白
  5395. 出镜角色:无
  5396. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5397. 画面类型:普通画面
  5398. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5399. "
  5400. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5401. 强制要求:\n
  5402. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5403. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5404. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5405. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5406. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5407. 普通要求:\n
  5408. 1.剧本名(必须生成)必须与文档内容高度相关
  5409. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5410. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5411. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5412. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5413. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5414. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5415. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5416. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5417. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5418. 4.$mappedArtStyle_prompt\n\n
  5419. 示例如下:\n
  5420. ###剧本名:西昆仑
  5421. ###故事梗概
  5422. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5423. ###剧本亮点
  5424. 亮点1:绝境奇药,生死一线
  5425. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5426. 亮点2:结拜兄妹,化解尴尬
  5427. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5428. 亮点3:纤发夺命,情愫暗涌
  5429. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5430. ###人物关系
  5431. 阿雪与梁萧之间存在兄妹之情。
  5432. ###核心矛盾
  5433. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5434. ###主体列表
  5435. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5436. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5437. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5438. 姿态:站立。}{{甜心小美}}
  5439. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5440. 全景,正面拍摄,青年女性,亚洲人。
  5441. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5442. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5443. 姿态:站立。}{{阳光青年}}
  5444. ###美术风格
  5445. 基础画风风格词:厚涂古风
  5446. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5447. ###场景列表
  5448. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5449. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5450. 无人物。}"];
  5451. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  5452. $episode_count = $this->extractEpisodeNumber($prompt);
  5453. if ((int)getProp($anime, 'is_multi') !== 1) {
  5454. yield [
  5455. 'type' => 'done',
  5456. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  5457. 'reasoning' => '',
  5458. 'usage' => []
  5459. ];
  5460. return;
  5461. }
  5462. if ($episode_count) {
  5463. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  5464. $system_message = [
  5465. 'role' => 'system',
  5466. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5467. 强制要求:\n
  5468. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5469. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5470. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5471. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5472. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5473. 普通要求:\n
  5474. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5475. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5476. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5477. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5478. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5479. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5480. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5481. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5482. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5483. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  5484. 示例如下:\n
  5485. ###剧本名:西昆仑
  5486. ###故事梗概
  5487. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5488. ###剧本亮点
  5489. 亮点1:绝境奇药,生死一线
  5490. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5491. 亮点2:结拜兄妹,化解尴尬
  5492. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5493. 亮点3:纤发夺命,情愫暗涌
  5494. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5495. ###人物关系
  5496. 阿雪与梁萧之间存在兄妹之情。
  5497. ###核心矛盾
  5498. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5499. ###主体列表
  5500. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5501. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5502. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5503. 姿态:站立。}{{甜心小美}}
  5504. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5505. 全景,正面拍摄,青年女性,亚洲人。
  5506. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5507. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5508. 姿态:站立。}{{阳光青年}}
  5509. ###美术风格
  5510. 基础画风风格词:厚涂古风
  5511. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5512. ###场景列表
  5513. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5514. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5515. 无人物。}
  5516. ###分集详细内容
  5517. ##第1章 重生
  5518. 我重生了。
  5519. 源于一个男人偏执的暗恋。
  5520. ##第2章 相救
  5521. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  5522. 我眼睛扫向站在锅炉后的卞大伟。"
  5523. ];
  5524. // 构建消息
  5525. $messages = [
  5526. $system_message,
  5527. [
  5528. 'role' => 'user',
  5529. 'content' => "以下是文档内容:
  5530. {$content}
  5531. 用户问题:
  5532. {$question}"
  5533. ]
  5534. ];
  5535. }else {
  5536. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  5537. // 构建消息
  5538. $messages = [
  5539. $system_message,
  5540. [
  5541. 'role' => 'user',
  5542. 'content' => "以下是文档内容:
  5543. {$content}
  5544. 用户问题:
  5545. {$question}"
  5546. ]
  5547. ];
  5548. }else {
  5549. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  5550. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  5551. return (array)$value;
  5552. })->toArray();
  5553. array_unshift($messages, $system_message);
  5554. $messages[] = [
  5555. 'role' => 'user',
  5556. 'content' => $prompt
  5557. ];
  5558. }
  5559. }
  5560. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5561. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5562. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5563. if ($model === 'deepseek-chat') {
  5564. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5565. $model = 'deepseek-v4-flash';
  5566. $thinkingMode = 'disabled';
  5567. } elseif ($model === 'deepseek-reasoner') {
  5568. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5569. $model = 'deepseek-v4-flash';
  5570. $thinkingMode = 'enabled';
  5571. }
  5572. $post_data = [
  5573. 'model' => $model,
  5574. 'messages' => $messages,
  5575. // 'max_tokens' => 8192,
  5576. 'temperature' => 0.7,
  5577. 'frequency_penalty' => 0,
  5578. 'presence_penalty' => 0,
  5579. 'response_format' => ['type' => 'text'],
  5580. 'thinking' => ['type' => $thinkingMode],
  5581. 'stream' => true // 启用流式输出
  5582. ];
  5583. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5584. // 根据模型类型选择调用方法
  5585. $fullContent = '';
  5586. $fullReasoningContent = '';
  5587. $usage = [];
  5588. // dd($post_data);
  5589. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  5590. try {
  5591. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5592. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5593. } else if (in_array($model, $this->gpt_text_models)) {
  5594. // GPT-5.4 模型使用 TokenRouter API
  5595. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5596. } else if (in_array($model, $this->gemini_text_models)) {
  5597. // Gemini 模型使用 Gemini API
  5598. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5599. } else {
  5600. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5601. }
  5602. // 验证返回值类型
  5603. if (!is_iterable($streamGenerator)) {
  5604. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5605. dLog('deepseek')->error('方法名流式生成器无效', [
  5606. 'generator_type' => $errorType,
  5607. 'model' => $model,
  5608. // 添加其他上下文信息
  5609. ]);
  5610. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  5611. 'type' => $errorType,
  5612. 'model' => $model
  5613. ]);
  5614. yield [
  5615. 'type' => 'error',
  5616. // 根据方法返回相应的空数据结构
  5617. 'answer' => '',
  5618. 'reasoning' => '',
  5619. 'usage' => [],
  5620. 'error' => '接口返回数据异常,请重新请求'
  5621. ];
  5622. return;
  5623. }
  5624. // 处理流式输出
  5625. foreach ($streamGenerator as $chunk) {
  5626. if (isset($chunk['type'])) {
  5627. if ($chunk['type'] === 'done') {
  5628. $fullContent = $chunk['full_content'];
  5629. $fullReasoningContent = $chunk['full_reasoning'];
  5630. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5631. } else {
  5632. yield $chunk;
  5633. }
  5634. }
  5635. }
  5636. } catch (\Exception $e) {
  5637. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  5638. 'model' => $model,
  5639. 'trace' => $e->getTraceAsString()
  5640. ]);
  5641. logDB('deepseek', 'error', '方法名流式处理失败', [
  5642. 'error' => $e->getMessage(),
  5643. 'model' => $model
  5644. ]);
  5645. yield [
  5646. 'type' => 'error',
  5647. // 根据方法返回相应的空数据结构
  5648. 'answer' => '',
  5649. 'reasoning' => '',
  5650. 'usage' => [],
  5651. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5652. ];
  5653. return;
  5654. }
  5655. dLog('deepseek')->info('完整内容: '.$fullContent);
  5656. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5657. // 处理完整内容并返回最终结果
  5658. $script_arr = [];
  5659. if ($fullContent) {
  5660. $script_arr = handleScriptContent($fullContent);
  5661. dLog('deepseek')->info('解析内容', $script_arr);
  5662. logDB('deepseek', 'info', '解析内容', $script_arr);
  5663. }
  5664. if (empty($script_arr['roles'])) {
  5665. // 未生成剧本相关内容,保存对话记录并返回提示
  5666. dLog('deepseek')->info('未生成剧本相关的内容');
  5667. try {
  5668. $now = date('Y-m-d H:i:s');
  5669. // 保存对话记录
  5670. $records = [
  5671. [
  5672. 'uid' => $uid,
  5673. 'anime_id' => $anime_id,
  5674. 'sequence' => 0,
  5675. 'role' => 'user',
  5676. 'content' => $prompt,
  5677. 'created_at' => $now,
  5678. 'updated_at' => $now
  5679. ],
  5680. [
  5681. 'uid' => $uid,
  5682. 'anime_id' => $anime_id,
  5683. 'sequence' => 0,
  5684. 'role' => 'assistant',
  5685. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  5686. 'created_at' => $now,
  5687. 'updated_at' => $now
  5688. ]
  5689. ];
  5690. DB::table('mp_anime_records')->insert($records);
  5691. } catch (\Exception $e) {
  5692. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5693. }
  5694. yield [
  5695. 'type' => 'done',
  5696. 'script' => [],
  5697. 'episode' => [],
  5698. 'answer' => $fullContent,
  5699. 'reasoning' => $fullReasoningContent,
  5700. 'usage' => $usage,
  5701. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5702. ];
  5703. return;
  5704. }
  5705. // 替换美术风格
  5706. if ($mappedArtStyle !== '') {
  5707. $script_arr['art_style'] = $mappedArtStyle;
  5708. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5709. }
  5710. if ($user_anime_name != '新剧本策划') {
  5711. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5712. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5713. // 确认对话名称唯一性
  5714. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5715. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  5716. }
  5717. }else {
  5718. $anime_name = $user_anime_name;
  5719. }
  5720. $table_data = [
  5721. 'user_id' => $uid,
  5722. 'model' => $model,
  5723. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5724. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5725. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5726. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5727. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5728. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5729. 'art_style_type' => $input_art_style,
  5730. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5731. 'status' => '解析完成',
  5732. 'generate_status' => '待执行',
  5733. 'updated_at' => date('Y-m-d H:i:s')
  5734. ];
  5735. if ($anime_name) $table_data['anime_name'] = $anime_name;
  5736. // 如果是修改集数,则将content内容更新(会改变原文)
  5737. if (isset($episode_count) && $episode_count > 0) {
  5738. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  5739. $table_data['start_episode_sequence'] = 1;
  5740. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  5741. }else {
  5742. // 如果需要生成原文内容,从script_arr中提取
  5743. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5744. $table_data['content'] = $script_arr['content'];
  5745. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  5746. if (!$table_data['content']) {
  5747. yield [
  5748. 'type' => 'done',
  5749. 'script' => [],
  5750. 'episode' => [],
  5751. 'answer' => $fullContent,
  5752. 'reasoning' => $fullReasoningContent,
  5753. 'usage' => $usage,
  5754. 'error' => '未生成剧本内容,请调整提示词再试'
  5755. ];
  5756. return;
  5757. }
  5758. }
  5759. if (isset($table_data['content']) && $table_data['content']) {
  5760. $chapters = splitContent($table_data['content']);
  5761. $chapter_count = count($chapters);
  5762. if ($chapter_count > 0) {
  5763. $table_data['start_episode_sequence'] = 1;
  5764. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5765. }
  5766. }
  5767. }
  5768. $single_episode = [];
  5769. try {
  5770. DB::beginTransaction();
  5771. $now = date('Y-m-d H:i:s');
  5772. // 更新动漫大纲
  5773. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5774. if (!$boolen) {
  5775. dLog('deepseek')->info('对话修改失败', $table_data);
  5776. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  5777. Utils::throwError('20003:对话修改失败');
  5778. }
  5779. // 保存对话记录
  5780. $records = [
  5781. [
  5782. 'uid' => $uid,
  5783. 'anime_id' => $anime_id,
  5784. 'sequence' => 0,
  5785. 'role' => 'user',
  5786. 'content' => $prompt,
  5787. 'created_at' => $now,
  5788. 'updated_at' => $now
  5789. ],
  5790. [
  5791. 'uid' => $uid,
  5792. 'anime_id' => $anime_id,
  5793. 'sequence' => 0,
  5794. 'role' => 'assistant',
  5795. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5796. 'content' => $fullContent,
  5797. 'created_at' => $now,
  5798. 'updated_at' => $now
  5799. ]
  5800. ];
  5801. // 保存对话记录
  5802. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5803. if (!$boolen3) {
  5804. Utils::throwError('20003:对话记录保存失败');
  5805. }
  5806. // 单剧集模式:生成并保存剧集信息
  5807. if ($is_single) {
  5808. $anime_name = getProp($anime, 'anime_name', '未命名');
  5809. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5810. if (empty($episode_arr['acts'])) {
  5811. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5812. }
  5813. $saveResult = $this->saveEpisodeVersionData(
  5814. $anime_id,
  5815. 1,
  5816. $episode_arr,
  5817. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5818. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5819. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5820. null,
  5821. null,
  5822. false,
  5823. $content,
  5824. $now
  5825. );
  5826. $single_episode = $saveResult['episode'];
  5827. $episode_id = $saveResult['episode_id'];
  5828. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5829. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5830. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5831. 'props' => json_encode($saveResult['merged_props'], 256),
  5832. 'updated_at' => $now
  5833. ]);
  5834. if ($boolen5 === false) {
  5835. Utils::throwError('20003:单剧集主表资源同步失败');
  5836. }
  5837. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5838. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5839. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5840. $episode_record_content = '确认分镜大纲';
  5841. if ($content !== '') {
  5842. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5843. }
  5844. $episode_records = [
  5845. [
  5846. 'uid' => $uid,
  5847. 'anime_id' => $anime_id,
  5848. 'role' => 'user',
  5849. 'content' => $episode_record_content,
  5850. 'sequence' => 1,
  5851. 'episode_id' => $episode_id,
  5852. 'created_at' => $now,
  5853. 'updated_at' => $now
  5854. ],
  5855. [
  5856. 'uid' => $uid,
  5857. 'anime_id' => $anime_id,
  5858. 'role' => 'assistant',
  5859. 'content' => $fullContent,
  5860. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5861. 'sequence' => 1,
  5862. 'episode_id' => $episode_id,
  5863. 'created_at' => $now,
  5864. 'updated_at' => $now
  5865. ]
  5866. ];
  5867. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5868. if (!$boolen4) {
  5869. Utils::throwError('20003:单剧集分镜记录保存失败');
  5870. }
  5871. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  5872. if ($is_single && !empty($single_episode)) {
  5873. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5874. 'anime_id' => $anime_id,
  5875. 'episode_id' => $episode_id ?? 0,
  5876. ]);
  5877. }
  5878. }
  5879. }catch (\Exception $e) {
  5880. DB::rollBack();
  5881. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  5882. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  5883. yield [
  5884. 'type' => 'done',
  5885. 'answer' => $fullContent,
  5886. 'reasoning' => $fullReasoningContent,
  5887. 'usage' => $usage,
  5888. 'error' => $e->getMessage(),
  5889. ];
  5890. return;
  5891. }
  5892. DB::commit();
  5893. dLog('deepseek')->info('保存完毕');
  5894. if ($is_single && !empty($single_episode)) {
  5895. // $this->batchSetGlobalRoleImg([
  5896. // 'anime_id' => $anime_id,
  5897. // ]);
  5898. // $this->batchSetGlobalSceneImg([
  5899. // 'anime_id' => $anime_id,
  5900. // ]);
  5901. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5902. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5903. }
  5904. $table_data['anime_id'] = $anime_id;
  5905. $table_data['roles'] = json_decode($table_data['roles'], true);
  5906. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5907. unset($table_data['updated_at']);
  5908. unset($table_data['status']);
  5909. yield [
  5910. 'type' => 'done',
  5911. 'script' => $table_data,
  5912. 'episode' => $single_episode,
  5913. 'answer' => $fullContent,
  5914. 'reasoning' => $fullReasoningContent,
  5915. 'usage' => $usage
  5916. ];
  5917. }
  5918. public function chat($data) {
  5919. $uid = Site::getUid();
  5920. // 积分余额预检(不足直接报错)
  5921. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  5922. $anime_id = getProp($data, 'anime_id');
  5923. $file = getProp($data, 'file');
  5924. $content = getProp($data, 'content', '');
  5925. $bid = getProp($data, 'bid', 0);
  5926. $script_id = getProp($data, 'script_id', 0);
  5927. $episode_number = getProp($data, 'episode_number', 1);
  5928. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5929. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5930. if (!$anime) Utils::throwError('20003:该对话不存在!');
  5931. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  5932. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  5933. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  5934. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  5935. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  5936. $roles = is_array($roles) ? $roles : [];
  5937. $scenes = is_array($scenes) ? $scenes : [];
  5938. // 获取最后一集序号
  5939. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  5940. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  5941. // 转换主体列表和场景列表的格式
  5942. // 获取参考主体或场景
  5943. if ((int)$episode_number === 1) {
  5944. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  5945. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  5946. }else {
  5947. $prev_episode_number = $episode_number - 1;
  5948. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  5949. }
  5950. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  5951. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  5952. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  5953. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  5954. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5955. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5956. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5957. 中年女:邻居阿姨
  5958. 老年男:幽默大爷
  5959. 老年女:婆婆
  5960. 萌娃:奶气萌娃";
  5961. if ($roles_content) {
  5962. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  5963. 主体范围:\n {$roles_content}\n
  5964. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  5965. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5966. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  5967. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5968. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  5969. }else {
  5970. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5971. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5972. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  5973. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5974. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  5975. }
  5976. if ($scenes_content) {
  5977. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  5978. 场景范围:\n {$scenes_content}\n
  5979. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  5980. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5981. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5982. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  5983. }else {
  5984. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5985. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5986. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5987. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  5988. }
  5989. // 提取文件内容
  5990. if ($file) {
  5991. $uploaded_content = $this->extractFileContent($file);
  5992. if (!$uploaded_content) {
  5993. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5994. }
  5995. } elseif ($script_id) {
  5996. $uploaded_content = $this->getContentByScriptId($script_id);
  5997. if (!$uploaded_content) {
  5998. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5999. }
  6000. } elseif ($bid) {
  6001. $uploaded_content = $this->getContentByBid($bid);
  6002. if (!$uploaded_content) {
  6003. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6004. }
  6005. } elseif ($content) {
  6006. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  6007. }
  6008. // elseif ($prompt) {
  6009. // $uploaded_content = filterContent($prompt);
  6010. // }
  6011. else {
  6012. $uploaded_content = '';
  6013. }
  6014. $input_art_style = getProp($anime, 'art_style');
  6015. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6016. // 美术风格
  6017. if (!$mappedArtStyle) {
  6018. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6019. }else {
  6020. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6021. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6022. }else {
  6023. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6024. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6025. }
  6026. }
  6027. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6028. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6029. // 强制要求:
  6030. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6031. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6032. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6033. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  6034. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  6035. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  6036. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  6037. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  6038. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  6039. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  6040. // - 分镜要和场景列表、人物主体保持一致\n
  6041. // 普通要求:
  6042. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6043. // {$role_demo}
  6044. // {$scene_demo}
  6045. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6046. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6047. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6048. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  6049. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6050. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6051. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6052. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6053. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6054. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6055. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6056. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6057. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6058. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6059. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6060. // 5.$mappedArtStyle_prompt\n\n
  6061. // 示例格式:\n
  6062. // 第1集:隐形的守护者
  6063. // ###故事梗概
  6064. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6065. // ###美术风格
  6066. // 基础画风风格词:韩漫二次元
  6067. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6068. // ###主体列表
  6069. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6070. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6071. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6072. // ###场景列表
  6073. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6074. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6075. // 无人物。}
  6076. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6077. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6078. // 无人物。}
  6079. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6080. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6081. // 无人物。}
  6082. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6083. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6084. // 无人物。}
  6085. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6086. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6087. // 无人物。}
  6088. // ###分镜剧本
  6089. // ##第1幕:徐家老旧厨房 白天 室内
  6090. // 分镜1
  6091. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6092. // 场景:徐家老旧厨房
  6093. // 构图设计:全景,低角度仰视
  6094. // 运镜调度:手持拍摄
  6095. // 配音角色:旁白
  6096. // 出镜角色:许芸-校服装、徐母
  6097. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6098. // 画面类型:普通画面
  6099. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6100. // 分镜2
  6101. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6102. // 场景:徐家老旧厨房
  6103. // 构图设计:近景,徐母面部特写
  6104. // 运镜调度:固定镜头
  6105. // 配音角色:徐母
  6106. // 出镜角色:徐母
  6107. // 台词内容:问我夜不归宿死哪儿去了。
  6108. // 画面类型:对口型
  6109. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6110. // ##第2幕:徐家简陋客厅 黄昏 室内
  6111. // 分镜3
  6112. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6113. // 场景:徐家简陋客厅
  6114. // 构图设计:全景,景深虚化
  6115. // 运镜调度:固定镜头
  6116. // 配音角色:旁白
  6117. // 出镜角色:无
  6118. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6119. // 画面类型:普通画面
  6120. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6121. // 分镜4
  6122. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6123. // 场景:徐家简陋客厅
  6124. // 构图设计:特写,火车票
  6125. // 运镜调度:固定镜头
  6126. // 配音角色:旁白
  6127. // 出镜角色:无
  6128. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6129. // 画面类型:普通画面
  6130. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6131. // \n\n";
  6132. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  6133. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  6134. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  6135. 普通要求:
  6136. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6137. {$role_demo}
  6138. {$scene_demo}
  6139. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6140. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6141. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6142. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6143. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6144. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6145. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6146. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6147. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6148. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6149. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6150. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6151. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6152. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6153. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6154. 5.$mappedArtStyle_prompt
  6155. 6.《情绪-视听语言映射表》:
  6156. 6.1 场景空间与时间心理学 (Scene & Temporality)
  6157. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6158. -----|---------|------------|----------------
  6159. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  6160. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  6161. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  6162. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  6163. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  6164. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6165. -----|---------|------------|----------------
  6166. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  6167. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  6168. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  6169. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  6170. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  6171. --------|---------|--------------|-------------
  6172. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  6173. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  6174. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  6175. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  6176. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  6177. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  6178. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  6179. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  6180. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  6181. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  6182. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  6183. -----|---------|------------|------------
  6184. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  6185. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  6186. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  6187. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  6188. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  6189. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  6190. --------|---------|--------------|----------
  6191. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  6192. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  6193. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  6194. 6.6 声音设计与潜意识影响 (Soundscape)
  6195. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  6196. -----|---------|------------|------------------
  6197. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  6198. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  6199. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  6200. 理论基石:
  6201. - The Five C's of Cinematography by Joseph V. Mascelli
  6202. - Film Art: An Introduction by David Bordwell
  6203. - Sight, Sound, Motion by Herbert Zettl
  6204. - Notes on the Cinematograph by Robert Bresson
  6205. \n\n
  6206. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  6207. 示例格式:\n
  6208. 第1集:隐形的守护者
  6209. ###故事梗概
  6210. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6211. ###美术风格
  6212. 基础画风风格词:韩漫二次元
  6213. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6214. ###主体列表
  6215. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6216. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6217. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6218. ###场景列表
  6219. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6220. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6221. 无人物。}
  6222. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6223. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6224. 无人物。}
  6225. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6226. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6227. 无人物。}
  6228. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6229. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6230. 无人物。}
  6231. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6232. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6233. 无人物。}
  6234. ###分镜剧本
  6235. ##第1幕:徐家老旧厨房 白天 室内
  6236. 分镜1
  6237. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6238. 场景:徐家老旧厨房
  6239. 构图设计:全景,低角度仰视
  6240. 运镜调度:手持拍摄
  6241. 配音角色:旁白
  6242. 出镜角色:许芸-校服装、徐母
  6243. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6244. 画面类型:普通画面
  6245. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6246. 分镜2
  6247. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6248. 场景:徐家老旧厨房
  6249. 构图设计:近景,徐母面部特写
  6250. 运镜调度:固定镜头
  6251. 配音角色:徐母
  6252. 出镜角色:徐母
  6253. 台词内容:问我夜不归宿死哪儿去了。
  6254. 画面类型:对口型
  6255. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6256. ##第2幕:徐家简陋客厅 黄昏 室内
  6257. 分镜3
  6258. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6259. 场景:徐家简陋客厅
  6260. 构图设计:全景,景深虚化
  6261. 运镜调度:固定镜头
  6262. 配音角色:旁白
  6263. 出镜角色:无
  6264. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6265. 画面类型:普通画面
  6266. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6267. 分镜4
  6268. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6269. 场景:徐家简陋客厅
  6270. 构图设计:特写,火车票
  6271. 运镜调度:固定镜头
  6272. 配音角色:旁白
  6273. 出镜角色:无
  6274. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6275. 画面类型:普通画面
  6276. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6277. \n\n";
  6278. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6279. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  6280. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  6281. $prompt = $origin_prompt;
  6282. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  6283. // 获取章节内容
  6284. $full_content = getProp($anime, 'content');
  6285. if ($uploaded_content) {
  6286. $full_content = $uploaded_content;
  6287. }
  6288. // 根据章节内容拆分章节
  6289. $chapters = splitContent($full_content);
  6290. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  6291. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  6292. $messages = [];
  6293. if ($prompt == '确认分镜大纲') {
  6294. // 暂时保留
  6295. $content = $chapter_content;
  6296. if ($is_single) $content = $full_content; // 单剧集使用全文
  6297. if (!$content) {
  6298. Utils::throwError('20003:章节内容无法获取,请确认');
  6299. }
  6300. $question = $is_single
  6301. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  6302. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  6303. // 构建消息
  6304. $messages[] =
  6305. [
  6306. 'role' => 'user',
  6307. 'content' => $question
  6308. ];
  6309. }else if ($prompt == '继续策划下一集') {
  6310. if ($is_single) {
  6311. Utils::throwError('20003:单剧集不支持继续策划下一集');
  6312. }
  6313. $content = $chapter_content;
  6314. if (!$content) {
  6315. Utils::throwError('20003:章节内容无法获取,请确认');
  6316. }
  6317. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  6318. // 获取上一集最后记录
  6319. $prev_sequence = $episode_number - 1;
  6320. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  6321. // 构建消息
  6322. $messages[] =
  6323. [
  6324. 'role' => 'user',
  6325. 'content' => $question
  6326. ];
  6327. }else {
  6328. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  6329. if (!$content) {
  6330. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  6331. }
  6332. if (!$content) {
  6333. Utils::throwError('20003:章节内容无法获取,请确认');
  6334. }
  6335. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  6336. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  6337. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  6338. if ($origin_prompt) {
  6339. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  6340. }
  6341. $messages[] =
  6342. [
  6343. 'role' => 'user',
  6344. 'content' => $question
  6345. ];
  6346. }
  6347. // 处理文本模型
  6348. $model = getProp($data, 'model');
  6349. if (!$model) {
  6350. // 用户没有输入,从anime表获取
  6351. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6352. $model = getProp($anime, 'model');
  6353. if (!$model) {
  6354. // anime表也没有,使用默认值
  6355. $model = 'doubao-seed-2-0-mini-260215';
  6356. }
  6357. }
  6358. // 验证模型是否在可用模型表中
  6359. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6360. $model = 'doubao-seed-2-0-mini-260215';
  6361. }
  6362. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6363. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6364. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6365. if ($model === 'deepseek-chat') {
  6366. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6367. $model = 'deepseek-v4-flash';
  6368. $thinkingMode = 'disabled';
  6369. } elseif ($model === 'deepseek-reasoner') {
  6370. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6371. $model = 'deepseek-v4-flash';
  6372. $thinkingMode = 'enabled';
  6373. }
  6374. $post_data = [
  6375. 'model' => $model,
  6376. 'messages' => $messages,
  6377. // 'max_tokens' => 8192,
  6378. 'temperature' => 0.2,
  6379. 'frequency_penalty' => 0,
  6380. 'presence_penalty' => 0,
  6381. 'response_format' => ['type' => 'text'],
  6382. 'thinking' => ['type' => $thinkingMode],
  6383. 'stream' => true // 启用流式输出
  6384. ];
  6385. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6386. // 根据模型类型选择调用方法
  6387. $fullContent = '';
  6388. $fullReasoningContent = '';
  6389. $usage = [];
  6390. try {
  6391. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6392. // DeepSeek 官方模型使用 DeepSeek API
  6393. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6394. } else if (in_array($model, $this->gpt_text_models)) {
  6395. // GPT-5.4 模型使用 TokenRouter API
  6396. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6397. } else if (in_array($model, $this->gemini_text_models)) {
  6398. // Gemini 模型使用 Gemini API
  6399. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6400. } else {
  6401. // 其他模型使用火山引擎API
  6402. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6403. }
  6404. // 验证返回值类型
  6405. if (!is_iterable($streamGenerator)) {
  6406. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6407. dLog('deepseek')->error('chat流式生成器无效', [
  6408. 'generator_type' => $errorType,
  6409. 'model' => $model,
  6410. 'anime_id' => $anime_id,
  6411. 'episode_number' => $episode_number
  6412. ]);
  6413. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  6414. 'type' => $errorType,
  6415. 'model' => $model
  6416. ]);
  6417. yield [
  6418. 'type' => 'error',
  6419. 'episode' => [],
  6420. 'answer' => '',
  6421. 'reasoning' => '',
  6422. 'usage' => [],
  6423. 'error' => '接口返回数据异常,请重新请求'
  6424. ];
  6425. return;
  6426. }
  6427. // 处理流式输出
  6428. foreach ($streamGenerator as $chunk) {
  6429. if (isset($chunk['type'])) {
  6430. if ($chunk['type'] === 'done') {
  6431. // 最终结果
  6432. $fullContent = $chunk['full_content'];
  6433. $fullReasoningContent = $chunk['full_reasoning'];
  6434. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6435. } else {
  6436. // 逐块yield数据
  6437. yield $chunk;
  6438. }
  6439. }
  6440. }
  6441. } catch (\Exception $e) {
  6442. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  6443. 'model' => $model,
  6444. 'anime_id' => $anime_id,
  6445. 'episode_number' => $episode_number,
  6446. 'trace' => $e->getTraceAsString()
  6447. ]);
  6448. logDB('deepseek', 'error', 'chat流式处理失败', [
  6449. 'error' => $e->getMessage(),
  6450. 'model' => $model
  6451. ]);
  6452. yield [
  6453. 'type' => 'error',
  6454. 'episode' => [],
  6455. 'answer' => '',
  6456. 'reasoning' => '',
  6457. 'usage' => [],
  6458. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6459. ];
  6460. return;
  6461. }
  6462. dLog('deepseek')->info('完整内容: '.$fullContent);
  6463. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6464. // 处理完整内容并返回最终结果
  6465. $episode_arr = handleEpisodeContent($fullContent);
  6466. logDB('deepseek', 'info', '解析内容', $episode_arr);
  6467. if (empty($episode_arr['acts'])) {
  6468. // 未生成剧本相关内容,保存对话记录并返回提示
  6469. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  6470. try {
  6471. $now = date('Y-m-d H:i:s');
  6472. // 保存对话记录
  6473. $records = [
  6474. [
  6475. 'uid' => $uid,
  6476. 'anime_id' => $anime_id,
  6477. 'sequence' => $episode_number,
  6478. 'role' => 'user',
  6479. 'content' => $prompt,
  6480. 'created_at' => $now,
  6481. 'updated_at' => $now
  6482. ],
  6483. [
  6484. 'uid' => $uid,
  6485. 'anime_id' => $anime_id,
  6486. 'sequence' => $episode_number,
  6487. 'role' => 'assistant',
  6488. 'content' => $fullContent,
  6489. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6490. 'created_at' => $now,
  6491. 'updated_at' => $now
  6492. ]
  6493. ];
  6494. DB::table('mp_anime_records')->insert($records);
  6495. } catch (\Exception $e) {
  6496. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6497. }
  6498. yield [
  6499. 'type' => 'done',
  6500. 'episode' => [],
  6501. 'answer' => $fullContent,
  6502. 'reasoning' => $fullReasoningContent,
  6503. 'usage' => $usage,
  6504. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  6505. ];
  6506. return;
  6507. }
  6508. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  6509. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  6510. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  6511. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  6512. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  6513. $existing_props = is_array($existing_props) ? $existing_props : [];
  6514. $now = date('Y-m-d H:i:s');
  6515. try {
  6516. DB::beginTransaction();
  6517. $saveResult = $this->saveEpisodeVersionData(
  6518. $anime_id,
  6519. $episode_number,
  6520. $episode_arr,
  6521. $existing_roles,
  6522. $existing_scenes,
  6523. $existing_props,
  6524. $current_episode,
  6525. $base_episode,
  6526. $is_regenerate_version,
  6527. $content,
  6528. $now
  6529. );
  6530. $episode = $saveResult['episode'];
  6531. $episode_id = $saveResult['episode_id'];
  6532. $merged_roles = $saveResult['merged_roles'];
  6533. $merged_scenes = $saveResult['merged_scenes'];
  6534. $merged_props = $saveResult['merged_props'];
  6535. $record_content = $origin_prompt;
  6536. if ($uploaded_content !== '') {
  6537. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  6538. }
  6539. $records = [
  6540. [
  6541. 'uid' => $uid,
  6542. 'anime_id' => $anime_id,
  6543. 'role' => 'user',
  6544. 'content' => $record_content,
  6545. 'sequence' => $episode_number,
  6546. 'episode_id' => $episode_id,
  6547. 'created_at' => $now,
  6548. 'updated_at' => $now
  6549. ],
  6550. [
  6551. 'uid' => $uid,
  6552. 'anime_id' => $anime_id,
  6553. 'role' => 'assistant',
  6554. 'content' => $fullContent,
  6555. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6556. 'sequence' => $episode_number,
  6557. 'episode_id' => $episode_id,
  6558. 'created_at' => $now,
  6559. 'updated_at' => $now
  6560. ]
  6561. ];
  6562. $boolen4 = DB::table('mp_anime_records')->insert($records);
  6563. if (!$boolen4) {
  6564. Utils::throwError('20003:对话记录保存失败');
  6565. }
  6566. // 保存模型和内容到anime表
  6567. $update_anime_data = [
  6568. 'model' => $model,
  6569. 'updated_at' => $now
  6570. ];
  6571. if ($uploaded_content) {
  6572. $update_anime_data['content'] = $uploaded_content;
  6573. }
  6574. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  6575. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6576. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6577. 'anime_id' => $anime_id,
  6578. 'episode_number' => $episode_number,
  6579. 'model' => $model,
  6580. ]);
  6581. }catch (\Exception $e) {
  6582. DB::rollBack();
  6583. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6584. yield [
  6585. 'type' => 'done',
  6586. 'answer' => $fullContent,
  6587. 'reasoning' => $fullReasoningContent,
  6588. 'usage' => $usage,
  6589. 'error' => $e->getMessage(),
  6590. ];
  6591. return;
  6592. }
  6593. DB::commit();
  6594. if ($is_global_generate_pics) {
  6595. // // 批量生成全局角色图片
  6596. // $this->batchSetGlobalRoleImg([
  6597. // 'anime_id' => $anime_id,
  6598. // ], true);
  6599. // // 批量生成全局场景图片
  6600. // $this->batchSetGlobalSceneImg([
  6601. // 'anime_id' => $anime_id,
  6602. // ], true);
  6603. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6604. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6605. }
  6606. $episode['episode_id'] = $episode_id;
  6607. $episode['roles'] = $merged_roles;
  6608. $episode['scenes'] = $merged_scenes;
  6609. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  6610. yield [
  6611. 'type' => 'done',
  6612. 'episode' => $episode,
  6613. 'answer' => $fullContent,
  6614. 'reasoning' => $fullReasoningContent,
  6615. 'usage' => $usage
  6616. ];
  6617. }
  6618. public function addChatForAce($data) {
  6619. $uid = Site::getUid();
  6620. $anime_id = getProp($data, 'anime_id');
  6621. if (!$anime_id) Utils::throwError('20003:请选择对话');
  6622. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  6623. if (!$anime) Utils::throwError('20003:对话不存在');
  6624. $file = getProp($data, 'file');
  6625. $content = getProp($data, 'content', '');
  6626. $bid = getProp($data, 'bid', 0);
  6627. $script_id = getProp($data, 'script_id', 0);
  6628. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  6629. $prompt = getProp($data, 'prompt');
  6630. $is_multi = getProp($anime, 'is_multi');
  6631. $is_single = (int)$is_multi !== 1;
  6632. // 积分余额预检(仅单剧集模式收费)
  6633. if ($is_single) {
  6634. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  6635. }
  6636. $extra_products = getProp($data, 'products', []);
  6637. if (!$extra_products) {
  6638. $extra_products = getProp($anime, 'extra_products');
  6639. if ($extra_products) {
  6640. $extra_products = json_decode($extra_products, true);
  6641. }else {
  6642. $extra_products = [];
  6643. }
  6644. }else {
  6645. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6646. }
  6647. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6648. $anime_script_id = getProp($anime, 'script_id');
  6649. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  6650. $cpid = Site::getCpid();
  6651. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6652. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6653. ->where('mapping.script_id', $anime_script_id)
  6654. ->where('product.cpid', $cpid)
  6655. ->where('product.is_deleted', 0);
  6656. $mappings = $script_products_mappings->select(
  6657. 'mapping.product_id',
  6658. 'mapping.episode_number',
  6659. 'product.product_name',
  6660. 'product.type',
  6661. 'product.product',
  6662. 'product.pic_prompt',
  6663. 'product.url',
  6664. 'product.pic_task_id',
  6665. 'product.pic_task_status',
  6666. 'product.three_view_image_url'
  6667. )
  6668. ->get();
  6669. // 按 product_id 分组,合并 episode_number
  6670. $productMap = [];
  6671. foreach ($mappings as $item) {
  6672. $product_id = $item->product_id;
  6673. $product_name = $item->product_name;
  6674. // 处理product_name两边的符号
  6675. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6676. if (!isset($productMap[$product_id])) {
  6677. $productMap[$product_id] = [
  6678. 'product_id' => $product_id,
  6679. 'product_name' => $product_name,
  6680. 'type' => (int)$item->type,
  6681. 'product' => (int)$item->product,
  6682. 'pic_prompt' => $item->pic_prompt,
  6683. 'url' => $item->url,
  6684. 'pic_task_id' => $item->pic_task_id,
  6685. 'pic_task_status' => $item->pic_task_status,
  6686. 'episode_numbers' => [],
  6687. ];
  6688. }
  6689. // 添加 episode_number(去重)
  6690. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6691. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6692. }
  6693. }
  6694. // 将查询到的剧本资产合并到extra_products中
  6695. // 先构建extra_products的索引(以product_id为key,用于去重)
  6696. $extraProductsMap = [];
  6697. foreach ($extra_products as $item) {
  6698. $key = getProp($item, 'product_id');
  6699. if ($key) {
  6700. $extraProductsMap[$key] = $item;
  6701. }
  6702. }
  6703. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6704. foreach ($productMap as $product) {
  6705. $product_id = $product['product_id'];
  6706. // 如果不存在则添加(不带episode_number信息)
  6707. if (!isset($extraProductsMap[$product_id])) {
  6708. $extraProductsMap[$product_id] = [
  6709. 'product_id' => $product['product_id'],
  6710. 'product_name' => $product['product_name'],
  6711. 'type' => $product['type'],
  6712. 'product' => $product['product'],
  6713. 'pic_prompt' => $product['pic_prompt'],
  6714. 'url' => $product['url'],
  6715. 'pic_task_id' => $product['pic_task_id'],
  6716. 'pic_task_status' => $product['pic_task_status'],
  6717. ];
  6718. }
  6719. }
  6720. // 重新赋值给extra_products
  6721. $extra_products = array_values($extraProductsMap);
  6722. }
  6723. $user_anime_name = getProp($anime, 'anime_name');
  6724. // 处理提示词
  6725. if ($prompt && $extra_products) {
  6726. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6727. foreach($extra_products as $item) {
  6728. $product_name = getProp($item, 'product_name');
  6729. if ($product_name) {
  6730. // 替换 {product_name} 为 product_name
  6731. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6732. }
  6733. }
  6734. }
  6735. // 处理文本模型
  6736. $model = getProp($data, 'model');
  6737. if (!$model) {
  6738. // 用户没有输入,从anime表获取
  6739. $model = getProp($anime, 'model');
  6740. if (!$model) {
  6741. // anime表也没有,使用默认值
  6742. $model = 'deepseek-v4-pro';
  6743. }
  6744. }
  6745. // 验证模型是否在可用模型表中
  6746. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6747. $model = 'deepseek-v4-pro';
  6748. }
  6749. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6750. if ($prompt) {
  6751. $question .= "本次修改要求如下:\n{$prompt}";
  6752. }
  6753. // if (!$file && !$content && !$bid) {
  6754. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  6755. // }
  6756. // 提取文件内容
  6757. if ($file) {
  6758. $content = $this->extractFileContent($file);
  6759. if (!$content) {
  6760. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6761. }
  6762. } elseif ($script_id) {
  6763. $content = $this->getContentByScriptId($script_id);
  6764. if (!$content) {
  6765. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6766. }
  6767. } elseif ($bid) {
  6768. $content = $this->getContentByBid($bid);
  6769. if (!$content) {
  6770. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6771. }
  6772. } elseif ($content) {
  6773. $content = filterContent($content);
  6774. } else {
  6775. $content = getProp($anime, 'content');
  6776. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6777. $need_generate_content = true;
  6778. }
  6779. }
  6780. // 美术风格
  6781. $input_art_style = getProp($data, 'art_style');
  6782. if (!$input_art_style) {
  6783. $mappedArtStyle = getProp($anime, 'art_style');
  6784. }else {
  6785. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6786. }
  6787. // 判断是否需要生成原文内容
  6788. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6789. // 如果需要生成原文内容,添加额外的要求
  6790. $content_generation_requirement = $need_generate_content
  6791. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6792. : "";
  6793. // 美术风格
  6794. if (!$mappedArtStyle) {
  6795. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6796. }else {
  6797. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6798. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6799. }else {
  6800. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6801. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6802. }
  6803. }
  6804. // 构建主体、场景和道具提示词
  6805. $extra_role_prompt = "\n";
  6806. $extra_scene_prompt = "\n";
  6807. $extra_prop_prompt = "\n";
  6808. $ref_products = []; // 参考资产
  6809. if ($extra_products) {
  6810. foreach($extra_products as $item) {
  6811. $product = getProp($item, 'product');
  6812. $product_name = getProp($item, 'product_name');
  6813. if ($product_name == '旁白') continue;
  6814. $ref_products[$product_name] = $item;
  6815. $pic_prompt = getProp($item, 'pic_prompt');
  6816. if ((int)$product === 1) {
  6817. // 拼接角色信息
  6818. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6819. } elseif ((int)$product === 2) {
  6820. // 拼接场景信息
  6821. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6822. } elseif ((int)$product === 3) {
  6823. // 拼接道具信息
  6824. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6825. }
  6826. }
  6827. // 优化提示词,融入剧本
  6828. if (!empty(trim($extra_role_prompt))) {
  6829. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6830. }
  6831. if (!empty(trim($extra_scene_prompt))) {
  6832. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6833. }
  6834. if (!empty(trim($extra_prop_prompt))) {
  6835. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6836. }
  6837. }
  6838. if ($anime_script_id && $is_single) {
  6839. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6840. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6841. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6842. }else {
  6843. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6844. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6845. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6846. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6847. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6848. {$extra_role_prompt}";
  6849. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6850. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6851. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6852. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6853. {$extra_scene_prompt}";
  6854. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6855. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6856. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6857. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6858. {$extra_prop_prompt}";
  6859. }
  6860. $systemPrompt = $is_single
  6861. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6862. 强制要求:
  6863. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6864. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6865. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6866. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6867. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6868. 普通要求:
  6869. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6870. $role_demo
  6871. $scene_demo
  6872. $prop_demo
  6873. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6874. 5.1片段分割逻辑(优先级从高到低):
  6875. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6876. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6877. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6878. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6879. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6880. - 片段数量格式为: 片段数量:8
  6881. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6882. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6883. 5.3分镜结构:每个分镜包含以下字段:
  6884. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6885. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6886. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6887. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6888. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6889. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6890. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6891. - 运镜:场景+画面描述+运镜
  6892. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6893. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6894. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6895. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6896. 6.{$mappedArtStyle_prompt}\n\n
  6897. 示例如下:\n
  6898. ###剧本名:西昆仑
  6899. ###故事梗概
  6900. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6901. ###剧本亮点
  6902. 亮点1:绝境奇药,生死一线
  6903. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6904. 亮点2:结拜兄妹,化解尴尬
  6905. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6906. 亮点3:纤发夺命,情愫暗涌
  6907. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6908. ###人物关系
  6909. 阿雪与梁萧之间存在兄妹之情。
  6910. ###核心矛盾
  6911. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6912. ###主体列表
  6913. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6914. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6915. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6916. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6917. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6918. 全景,正面拍摄,青年女性,亚洲人。
  6919. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6920. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6921. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6922. ###美术风格
  6923. 基础画风风格词:厚涂古风
  6924. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6925. ###场景列表
  6926. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6927. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6928. 无人物。}
  6929. ###分段剧本
  6930. 片段数量:8
  6931. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6932. ##片段1
  6933. 时长:12s
  6934. 分镜1
  6935. 出场角色:刀疤脸
  6936. 场景:边境小镇街道
  6937. 出场道具:酒杯-高脚杯
  6938. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6939. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6940. 配音台词:
  6941. 背景音效:
  6942. 分镜2
  6943. 出场角色:刀疤脸
  6944. 场景:悦来酒馆
  6945. 出场道具:酒杯-高脚杯
  6946. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6947. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6948. 配音台词:
  6949. 背景音效:
  6950. 分镜3
  6951. 出场角色:刀疤脸
  6952. 场景:悦来酒馆
  6953. 出场道具:酒杯-高脚杯
  6954. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6955. 运镜:从中景推向令牌特写。
  6956. 配音台词:
  6957. 背景音效:
  6958. 分镜4
  6959. 出场角色:刀疤脸
  6960. 场景:悦来酒馆
  6961. 出场道具:酒杯-高脚杯
  6962. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6963. 运镜:极速推向酒水溅起的瞬间。
  6964. 配音台词:
  6965. 背景音效:
  6966. 分镜5
  6967. 出场角色:刀疤脸
  6968. 场景:悦来酒馆
  6969. 出场道具:酒杯-高脚杯
  6970. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6971. 运镜:固定机位,利用倾斜构图制造压迫感。
  6972. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6973. 背景音效:
  6974. \n\n"
  6975. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6976. 强制要求:\n
  6977. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6978. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6979. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6980. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6981. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6982. 普通要求:\n
  6983. 1.剧本名(必须生成)必须与文档内容高度相关
  6984. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6985. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6986. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6987. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6988. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6989. {$extra_role_prompt}
  6990. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6991. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6992. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6993. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6994. {$extra_scene_prompt}
  6995. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6996. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6997. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6998. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6999. {$extra_prop_prompt}
  7000. 5.{$mappedArtStyle_prompt}\n\n
  7001. 示例如下:\n
  7002. ###剧本名:西昆仑
  7003. ###故事梗概
  7004. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7005. ###剧本亮点
  7006. 亮点1:绝境奇药,生死一线
  7007. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7008. 亮点2:结拜兄妹,化解尴尬
  7009. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7010. 亮点3:纤发夺命,情愫暗涌
  7011. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7012. ###人物关系
  7013. 阿雪与梁萧之间存在兄妹之情。
  7014. ###核心矛盾
  7015. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7016. ###主体列表
  7017. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7018. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7019. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7020. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7021. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7022. 全景,正面拍摄,青年女性,亚洲人。
  7023. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7024. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7025. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7026. ###美术风格
  7027. 基础画风风格词:厚涂古风
  7028. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7029. ###场景列表
  7030. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7031. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7032. 无人物。}
  7033. ###道具列表
  7034. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  7035. // 构建消息
  7036. $messages = [
  7037. [
  7038. 'role' => 'system',
  7039. 'content' => $systemPrompt
  7040. ],
  7041. [
  7042. 'role' => 'user',
  7043. 'content' => "以下是文档内容:
  7044. {$content}
  7045. 用户问题:
  7046. {$question}"
  7047. ]
  7048. ];
  7049. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7050. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7051. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7052. if ($model === 'deepseek-chat') {
  7053. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7054. $model = 'deepseek-v4-flash';
  7055. $thinkingMode = 'disabled';
  7056. } elseif ($model === 'deepseek-reasoner') {
  7057. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7058. $model = 'deepseek-v4-flash';
  7059. $thinkingMode = 'enabled';
  7060. }
  7061. $post_data = [
  7062. 'model' => $model,
  7063. 'messages' => $messages,
  7064. // 'max_tokens' => 8192,
  7065. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7066. 'frequency_penalty' => 0,
  7067. 'presence_penalty' => 0,
  7068. 'response_format' => ['type' => 'text'],
  7069. 'thinking' => ['type'=>$thinkingMode],
  7070. 'stream' => true // 启用流式输出
  7071. ];
  7072. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7073. // 根据模型类型选择调用方法
  7074. $fullContent = '';
  7075. $fullReasoningContent = '';
  7076. $usage = [];
  7077. try {
  7078. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7079. // DeepSeek 官方模型使用 DeepSeek API
  7080. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7081. } else if (in_array($model, $this->gpt_text_models)) {
  7082. // GPT-5.4 模型使用 TokenRouter API
  7083. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7084. } else if (in_array($model, $this->gemini_text_models)) {
  7085. // Gemini 模型使用 Gemini API
  7086. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  7087. } else {
  7088. // 其他模型使用火山引擎API
  7089. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7090. }
  7091. // 验证返回值类型
  7092. if (!is_iterable($streamGenerator)) {
  7093. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7094. dLog('deepseek')->error('addChat流式生成器无效', [
  7095. 'generator_type' => $errorType,
  7096. 'model' => $model,
  7097. 'anime_id' => $anime_id
  7098. ]);
  7099. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  7100. 'type' => $errorType,
  7101. 'model' => $model
  7102. ]);
  7103. yield [
  7104. 'type' => 'error',
  7105. 'script' => [],
  7106. 'episode' => [],
  7107. 'answer' => '',
  7108. 'reasoning' => '',
  7109. 'usage' => [],
  7110. 'error' => '接口返回数据异常,请重新请求'
  7111. ];
  7112. return;
  7113. }
  7114. // 处理流式输出
  7115. foreach ($streamGenerator as $chunk) {
  7116. if (isset($chunk['type'])) {
  7117. if ($chunk['type'] === 'done') {
  7118. // 最终结果
  7119. $fullContent = $chunk['full_content'];
  7120. $fullReasoningContent = $chunk['full_reasoning'];
  7121. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7122. } else {
  7123. // 逐块yield数据
  7124. yield $chunk;
  7125. }
  7126. }
  7127. }
  7128. } catch (\Exception $e) {
  7129. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  7130. 'model' => $model,
  7131. 'anime_id' => $anime_id,
  7132. 'trace' => $e->getTraceAsString()
  7133. ]);
  7134. logDB('deepseek', 'error', 'addChat流式处理失败', [
  7135. 'error' => $e->getMessage(),
  7136. 'model' => $model
  7137. ]);
  7138. yield [
  7139. 'type' => 'error',
  7140. 'script' => [],
  7141. 'episode' => [],
  7142. 'answer' => '',
  7143. 'reasoning' => '',
  7144. 'usage' => [],
  7145. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7146. ];
  7147. return;
  7148. }
  7149. dLog('deepseek')->info('完整内容: '.$fullContent);
  7150. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7151. // 处理完整内容并返回最终结果
  7152. $script_arr = [];
  7153. if ($fullContent) {
  7154. $script_arr = handleScriptContentForAce($fullContent);
  7155. dLog('deepseek')->info('解析内容', $script_arr);
  7156. logDB('deepseek', 'info', '解析内容', $script_arr);
  7157. }
  7158. if (empty($script_arr['roles'])) {
  7159. // 未生成剧本相关内容,保存对话记录并返回提示
  7160. dLog('deepseek')->info('未生成剧本相关的内容');
  7161. try {
  7162. DB::beginTransaction();
  7163. $now = date('Y-m-d H:i:s');
  7164. // 保存对话记录
  7165. $records = [
  7166. [
  7167. 'uid' => $uid,
  7168. 'anime_id' => $anime_id,
  7169. 'sequence' => 0,
  7170. 'role' => 'user',
  7171. 'content' => $prompt,
  7172. 'created_at' => $now,
  7173. 'updated_at' => $now
  7174. ],
  7175. [
  7176. 'uid' => $uid,
  7177. 'anime_id' => $anime_id,
  7178. 'sequence' => 0,
  7179. 'role' => 'assistant',
  7180. // 'content' => $fullContent,
  7181. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  7182. 'created_at' => $now,
  7183. 'updated_at' => $now
  7184. ]
  7185. ];
  7186. DB::table('mp_anime_records')->insert($records);
  7187. DB::commit();
  7188. } catch (\Exception $e) {
  7189. DB::rollBack();
  7190. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7191. }
  7192. yield [
  7193. 'type' => 'done',
  7194. 'script' => [],
  7195. 'episode' => [],
  7196. 'answer' => $fullContent,
  7197. 'reasoning' => $fullReasoningContent,
  7198. 'usage' => $usage,
  7199. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7200. ];
  7201. return;
  7202. }
  7203. // 如果需要生成原文内容,从script_arr中提取
  7204. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7205. $content = $script_arr['content'];
  7206. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  7207. if (!$content) {
  7208. yield [
  7209. 'type' => 'done',
  7210. 'script' => [],
  7211. 'episode' => [],
  7212. 'answer' => $fullContent,
  7213. 'reasoning' => $fullReasoningContent,
  7214. 'usage' => $usage,
  7215. 'error' => '未生成剧本内容,请调整提示词再试'
  7216. ];
  7217. return;
  7218. }
  7219. }
  7220. // 替换美术风格
  7221. if ($mappedArtStyle !== '') {
  7222. $script_arr['art_style'] = $mappedArtStyle;
  7223. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7224. }
  7225. // 新建动漫
  7226. if ($user_anime_name == '新剧本策划') {
  7227. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7228. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7229. // if (!$anime_name) {
  7230. // // 未识别到剧本名,保存对话记录并返回提示
  7231. // dLog('deepseek')->info('未能识别到剧本名称');
  7232. // try {
  7233. // DB::beginTransaction();
  7234. // $now = date('Y-m-d H:i:s');
  7235. // // 保存对话记录
  7236. // $records = [
  7237. // [
  7238. // 'uid' => $uid,
  7239. // 'anime_id' => $anime_id,
  7240. // 'sequence' => 0,
  7241. // 'role' => 'user',
  7242. // 'content' => $prompt,
  7243. // 'created_at' => $now,
  7244. // 'updated_at' => $now
  7245. // ],
  7246. // [
  7247. // 'uid' => $uid,
  7248. // 'anime_id' => $anime_id,
  7249. // 'sequence' => 0,
  7250. // 'role' => 'assistant',
  7251. // 'content' => '未能生成剧本名称,请重试',
  7252. // 'created_at' => $now,
  7253. // 'updated_at' => $now
  7254. // ]
  7255. // ];
  7256. // DB::table('mp_anime_records')->insert($records);
  7257. // DB::commit();
  7258. // } catch (\Exception $e) {
  7259. // DB::rollBack();
  7260. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7261. // }
  7262. // yield [
  7263. // 'type' => 'done',
  7264. // 'script' => [],
  7265. // 'episode' => [],
  7266. // 'answer' => $fullContent,
  7267. // 'reasoning' => $fullReasoningContent,
  7268. // 'usage' => $usage,
  7269. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  7270. // ];
  7271. // return;
  7272. // }
  7273. // 确认对话名称唯一性
  7274. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7275. $anime_name = $anime_name . '_' . date('YmdHis');
  7276. }
  7277. }else {
  7278. $anime_name = $user_anime_name;
  7279. }
  7280. $table_data = [
  7281. 'user_id' => $uid,
  7282. 'anime_name' => $anime_name,
  7283. 'model' => $model,
  7284. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7285. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7286. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7287. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7288. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7289. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7290. 'art_style_type' => $input_art_style,
  7291. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7292. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7293. 'status' => '解析完成',
  7294. 'content' => $content,
  7295. 'is_multi' => $is_multi,
  7296. 'ace_mode' => $ace_mode,
  7297. 'generate_status' => '待执行',
  7298. 'updated_at' => date('Y-m-d H:i:s')
  7299. ];
  7300. if ($table_data['content']) {
  7301. $chapters = splitContent($table_data['content']);
  7302. $chapter_count = count($chapters);
  7303. if ($chapter_count > 0) {
  7304. $table_data['start_episode_sequence'] = 1;
  7305. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7306. }
  7307. }
  7308. if ($extra_products) {
  7309. $table_data['extra_products'] = json_encode($extra_products, 256);
  7310. }
  7311. // 如果有剧本ID则进行绑定
  7312. if ($script_id) {
  7313. $table_data['script_id'] = $script_id;
  7314. }
  7315. $single_episode = [];
  7316. try {
  7317. DB::beginTransaction();
  7318. $now = date('Y-m-d H:i:s');
  7319. // 更新动漫大纲
  7320. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7321. if (!$boolen) {
  7322. dLog('deepseek')->info('动漫保存失败', $table_data);
  7323. Utils::throwError('20003:动漫保存失败');
  7324. }
  7325. // 保存对话记录
  7326. $records = [
  7327. [
  7328. 'uid' => $uid,
  7329. 'anime_id' => $anime_id,
  7330. 'sequence' => 0,
  7331. 'role' => 'user',
  7332. 'content' => $prompt,
  7333. 'created_at' => date('Y-m-d H:i:s'),
  7334. 'updated_at' => date('Y-m-d H:i:s')
  7335. ],
  7336. [
  7337. 'uid' => $uid,
  7338. 'anime_id' => $anime_id,
  7339. 'sequence' => 0,
  7340. 'role' => 'assistant',
  7341. 'content' => $fullContent,
  7342. 'created_at' => date('Y-m-d H:i:s'),
  7343. 'updated_at' => date('Y-m-d H:i:s')
  7344. ]
  7345. ];
  7346. // 保存对话记录
  7347. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7348. if (!$boolen3) {
  7349. Utils::throwError('20003:对话记录保存失败');
  7350. }
  7351. if ($is_single) {
  7352. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7353. if (empty($episode_arr['acts'])) {
  7354. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7355. }
  7356. $saveResult = $this->saveEpisodeVersionData(
  7357. $anime_id,
  7358. 1,
  7359. $episode_arr,
  7360. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7361. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7362. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7363. null,
  7364. null,
  7365. false,
  7366. $content,
  7367. $now,
  7368. $ref_products
  7369. );
  7370. $single_episode = $saveResult['episode'];
  7371. $episode_id = $saveResult['episode_id'];
  7372. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7373. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7374. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7375. 'props' => json_encode($saveResult['merged_props'], 256),
  7376. 'updated_at' => $now
  7377. ]);
  7378. if ($boolen5 === false) {
  7379. Utils::throwError('20003:单剧集主表资源同步失败');
  7380. }
  7381. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7382. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7383. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7384. $episode_record_content = '确认分镜大纲';
  7385. if ($content !== '') {
  7386. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7387. }
  7388. $episode_records = [
  7389. [
  7390. 'uid' => $uid,
  7391. 'anime_id' => $anime_id,
  7392. 'role' => 'user',
  7393. 'content' => $episode_record_content,
  7394. 'sequence' => 1,
  7395. 'episode_id' => $episode_id,
  7396. 'created_at' => $now,
  7397. 'updated_at' => $now
  7398. ],
  7399. [
  7400. 'uid' => $uid,
  7401. 'anime_id' => $anime_id,
  7402. 'role' => 'assistant',
  7403. 'content' => $fullContent,
  7404. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7405. 'sequence' => 1,
  7406. 'episode_id' => $episode_id,
  7407. 'created_at' => $now,
  7408. 'updated_at' => $now
  7409. ]
  7410. ];
  7411. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7412. if (!$boolen4) {
  7413. Utils::throwError('20003:单剧集分镜记录保存失败');
  7414. }
  7415. }
  7416. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7417. if ($is_single && !empty($single_episode)) {
  7418. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7419. 'anime_id' => $anime_id,
  7420. 'episode_id' => $episode_id ?? 0,
  7421. ]);
  7422. }
  7423. }catch (\Exception $e) {
  7424. DB::rollBack();
  7425. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7426. yield [
  7427. 'type' => 'done',
  7428. 'answer' => $fullContent,
  7429. 'reasoning' => $fullReasoningContent,
  7430. 'usage' => $usage,
  7431. 'error' => $e->getMessage(),
  7432. ];
  7433. return;
  7434. }
  7435. DB::commit();
  7436. dLog('deepseek')->info('保存完毕');
  7437. if ($is_single && !empty($single_episode)) {
  7438. // $this->batchSetGlobalRoleImg([
  7439. // 'anime_id' => $anime_id,
  7440. // ]);
  7441. // $this->batchSetGlobalSceneImg([
  7442. // 'anime_id' => $anime_id,
  7443. // ]);
  7444. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7445. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7446. }
  7447. $table_data['anime_id'] = $anime_id;
  7448. $table_data['roles'] = json_decode($table_data['roles'], true);
  7449. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7450. // $table_data['episodes'] = $script_arr['episodes'];
  7451. unset($table_data['created_at']);
  7452. unset($table_data['updated_at']);
  7453. unset($table_data['status']);
  7454. dLog('deepseek')->info('开始返回');
  7455. yield [
  7456. 'type' => 'done',
  7457. 'script' => $table_data,
  7458. 'episode' => $single_episode,
  7459. 'answer' => $fullContent,
  7460. 'reasoning' => $fullReasoningContent,
  7461. 'usage' => $usage
  7462. ];
  7463. }
  7464. public function reGenerateAnimeForAce($data) {
  7465. $uid = Site::getUid();
  7466. $file = getProp($data, 'file');
  7467. $content = getProp($data, 'content', '');
  7468. $bid = getProp($data, 'bid', 0);
  7469. $script_id = getProp($data, 'script_id', 0);
  7470. $anime_id = getProp($data, 'anime_id');
  7471. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7472. if (!$anime) {
  7473. Utils::throwError('20003:该对话不存在');
  7474. }
  7475. $is_multi = getProp($anime, 'is_multi', 1);
  7476. $is_single = (int)$is_multi !== 1;
  7477. // 积分余额预检(仅单剧集模式收费)
  7478. if ($is_single) {
  7479. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  7480. }
  7481. $extra_products = getProp($data, 'products', []);
  7482. if (!$extra_products) {
  7483. $extra_products = getProp($anime, 'extra_products');
  7484. if ($extra_products) {
  7485. $extra_products = json_decode($extra_products, true);
  7486. }else {
  7487. $extra_products = [];
  7488. }
  7489. }else {
  7490. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7491. }
  7492. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7493. $anime_script_id = getProp($anime, 'script_id');
  7494. if ($anime_script_id && $is_single) {
  7495. $cpid = Site::getCpid();
  7496. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7497. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7498. ->where('mapping.script_id', $anime_script_id)
  7499. ->where('product.cpid', $cpid)
  7500. ->where('product.is_deleted', 0);
  7501. $mappings = $script_products_mappings->select(
  7502. 'mapping.product_id',
  7503. 'mapping.episode_number',
  7504. 'product.product_name',
  7505. 'product.type',
  7506. 'product.product',
  7507. 'product.pic_prompt',
  7508. 'product.url',
  7509. 'product.pic_task_id',
  7510. 'product.pic_task_status',
  7511. 'product.three_view_image_url'
  7512. )
  7513. ->get();
  7514. // 按 product_id 分组,合并 episode_number
  7515. $productMap = [];
  7516. foreach ($mappings as $item) {
  7517. $product_id = $item->product_id;
  7518. $product_name = $item->product_name;
  7519. // 处理product_name两边的符号
  7520. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7521. if (!isset($productMap[$product_id])) {
  7522. $productMap[$product_id] = [
  7523. 'product_id' => $product_id,
  7524. 'product_name' => $product_name,
  7525. 'type' => (int)$item->type,
  7526. 'product' => (int)$item->product,
  7527. 'pic_prompt' => $item->pic_prompt,
  7528. 'url' => $item->url,
  7529. 'pic_task_id' => $item->pic_task_id,
  7530. 'pic_task_status' => $item->pic_task_status,
  7531. 'episode_numbers' => [],
  7532. ];
  7533. }
  7534. // 添加 episode_number(去重)
  7535. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7536. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7537. }
  7538. }
  7539. // 将查询到的剧本资产合并到extra_products中
  7540. // 先构建extra_products的索引(以product_id为key,用于去重)
  7541. $extraProductsMap = [];
  7542. foreach ($extra_products as $item) {
  7543. $key = getProp($item, 'product_id');
  7544. if ($key) {
  7545. $extraProductsMap[$key] = $item;
  7546. }
  7547. }
  7548. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7549. foreach ($productMap as $product) {
  7550. $product_id = $product['product_id'];
  7551. // 如果不存在则添加(不带episode_number信息)
  7552. if (!isset($extraProductsMap[$product_id])) {
  7553. $extraProductsMap[$product_id] = [
  7554. 'product_id' => $product['product_id'],
  7555. 'product_name' => $product['product_name'],
  7556. 'type' => $product['type'],
  7557. 'product' => $product['product'],
  7558. 'pic_prompt' => $product['pic_prompt'],
  7559. 'url' => $product['url'],
  7560. 'pic_task_id' => $product['pic_task_id'],
  7561. 'pic_task_status' => $product['pic_task_status'],
  7562. ];
  7563. }
  7564. }
  7565. // 重新赋值给extra_products
  7566. $extra_products = array_values($extraProductsMap);
  7567. }
  7568. $user_anime_name = getProp($anime, 'anime_name');
  7569. $prompt = getProp($data, 'prompt');
  7570. // 处理提示词
  7571. if ($prompt && $extra_products) {
  7572. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7573. foreach($extra_products as $item) {
  7574. $product_name = getProp($item, 'product_name');
  7575. if ($product_name) {
  7576. // 替换 {product_name} 为 product_name
  7577. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7578. }
  7579. }
  7580. }
  7581. // 处理文本模型
  7582. $model = getProp($data, 'model');
  7583. if (!$model) {
  7584. // 用户没有输入,从anime表获取
  7585. $model = getProp($anime, 'model');
  7586. if (!$model) {
  7587. // anime表也没有,使用默认值
  7588. $model = 'deepseek-v4-pro';
  7589. }
  7590. }
  7591. // 验证模型是否在可用模型表中
  7592. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7593. $model = 'deepseek-v4-pro';
  7594. }
  7595. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  7596. if ($is_single) {
  7597. $episode_exists = DB::table('mp_anime_episodes')
  7598. ->where('anime_id', $anime_id)
  7599. ->where('sequence', 1)
  7600. ->exists();
  7601. if ($episode_exists) {
  7602. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  7603. }
  7604. }
  7605. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7606. if ($prompt) {
  7607. $question .= "本次修改要求如下:\n{$prompt}";
  7608. }
  7609. // 提取文件内容
  7610. if ($file) {
  7611. $content = $this->extractFileContent($file);
  7612. if (!$content) {
  7613. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7614. }
  7615. } elseif ($script_id) {
  7616. $content = $this->getContentByScriptId($script_id);
  7617. if (!$content) {
  7618. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7619. }
  7620. } elseif ($bid) {
  7621. $content = $this->getContentByBid($bid);
  7622. if (!$content) {
  7623. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7624. }
  7625. } elseif ($content) {
  7626. $content = filterContent($content);
  7627. }else {
  7628. $content = filterContent(getProp($anime, 'content'));
  7629. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7630. $need_generate_content = true;
  7631. }
  7632. }
  7633. // 判断是否需要生成原文内容
  7634. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7635. // 如果需要生成原文内容,添加额外的要求
  7636. $content_generation_requirement = $need_generate_content
  7637. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7638. : "";
  7639. // 美术风格
  7640. $input_art_style = getProp($data, 'art_style');
  7641. if (!$input_art_style) {
  7642. $mappedArtStyle = getProp($anime, 'art_style');
  7643. }else {
  7644. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7645. }
  7646. if (!$mappedArtStyle) {
  7647. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7648. }else {
  7649. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7650. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7651. }else {
  7652. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7653. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7654. }
  7655. }
  7656. // 构建主体、场景和道具提示词
  7657. $extra_role_prompt = "\n";
  7658. $extra_scene_prompt = "\n";
  7659. $extra_prop_prompt = "\n";
  7660. $ref_products = []; // 参考资产
  7661. if ($extra_products) {
  7662. foreach($extra_products as $item) {
  7663. $product = getProp($item, 'product');
  7664. $product_name = getProp($item, 'product_name');
  7665. if ($product_name == '旁白') continue;
  7666. $ref_products[$product_name] = $item;
  7667. $pic_prompt = getProp($item, 'pic_prompt');
  7668. if ((int)$product === 1) {
  7669. // 拼接角色信息
  7670. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7671. } elseif ((int)$product === 2) {
  7672. // 拼接场景信息
  7673. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7674. } elseif ((int)$product === 3) {
  7675. // 拼接道具信息
  7676. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7677. }
  7678. }
  7679. // 优化提示词,融入剧本
  7680. if (!empty(trim($extra_role_prompt))) {
  7681. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7682. }
  7683. if (!empty(trim($extra_scene_prompt))) {
  7684. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7685. }
  7686. if (!empty(trim($extra_prop_prompt))) {
  7687. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7688. }
  7689. }
  7690. if ($anime_script_id && $is_single) {
  7691. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7692. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7693. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7694. }else {
  7695. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7696. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7697. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7698. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7699. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7700. {$extra_role_prompt}";
  7701. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7702. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7703. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7704. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7705. {$extra_scene_prompt}";
  7706. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7707. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7708. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7709. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7710. {$extra_prop_prompt}";
  7711. }
  7712. $system_message = ['role'=>'system', 'content'=>$is_single
  7713. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7714. 强制要求:
  7715. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7716. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7717. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7718. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7719. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7720. 普通要求:
  7721. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7722. $role_demo
  7723. $scene_demo
  7724. $prop_demo
  7725. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7726. 5.1片段分割逻辑(优先级从高到低):
  7727. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7728. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7729. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7730. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7731. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7732. - 片段数量格式为: 片段数量:8
  7733. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7734. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7735. 5.3分镜结构:每个分镜包含以下字段:
  7736. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7737. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7738. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7739. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7740. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7741. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7742. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7743. - 运镜:场景+画面描述+运镜
  7744. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7745. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7746. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7747. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7748. 6.{$mappedArtStyle_prompt}\n\n
  7749. 示例如下:\n
  7750. ###剧本名:西昆仑
  7751. ###故事梗概
  7752. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7753. ###剧本亮点
  7754. 亮点1:绝境奇药,生死一线
  7755. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7756. 亮点2:结拜兄妹,化解尴尬
  7757. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7758. 亮点3:纤发夺命,情愫暗涌
  7759. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7760. ###人物关系
  7761. 阿雪与梁萧之间存在兄妹之情。
  7762. ###核心矛盾
  7763. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7764. ###主体列表
  7765. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7766. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7767. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7768. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7769. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7770. 全景,正面拍摄,青年女性,亚洲人。
  7771. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7772. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7773. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7774. ###美术风格
  7775. 基础画风风格词:厚涂古风
  7776. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7777. ###场景列表
  7778. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7779. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7780. 无人物。}
  7781. ###分段剧本
  7782. 片段数量:8
  7783. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7784. ##片段1
  7785. 时长:12s
  7786. 分镜1
  7787. 出场角色:刀疤脸
  7788. 场景:边境小镇街道
  7789. 出场道具:酒杯-高脚杯
  7790. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7791. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7792. 配音台词:
  7793. 背景音效:
  7794. 分镜2
  7795. 出场角色:刀疤脸
  7796. 场景:悦来酒馆
  7797. 出场道具:酒杯-高脚杯
  7798. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7799. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7800. 配音台词:
  7801. 背景音效:
  7802. 分镜3
  7803. 出场角色:刀疤脸
  7804. 场景:悦来酒馆
  7805. 出场道具:酒杯-高脚杯
  7806. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7807. 运镜:从中景推向令牌特写。
  7808. 配音台词:
  7809. 背景音效:
  7810. 分镜4
  7811. 出场角色:刀疤脸
  7812. 场景:悦来酒馆
  7813. 出场道具:酒杯-高脚杯
  7814. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7815. 运镜:极速推向酒水溅起的瞬间。
  7816. 配音台词:
  7817. 背景音效:
  7818. 分镜5
  7819. 出场角色:刀疤脸
  7820. 场景:悦来酒馆
  7821. 出场道具:酒杯-高脚杯
  7822. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7823. 运镜:固定机位,利用倾斜构图制造压迫感。
  7824. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7825. 背景音效:
  7826. \n\n"
  7827. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7828. 强制要求:\n
  7829. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7830. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7831. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7832. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7833. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7834. 普通要求:\n
  7835. 1.剧本名(必须生成)必须与文档内容高度相关
  7836. $role_demo
  7837. $scene_demo
  7838. $prop_demo
  7839. 5.{$mappedArtStyle_prompt}\n\n
  7840. 示例如下:\n
  7841. ###剧本名:西昆仑
  7842. ###故事梗概
  7843. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7844. ###剧本亮点
  7845. 亮点1:绝境奇药,生死一线
  7846. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7847. 亮点2:结拜兄妹,化解尴尬
  7848. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7849. 亮点3:纤发夺命,情愫暗涌
  7850. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7851. ###人物关系
  7852. 阿雪与梁萧之间存在兄妹之情。
  7853. ###核心矛盾
  7854. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7855. ###主体列表
  7856. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7857. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7858. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7859. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7860. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7861. 全景,正面拍摄,青年女性,亚洲人。
  7862. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7863. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7864. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7865. ###美术风格
  7866. 基础画风风格词:厚涂古风
  7867. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7868. ###场景列表
  7869. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7870. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7871. 无人物。}
  7872. ###道具列表
  7873. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  7874. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  7875. $episode_count = $this->extractEpisodeNumber($prompt);
  7876. if ((int)getProp($anime, 'is_multi') !== 1) {
  7877. yield [
  7878. 'type' => 'done',
  7879. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  7880. 'reasoning' => '',
  7881. 'usage' => []
  7882. ];
  7883. return;
  7884. }
  7885. if ($episode_count) {
  7886. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  7887. $system_message = [
  7888. 'role' => 'system',
  7889. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7890. 强制要求:\n
  7891. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7892. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7893. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7894. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7895. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7896. 普通要求:\n
  7897. 1.<故事梗概>控制在200-300字左右
  7898. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7899. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7900. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7901. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7902. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7903. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7904. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7905. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7906. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7907. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  7908. 示例如下:\n
  7909. ###剧本名:西昆仑
  7910. ###故事梗概
  7911. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7912. ###剧本亮点
  7913. 亮点1:绝境奇药,生死一线
  7914. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7915. 亮点2:结拜兄妹,化解尴尬
  7916. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7917. 亮点3:纤发夺命,情愫暗涌
  7918. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7919. ###人物关系
  7920. 阿雪与梁萧之间存在兄妹之情。
  7921. ###核心矛盾
  7922. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7923. ###主体列表
  7924. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7925. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7926. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7927. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7928. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7929. 全景,正面拍摄,青年女性,亚洲人。
  7930. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7931. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7932. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7933. ###美术风格
  7934. 基础画风风格词:厚涂古风
  7935. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7936. ###场景列表
  7937. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7938. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7939. 无人物。}
  7940. ###分集详细内容
  7941. ##第1章 重生
  7942. 我重生了。
  7943. 源于一个男人偏执的暗恋。
  7944. ##第2章 相救
  7945. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  7946. 我眼睛扫向站在锅炉后的卞大伟。"
  7947. ];
  7948. // 构建消息
  7949. $messages = [
  7950. $system_message,
  7951. [
  7952. 'role' => 'user',
  7953. 'content' => "以下是文档内容:
  7954. {$content}
  7955. 用户问题:
  7956. {$question}"
  7957. ]
  7958. ];
  7959. }else {
  7960. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  7961. // 构建消息
  7962. $messages = [
  7963. $system_message,
  7964. [
  7965. 'role' => 'user',
  7966. 'content' => "以下是文档内容:
  7967. {$content}
  7968. 用户问题:
  7969. {$question}"
  7970. ]
  7971. ];
  7972. }else {
  7973. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  7974. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  7975. return (array)$value;
  7976. })->toArray();
  7977. array_unshift($messages, $system_message);
  7978. $messages[] = [
  7979. 'role' => 'user',
  7980. 'content' => $prompt
  7981. ];
  7982. }
  7983. }
  7984. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7985. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7986. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7987. if ($model === 'deepseek-chat') {
  7988. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7989. $model = 'deepseek-v4-flash';
  7990. $thinkingMode = 'disabled';
  7991. } elseif ($model === 'deepseek-reasoner') {
  7992. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7993. $model = 'deepseek-v4-flash';
  7994. $thinkingMode = 'enabled';
  7995. }
  7996. $post_data = [
  7997. 'model' => $model,
  7998. 'messages' => $messages,
  7999. // 'max_tokens' => 8192,
  8000. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8001. 'frequency_penalty' => 0,
  8002. 'presence_penalty' => 0,
  8003. 'response_format' => ['type' => 'text'],
  8004. 'thinking' => ['type' => $thinkingMode],
  8005. 'stream' => true // 启用流式输出
  8006. ];
  8007. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8008. // 根据模型类型选择调用方法
  8009. $fullContent = '';
  8010. $fullReasoningContent = '';
  8011. $usage = [];
  8012. // dd($post_data);
  8013. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  8014. try {
  8015. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8016. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8017. } else if (in_array($model, $this->gpt_text_models)) {
  8018. // GPT-5.4 模型使用 TokenRouter API
  8019. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8020. } else if (in_array($model, $this->gemini_text_models)) {
  8021. // Gemini 模型使用 Gemini API
  8022. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8023. } else {
  8024. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8025. }
  8026. // 验证返回值类型
  8027. if (!is_iterable($streamGenerator)) {
  8028. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8029. dLog('deepseek')->error('方法名流式生成器无效', [
  8030. 'generator_type' => $errorType,
  8031. 'model' => $model,
  8032. // 添加其他上下文信息
  8033. ]);
  8034. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  8035. 'type' => $errorType,
  8036. 'model' => $model
  8037. ]);
  8038. yield [
  8039. 'type' => 'error',
  8040. // 根据方法返回相应的空数据结构
  8041. 'answer' => '',
  8042. 'reasoning' => '',
  8043. 'usage' => [],
  8044. 'error' => '接口返回数据异常,请重新请求'
  8045. ];
  8046. return;
  8047. }
  8048. // 处理流式输出
  8049. foreach ($streamGenerator as $chunk) {
  8050. if (isset($chunk['type'])) {
  8051. if ($chunk['type'] === 'done') {
  8052. $fullContent = $chunk['full_content'];
  8053. $fullReasoningContent = $chunk['full_reasoning'];
  8054. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8055. } else {
  8056. yield $chunk;
  8057. }
  8058. }
  8059. }
  8060. } catch (\Exception $e) {
  8061. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  8062. 'model' => $model,
  8063. 'trace' => $e->getTraceAsString()
  8064. ]);
  8065. logDB('deepseek', 'error', '方法名流式处理失败', [
  8066. 'error' => $e->getMessage(),
  8067. 'model' => $model
  8068. ]);
  8069. yield [
  8070. 'type' => 'error',
  8071. // 根据方法返回相应的空数据结构
  8072. 'answer' => '',
  8073. 'reasoning' => '',
  8074. 'usage' => [],
  8075. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8076. ];
  8077. return;
  8078. }
  8079. dLog('deepseek')->info('完整内容: '.$fullContent);
  8080. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8081. // 处理完整内容并返回最终结果
  8082. $script_arr = [];
  8083. if ($fullContent) {
  8084. $script_arr = handleScriptContentForAce($fullContent);
  8085. dLog('deepseek')->info('解析内容', $script_arr);
  8086. logDB('deepseek', 'info', '解析内容', $script_arr);
  8087. }
  8088. if (empty($script_arr['roles'])) {
  8089. // 未生成剧本相关内容,保存对话记录并返回提示
  8090. dLog('deepseek')->info('未生成剧本相关的内容');
  8091. try {
  8092. $now = date('Y-m-d H:i:s');
  8093. // 保存对话记录
  8094. $records = [
  8095. [
  8096. 'uid' => $uid,
  8097. 'anime_id' => $anime_id,
  8098. 'sequence' => 0,
  8099. 'role' => 'user',
  8100. 'content' => $prompt,
  8101. 'created_at' => $now,
  8102. 'updated_at' => $now
  8103. ],
  8104. [
  8105. 'uid' => $uid,
  8106. 'anime_id' => $anime_id,
  8107. 'sequence' => 0,
  8108. 'role' => 'assistant',
  8109. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  8110. 'created_at' => $now,
  8111. 'updated_at' => $now
  8112. ]
  8113. ];
  8114. DB::table('mp_anime_records')->insert($records);
  8115. } catch (\Exception $e) {
  8116. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8117. }
  8118. yield [
  8119. 'type' => 'done',
  8120. 'script' => [],
  8121. 'episode' => [],
  8122. 'answer' => $fullContent,
  8123. 'reasoning' => $fullReasoningContent,
  8124. 'usage' => $usage,
  8125. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  8126. ];
  8127. return;
  8128. }
  8129. // 替换美术风格
  8130. if ($mappedArtStyle !== '') {
  8131. $script_arr['art_style'] = $mappedArtStyle;
  8132. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8133. }
  8134. if ($user_anime_name != '新剧本策划') {
  8135. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  8136. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  8137. // 确认对话名称唯一性
  8138. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  8139. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  8140. }
  8141. }else {
  8142. $anime_name = $user_anime_name;
  8143. }
  8144. $table_data = [
  8145. 'user_id' => $uid,
  8146. 'model' => $model,
  8147. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  8148. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  8149. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  8150. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  8151. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  8152. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  8153. 'art_style_type' => $input_art_style,
  8154. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  8155. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  8156. 'status' => '解析完成',
  8157. 'generate_status' => '待执行',
  8158. 'updated_at' => date('Y-m-d H:i:s')
  8159. ];
  8160. if ($anime_name) $table_data['anime_name'] = $anime_name;
  8161. // 如果是修改集数,则将content内容更新(会改变原文)
  8162. if (isset($episode_count) && $episode_count > 0) {
  8163. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  8164. $table_data['start_episode_sequence'] = 1;
  8165. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  8166. }else {
  8167. // 如果需要生成原文内容,从script_arr中提取
  8168. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  8169. $table_data['content'] = $script_arr['content'];
  8170. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  8171. if (!$table_data['content']) {
  8172. yield [
  8173. 'type' => 'done',
  8174. 'script' => [],
  8175. 'episode' => [],
  8176. 'answer' => $fullContent,
  8177. 'reasoning' => $fullReasoningContent,
  8178. 'usage' => $usage,
  8179. 'error' => '未生成剧本内容,请调整提示词再试'
  8180. ];
  8181. return;
  8182. }
  8183. }
  8184. if (isset($table_data['content']) && $table_data['content']) {
  8185. $chapters = splitContent($table_data['content']);
  8186. $chapter_count = count($chapters);
  8187. if ($chapter_count > 0) {
  8188. $table_data['start_episode_sequence'] = 1;
  8189. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  8190. }
  8191. }
  8192. }
  8193. if ($extra_products) {
  8194. $table_data['extra_products'] = json_encode($extra_products, 256);
  8195. }
  8196. $single_episode = [];
  8197. try {
  8198. DB::beginTransaction();
  8199. $now = date('Y-m-d H:i:s');
  8200. // 更新动漫大纲
  8201. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8202. if (!$boolen) {
  8203. dLog('deepseek')->info('对话修改失败', $table_data);
  8204. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  8205. Utils::throwError('20003:对话修改失败');
  8206. }
  8207. // 保存对话记录
  8208. $records = [
  8209. [
  8210. 'uid' => $uid,
  8211. 'anime_id' => $anime_id,
  8212. 'sequence' => 0,
  8213. 'role' => 'user',
  8214. 'content' => $prompt,
  8215. 'created_at' => $now,
  8216. 'updated_at' => $now
  8217. ],
  8218. [
  8219. 'uid' => $uid,
  8220. 'anime_id' => $anime_id,
  8221. 'sequence' => 0,
  8222. 'role' => 'assistant',
  8223. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8224. 'content' => $fullContent,
  8225. 'created_at' => $now,
  8226. 'updated_at' => $now
  8227. ]
  8228. ];
  8229. // 保存对话记录
  8230. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8231. if (!$boolen3) {
  8232. Utils::throwError('20003:对话记录保存失败');
  8233. }
  8234. // 单剧集模式:生成并保存剧集信息
  8235. if ($is_single) {
  8236. $anime_name = getProp($anime, 'anime_name', '未命名');
  8237. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8238. if (empty($episode_arr['acts'])) {
  8239. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8240. }
  8241. $saveResult = $this->saveEpisodeVersionData(
  8242. $anime_id,
  8243. 1,
  8244. $episode_arr,
  8245. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8246. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8247. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8248. null,
  8249. null,
  8250. false,
  8251. $content,
  8252. $now,
  8253. $ref_products
  8254. );
  8255. $single_episode = $saveResult['episode'];
  8256. $episode_id = $saveResult['episode_id'];
  8257. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8258. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8259. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8260. 'props' => json_encode($saveResult['merged_props'], 256),
  8261. 'updated_at' => $now
  8262. ]);
  8263. if ($boolen5 === false) {
  8264. Utils::throwError('20003:单剧集主表资源同步失败');
  8265. }
  8266. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8267. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8268. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8269. $episode_record_content = '确认分镜大纲';
  8270. if ($content !== '') {
  8271. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8272. }
  8273. $episode_records = [
  8274. [
  8275. 'uid' => $uid,
  8276. 'anime_id' => $anime_id,
  8277. 'role' => 'user',
  8278. 'content' => $episode_record_content,
  8279. 'sequence' => 1,
  8280. 'episode_id' => $episode_id,
  8281. 'created_at' => $now,
  8282. 'updated_at' => $now
  8283. ],
  8284. [
  8285. 'uid' => $uid,
  8286. 'anime_id' => $anime_id,
  8287. 'role' => 'assistant',
  8288. 'content' => $fullContent,
  8289. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8290. 'sequence' => 1,
  8291. 'episode_id' => $episode_id,
  8292. 'created_at' => $now,
  8293. 'updated_at' => $now
  8294. ]
  8295. ];
  8296. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8297. if (!$boolen4) {
  8298. Utils::throwError('20003:单剧集分镜记录保存失败');
  8299. }
  8300. }
  8301. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8302. if ($is_single && !empty($single_episode)) {
  8303. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8304. 'anime_id' => $anime_id,
  8305. 'episode_id' => $episode_id ?? 0,
  8306. ]);
  8307. }
  8308. }catch (\Exception $e) {
  8309. DB::rollBack();
  8310. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  8311. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  8312. yield [
  8313. 'type' => 'done',
  8314. 'answer' => $fullContent,
  8315. 'reasoning' => $fullReasoningContent,
  8316. 'usage' => $usage,
  8317. 'error' => $e->getMessage(),
  8318. ];
  8319. return;
  8320. }
  8321. DB::commit();
  8322. dLog('deepseek')->info('保存完毕');
  8323. if ($is_single && !empty($single_episode)) {
  8324. // $this->batchSetGlobalRoleImg([
  8325. // 'anime_id' => $anime_id,
  8326. // ]);
  8327. // $this->batchSetGlobalSceneImg([
  8328. // 'anime_id' => $anime_id,
  8329. // ]);
  8330. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8331. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8332. }
  8333. $table_data['anime_id'] = $anime_id;
  8334. $table_data['roles'] = json_decode($table_data['roles'], true);
  8335. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8336. $table_data['props'] = json_decode($table_data['props'], true);
  8337. unset($table_data['updated_at']);
  8338. unset($table_data['status']);
  8339. yield [
  8340. 'type' => 'done',
  8341. 'script' => $table_data,
  8342. 'episode' => $single_episode,
  8343. 'answer' => $fullContent,
  8344. 'reasoning' => $fullReasoningContent,
  8345. 'usage' => $usage
  8346. ];
  8347. }
  8348. public function chatForAce($data) {
  8349. $uid = Site::getUid();
  8350. // 积分余额预检(不足直接报错)
  8351. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  8352. $anime_id = getProp($data, 'anime_id');
  8353. $file = getProp($data, 'file');
  8354. $content = getProp($data, 'content', '');
  8355. $bid = getProp($data, 'bid', 0);
  8356. $script_id = getProp($data, 'script_id', 0);
  8357. $episode_number = getProp($data, 'episode_number', 1);
  8358. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8359. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8360. if (!$anime) Utils::throwError('20003:该对话不存在!');
  8361. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  8362. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  8363. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  8364. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  8365. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  8366. $roles = is_array($roles) ? $roles : [];
  8367. $scenes = is_array($scenes) ? $scenes : [];
  8368. $extra_products = getProp($data, 'products', []);
  8369. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8370. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8371. $anime_script_id = getProp($anime, 'script_id');
  8372. if ($anime_script_id) {
  8373. $cpid = Site::getCpid();
  8374. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8375. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8376. ->where('mapping.script_id', $anime_script_id)
  8377. ->where('product.cpid', $cpid)
  8378. ->where('product.is_deleted', 0);
  8379. // 如果提供了 episode_number,则过滤指定集数
  8380. if ($episode_number !== null && $episode_number !== '') {
  8381. $script_products_mappings->where('mapping.episode_number', $episode_number);
  8382. }
  8383. $mappings = $script_products_mappings->select(
  8384. 'mapping.product_id',
  8385. 'mapping.episode_number',
  8386. 'product.product_name',
  8387. 'product.type',
  8388. 'product.product',
  8389. 'product.pic_prompt',
  8390. 'product.url',
  8391. 'product.pic_task_id',
  8392. 'product.pic_task_status',
  8393. 'product.three_view_image_url'
  8394. )
  8395. ->get();
  8396. // 按 product_id 分组,合并 episode_number
  8397. $productMap = [];
  8398. foreach ($mappings as $item) {
  8399. $product_id = $item->product_id;
  8400. $product_name = $item->product_name;
  8401. // 处理product_name两边的符号
  8402. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8403. if (!isset($productMap[$product_id])) {
  8404. $productMap[$product_id] = [
  8405. 'product_id' => $product_id,
  8406. 'product_name' => $product_name,
  8407. 'type' => (int)$item->type,
  8408. 'product' => (int)$item->product,
  8409. 'pic_prompt' => $item->pic_prompt,
  8410. 'url' => $item->url,
  8411. 'pic_task_id' => $item->pic_task_id,
  8412. 'pic_task_status' => $item->pic_task_status,
  8413. 'episode_numbers' => [],
  8414. ];
  8415. }
  8416. // 添加 episode_number(去重)
  8417. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8418. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8419. }
  8420. }
  8421. // 将查询到的剧本资产合并到extra_products中
  8422. // 先构建extra_products的索引(以product_id+episode_number为key)
  8423. $extraProductsMap = [];
  8424. foreach ($extra_products as $item) {
  8425. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  8426. $extraProductsMap[$key] = $item;
  8427. }
  8428. // 合并剧本资产(去重:product_id+episode_number)
  8429. foreach ($productMap as $product) {
  8430. foreach ($product['episode_numbers'] as $ep_num) {
  8431. $key = $product['product_id'] . '_' . $ep_num;
  8432. // 如果不存在则添加
  8433. if (!isset($extraProductsMap[$key])) {
  8434. $extraProductsMap[$key] = [
  8435. 'product_id' => $product['product_id'],
  8436. 'product_name' => $product['product_name'],
  8437. 'type' => $product['type'],
  8438. 'product' => $product['product'],
  8439. 'pic_prompt' => $product['pic_prompt'],
  8440. 'url' => $product['url'],
  8441. 'pic_task_id' => $product['pic_task_id'],
  8442. 'pic_task_status' => $product['pic_task_status'],
  8443. 'episode_number' => $ep_num,
  8444. ];
  8445. }
  8446. }
  8447. }
  8448. // 重新赋值给extra_products
  8449. $extra_products = array_values($extraProductsMap);
  8450. }
  8451. // 处理提示词
  8452. if ($prompt && $extra_products) {
  8453. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8454. foreach($extra_products as $item) {
  8455. $product_name = getProp($item, 'product_name');
  8456. if ($product_name) {
  8457. // 替换 {product_name} 为 product_name
  8458. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8459. }
  8460. }
  8461. }
  8462. // 获取最后一集序号
  8463. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  8464. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  8465. // 转换主体列表和场景列表的格式
  8466. // 获取参考主体或场景
  8467. if ((int)$episode_number === 1) {
  8468. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  8469. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  8470. }else {
  8471. $prev_episode_number = $episode_number - 1;
  8472. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  8473. }
  8474. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  8475. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  8476. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  8477. // 合并anime_products和extra_products(extra_products优先,去重)
  8478. $anime_products = getProp($anime, 'extra_products');
  8479. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  8480. $ref_products = [];
  8481. foreach($anime_products as $item) {
  8482. $product_name = getProp($item, 'product_name');
  8483. $ref_products[$product_name] = $item;
  8484. }
  8485. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  8486. $extra_roles = []; // 从extra_products中提取的角色
  8487. $extra_scenes = []; // 从extra_products中提取的场景
  8488. $extra_props = []; // 从extra_products中提取的道具
  8489. if ($extra_products && is_array($extra_products)) {
  8490. foreach($extra_products as $item) {
  8491. $product = (int)getProp($item, 'product');
  8492. $product_name = getProp($item, 'product_name');
  8493. if ($product_name == '旁白') continue;
  8494. $pic_prompt = getProp($item, 'pic_prompt');
  8495. $ref_products[$product_name] = $item;
  8496. if ($product === 1) {
  8497. // 角色
  8498. $extra_roles[$product_name] = [
  8499. 'role' => $product_name,
  8500. 'pic_prompt' => $pic_prompt,
  8501. 'url' => getProp($item, 'url', ''),
  8502. ];
  8503. } elseif ($product === 2) {
  8504. // 场景
  8505. $extra_scenes[$product_name] = [
  8506. 'scene' => $product_name,
  8507. 'pic_prompt' => $pic_prompt,
  8508. 'url' => getProp($item, 'url', ''),
  8509. ];
  8510. } elseif ($product === 3) {
  8511. // 道具
  8512. $extra_props[$product_name] = [
  8513. 'prop' => $product_name,
  8514. 'pic_prompt' => $pic_prompt,
  8515. 'url' => getProp($item, 'url', ''),
  8516. ];
  8517. }
  8518. }
  8519. }
  8520. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  8521. $merged_roles = [];
  8522. foreach($ref_roles as $role) {
  8523. $role_name = getProp($role, 'role');
  8524. if (!isset($extra_roles[$role_name])) {
  8525. $merged_roles[$role_name] = $role;
  8526. }
  8527. }
  8528. // 添加extra_roles
  8529. foreach($extra_roles as $role_name => $role) {
  8530. $merged_roles[$role_name] = $role;
  8531. }
  8532. $ref_roles = array_values($merged_roles);
  8533. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  8534. $merged_scenes = [];
  8535. foreach($ref_scenes as $scene) {
  8536. $scene_name = getProp($scene, 'scene');
  8537. if (!isset($extra_scenes[$scene_name])) {
  8538. $merged_scenes[$scene_name] = $scene;
  8539. }
  8540. }
  8541. // 添加extra_scenes
  8542. foreach($extra_scenes as $scene_name => $scene) {
  8543. $merged_scenes[$scene_name] = $scene;
  8544. }
  8545. $ref_scenes = array_values($merged_scenes);
  8546. // 合并ref_props和extra_props(extra_props优先,去重)
  8547. $merged_props = [];
  8548. foreach($ref_props as $prop) {
  8549. $prop_name = getProp($prop, 'prop');
  8550. if (!isset($extra_props[$prop_name])) {
  8551. $merged_props[$prop_name] = $prop;
  8552. }
  8553. }
  8554. // 添加extra_props
  8555. foreach($extra_props as $prop_name => $prop) {
  8556. $merged_props[$prop_name] = $prop;
  8557. }
  8558. $ref_props = array_values($merged_props);
  8559. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  8560. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  8561. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  8562. // 构建强制主体、场景和道具提示词
  8563. $forced_roles_prompt = "";
  8564. $forced_scenes_prompt = "";
  8565. $forced_props_prompt = "";
  8566. if (!empty($extra_roles)) {
  8567. $forced_roles_list = "";
  8568. foreach($extra_roles as $role_name => $role) {
  8569. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  8570. }
  8571. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8572. }
  8573. if (!empty($extra_scenes)) {
  8574. $forced_scenes_list = "";
  8575. foreach($extra_scenes as $scene_name => $scene) {
  8576. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  8577. }
  8578. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8579. }
  8580. if (!empty($extra_props)) {
  8581. $forced_props_list = "";
  8582. foreach($extra_props as $prop_name => $prop) {
  8583. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  8584. }
  8585. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8586. }
  8587. if ($anime_script_id) {
  8588. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  8589. }else if ($roles_content) {
  8590. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  8591. 主体范围:\n {$roles_content}\n
  8592. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  8593. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8594. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8595. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8596. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8597. }else {
  8598. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8599. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8600. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8601. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8602. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8603. }
  8604. if ($anime_script_id) {
  8605. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  8606. }else if ($scenes_content) {
  8607. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8608. 场景范围:\n {$scenes_content}\n
  8609. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  8610. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  8611. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8612. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8613. }else {
  8614. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8615. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8616. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8617. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8618. }
  8619. if ($anime_script_id) {
  8620. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  8621. }else if ($props_content) {
  8622. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8623. 道具范围:\n {$props_content}\n
  8624. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  8625. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  8626. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8627. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8628. }else {
  8629. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8630. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  8631. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8632. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8633. }
  8634. // 提取文件内容
  8635. if ($file) {
  8636. $uploaded_content = $this->extractFileContent($file);
  8637. if (!$uploaded_content) {
  8638. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8639. }
  8640. } elseif ($script_id) {
  8641. $uploaded_content = $this->getContentByScriptId($script_id);
  8642. if (!$uploaded_content) {
  8643. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8644. }
  8645. } elseif ($bid) {
  8646. $uploaded_content = $this->getContentByBid($bid);
  8647. if (!$uploaded_content) {
  8648. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8649. }
  8650. } elseif ($content) {
  8651. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  8652. }
  8653. // elseif ($prompt) {
  8654. // $uploaded_content = filterContent($prompt);
  8655. // }
  8656. else {
  8657. $uploaded_content = '';
  8658. }
  8659. // 美术风格
  8660. $input_art_style = getProp($data, 'art_style');
  8661. if (!$input_art_style) {
  8662. $mappedArtStyle = getProp($anime, 'art_style');
  8663. }else {
  8664. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8665. }
  8666. if (!$mappedArtStyle) {
  8667. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8668. }else {
  8669. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8670. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8671. }else {
  8672. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8673. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8674. }
  8675. }
  8676. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8677. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8678. // 强制要求:
  8679. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8680. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8681. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8682. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  8683. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  8684. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  8685. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  8686. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  8687. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  8688. // 10.分镜要和场景列表、人物主体保持一致\n
  8689. // 普通要求:
  8690. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8691. // {$role_demo}
  8692. // {$scene_demo}
  8693. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8694. // 4.1片段分割逻辑(优先级从高到低):
  8695. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8696. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8697. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8698. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8699. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8700. // - 片段数量格式为: 片段数量:8
  8701. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8702. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8703. // 4.3分镜结构:每个分镜包含以下字段:
  8704. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  8705. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  8706. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8707. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  8708. // - 运镜:场景+画面描述+运镜
  8709. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  8710. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8711. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8712. // 5.$mappedArtStyle_prompt\n\n
  8713. // 示例格式:\n
  8714. // 第1集:隐形的守护者
  8715. // ###故事梗概
  8716. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8717. // ###美术风格
  8718. // 基础画风风格词:胡金铨武侠
  8719. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8720. // ###主体列表
  8721. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8722. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8723. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8724. // ###场景列表
  8725. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8726. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8727. // ###分段剧本
  8728. // 片段数量:8
  8729. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8730. // ##片段1
  8731. // 时长:12s
  8732. // 分镜1
  8733. // 场景:边境小镇街道
  8734. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8735. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8736. // 配音台词:
  8737. // 背景音效:
  8738. // 分镜2
  8739. // 场景:悦来酒馆
  8740. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8741. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8742. // 配音台词:
  8743. // 背景音效:
  8744. // 分镜3
  8745. // 场景:悦来酒馆
  8746. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8747. // 运镜:从中景推向令牌特写。
  8748. // 配音台词:
  8749. // 背景音效:
  8750. // 分镜4
  8751. // 场景:悦来酒馆
  8752. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8753. // 运镜:极速推向酒水溅起的瞬间。
  8754. // 配音台词:
  8755. // 背景音效:
  8756. // 分镜5
  8757. // 镜头描述
  8758. // 场景:悦来酒馆
  8759. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8760. // 运镜:固定机位,利用倾斜构图制造压迫感。
  8761. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8762. // 背景音效:
  8763. // \n\n";
  8764. /*
  8765. // ====== 旧版 $demo(缓存优化前版本,动态数据内嵌在规则中间) ======
  8766. // 如需换回:删除下方新版 $demo,并把本块恢复为活动代码(去掉首尾注释标记)
  8767. // ===================================================================
  8768. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  8769. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  8770. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  8771. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  8772. 强制要求:
  8773. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  8774. 普通要求:
  8775. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8776. {$role_demo}
  8777. {$scene_demo}
  8778. {$prop_demo}
  8779. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8780. 5.1片段分割逻辑(优先级从高到低):
  8781. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8782. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8783. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8784. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8785. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8786. - 片段数量格式为: 片段数量:8
  8787. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8788. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8789. 5.3分镜结构:每个分镜包含以下字段:
  8790. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8791. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8792. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8793. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8794. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8795. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8796. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8797. - 运镜:场景+画面描述+运镜
  8798. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8799. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8800. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8801. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8802. 6.《情绪-视听语言映射表》:
  8803. 6.1 场景空间与时间心理学 (Scene & Temporality)
  8804. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8805. -----|---------|------------|----------------
  8806. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  8807. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  8808. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  8809. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  8810. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  8811. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8812. -----|---------|------------|----------------
  8813. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  8814. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  8815. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  8816. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  8817. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  8818. --------|---------|--------------|-------------
  8819. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  8820. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  8821. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  8822. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  8823. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  8824. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  8825. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  8826. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  8827. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  8828. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  8829. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  8830. -----|---------|------------|------------
  8831. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8832. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8833. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8834. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8835. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8836. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8837. --------|---------|--------------|----------
  8838. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8839. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8840. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8841. 6.6 声音设计与潜意识影响 (Soundscape)
  8842. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8843. -----|---------|------------|------------------
  8844. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8845. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8846. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8847. 理论基石:
  8848. - The Five C's of Cinematography by Joseph V. Mascelli
  8849. - Film Art: An Introduction by David Bordwell
  8850. - Sight, Sound, Motion by Herbert Zettl
  8851. - Notes on the Cinematograph by Robert Bresson
  8852. \n\n
  8853. 7.{$mappedArtStyle_prompt}
  8854. 示例格式:\n
  8855. 第1集:隐形的守护者
  8856. ###故事梗概
  8857. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8858. ###美术风格
  8859. 基础画风风格词:胡金铨武侠
  8860. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8861. ###主体列表
  8862. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8863. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8864. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8865. ###场景列表
  8866. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8867. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8868. ###道具列表
  8869. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  8870. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  8871. ###分段剧本
  8872. 片段数量:8
  8873. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8874. ##片段1
  8875. 时长:12s
  8876. 分镜1
  8877. 出场角色:刀疤脸
  8878. 场景:边境小镇街道
  8879. 出场道具:酒杯-高脚杯
  8880. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8881. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8882. 配音台词:
  8883. 背景音效:
  8884. 分镜2
  8885. 出场角色:刀疤脸
  8886. 场景:悦来酒馆
  8887. 出场道具:酒杯-高脚杯
  8888. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8889. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8890. 配音台词:
  8891. 背景音效:
  8892. 分镜3
  8893. 出场角色:刀疤脸
  8894. 场景:悦来酒馆
  8895. 出场道具:酒杯-高脚杯
  8896. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8897. 运镜:从中景推向令牌特写。
  8898. 配音台词:
  8899. 背景音效:
  8900. 分镜4
  8901. 出场角色:刀疤脸
  8902. 场景:悦来酒馆
  8903. 出场道具:酒杯-高脚杯
  8904. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8905. 运镜:极速推向酒水溅起的瞬间。
  8906. 配音台词:
  8907. 背景音效:
  8908. 分镜5
  8909. 出场角色:刀疤脸
  8910. 场景:悦来酒馆
  8911. 出场道具:酒杯-高脚杯
  8912. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8913. 运镜:固定机位,利用倾斜构图制造压迫感。
  8914. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8915. 背景音效:
  8916. \n\n";
  8917. */
  8918. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  8919. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  8920. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  8921. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  8922. 强制要求:
  8923. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  8924. 普通要求:
  8925. 1.剧集标题必须与文档内容高度相关,剧集序号见文末【本次剧集信息】。
  8926. 2.<主体列表>的详细规则和可选范围见文末【本次生成数据-主体列表】。
  8927. 3.<场景列表>的详细规则和可选范围见文末【本次生成数据-场景列表】。
  8928. 4.<道具列表>的详细规则和可选范围见文末【本次生成数据-道具列表】。
  8929. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8930. 5.1片段分割逻辑(优先级从高到低):
  8931. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8932. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8933. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8934. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8935. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8936. - 片段数量格式为: 片段数量:8
  8937. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8938. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8939. 5.3分镜结构:每个分镜包含以下字段:
  8940. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  8941. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8942. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8943. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8944. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8945. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8946. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8947. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8948. - 运镜:场景+画面描述+运镜
  8949. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8950. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8951. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8952. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8953. 6.《情绪-视听语言映射表》:
  8954. 6.1 场景空间与时间心理学 (Scene & Temporality)
  8955. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8956. -----|---------|------------|----------------
  8957. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  8958. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  8959. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  8960. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  8961. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  8962. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8963. -----|---------|------------|----------------
  8964. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  8965. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  8966. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  8967. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  8968. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  8969. --------|---------|--------------|-------------
  8970. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  8971. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  8972. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  8973. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  8974. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  8975. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  8976. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  8977. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  8978. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  8979. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  8980. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  8981. -----|---------|------------|------------
  8982. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8983. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8984. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8985. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8986. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8987. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8988. --------|---------|--------------|----------
  8989. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8990. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8991. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8992. 6.6 声音设计与潜意识影响 (Soundscape)
  8993. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8994. -----|---------|------------|------------------
  8995. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8996. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8997. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8998. 理论基石:
  8999. - The Five C's of Cinematography by Joseph V. Mascelli
  9000. - Film Art: An Introduction by David Bordwell
  9001. - Sight, Sound, Motion by Herbert Zettl
  9002. - Notes on the Cinematograph by Robert Bresson
  9003. \n\n
  9004. 7.美术风格要求见文末【本次生成数据-美术风格】。
  9005. 示例格式:\n
  9006. 第1集:隐形的守护者
  9007. ###故事梗概
  9008. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9009. ###美术风格
  9010. 基础画风风格词:胡金铨武侠
  9011. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9012. ###主体列表
  9013. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9014. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9015. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9016. ###场景列表
  9017. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9018. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9019. ###道具列表
  9020. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  9021. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  9022. ###分段剧本
  9023. 片段数量:8
  9024. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9025. ##片段1
  9026. 时长:12s
  9027. 分镜1
  9028. 出场角色:刀疤脸
  9029. 场景:边境小镇街道
  9030. 出场道具:酒杯-高脚杯
  9031. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9032. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9033. 配音台词:
  9034. 背景音效:
  9035. 分镜2
  9036. 出场角色:刀疤脸
  9037. 场景:悦来酒馆
  9038. 出场道具:酒杯-高脚杯
  9039. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9040. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9041. 配音台词:
  9042. 背景音效:
  9043. 分镜3
  9044. 出场角色:刀疤脸
  9045. 场景:悦来酒馆
  9046. 出场道具:酒杯-高脚杯
  9047. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9048. 运镜:从中景推向令牌特写。
  9049. 配音台词:
  9050. 背景音效:
  9051. 分镜4
  9052. 出场角色:刀疤脸
  9053. 场景:悦来酒馆
  9054. 出场道具:酒杯-高脚杯
  9055. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9056. 运镜:极速推向酒水溅起的瞬间。
  9057. 配音台词:
  9058. 背景音效:
  9059. 分镜5
  9060. 出场角色:刀疤脸
  9061. 场景:悦来酒馆
  9062. 出场道具:酒杯-高脚杯
  9063. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9064. 运镜:固定机位,利用倾斜构图制造压迫感。
  9065. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9066. 背景音效:
  9067. \n\n本次生成数据(以上规则的动态数据均在此处,优先级等同对应编号规则):
  9068. 【本次剧集信息】剧集序号是{$episode_number}。
  9069. 【本次生成数据-主体列表】{$role_demo}
  9070. 【本次生成数据-场景列表】{$scene_demo}
  9071. 【本次生成数据-道具列表】{$prop_demo}
  9072. 【本次生成数据-美术风格】{$mappedArtStyle_prompt}
  9073. \n\n";
  9074. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  9075. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  9076. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  9077. $prompt = $origin_prompt;
  9078. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  9079. // 获取章节内容
  9080. $full_content = getProp($anime, 'content');
  9081. if ($uploaded_content) {
  9082. $full_content = $uploaded_content;
  9083. }
  9084. // 根据章节内容拆分章节
  9085. $chapters = splitContent($full_content);
  9086. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  9087. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  9088. $messages = [];
  9089. if ($prompt == '确认分镜大纲') {
  9090. // 暂时保留
  9091. $content = $chapter_content;
  9092. if ($is_single) $content = $full_content; // 单剧集使用全文
  9093. if (!$content) {
  9094. Utils::throwError('20003:章节内容无法获取,请确认');
  9095. }
  9096. $question = $is_single
  9097. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  9098. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  9099. // 构建消息
  9100. $messages[] =
  9101. [
  9102. 'role' => 'user',
  9103. 'content' => $question
  9104. ];
  9105. }else if ($prompt == '继续策划下一集') {
  9106. if ($is_single) {
  9107. Utils::throwError('20003:单剧集不支持继续策划下一集');
  9108. }
  9109. $content = $chapter_content;
  9110. if (!$content) {
  9111. Utils::throwError('20003:章节内容无法获取,请确认');
  9112. }
  9113. // 获取上一集最后记录
  9114. $prev_sequence = $episode_number - 1;
  9115. $messages = array_merge(
  9116. [
  9117. [
  9118. 'role' => 'system',
  9119. 'content' => $demo
  9120. ]
  9121. ],
  9122. $this->getEpisodeChatContent($anime_id, $prev_sequence, $content)
  9123. );
  9124. // 构建消息
  9125. $messages[] =
  9126. [
  9127. 'role' => 'user',
  9128. 'content' => "请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)"
  9129. ];
  9130. /*
  9131. // 旧版逻辑
  9132. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  9133. // 构建消息
  9134. $messages[] =
  9135. [
  9136. 'role' => 'user',
  9137. 'content' => $question
  9138. ];
  9139. */
  9140. // dd($messages);
  9141. }else {
  9142. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  9143. if (!$content) {
  9144. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  9145. }
  9146. if (!$content) {
  9147. Utils::throwError('20003:章节内容无法获取,请确认');
  9148. }
  9149. $messages = array_merge(
  9150. [
  9151. [
  9152. 'role' => 'system',
  9153. 'content' => $demo
  9154. ]
  9155. ],
  9156. $this->getEpisodeChatMessages($anime_id, $episode_number)
  9157. );
  9158. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  9159. $question = "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  9160. if ($origin_prompt) {
  9161. $question .= "本次修改要求如下:\n{$origin_prompt}";
  9162. }
  9163. // 将本集原文加入消息,供模型逐字摘录原文台词(修复重新生成时配音台词全部为"无"的问题)
  9164. $messages[] = [
  9165. 'role' => 'user',
  9166. 'content' => "本集剧情内容:\n\n{$content}\n"
  9167. ];
  9168. $messages[] =
  9169. [
  9170. 'role' => 'user',
  9171. 'content' => $question
  9172. ];
  9173. }
  9174. // 处理文本模型
  9175. $model = getProp($data, 'model');
  9176. if (!$model) {
  9177. // 用户没有输入,从anime表获取
  9178. $model = getProp($anime, 'model');
  9179. if (!$model) {
  9180. // anime表也没有,使用默认值
  9181. $model = 'deepseek-v4-pro';
  9182. }
  9183. }
  9184. // 验证模型是否在可用模型表中
  9185. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9186. $model = 'deepseek-v4-pro';
  9187. }
  9188. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  9189. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  9190. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  9191. if ($model === 'deepseek-chat') {
  9192. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  9193. $model = 'deepseek-v4-flash';
  9194. $thinkingMode = 'disabled';
  9195. } elseif ($model === 'deepseek-reasoner') {
  9196. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  9197. $model = 'deepseek-v4-flash';
  9198. $thinkingMode = 'enabled';
  9199. }
  9200. $post_data = [
  9201. 'model' => $model,
  9202. 'messages' => $messages,
  9203. // 'max_tokens' => 8192,
  9204. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9205. 'frequency_penalty' => 0,
  9206. 'presence_penalty' => 0,
  9207. 'response_format' => ['type' => 'text'],
  9208. 'thinking' => ['type' => $thinkingMode],
  9209. 'stream' => true // 启用流式输出
  9210. ];
  9211. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9212. // 根据模型类型选择调用方法
  9213. $fullContent = '';
  9214. $fullReasoningContent = '';
  9215. $usage = [];
  9216. try {
  9217. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9218. // DeepSeek 官方模型使用 DeepSeek API
  9219. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9220. } else if (in_array($model, $this->gpt_text_models)) {
  9221. // GPT-5.4 模型使用 TokenRouter API
  9222. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9223. } else if (in_array($model, $this->gemini_text_models)) {
  9224. // Gemini 模型使用 Gemini API
  9225. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9226. } else {
  9227. // 其他模型使用火山引擎API
  9228. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9229. }
  9230. // 验证返回值类型
  9231. if (!is_iterable($streamGenerator)) {
  9232. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  9233. dLog('deepseek')->error('chat流式生成器无效', [
  9234. 'generator_type' => $errorType,
  9235. 'model' => $model,
  9236. 'anime_id' => $anime_id,
  9237. 'episode_number' => $episode_number
  9238. ]);
  9239. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  9240. 'type' => $errorType,
  9241. 'model' => $model
  9242. ]);
  9243. yield [
  9244. 'type' => 'error',
  9245. 'episode' => [],
  9246. 'answer' => '',
  9247. 'reasoning' => '',
  9248. 'usage' => [],
  9249. 'error' => '接口返回数据异常,请重新请求'
  9250. ];
  9251. return;
  9252. }
  9253. // 处理流式输出
  9254. foreach ($streamGenerator as $chunk) {
  9255. if (isset($chunk['type'])) {
  9256. if ($chunk['type'] === 'done') {
  9257. // 最终结果
  9258. $fullContent = $chunk['full_content'];
  9259. $fullReasoningContent = $chunk['full_reasoning'];
  9260. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9261. } else {
  9262. // 逐块yield数据
  9263. yield $chunk;
  9264. }
  9265. }
  9266. }
  9267. } catch (\Exception $e) {
  9268. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  9269. 'model' => $model,
  9270. 'anime_id' => $anime_id,
  9271. 'episode_number' => $episode_number,
  9272. 'trace' => $e->getTraceAsString()
  9273. ]);
  9274. logDB('deepseek', 'error', 'chat流式处理失败', [
  9275. 'error' => $e->getMessage(),
  9276. 'model' => $model
  9277. ]);
  9278. yield [
  9279. 'type' => 'error',
  9280. 'episode' => [],
  9281. 'answer' => '',
  9282. 'reasoning' => '',
  9283. 'usage' => [],
  9284. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  9285. ];
  9286. return;
  9287. }
  9288. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  9289. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9290. dLog('deepseek')->info('完整内容: '.$fullContent);
  9291. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  9292. // 处理完整内容并返回最终结果
  9293. $episode_arr = handleEpisodeContentForAce($fullContent);
  9294. dLog('deepseek')->info('解析内容: ', $episode_arr);
  9295. logDB('deepseek', 'info', '解析内容', $episode_arr);
  9296. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  9297. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9298. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9299. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  9300. // }
  9301. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  9302. $max_retries = 3;
  9303. $retry_count = 0;
  9304. $validation_failed = false;
  9305. $validation_error_msg = '';
  9306. // 验证生成的内容
  9307. if ($anime_script_id) {
  9308. // 检查是否有acts数据
  9309. if (empty($episode_arr['acts'])) {
  9310. $validation_failed = true;
  9311. $validation_error_msg = '未生成分镜剧本相关的内容';
  9312. } else {
  9313. // 校验主体列表:不能为空主体(旁白不算)
  9314. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9315. // 过滤掉"旁白"角色
  9316. $generated_roles = array_filter($generated_roles, function($role) {
  9317. return $role !== '旁白';
  9318. });
  9319. if (empty($generated_roles)) {
  9320. $validation_failed = true;
  9321. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9322. }
  9323. // 仅当存在强制主体设定时校验主体列表
  9324. if (!$validation_failed && !empty($extra_roles)) {
  9325. $expected_roles = array_keys($extra_roles);
  9326. // 找出生成的主体中不在预期列表中的主体
  9327. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9328. if (!empty($invalid_roles)) {
  9329. $validation_failed = true;
  9330. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9331. }
  9332. }
  9333. // 仅当存在强制场景设定时校验场景列表
  9334. if (!$validation_failed && !empty($extra_scenes)) {
  9335. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9336. $expected_scenes = array_keys($extra_scenes);
  9337. // 找出生成的场景中不在预期列表中的场景
  9338. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9339. if (!empty($invalid_scenes)) {
  9340. $validation_failed = true;
  9341. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9342. }
  9343. }
  9344. // 仅当存在强制道具设定时校验道具列表
  9345. if (!$validation_failed && !empty($extra_props)) {
  9346. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9347. $expected_props = array_keys($extra_props);
  9348. // 找出生成的道具中不在预期列表中的道具
  9349. $invalid_props = array_diff($generated_props, $expected_props);
  9350. if (!empty($invalid_props)) {
  9351. $validation_failed = true;
  9352. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9353. }
  9354. }
  9355. }
  9356. } else {
  9357. // 如果没有anime_script_id,只检查是否有acts数据
  9358. if (empty($episode_arr['acts'])) {
  9359. $validation_failed = true;
  9360. $validation_error_msg = '未生成分镜剧本相关的内容';
  9361. } else {
  9362. // 校验主体列表:不能为空主体(旁白不算)
  9363. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9364. // 过滤掉"旁白"角色
  9365. $generated_roles = array_filter($generated_roles, function($role) {
  9366. return $role !== '旁白';
  9367. });
  9368. if (empty($generated_roles)) {
  9369. $validation_failed = true;
  9370. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9371. }
  9372. }
  9373. }
  9374. // 重试逻辑
  9375. while ($validation_failed && $retry_count < $max_retries) {
  9376. $retry_count++;
  9377. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  9378. 'reason' => $validation_error_msg,
  9379. 'anime_id' => $anime_id,
  9380. 'episode_number' => $episode_number
  9381. ]);
  9382. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  9383. 'reason' => $validation_error_msg,
  9384. 'anime_id' => $anime_id
  9385. ]);
  9386. // 发送流式重试提示
  9387. yield [
  9388. 'type' => 'retry',
  9389. 'retry_count' => $retry_count,
  9390. 'reason' => $validation_error_msg
  9391. ];
  9392. // 构建重试提示词
  9393. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  9394. if ($anime_script_id) {
  9395. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  9396. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9397. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  9398. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  9399. } else {
  9400. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9401. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  9402. }
  9403. // 添加重试消息到messages
  9404. $messages[] = [
  9405. 'role' => 'assistant',
  9406. 'content' => $fullContent
  9407. ];
  9408. $messages[] = [
  9409. 'role' => 'user',
  9410. 'content' => $retry_prompt
  9411. ];
  9412. // 更新post_data的messages
  9413. $post_data['messages'] = $messages;
  9414. // 重新调用API
  9415. try {
  9416. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9417. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9418. } else if (in_array($model, $this->gpt_text_models)) {
  9419. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9420. } else if (in_array($model, $this->gemini_text_models)) {
  9421. // Gemini 模型使用 Gemini API
  9422. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9423. } else {
  9424. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9425. }
  9426. // 处理流式输出
  9427. $fullContent = '';
  9428. $fullReasoningContent = '';
  9429. foreach ($streamGenerator as $chunk) {
  9430. if (isset($chunk['type'])) {
  9431. if ($chunk['type'] === 'done') {
  9432. $fullContent = $chunk['full_content'];
  9433. $fullReasoningContent = $chunk['full_reasoning'];
  9434. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9435. } else {
  9436. yield $chunk;
  9437. }
  9438. }
  9439. }
  9440. // 重新解析内容
  9441. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9442. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9443. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  9444. $episode_arr = handleEpisodeContentForAce($fullContent);
  9445. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  9446. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9447. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9448. // }
  9449. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  9450. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  9451. // 重新验证
  9452. $validation_failed = false;
  9453. $validation_error_msg = '';
  9454. if ($anime_script_id) {
  9455. if (empty($episode_arr['acts'])) {
  9456. $validation_failed = true;
  9457. $validation_error_msg = '未生成分镜剧本相关的内容';
  9458. } else {
  9459. // 校验主体列表:不能为空主体(旁白不算)
  9460. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9461. // 过滤掉"旁白"角色
  9462. $generated_roles = array_filter($generated_roles, function($role) {
  9463. return $role !== '旁白';
  9464. });
  9465. if (empty($generated_roles)) {
  9466. $validation_failed = true;
  9467. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9468. }
  9469. // 仅当存在强制主体设定时校验主体列表
  9470. if (!$validation_failed && !empty($extra_roles)) {
  9471. $expected_roles = array_keys($extra_roles);
  9472. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9473. if (!empty($invalid_roles)) {
  9474. $validation_failed = true;
  9475. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9476. }
  9477. }
  9478. // 仅当存在强制场景设定时校验场景列表
  9479. if (!$validation_failed && !empty($extra_scenes)) {
  9480. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9481. $expected_scenes = array_keys($extra_scenes);
  9482. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9483. if (!empty($invalid_scenes)) {
  9484. $validation_failed = true;
  9485. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9486. }
  9487. }
  9488. // 仅当存在强制道具设定时校验道具列表
  9489. if (!$validation_failed && !empty($extra_props)) {
  9490. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9491. $expected_props = array_keys($extra_props);
  9492. $invalid_props = array_diff($generated_props, $expected_props);
  9493. if (!empty($invalid_props)) {
  9494. $validation_failed = true;
  9495. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9496. }
  9497. }
  9498. }
  9499. } else {
  9500. if (empty($episode_arr['acts'])) {
  9501. $validation_failed = true;
  9502. $validation_error_msg = '未生成分镜剧本相关的内容';
  9503. } else {
  9504. // 校验主体列表:不能为空主体(旁白不算)
  9505. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9506. // 过滤掉"旁白"角色
  9507. $generated_roles = array_filter($generated_roles, function($role) {
  9508. return $role !== '旁白';
  9509. });
  9510. if (empty($generated_roles)) {
  9511. $validation_failed = true;
  9512. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9513. }
  9514. }
  9515. }
  9516. } catch (\Exception $e) {
  9517. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  9518. 'trace' => $e->getTraceAsString()
  9519. ]);
  9520. break;
  9521. }
  9522. }
  9523. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  9524. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  9525. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  9526. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  9527. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  9528. if ($validation_failed && $retry_count >= $max_retries) {
  9529. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  9530. 'retry_count' => $retry_count,
  9531. 'last_error' => $validation_error_msg
  9532. ]);
  9533. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  9534. 'error' => $validation_error_msg,
  9535. 'anime_id' => $anime_id
  9536. ]);
  9537. $validation_failed = false;
  9538. $validation_error_msg = '';
  9539. }
  9540. // 如果重试后仍然失败
  9541. if ($validation_failed) {
  9542. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  9543. 'retry_count' => $retry_count,
  9544. 'last_error' => $validation_error_msg
  9545. ]);
  9546. try {
  9547. $now = date('Y-m-d H:i:s');
  9548. $records = [
  9549. [
  9550. 'uid' => $uid,
  9551. 'anime_id' => $anime_id,
  9552. 'sequence' => $episode_number,
  9553. 'role' => 'user',
  9554. 'content' => $prompt,
  9555. 'created_at' => $now,
  9556. 'updated_at' => $now
  9557. ],
  9558. [
  9559. 'uid' => $uid,
  9560. 'anime_id' => $anime_id,
  9561. 'sequence' => $episode_number,
  9562. 'role' => 'assistant',
  9563. 'content' => $fullContent,
  9564. 'created_at' => $now,
  9565. 'updated_at' => $now
  9566. ]
  9567. ];
  9568. DB::table('mp_anime_records')->insert($records);
  9569. } catch (\Exception $e) {
  9570. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9571. }
  9572. yield [
  9573. 'type' => 'done',
  9574. 'episode' => [],
  9575. 'answer' => $fullContent,
  9576. 'reasoning' => $fullReasoningContent,
  9577. 'usage' => $usage,
  9578. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  9579. ];
  9580. return;
  9581. }
  9582. // 验证成功,记录日志
  9583. if ($retry_count > 0) {
  9584. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  9585. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  9586. }
  9587. // 老逻辑
  9588. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  9589. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  9590. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  9591. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  9592. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  9593. $existing_props = is_array($existing_props) ? $existing_props : [];
  9594. $now = date('Y-m-d H:i:s');
  9595. try {
  9596. DB::beginTransaction();
  9597. $saveResult = $this->saveEpisodeVersionData(
  9598. $anime_id,
  9599. $episode_number,
  9600. $episode_arr,
  9601. $existing_roles,
  9602. $existing_scenes,
  9603. $existing_props,
  9604. $current_episode,
  9605. $base_episode,
  9606. $is_regenerate_version,
  9607. $content,
  9608. $now,
  9609. $ref_products
  9610. );
  9611. $episode = $saveResult['episode'];
  9612. $episode_id = $saveResult['episode_id'];
  9613. $merged_roles = $saveResult['merged_roles'];
  9614. $merged_scenes = $saveResult['merged_scenes'];
  9615. $merged_props = $saveResult['merged_props'];
  9616. $record_content = $origin_prompt;
  9617. if ($uploaded_content !== '') {
  9618. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  9619. }
  9620. $records = [
  9621. [
  9622. 'uid' => $uid,
  9623. 'anime_id' => $anime_id,
  9624. 'role' => 'user',
  9625. 'content' => $record_content,
  9626. 'sequence' => $episode_number,
  9627. 'episode_id' => $episode_id,
  9628. 'created_at' => $now,
  9629. 'updated_at' => $now
  9630. ],
  9631. [
  9632. 'uid' => $uid,
  9633. 'anime_id' => $anime_id,
  9634. 'role' => 'assistant',
  9635. 'content' => $fullContent,
  9636. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9637. 'sequence' => $episode_number,
  9638. 'episode_id' => $episode_id,
  9639. 'created_at' => $now,
  9640. 'updated_at' => $now
  9641. ]
  9642. ];
  9643. $boolen4 = DB::table('mp_anime_records')->insert($records);
  9644. if (!$boolen4) {
  9645. Utils::throwError('20003:对话记录保存失败');
  9646. }
  9647. // 保存模型到anime表
  9648. $update_anime_data = [
  9649. 'model' => $model,
  9650. 'updated_at' => $now
  9651. ];
  9652. if ($uploaded_content) {
  9653. $update_anime_data['content'] = $uploaded_content;
  9654. }
  9655. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  9656. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  9657. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  9658. 'anime_id' => $anime_id,
  9659. 'episode_number' => $episode_number,
  9660. 'model' => $model,
  9661. ]);
  9662. }catch (\Exception $e) {
  9663. DB::rollBack();
  9664. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  9665. yield [
  9666. 'type' => 'done',
  9667. 'answer' => $fullContent,
  9668. 'reasoning' => $fullReasoningContent,
  9669. 'usage' => $usage,
  9670. 'error' => $e->getMessage(),
  9671. ];
  9672. return;
  9673. }
  9674. DB::commit();
  9675. if ($is_global_generate_pics) {
  9676. // // 批量生成全局角色图片
  9677. // $this->batchSetGlobalRoleImg([
  9678. // 'anime_id' => $anime_id,
  9679. // ], true);
  9680. // // 批量生成全局场景图片
  9681. // $this->batchSetGlobalSceneImg([
  9682. // 'anime_id' => $anime_id,
  9683. // ], true);
  9684. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  9685. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  9686. }
  9687. $episode['episode_id'] = $episode_id;
  9688. $episode['roles'] = $merged_roles;
  9689. $episode['scenes'] = $merged_scenes;
  9690. $episode['props'] = $merged_props;
  9691. $episode['end_episode_sequence'] = $end_episode_sequence;
  9692. // 获取mp_animes表中的视频参数
  9693. $episode['video_params'] = [
  9694. 'video_model' => getProp($anime, 'video_model'),
  9695. 'video_resolution' => getProp($anime, 'video_resolution'),
  9696. 'ratio' => getProp($anime, 'video_ratio'),
  9697. ];
  9698. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9699. yield [
  9700. 'type' => 'done',
  9701. 'episode' => $episode,
  9702. 'answer' => $fullContent,
  9703. 'reasoning' => $fullReasoningContent,
  9704. 'usage' => $usage
  9705. ];
  9706. }
  9707. /**
  9708. * chatForAce的非流式版本 - 用于定时任务
  9709. * 只获取最终 type=done 的数据,并验证必要字段
  9710. *
  9711. * @param array $data 请求数据
  9712. * @return array 生成结果
  9713. */
  9714. public function chatForAceNonStream($data) {
  9715. $finalResult = null;
  9716. // 调用流式方法,只保存 type=done 的数据
  9717. foreach ($this->chatForAce($data) as $chunk) {
  9718. // 只关注最终结果
  9719. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  9720. $finalResult = $chunk;
  9721. break; // 找到 done 就退出循环
  9722. }
  9723. }
  9724. // 验证最终结果
  9725. if (!$finalResult) {
  9726. return ['error' => '生成失败:未获取到最终结果'];
  9727. }
  9728. // 检查是否有错误
  9729. if (isset($finalResult['error']) && $finalResult['error']) {
  9730. return $finalResult;
  9731. }
  9732. // 验证必要字段
  9733. $episode = $finalResult['episode'] ?? [];
  9734. // 验证 roles(旁白不算主体,过滤后不能为空)
  9735. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  9736. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  9737. }
  9738. $nonNarratorRoles = array_filter(array_column($episode['roles'], 'role'), function($role) {
  9739. return $role !== '旁白';
  9740. });
  9741. if (empty($nonNarratorRoles)) {
  9742. return ['error' => '生成失败:主体列表(roles)为空或格式错误(旁白不算)'];
  9743. }
  9744. // 验证 scenes
  9745. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  9746. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  9747. }
  9748. // 验证 props(道具可以为空,但必须存在且为数组)
  9749. if (!isset($episode['props']) || !is_array($episode['props'])) {
  9750. $episode['props'] = [];
  9751. }
  9752. // 验证 acts(分镜剧本)
  9753. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  9754. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  9755. }
  9756. // 更新验证后的 episode 数据
  9757. $finalResult['episode'] = $episode;
  9758. // 记录验证成功日志
  9759. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  9760. 'roles_count' => count($episode['roles']),
  9761. 'scenes_count' => count($episode['scenes']),
  9762. 'props_count' => count($episode['props']),
  9763. 'acts_count' => count($episode['acts'])
  9764. ]);
  9765. return $finalResult;
  9766. }
  9767. /**
  9768. * 批量生成多个分集
  9769. *
  9770. * @param array $data 请求数据
  9771. * @return array 任务信息
  9772. */
  9773. public function batchGenerateEpisodes($data) {
  9774. $uid = Site::getUid();
  9775. $cpid = Site::getCpid();
  9776. $anime_id = getProp($data, 'anime_id');
  9777. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  9778. if (!$anime_id) {
  9779. Utils::throwError('20003:anime_id参数缺失');
  9780. }
  9781. if ($generate_episode_number < 1) {
  9782. Utils::throwError('20003:生成集数必须大于0');
  9783. }
  9784. // 获取动漫信息
  9785. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9786. if (!$anime) {
  9787. Utils::throwError('20003:该剧集不存在');
  9788. }
  9789. // 检查是否是全能模式
  9790. if ((int)getProp($anime, 'ace_mode') !== 1) {
  9791. Utils::throwError('20003:只有全能模式才支持批量生成');
  9792. }
  9793. // 检查是否是多剧集模式
  9794. if ((int)getProp($anime, 'is_multi') !== 1) {
  9795. Utils::throwError('20003:单剧集不支持批量生成');
  9796. }
  9797. // 获取当前已生成的最大集数
  9798. $currentMaxEpisode = DB::table('mp_anime_episodes')
  9799. ->where('anime_id', $anime_id)
  9800. ->where('is_default', 1)
  9801. ->max('episode_number');
  9802. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  9803. // 确定起始集数
  9804. $startEpisodeNumber = $currentMaxEpisode + 1;
  9805. // 计算结束集数
  9806. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  9807. // 检查是否超过总集数限制
  9808. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  9809. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  9810. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  9811. }
  9812. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  9813. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  9814. ->where('anime_id', $anime_id)
  9815. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  9816. ->whereIn('status', ['pending', 'processing', 'completed'])
  9817. ->count();
  9818. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  9819. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  9820. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  9821. if ($needEpisodeCount > 0) {
  9822. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS * $needEpisodeCount, $uid);
  9823. }
  9824. $now = date('Y-m-d H:i:s');
  9825. $createdTasks = [];
  9826. $skippedTasks = [];
  9827. // 为每一集创建详情记录
  9828. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  9829. // 检查是否已有该集的任务记录
  9830. $existingTask = DB::table('mp_batch_episode_generation_details')
  9831. ->where('anime_id', $anime_id)
  9832. ->where('episode_number', $episodeNumber)
  9833. ->first();
  9834. if ($existingTask) {
  9835. // 如果已存在且未完成,跳过
  9836. if (in_array($existingTask->status, ['pending', 'processing'])) {
  9837. $skippedTasks[] = $episodeNumber;
  9838. continue;
  9839. }
  9840. // 如果是失败状态,可以重新创建(删除旧记录)
  9841. if ($existingTask->status === 'failed') {
  9842. DB::table('mp_batch_episode_generation_details')
  9843. ->where('id', $existingTask->id)
  9844. ->delete();
  9845. }
  9846. // 如果是已完成状态,也跳过
  9847. if ($existingTask->status === 'completed') {
  9848. $skippedTasks[] = $episodeNumber;
  9849. continue;
  9850. }
  9851. }
  9852. // 准备任务数据
  9853. $taskData = [
  9854. 'anime_id' => $anime_id,
  9855. 'uid' => $uid,
  9856. 'cpid' => $cpid,
  9857. 'episode_number' => $episodeNumber,
  9858. 'status' => 'pending',
  9859. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  9860. 'retry_count' => 0,
  9861. 'created_at' => $now,
  9862. 'updated_at' => $now
  9863. ];
  9864. // 创建任务记录
  9865. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  9866. if ($taskId) {
  9867. $createdTasks[] = $episodeNumber;
  9868. }
  9869. }
  9870. if (empty($createdTasks)) {
  9871. if (!empty($skippedTasks)) {
  9872. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  9873. } else {
  9874. Utils::throwError('20003:创建批量生成任务失败');
  9875. }
  9876. }
  9877. return [
  9878. 'anime_id' => $anime_id,
  9879. 'start_episode' => $startEpisodeNumber,
  9880. 'end_episode' => $endEpisodeNumber,
  9881. 'total_episodes' => $generate_episode_number,
  9882. 'created_episodes' => $createdTasks,
  9883. 'skipped_episodes' => $skippedTasks,
  9884. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  9885. "已创建: " . implode(',', $createdTasks) .
  9886. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  9887. ];
  9888. }
  9889. /**
  9890. * 获取批量生成任务状态
  9891. *
  9892. * @param array $data 请求数据
  9893. * @return array 任务状态信息
  9894. */
  9895. public function getBatchGenerationTaskStatus($data) {
  9896. $anime_id = getProp($data, 'anime_id');
  9897. if (!$anime_id) {
  9898. Utils::throwError('20003:anime_id参数缺失');
  9899. }
  9900. // 获取该anime的所有任务
  9901. $tasks = DB::table('mp_batch_episode_generation_details')
  9902. ->where('anime_id', $anime_id)
  9903. ->orderBy('episode_number')
  9904. ->get()
  9905. ->map(function($item) {
  9906. return [
  9907. 'id' => $item->id,
  9908. 'episode_number' => $item->episode_number,
  9909. 'status' => $item->status,
  9910. 'error_message' => $item->error_message,
  9911. 'retry_count' => $item->retry_count,
  9912. 'created_at' => $item->created_at,
  9913. 'updated_at' => $item->updated_at,
  9914. 'completed_at' => $item->completed_at
  9915. ];
  9916. })
  9917. ->toArray();
  9918. if (empty($tasks)) {
  9919. Utils::throwError('20003:该剧集没有批量生成任务');
  9920. }
  9921. // 统计各状态数量
  9922. $totalCount = count($tasks);
  9923. $pendingCount = 0;
  9924. $processingCount = 0;
  9925. $completedCount = 0;
  9926. $failedCount = 0;
  9927. $failed_episodes = [];
  9928. foreach ($tasks as $task) {
  9929. switch ($task['status']) {
  9930. case 'pending':
  9931. $pendingCount++;
  9932. break;
  9933. case 'processing':
  9934. $processingCount++;
  9935. break;
  9936. case 'completed':
  9937. $completedCount++;
  9938. break;
  9939. case 'failed':
  9940. $failedCount++;
  9941. // 组装失败分集对象(新对象):分集序号、错误原因
  9942. $failed_episodes[] = [
  9943. 'episode_number' => $task['episode_number'],
  9944. 'error_message' => $task['error_message'] ?? ''
  9945. ];
  9946. break;
  9947. }
  9948. }
  9949. // 计算进度百分比
  9950. $progress = 0;
  9951. if ($totalCount > 0) {
  9952. $progress = round(($completedCount / $totalCount) * 100, 2);
  9953. }
  9954. // 判断整体状态
  9955. $overallStatus = 'processing';
  9956. if ($completedCount === $totalCount) {
  9957. $overallStatus = 'completed';
  9958. } elseif ($pendingCount === $totalCount) {
  9959. $overallStatus = 'pending';
  9960. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  9961. $overallStatus = 'failed';
  9962. }
  9963. return [
  9964. 'anime_id' => $anime_id,
  9965. 'total_episodes' => $totalCount,
  9966. 'pending_count' => $pendingCount,
  9967. 'processing_count' => $processingCount,
  9968. 'completed_count' => $completedCount,
  9969. 'failed_count' => $failedCount,
  9970. 'progress' => $progress,
  9971. 'overall_status' => $overallStatus,
  9972. 'failed_episodes' => $failed_episodes,
  9973. 'tasks' => $tasks
  9974. ];
  9975. }
  9976. /**
  9977. * 将生成内容中不在强制列表中的资源合并进强制列表
  9978. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  9979. *
  9980. * @param array $generated 生成内容中的资源列表
  9981. * @param array $forced 强制资源列表(key为资源名称)
  9982. * @param string $type 资源类型:role、scene、prop
  9983. * @return array
  9984. */
  9985. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  9986. {
  9987. foreach ($generated as $item) {
  9988. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  9989. if ($name === null || $name === '') {
  9990. continue;
  9991. }
  9992. if ($name === '旁白') {
  9993. continue;
  9994. }
  9995. if (!isset($forced[$name])) {
  9996. $forced[$name] = $item;
  9997. }
  9998. }
  9999. return $forced;
  10000. }
  10001. /**
  10002. * 智能匹配并替换主体和场景名称
  10003. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  10004. *
  10005. * @param array $episode_arr 解析后的剧集数据
  10006. * @param array $extra_roles 强制主体设定(key为主体名称)
  10007. * @param array $extra_scenes 强制场景设定(key为场景名称)
  10008. * @return array 替换后的剧集数据
  10009. */
  10010. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  10011. $replaced_count = 0;
  10012. // 1. 处理主体列表
  10013. if (!empty($episode_arr['roles'])) {
  10014. foreach ($episode_arr['roles'] as &$role) {
  10015. $generated_role_name = $role['role'] ?? '';
  10016. // 跳过旁白
  10017. if ($generated_role_name === '旁白') {
  10018. continue;
  10019. }
  10020. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  10021. if (!isset($extra_roles[$generated_role_name])) {
  10022. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  10023. if ($matched_role) {
  10024. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  10025. $role['role'] = $matched_role;
  10026. $replaced_count++;
  10027. }
  10028. }
  10029. }
  10030. }
  10031. // 2. 处理场景列表
  10032. if (!empty($episode_arr['scenes'])) {
  10033. foreach ($episode_arr['scenes'] as &$scene) {
  10034. $generated_scene_name = $scene['scene'] ?? '';
  10035. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  10036. if (!isset($extra_scenes[$generated_scene_name])) {
  10037. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  10038. if ($matched_scene) {
  10039. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  10040. $scene['scene'] = $matched_scene;
  10041. $replaced_count++;
  10042. }
  10043. }
  10044. }
  10045. }
  10046. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  10047. if (!empty($episode_arr['acts'])) {
  10048. foreach ($episode_arr['acts'] as &$act) {
  10049. if (!empty($act['segments'])) {
  10050. foreach ($act['segments'] as &$segment) {
  10051. if (!empty($segment['segment_content'])) {
  10052. $original_content = $segment['segment_content'];
  10053. $replaced_content = $original_content;
  10054. // 替换场景名 - 在文本中查找并替换
  10055. foreach (array_keys($extra_scenes) as $full_scene_name) {
  10056. // 尝试找到可能的短名称
  10057. $potential_short_names = [];
  10058. // 提取场景名的主要部分(冒号之前)
  10059. if (mb_strpos($full_scene_name, ':') !== false) {
  10060. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10061. $potential_short_names[] = $short_name;
  10062. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  10063. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10064. $potential_short_names[] = $short_name;
  10065. }
  10066. // 替换场景字段中的短名称
  10067. foreach ($potential_short_names as $short_name) {
  10068. if ($short_name !== $full_scene_name) {
  10069. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  10070. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  10071. if ($new_content !== $replaced_content) {
  10072. $replaced_content = $new_content;
  10073. $replaced_count++;
  10074. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  10075. }
  10076. }
  10077. }
  10078. }
  10079. // 替换配音角色名(跳过旁白)
  10080. foreach (array_keys($extra_roles) as $full_role_name) {
  10081. if ($full_role_name === '旁白') {
  10082. continue;
  10083. }
  10084. // 尝试找到可能的短名称
  10085. $potential_short_names = [];
  10086. // 提取角色名的主要部分(短横线之前)
  10087. if (mb_strpos($full_role_name, '-') !== false) {
  10088. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  10089. $potential_short_names[] = $short_name;
  10090. }
  10091. // 替换配音台词中的短名称
  10092. foreach ($potential_short_names as $short_name) {
  10093. if ($short_name !== $full_role_name) {
  10094. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  10095. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  10096. if ($new_content !== $replaced_content) {
  10097. $replaced_content = $new_content;
  10098. $replaced_count++;
  10099. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  10100. }
  10101. }
  10102. }
  10103. }
  10104. // 如果有替换,更新segment_content
  10105. if ($replaced_content !== $original_content) {
  10106. $segment['segment_content'] = $replaced_content;
  10107. }
  10108. }
  10109. }
  10110. }
  10111. }
  10112. }
  10113. if ($replaced_count > 0) {
  10114. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  10115. 'replaced_count' => $replaced_count
  10116. ]);
  10117. }
  10118. return $episode_arr;
  10119. }
  10120. /**
  10121. * 查找匹配的名称
  10122. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  10123. *
  10124. * @param string $generated_name 生成的名称
  10125. * @param array $expected_names 预期的名称列表
  10126. * @return string|null 匹配到的名称,如果没有匹配则返回null
  10127. */
  10128. private function findMatchingName($generated_name, $expected_names) {
  10129. if (empty($generated_name)) {
  10130. return null;
  10131. }
  10132. // 尝试精确匹配
  10133. if (in_array($generated_name, $expected_names)) {
  10134. return $generated_name;
  10135. }
  10136. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  10137. foreach ($expected_names as $expected_name) {
  10138. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  10139. if (mb_strpos($expected_name, $generated_name) === 0) {
  10140. return $expected_name;
  10141. }
  10142. }
  10143. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  10144. // 这样可以处理一些变体,但优先级较低
  10145. foreach ($expected_names as $expected_name) {
  10146. if (mb_strpos($expected_name, $generated_name) !== false) {
  10147. return $expected_name;
  10148. }
  10149. }
  10150. return null;
  10151. }
  10152. /**
  10153. * 重新生成分段剧本
  10154. * @param array $data 包含以下字段:
  10155. * - prompt: string|null 用户修改要求(可选)
  10156. * - template_id: int|null 提示词模板ID(可选)
  10157. * - act_id: int|null 单个片段ID(与episode_id二选一)
  10158. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  10159. * @return array 返回生成结果
  10160. */
  10161. public function regenerateSegmentScript($data) {
  10162. $uid = Site::getUid();
  10163. $prompt = trim((string)getProp($data, 'prompt', ''));
  10164. $template_id = getProp($data, 'template_id', 0);
  10165. $act_id = getProp($data, 'act_id', 0);
  10166. $episode_id = getProp($data, 'episode_id', 0);
  10167. // 验证:prompt和template_id至少提供一个
  10168. if (empty($prompt) && empty($template_id)) {
  10169. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  10170. }
  10171. // 验证:act_id和episode_id二选一
  10172. if (empty($act_id) && empty($episode_id)) {
  10173. Utils::throwError('20003:请提供片段ID或剧集ID');
  10174. }
  10175. if (!empty($act_id) && !empty($episode_id)) {
  10176. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  10177. }
  10178. // 积分余额预检(仅剧集ID模式收费)
  10179. if (!empty($episode_id)) {
  10180. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  10181. }
  10182. // 如果提供了template_id,获取模板提示词
  10183. $template_prompt = '';
  10184. if ($template_id > 0) {
  10185. $template = DB::table('mp_prompt_templates')
  10186. ->where('id', $template_id)
  10187. ->where('is_deleted', 0)
  10188. ->first();
  10189. if (!$template) {
  10190. Utils::throwError('20003:提示词模板不存在或已删除');
  10191. }
  10192. $template_prompt = $template->template_prompt ?? '';
  10193. }
  10194. // 合并用户提示词和模板提示词
  10195. $final_prompt = '';
  10196. if (!empty($template_prompt)) {
  10197. $final_prompt = $template_prompt;
  10198. if (!empty($prompt)) {
  10199. $final_prompt .= "\n\n补充要求:" . $prompt;
  10200. }
  10201. } else {
  10202. $final_prompt = $prompt;
  10203. }
  10204. // 获取需要重新生成的内容参考
  10205. $reference_content = '';
  10206. $target_episode_id = 0;
  10207. $target_anime_id = 0;
  10208. $target_episode_number = 0;
  10209. if ($act_id > 0) {
  10210. // 单个片段模式:获取该片段的内容
  10211. $segment = DB::table('mp_episode_segments')
  10212. ->where('id', $act_id)
  10213. ->first();
  10214. if (!$segment) {
  10215. Utils::throwError('20003:片段不存在');
  10216. }
  10217. $target_episode_id = $segment->episode_id;
  10218. $target_anime_id = $segment->anime_id;
  10219. $target_episode_number = $segment->episode_number;
  10220. $reference_content = $segment->act_content ?? '';
  10221. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  10222. } else {
  10223. // 整个剧集模式:获取所有片段的内容
  10224. $segments = DB::table('mp_episode_segments')
  10225. ->where('episode_id', $episode_id)
  10226. ->orderBy('act_number')
  10227. ->get();
  10228. if ($segments->isEmpty()) {
  10229. Utils::throwError('20003:该剧集没有片段数据');
  10230. }
  10231. $target_episode_id = $episode_id;
  10232. $target_anime_id = $segments[0]->anime_id;
  10233. $target_episode_number = $segments[0]->episode_number;
  10234. // 拼接所有片段内容,保留格式用于AI理解
  10235. $act_contents = [];
  10236. foreach ($segments as $seg) {
  10237. $act_number = $seg->act_number;
  10238. $act_content = $seg->act_content ?? '';
  10239. if (!empty($act_content)) {
  10240. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  10241. }
  10242. }
  10243. $reference_content = implode("\n\n", $act_contents);
  10244. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  10245. if ($episode_content) {
  10246. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  10247. }else {
  10248. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  10249. }
  10250. }
  10251. if (empty($reference_content)) {
  10252. Utils::throwError('20003:没有可参考的片段内容');
  10253. }
  10254. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  10255. $episode = DB::table('mp_anime_episodes')
  10256. ->where('id', $target_episode_id)
  10257. ->first();
  10258. if (!$episode) {
  10259. Utils::throwError('20003:剧集不存在');
  10260. }
  10261. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  10262. $anime_script_id = getProp($anime, 'script_id');
  10263. $intro = $episode->intro ?? '';
  10264. $art_style = $episode->art_style ?? '';
  10265. $roles = json_decode($episode->roles ?? '[]', true);
  10266. $scenes = json_decode($episode->scenes ?? '[]', true);
  10267. $props = json_decode($episode->props ?? '[]', true);
  10268. // 构建提示词中的主体列表和场景列表参考
  10269. $roles_ref = '';
  10270. if (!empty($roles) && is_array($roles)) {
  10271. $roles_list = [];
  10272. foreach ($roles as $role) {
  10273. $role_name = getProp($role, 'role', '');
  10274. $role_desc = getProp($role, 'description', '');
  10275. $pic_prompt = getProp($role, 'pic_prompt', '');
  10276. $voice_prompt = getProp($role, 'voice_prompt', '');
  10277. if (!empty($role_name)) {
  10278. $role_line = $role_name;
  10279. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  10280. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  10281. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  10282. $roles_list[] = $role_line;
  10283. }
  10284. }
  10285. if (!empty($roles_list)) {
  10286. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  10287. }
  10288. }
  10289. $scenes_ref = '';
  10290. if (!empty($scenes) && is_array($scenes)) {
  10291. $scenes_list = [];
  10292. foreach ($scenes as $scene) {
  10293. $scene_name = getProp($scene, 'scene', '');
  10294. $scene_desc = getProp($scene, 'description', '');
  10295. $pic_prompt = getProp($scene, 'pic_prompt', '');
  10296. if (!empty($scene_name)) {
  10297. $scene_line = $scene_name;
  10298. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  10299. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  10300. $scenes_list[] = $scene_line;
  10301. }
  10302. }
  10303. if (!empty($scenes_list)) {
  10304. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  10305. }
  10306. }
  10307. $props_ref = '';
  10308. if (!empty($props) && is_array($props)) {
  10309. $props_list = [];
  10310. foreach ($props as $prop) {
  10311. $prop_name = getProp($prop, 'prop', '');
  10312. $prop_desc = getProp($prop, 'description', '');
  10313. $pic_prompt = getProp($prop, 'pic_prompt', '');
  10314. if (!empty($prop_name)) {
  10315. $prop_line = $prop_name;
  10316. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  10317. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  10318. $props_list[] = $prop_line;
  10319. }
  10320. }
  10321. if (!empty($props_list)) {
  10322. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  10323. }
  10324. }
  10325. // 构建美术风格参考
  10326. $art_style_ref = '';
  10327. if (!empty($art_style)) {
  10328. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  10329. }
  10330. // 构建内容简介参考
  10331. $intro_ref = '';
  10332. if (!empty($intro)) {
  10333. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  10334. }
  10335. // 构建完整的AI提示词
  10336. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  10337. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  10338. $user_prompt .= $intro_ref;
  10339. $user_prompt .= $art_style_ref;
  10340. $user_prompt .= $reference_content;
  10341. // $user_prompt .= $roles_ref;
  10342. // $user_prompt .= $scenes_ref;
  10343. $system_prompt = "\n\n【强制要求】\n";
  10344. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  10345. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  10346. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  10347. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  10348. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  10349. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  10350. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  10351. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  10352. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  10353. ###分段剧本
  10354. 片段数量:8
  10355. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10356. ##片段1
  10357. 时长:12s
  10358. 分镜1
  10359. 出场角色:刀疤脸
  10360. 场景:边境小镇街道
  10361. 出场道具:酒杯-高脚杯
  10362. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10363. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10364. 配音台词:
  10365. 背景音效:
  10366. 分镜2
  10367. 出场角色:刀疤脸
  10368. 场景:悦来酒馆
  10369. 出场道具:酒杯-高脚杯
  10370. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10371. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10372. 配音台词:
  10373. 背景音效:
  10374. 分镜3
  10375. 出场角色:刀疤脸
  10376. 场景:悦来酒馆
  10377. 出场道具:酒杯-高脚杯
  10378. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10379. 运镜:从中景推向令牌特写。
  10380. 配音台词:
  10381. 背景音效:
  10382. 分镜4
  10383. 出场角色:刀疤脸
  10384. 场景:悦来酒馆
  10385. 出场道具:酒杯-高脚杯
  10386. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10387. 运镜:极速推向酒水溅起的瞬间。
  10388. 配音台词:
  10389. 背景音效:
  10390. 分镜5
  10391. 出场角色:刀疤脸
  10392. 场景:悦来酒馆
  10393. 出场道具:酒杯-高脚杯
  10394. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10395. 运镜:固定机位,利用倾斜构图制造压迫感。
  10396. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10397. 背景音效:";
  10398. // 获取模型配置
  10399. $model = getProp($data, 'model');
  10400. if (!$model) {
  10401. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  10402. }
  10403. // 验证模型是否在可用模型表中
  10404. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10405. $model = 'deepseek-v4-pro';
  10406. }
  10407. // 模型兼容性处理
  10408. $thinkingMode = 'disabled';
  10409. $reasoningEffort = 'high';
  10410. if ($model === 'deepseek-chat') {
  10411. $model = 'deepseek-v4-flash';
  10412. $thinkingMode = 'disabled';
  10413. } elseif ($model === 'deepseek-reasoner') {
  10414. $model = 'deepseek-v4-flash';
  10415. $thinkingMode = 'enabled';
  10416. }
  10417. // 构建消息
  10418. $messages = [
  10419. [
  10420. 'role' => 'system',
  10421. 'content' => $system_prompt
  10422. ],
  10423. [
  10424. 'role' => 'user',
  10425. 'content' => $user_prompt
  10426. ]
  10427. ];
  10428. // dd($messages);
  10429. // 构建请求参数
  10430. $post_data = [
  10431. 'model' => $model,
  10432. 'messages' => $messages,
  10433. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  10434. 'frequency_penalty' => 0,
  10435. 'presence_penalty' => 0,
  10436. 'response_format' => ['type' => 'text'],
  10437. 'thinking' => ['type' => $thinkingMode],
  10438. 'stream' => false // 非流式输出
  10439. ];
  10440. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  10441. // 调用AI生成新的分段剧本
  10442. try {
  10443. $fullContent = '';
  10444. $usage = [];
  10445. // 根据模型类型选择调用方法
  10446. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10447. // DeepSeek 官方模型使用 DeepSeek API
  10448. $chatResult = $this->chatOnly($post_data);
  10449. } else if (in_array($model, $this->gpt_text_models)) {
  10450. // GPT 模型使用 TokenRouter API
  10451. $chatResult = $this->gpt54ChatOnly($post_data);
  10452. } else {
  10453. // 其他模型使用火山引擎API
  10454. $chatResult = $this->volcEngineChatCompletion($post_data);
  10455. }
  10456. if (is_array($chatResult)) {
  10457. $fullContent = $chatResult['fullContent'] ?? '';
  10458. $usage = $chatResult['usage'] ?? [];
  10459. }
  10460. $generated_content = $fullContent;
  10461. if (empty($generated_content)) {
  10462. Utils::throwError('20003:AI生成内容为空,请重试');
  10463. }
  10464. // 解析生成的内容 - 按片段分割
  10465. $parsed_segments = [];
  10466. // 先在开头添加换行符,确保第1片段也能被正确分割
  10467. $normalizedText = "\n" . $generated_content;
  10468. $parts = preg_split('/\n\s*##/', $normalizedText);
  10469. foreach ($parts as $part) {
  10470. $part = trim($part);
  10471. if (empty($part)) continue;
  10472. // 匹配"片段X"格式
  10473. if (!preg_match('/^片段\d+/', $part)) {
  10474. continue;
  10475. }
  10476. // 分离标题和内容
  10477. $lines = explode("\n", $part, 2);
  10478. $actTitle = trim($lines[0]);
  10479. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  10480. // 解析标题,提取序号
  10481. $actNumber = 0;
  10482. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  10483. $actNumber = intval($segmentTitleMatch[1]);
  10484. } else {
  10485. $actNumber = count($parsed_segments) + 1;
  10486. }
  10487. // 提取时长(仅保留数字)
  10488. $actDuration = 0;
  10489. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  10490. $actDurationStr = trim($actDurationMatch[1]);
  10491. // 提取数字部分(支持整数和小数)
  10492. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  10493. $actDuration = (float)$numMatch[1];
  10494. }
  10495. }
  10496. // 清理act_content:去除时长、旁白音色等非分镜内容行
  10497. // 只保留分镜内容,并确保分镜标记使用【】格式
  10498. $cleaned_content = '';
  10499. $content_lines = explode("\n", $actContent);
  10500. $is_capturing = false; // 标记是否开始捕获分镜内容
  10501. $count = 0;
  10502. foreach ($content_lines as $line) {
  10503. $trimmed_line = trim($line);
  10504. // 跳过时长和旁白音色行
  10505. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  10506. continue;
  10507. }
  10508. // 检测是否是分镜开始
  10509. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  10510. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  10511. $count++;
  10512. $is_capturing = true;
  10513. // 如果没有【】,则添加
  10514. if (!preg_match('/^【/u', $trimmed_line)) {
  10515. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  10516. }
  10517. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  10518. }
  10519. // 如果已经开始捕获,则添加该行
  10520. if ($is_capturing && !empty($trimmed_line)) {
  10521. $cleaned_content .= $trimmed_line."\n";
  10522. }
  10523. }
  10524. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  10525. $parsed_segments[] = [
  10526. 'act_number' => $actNumber,
  10527. 'act_title' => $actTitle,
  10528. 'act_duration' => $actDuration,
  10529. 'act_content' => $cleaned_content,
  10530. ];
  10531. }
  10532. if (empty($parsed_segments)) {
  10533. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  10534. }
  10535. // 收集所有资产名称(角色、场景、道具)
  10536. $product_names = [];
  10537. // 收集角色名称
  10538. if (!empty($roles) && is_array($roles)) {
  10539. foreach ($roles as $role) {
  10540. $role_name = getProp($role, 'role', '');
  10541. if (!empty($role_name)) {
  10542. $product_names[] = $role_name;
  10543. }
  10544. }
  10545. }
  10546. // 收集场景名称
  10547. if (!empty($scenes) && is_array($scenes)) {
  10548. foreach ($scenes as $scene) {
  10549. $scene_name = getProp($scene, 'scene', '');
  10550. if (!empty($scene_name)) {
  10551. $product_names[] = $scene_name;
  10552. }
  10553. }
  10554. }
  10555. // 收集道具名称
  10556. if (!empty($props) && is_array($props)) {
  10557. foreach ($props as $prop) {
  10558. $prop_name = getProp($prop, 'prop', '');
  10559. if (!empty($prop_name)) {
  10560. $product_names[] = $prop_name;
  10561. }
  10562. }
  10563. }
  10564. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  10565. $product_names = array_unique($product_names);
  10566. usort($product_names, function($a, $b) {
  10567. return mb_strlen($b) - mb_strlen($a);
  10568. });
  10569. // 处理每个片段的 act_show_content
  10570. foreach ($parsed_segments as &$segment) {
  10571. $act_content = getProp($segment, 'act_content', '');
  10572. if (empty($act_content)) {
  10573. $segment['act_show_content'] = '';
  10574. continue;
  10575. }
  10576. $processed_content = $act_content;
  10577. // 统一替换所有资产名称为 {资产名} 格式
  10578. // 使用占位符避免嵌套替换问题
  10579. $placeholder_map = [];
  10580. $placeholder_index = 0;
  10581. foreach ($product_names as $product_name) {
  10582. // 转义特殊字符
  10583. $escaped_product = preg_quote($product_name, '/');
  10584. // 检查是否匹配且未被 {} 包裹
  10585. $processed_content = preg_replace_callback(
  10586. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  10587. function($matches) use (&$placeholder_map, &$placeholder_index) {
  10588. // 使用唯一占位符
  10589. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  10590. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  10591. $placeholder_index++;
  10592. return $placeholder;
  10593. },
  10594. $processed_content
  10595. );
  10596. }
  10597. // 将所有占位符替换回实际内容
  10598. foreach ($placeholder_map as $placeholder => $replacement) {
  10599. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  10600. }
  10601. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  10602. $shot_counter = 0;
  10603. $processed_content = preg_replace_callback(
  10604. '/【(?:镜头|分镜)(\d+)】/u',
  10605. function($matches) use (&$shot_counter) {
  10606. $shot_counter++;
  10607. return '【镜头' . $shot_counter . '】';
  10608. },
  10609. $processed_content
  10610. );
  10611. $segment['act_show_content'] = $processed_content;
  10612. }
  10613. unset($segment); // 解除引用
  10614. // 保存到数据库
  10615. $now = date('Y-m-d H:i:s');
  10616. $saved_acts = []; // 用于记录保存后的片段信息
  10617. if ($act_id > 0) {
  10618. // 单个片段模式:更新单条记录
  10619. if (count($parsed_segments) > 0) {
  10620. $new_segment = $parsed_segments[0];
  10621. $update_data = [
  10622. 'act_content' => getProp($new_segment, 'act_content', ''),
  10623. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  10624. 'act_title' => getProp($new_segment, 'act_title', ''),
  10625. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  10626. 'updated_at' => $now,
  10627. ];
  10628. DB::table('mp_episode_segments')
  10629. ->where('id', $act_id)
  10630. ->update($update_data);
  10631. // 获取更新后的记录
  10632. $updated_act = DB::table('mp_episode_segments')
  10633. ->where('id', $act_id)
  10634. ->first();
  10635. if ($updated_act) {
  10636. $saved_acts[] = [
  10637. 'act_id' => $updated_act->id,
  10638. 'act_number' => $updated_act->act_number,
  10639. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  10640. 'act_content' => $updated_act->act_content,
  10641. 'act_show_content' => $updated_act->act_show_content,
  10642. 'video_url' => $updated_act->video_url ?? '',
  10643. 'video_duration' => $updated_act->video_duration ?? 0,
  10644. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  10645. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  10646. ];
  10647. }
  10648. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  10649. }
  10650. } else {
  10651. // 整个剧集模式:删除原有记录并批量保存新记录
  10652. DB::beginTransaction();
  10653. try {
  10654. // 删除原有的所有片段记录
  10655. DB::table('mp_episode_segments')
  10656. ->where('episode_id', $target_episode_id)
  10657. ->delete();
  10658. // 批量插入新的片段记录
  10659. $segments_to_insert = [];
  10660. foreach ($parsed_segments as $index => $segment) {
  10661. $act_number = $index + 1;
  10662. $segments_to_insert[] = [
  10663. 'anime_id' => $target_anime_id,
  10664. 'episode_id' => $target_episode_id,
  10665. 'episode_number' => $target_episode_number,
  10666. 'act_number' => $act_number,
  10667. 'act_title' => getProp($segment, 'act_title', ''),
  10668. 'act_duration' => getProp($segment, 'act_duration', 0),
  10669. 'act_content' => getProp($segment, 'act_content', ''),
  10670. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  10671. 'created_at' => $now,
  10672. 'updated_at' => $now,
  10673. ];
  10674. }
  10675. if (!empty($segments_to_insert)) {
  10676. DB::table('mp_episode_segments')->insert($segments_to_insert);
  10677. }
  10678. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  10679. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  10680. 'anime_id' => $target_anime_id,
  10681. 'episode_id' => $target_episode_id,
  10682. ]);
  10683. DB::commit();
  10684. // 查询保存后的所有片段记录
  10685. $saved_segments = DB::table('mp_episode_segments')
  10686. ->where('episode_id', $target_episode_id)
  10687. ->orderBy('act_number')
  10688. ->get();
  10689. foreach ($saved_segments as $saved_segment) {
  10690. $saved_acts[] = [
  10691. 'act_id' => $saved_segment->id,
  10692. 'act_number' => $saved_segment->act_number,
  10693. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  10694. 'act_content' => $saved_segment->act_content,
  10695. 'act_show_content' => $saved_segment->act_show_content,
  10696. 'video_url' => $saved_segment->video_url ?? '',
  10697. 'video_duration' => $saved_segment->video_duration ?? 0,
  10698. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  10699. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  10700. ];
  10701. }
  10702. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  10703. 'episode_id' => $target_episode_id,
  10704. 'segments_count' => count($segments_to_insert)
  10705. ]);
  10706. } catch (\Exception $e) {
  10707. DB::rollBack();
  10708. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  10709. Utils::throwError('20003:保存失败,请重试');
  10710. }
  10711. }
  10712. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  10713. return [
  10714. 'anime_id' => $target_anime_id,
  10715. 'episode_id' => $target_episode_id,
  10716. 'title' => getProp($episode, 'title', ''),
  10717. 'episode_number' => $target_episode_number,
  10718. 'is_generated' => getProp($episode, 'is_generated', 0),
  10719. 'acts' => $saved_acts,
  10720. ];
  10721. } catch (\Exception $e) {
  10722. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  10723. throw $e;
  10724. }
  10725. }
  10726. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  10727. {
  10728. $episode_arr = [
  10729. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  10730. 'intro' => getProp($script_arr, 'intro'),
  10731. 'art_style' => getProp($script_arr, 'art_style'),
  10732. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  10733. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  10734. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  10735. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  10736. ];
  10737. if (empty($episode_arr['acts'])) {
  10738. $fallback_episode_arr = handleEpisodeContent($fullContent);
  10739. if (!empty($fallback_episode_arr['acts'])) {
  10740. $episode_arr = array_merge($fallback_episode_arr, [
  10741. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  10742. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  10743. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  10744. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  10745. ]);
  10746. }
  10747. }
  10748. // if (!getProp($episode_arr, 'episode_title')) {
  10749. // $episode_title = '';
  10750. // $episodes = getProp($script_arr, 'episodes', []);
  10751. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  10752. // $episode_title = '第1集:' . $episodes[0]['title'];
  10753. // }
  10754. // if (!$episode_title) {
  10755. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  10756. // }
  10757. // $episode_arr['episode_title'] = $episode_title;
  10758. // }
  10759. return $episode_arr;
  10760. }
  10761. private function saveEpisodeVersionData(
  10762. int $anime_id,
  10763. int $episode_number,
  10764. array $episode_arr,
  10765. array $existing_roles,
  10766. array $existing_scenes,
  10767. array $existing_props,
  10768. $current_episode,
  10769. $base_episode,
  10770. bool $is_regenerate_version,
  10771. string $content,
  10772. string $now,
  10773. array $ref_products = []
  10774. ): array {
  10775. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  10776. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  10777. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  10778. // 过滤掉关键字段为空的条目
  10779. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  10780. return !empty($item['role'] ?? null);
  10781. }));
  10782. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  10783. return !empty($item['scene'] ?? null);
  10784. }));
  10785. $merged_props = array_values(array_filter($generated_props, function ($item) {
  10786. return !empty($item['prop'] ?? null);
  10787. }));
  10788. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  10789. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  10790. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  10791. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10792. $ace_mode = getProp($anime, 'ace_mode');
  10793. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  10794. $global_roles = json_decode(getProp($anime, 'roles'), true);
  10795. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  10796. $global_roles = is_array($global_roles) ? $global_roles : [];
  10797. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  10798. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  10799. $art_style_type = getProp($anime, 'art_style_type');
  10800. // 检查并创建 roles 的图片生成任务
  10801. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  10802. // 检查并创建 scenes 的图片生成任务
  10803. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  10804. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  10805. if ($arr && is_array($arr)) {
  10806. $merged_roles = $arr['roles'];
  10807. $merged_scenes = $arr['scenes'];
  10808. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  10809. }
  10810. // 确保数据是数组类型
  10811. if (!is_array($merged_roles)) {
  10812. dLog('deepseek')->error('merged_roles不是数组类型', [
  10813. 'type' => gettype($merged_roles),
  10814. 'value' => $merged_roles
  10815. ]);
  10816. $merged_roles = [];
  10817. }
  10818. if (!is_array($merged_scenes)) {
  10819. dLog('deepseek')->error('merged_scenes不是数组类型', [
  10820. 'type' => gettype($merged_scenes),
  10821. 'value' => $merged_scenes
  10822. ]);
  10823. $merged_scenes = [];
  10824. }
  10825. if (!is_array($merged_props)) {
  10826. dLog('deepseek')->error('merged_props不是数组类型', [
  10827. 'type' => gettype($merged_props),
  10828. 'value' => $merged_props
  10829. ]);
  10830. $merged_props = [];
  10831. }
  10832. // 同步新出现的主体和场景到全局
  10833. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  10834. $role_arr = [];
  10835. foreach ($merged_roles as $item) {
  10836. $role_arr[$item['role']] = $item;
  10837. }
  10838. $version_count = DB::table('mp_anime_episodes')
  10839. ->where('anime_id', $anime_id)
  10840. ->where('episode_number', $episode_number)
  10841. ->count('id');
  10842. $episode = [
  10843. 'anime_id' => $anime_id,
  10844. 'episode_number' => $episode_number,
  10845. 'title' => getProp($episode_arr, 'episode_title'),
  10846. 'content' => $content,
  10847. 'intro' => getProp($episode_arr, 'intro'),
  10848. 'art_style' => getProp($episode_arr, 'art_style'),
  10849. 'roles' => json_encode($merged_roles, 256),
  10850. 'scenes' => json_encode($merged_scenes, 256),
  10851. 'props' => json_encode($merged_props, 256),
  10852. 'generate_status' => '待执行',
  10853. 'generate_at' => $now,
  10854. 'is_default' => 1,
  10855. 'updated_at' => $now,
  10856. ];
  10857. $del_flag = false;
  10858. if ($is_regenerate_version) {
  10859. DB::table('mp_anime_episodes')
  10860. ->where('anime_id', $anime_id)
  10861. ->where('episode_number', $episode_number)
  10862. ->update(['is_default' => 0, 'updated_at' => $now]);
  10863. $episode['sequence'] = $version_count + 1;
  10864. $episode['created_at'] = $now;
  10865. $episode['cpid'] = Site::getCpid();
  10866. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  10867. if (!$episode_id) {
  10868. Utils::throwError('20003:创建剧集版本失败');
  10869. }
  10870. } else {
  10871. $target_episode = $current_episode ?: $base_episode;
  10872. if ($target_episode) {
  10873. $episode_id = getProp($target_episode, 'id');
  10874. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  10875. DB::table('mp_anime_episodes')
  10876. ->where('anime_id', $anime_id)
  10877. ->where('episode_number', $episode_number)
  10878. ->where('id', '<>', $episode_id)
  10879. ->update(['is_default' => 0, 'updated_at' => $now]);
  10880. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  10881. if ($boolen === false) {
  10882. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10883. Utils::throwError('20003:分集内容保存失败');
  10884. }
  10885. $del_flag = true;
  10886. } else {
  10887. DB::table('mp_anime_episodes')
  10888. ->where('anime_id', $anime_id)
  10889. ->where('episode_number', $episode_number)
  10890. ->update(['is_default' => 0, 'updated_at' => $now]);
  10891. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  10892. $episode['created_at'] = $now;
  10893. $episode['cpid'] = Site::getCpid();
  10894. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  10895. if (!$episode_id) {
  10896. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  10897. Utils::throwError('20003:分集内容保存失败');
  10898. }
  10899. }
  10900. }
  10901. $segments = [];
  10902. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  10903. // 如果是第2集及以后,获取上一集的主体音色数据
  10904. $previous_roles_voice = [];
  10905. if ($episode_number >= 2) {
  10906. $previous_episode = DB::table('mp_anime_episodes')
  10907. ->where('anime_id', $anime_id)
  10908. ->where('episode_number', $episode_number - 1)
  10909. ->where('is_default', 1)
  10910. ->first();
  10911. if ($previous_episode) {
  10912. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  10913. if (is_array($previous_roles)) {
  10914. foreach ($previous_roles as $prev_role) {
  10915. $role_name = getProp($prev_role, 'role');
  10916. if ($role_name) {
  10917. $previous_roles_voice[$role_name] = [
  10918. 'voice_name' => getProp($prev_role, 'voice_name'),
  10919. 'voice_type' => getProp($prev_role, 'voice_type'),
  10920. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  10921. ];
  10922. $voice_prompt = getProp($prev_role, 'voice_prompt');
  10923. if ($voice_prompt) {
  10924. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  10925. }
  10926. }
  10927. }
  10928. }
  10929. }
  10930. }
  10931. // 将继承的音色数据同步到当前集的主体列表
  10932. if (!empty($previous_roles_voice)) {
  10933. foreach ($merged_roles as &$role) {
  10934. $role_name = getProp($role, 'role');
  10935. if ($role_name && isset($previous_roles_voice[$role_name])) {
  10936. // 强制继承上一集的音色数据
  10937. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  10938. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  10939. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  10940. // 如果上一集有 voice_prompt 则继承,否则跳过
  10941. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  10942. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  10943. }
  10944. }
  10945. }
  10946. unset($role); // 解除引用
  10947. // 更新 role_arr 以便后续使用
  10948. $role_arr = [];
  10949. foreach ($merged_roles as $item) {
  10950. $role_arr[$item['role']] = $item;
  10951. }
  10952. }
  10953. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  10954. $emotion_list = array_flip($emotion_list);
  10955. foreach ($acts as $act) {
  10956. $act_segments = getProp($act, 'segments', []);
  10957. if (!is_array($act_segments)) {
  10958. continue;
  10959. }
  10960. if ((int)$ace_mode === 1) {
  10961. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  10962. $merged_parts = [];
  10963. foreach ($act_segments as $seg) {
  10964. $seg_num = getProp($seg, 'segment_number');
  10965. $seg_content = getProp($seg, 'segment_content');
  10966. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  10967. }
  10968. $act_content = implode("\n", $merged_parts);
  10969. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  10970. $segments[] = [
  10971. 'anime_id' => $anime_id,
  10972. 'episode_id' => $episode_id,
  10973. 'episode_number' => $episode_number,
  10974. 'act_number' => getProp($act, 'act_number'),
  10975. 'act_title' => getProp($act, 'act_title'),
  10976. 'act_duration' => getProp($act, 'act_duration'),
  10977. 'act_content' => $act_content,
  10978. 'created_at' => $now,
  10979. 'updated_at' => $now
  10980. ];
  10981. } else {
  10982. foreach ($act_segments as $segment) {
  10983. $voice_actor = getProp($segment, 'voice_actor');
  10984. // 优先从上一集继承音色数据
  10985. $timbre_info = [];
  10986. if (isset($previous_roles_voice[$voice_actor])) {
  10987. // 从上一集继承音色数据
  10988. $timbre_info = $previous_roles_voice[$voice_actor];
  10989. } elseif (isset($role_arr[$voice_actor])) {
  10990. // 使用当前集的主体音色数据
  10991. $timbre_info = $role_arr[$voice_actor];
  10992. }
  10993. $voice_type = getProp($timbre_info, 'voice_type');
  10994. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  10995. if ($timbre_emotion) {
  10996. $timbre_emotion = explode(',', $timbre_emotion);
  10997. } else {
  10998. $timbre_emotion = [];
  10999. }
  11000. $emotion = getProp($segment, 'emotion', '中性');
  11001. if (!in_array($emotion, $timbre_emotion)) {
  11002. $emotion = '中性';
  11003. }
  11004. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  11005. $segments[] = [
  11006. 'anime_id' => $anime_id,
  11007. 'episode_id' => $episode_id,
  11008. 'episode_number' => $episode_number,
  11009. 'act_number' => getProp($act, 'act_number'),
  11010. 'act_title' => getProp($act, 'act_title'),
  11011. 'act_duration' => getProp($act, 'act_duration'),
  11012. 'segment_id' => getProp($segment, 'segment_id'),
  11013. 'segment_number' => getProp($segment, 'segment_number'),
  11014. 'segment_content' => getProp($segment, 'segment_content'),
  11015. 'description' => getProp($segment, 'description'),
  11016. 'composition' => getProp($segment, 'composition'),
  11017. 'camera_movement' => getProp($segment, 'camera_movement'),
  11018. 'voice_actor' => $voice_actor,
  11019. 'dialogue' => getProp($segment, 'dialogue'),
  11020. 'frame_type' => getProp($segment, 'frame_type'),
  11021. 'scene' => getProp($segment, 'scene'),
  11022. 'characters' => getProp($segment, 'characters'),
  11023. 'tail_frame' => getProp($segment, 'tail_frame'),
  11024. 'voice_name' => getProp($timbre_info, 'voice_name'),
  11025. 'voice_type' => $voice_type,
  11026. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  11027. 'emotion' => $emotion,
  11028. 'emotion_type' => $emotion_type,
  11029. 'gender' => getProp($segment, 'gender', '0'),
  11030. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  11031. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  11032. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  11033. 'pitch' => getProp($segment, 'pitch', 0),
  11034. 'created_at' => $now,
  11035. 'updated_at' => $now
  11036. ];
  11037. }
  11038. }
  11039. }
  11040. if ($segments) {
  11041. if ($del_flag) {
  11042. DB::table('mp_episode_segments')
  11043. ->where('anime_id', $anime_id)
  11044. ->where('episode_id', $episode_id)
  11045. ->delete();
  11046. }
  11047. $boolen = DB::table('mp_episode_segments')->insert($segments);
  11048. if (!$boolen) {
  11049. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  11050. Utils::throwError('20003:分镜内容保存失败');
  11051. }
  11052. }
  11053. dLog('deepseek')->info('segments', $segments);
  11054. // ace_mode=1: acts 返回值按合并格式调整
  11055. if ((int)$ace_mode === 1) {
  11056. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  11057. $act_map = [];
  11058. foreach ($table_act_data as $item) {
  11059. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  11060. }
  11061. $restructured_acts = [];
  11062. foreach ($acts as $act) {
  11063. $act_segments = getProp($act, 'segments', []);
  11064. if (!is_array($act_segments)) {
  11065. continue;
  11066. }
  11067. $merged_parts = [];
  11068. foreach ($act_segments as $seg) {
  11069. $seg_num = getProp($seg, 'segment_number');
  11070. $seg_content = getProp($seg, 'segment_content');
  11071. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  11072. }
  11073. $act_content = implode("\n", $merged_parts);
  11074. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  11075. $restructured_acts[] = [
  11076. 'anime_id' => $anime_id,
  11077. 'episode_id' => $episode_id,
  11078. 'episode_number' => $episode_number,
  11079. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  11080. 'act_number' => getProp($act, 'act_number'),
  11081. 'act_title' => getProp($act, 'act_title'),
  11082. 'act_duration' => getProp($act, 'act_duration'),
  11083. 'act_content' => $act_content,
  11084. 'created_at' => $now,
  11085. 'updated_at' => $now,
  11086. ];
  11087. }
  11088. $acts = $restructured_acts;
  11089. }
  11090. $episode['episode_id'] = $episode_id;
  11091. $episode['roles'] = $merged_roles;
  11092. $episode['scenes'] = $merged_scenes;
  11093. $episode['props'] = $merged_props;
  11094. $episode['acts'] = $acts;
  11095. return [
  11096. 'episode' => $episode,
  11097. 'episode_id' => $episode_id,
  11098. 'merged_roles' => $merged_roles,
  11099. 'merged_scenes' => $merged_scenes,
  11100. 'merged_props' => $merged_props,
  11101. ];
  11102. }
  11103. private function buildEpisodeItemContent(array $items, string $nameKey): string
  11104. {
  11105. $content = '';
  11106. foreach ($items as $item) {
  11107. $name = trim((string)getProp($item, $nameKey));
  11108. if ($name === '' || $name === '旁白') {
  11109. continue;
  11110. }
  11111. $description = trim((string)getProp($item, 'description'));
  11112. $content .= $name . ': ' . $description;
  11113. if ($nameKey == 'role') {
  11114. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  11115. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11116. $voice_name = trim(getProp($item, 'voice_name'));
  11117. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  11118. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  11119. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  11120. }else {
  11121. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  11122. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11123. }
  11124. $content .= "\n";
  11125. }
  11126. return trim($content);
  11127. }
  11128. private function getEpisodeChatContent($animeId, $sequence, $content) {
  11129. if ((int)$sequence <= 0) {
  11130. return [];
  11131. }
  11132. $origin_content = '';
  11133. if ($content) {
  11134. $origin_content = '本集剧情内容:'.$content;
  11135. }else {
  11136. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  11137. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  11138. }
  11139. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  11140. // 获取分集信息
  11141. $episode = DB::table('mp_anime_episodes')
  11142. ->where('anime_id', $animeId)
  11143. ->where('episode_number', $sequence)
  11144. ->where('is_default', 1)
  11145. ->first();
  11146. if (!$episode) {
  11147. return [];
  11148. }
  11149. $episode_id = getProp($episode, 'id');
  11150. $episode_number = getProp($episode, 'episode_number');
  11151. $title = getProp($episode, 'title');
  11152. $intro = getProp($episode, 'intro');
  11153. $art_style = getProp($episode, 'art_style');
  11154. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  11155. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  11156. // 组装纯文本内容
  11157. $content = '';
  11158. // 添加分集标题和梗概
  11159. $content .= "###第{$episode_number}集:{$title}\n\n";
  11160. $content .= "###故事梗概\n";
  11161. $content .= trim($intro) . "\n\n";
  11162. // 添加美术风格
  11163. $content .= "###美术风格\n";
  11164. $content .= trim($art_style) . "\n\n";
  11165. // 添加主体列表
  11166. $content .= "###主体列表\n";
  11167. $pangbai_voice_prompt = "";
  11168. foreach ($roles as $role) {
  11169. $name = getProp($role, 'role');
  11170. $description = getProp($role, 'description');
  11171. $pic_prompt = getProp($role, 'pic_prompt');
  11172. $voice_prompt = getProp($role, 'voice_prompt');
  11173. $voice_name = getProp($role, 'voice_name');
  11174. $content .= "{$name}: {$description}";
  11175. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11176. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  11177. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  11178. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  11179. $content .= "\n";
  11180. }
  11181. $content .= "\n";
  11182. // 添加场景列表
  11183. $content .= "###场景列表\n";
  11184. foreach ($scenes as $scene) {
  11185. $name = getProp($scene, 'scene');
  11186. $description = getProp($scene, 'description');
  11187. $pic_prompt = getProp($scene, 'pic_prompt');
  11188. $content .= "{$name}: {$description}";
  11189. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11190. $content .= "\n";
  11191. }
  11192. $content .= "\n";
  11193. // 获取分镜信息
  11194. $segments = DB::table('mp_episode_segments')
  11195. ->where('anime_id', $animeId)
  11196. ->where('episode_id', $episode_id)
  11197. ->orderBy('segment_number')
  11198. ->get();
  11199. if ($segments && count($segments) > 0) {
  11200. if ((int)$ace_mode === 1) {
  11201. $content .= "###分段剧本\n";
  11202. // 获取片段数量
  11203. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  11204. $content .= "片段数量:{$act_count}\n";
  11205. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  11206. $content .= "\n";
  11207. }else {
  11208. $content .= "###分镜剧本\n";
  11209. }
  11210. // 按幕分组
  11211. $currentAct = null;
  11212. foreach ($segments as $segment) {
  11213. $act_number = getProp($segment, 'act_number');
  11214. $act_title = getProp($segment, 'act_title');
  11215. $act_duration = getProp($segment, 'act_duration');
  11216. $segment_number = getProp($segment, 'segment_number');
  11217. $segment_content = getProp($segment, 'segment_content');
  11218. $scene_description = getProp($segment, 'scene_description');
  11219. $scene_name = getProp($segment, 'scene_name');
  11220. $composition = getProp($segment, 'composition');
  11221. $camera_movement = getProp($segment, 'camera_movement');
  11222. $voice_type = getProp($segment, 'voice_type');
  11223. $characters = getProp($segment, 'characters');
  11224. $dialogue = getProp($segment, 'dialogue');
  11225. $frame_type = getProp($segment, 'frame_type');
  11226. $tail_frame_description = getProp($segment, 'tail_frame_description');
  11227. // 判断是否是全能模式
  11228. if ((int)$ace_mode === 1) { // 全能模式
  11229. // 如果是新的分段,添加分段标题
  11230. if ($act_number !== $currentAct) {
  11231. $currentAct = $act_number;
  11232. $content .= "##{$act_title}\n";
  11233. $content .= "时长:{$act_duration}s\n";
  11234. }
  11235. }else {
  11236. // 如果是新的幕,添加幕标题
  11237. if ($act_number !== $currentAct) {
  11238. $currentAct = $act_number;
  11239. $content .= "##第{$act_number}幕:{$scene_name}\n";
  11240. }
  11241. }
  11242. // 添加分镜信息
  11243. $content .= "分镜{$segment_number}\n";
  11244. $content .= "分镜内容:\n{$segment_content}\n";
  11245. // $content .= "画面描述:{$scene_description}\n";
  11246. // $content .= "场景:{$scene_name}\n";
  11247. // $content .= "构图设计:{$composition}\n";
  11248. // $content .= "运镜调度:{$camera_movement}\n";
  11249. // if (!empty($voice_type)) {
  11250. // $content .= "配音角色:{$voice_type}\n";
  11251. // }
  11252. // if (!empty($characters)) {
  11253. // $content .= "出镜角色:{$characters}\n";
  11254. // }
  11255. // if (!empty($dialogue)) {
  11256. // $content .= "台词内容:\"{$dialogue}\"\n";
  11257. // }
  11258. // $content .= "画面类型:{$frame_type}\n";
  11259. // $content .= "尾帧描述:{$tail_frame_description}\n";
  11260. $content .= "\n";
  11261. }
  11262. }
  11263. $content = trim($content);
  11264. if($content) $content = "上集剧本内容:\n{$content}";
  11265. return [
  11266. [
  11267. 'role' => 'user',
  11268. 'content' => $origin_content
  11269. ],
  11270. [
  11271. 'role' => 'assistant',
  11272. 'content' => $content
  11273. ]
  11274. ];
  11275. }
  11276. private function getEpisodeChatMessages($animeId, $sequence): array
  11277. {
  11278. if ((int)$sequence <= 0) {
  11279. return [];
  11280. }
  11281. return DB::table('mp_anime_records')
  11282. ->where('anime_id', $animeId)
  11283. ->where('sequence', $sequence)
  11284. ->where('episode_id', '>', 0)
  11285. ->select('role', 'content')
  11286. ->orderBy('created_at')
  11287. ->orderBy('id')
  11288. ->get()
  11289. ->map(function ($value) {
  11290. return (array)$value;
  11291. })
  11292. ->toArray();
  11293. }
  11294. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  11295. {
  11296. $existingMap = [];
  11297. foreach ($existingItems as $item) {
  11298. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11299. if ($itemKey === '') {
  11300. continue;
  11301. }
  11302. $existingMap[$itemKey] = $item;
  11303. }
  11304. if (!$generatedItems) {
  11305. return array_values($existingItems);
  11306. }
  11307. $merged = [];
  11308. foreach ($generatedItems as $item) {
  11309. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11310. if ($itemKey === '') {
  11311. continue;
  11312. }
  11313. if (isset($existingMap[$itemKey])) {
  11314. if (trim((string)getProp($item, 'description')) === '') {
  11315. $merged[] = $existingMap[$itemKey];
  11316. continue;
  11317. }
  11318. // 检查内容是否发生变化
  11319. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  11320. if (!$isChanged) {
  11321. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  11322. $mergedItem = [
  11323. $nameKey => trim((string)getProp($item, $nameKey)),
  11324. 'description' => trim((string)getProp($item, 'description')),
  11325. ];
  11326. // 如果有 pic_prompt,添加到合并项中
  11327. $picPrompt = getProp($item, 'pic_prompt');
  11328. if (!empty($picPrompt)) {
  11329. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  11330. }
  11331. // 继承现有项的 URL
  11332. $existingUrl = getProp($existingMap[$itemKey], 'url');
  11333. if (!empty($existingUrl)) {
  11334. $mergedItem['url'] = $existingUrl;
  11335. }
  11336. // 继承现有项的 task_id
  11337. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  11338. if (!empty($existingTaskId)) {
  11339. $mergedItem['task_id'] = $existingTaskId;
  11340. }
  11341. // 继承现有项的 task_status
  11342. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  11343. if (!empty($existingTaskStatus)) {
  11344. $mergedItem['task_status'] = $existingTaskStatus;
  11345. }
  11346. // 保留生成项的音色字段
  11347. $voiceName = getProp($item, 'voice_name');
  11348. if (!empty($voiceName)) {
  11349. $mergedItem['voice_name'] = $voiceName;
  11350. }
  11351. $voiceType = getProp($item, 'voice_type');
  11352. if (!empty($voiceType)) {
  11353. $mergedItem['voice_type'] = $voiceType;
  11354. }
  11355. $audioUrl = getProp($item, 'voice_audio_url');
  11356. if (!empty($audioUrl)) {
  11357. $mergedItem['voice_audio_url'] = $audioUrl;
  11358. }
  11359. $merged[] = $mergedItem;
  11360. } else {
  11361. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  11362. $mergedItem = [
  11363. $nameKey => trim((string)getProp($item, $nameKey)),
  11364. 'description' => trim((string)getProp($item, 'description')),
  11365. ];
  11366. // 如果有 pic_prompt,添加到合并项中
  11367. $picPrompt = getProp($item, 'pic_prompt');
  11368. if (!empty($picPrompt)) {
  11369. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  11370. }
  11371. // 保留生成项的音色字段
  11372. $voiceName = getProp($item, 'voice_name');
  11373. if (!empty($voiceName)) {
  11374. $mergedItem['voice_name'] = $voiceName;
  11375. }
  11376. $voiceType = getProp($item, 'voice_type');
  11377. if (!empty($voiceType)) {
  11378. $mergedItem['voice_type'] = $voiceType;
  11379. }
  11380. $audioUrl = getProp($item, 'voice_audio_url');
  11381. if (!empty($audioUrl)) {
  11382. $mergedItem['voice_audio_url'] = $audioUrl;
  11383. }
  11384. // 不继承 URL、task_id 和 task_status(重置状态)
  11385. $merged[] = $mergedItem;
  11386. }
  11387. } else {
  11388. // 新增项,保留生成项的所有字段
  11389. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  11390. }
  11391. }
  11392. return $merged ?: array_values($existingItems);
  11393. }
  11394. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  11395. {
  11396. $resetItem = [
  11397. $nameKey => trim((string)getProp($item, $nameKey)),
  11398. 'description' => trim((string)getProp($item, 'description')),
  11399. ];
  11400. // 保留指定的字段
  11401. foreach ($preserveFields as $field) {
  11402. $value = getProp($item, $field);
  11403. if (!empty($value)) {
  11404. $resetItem[$field] = $value;
  11405. }
  11406. }
  11407. return $resetItem;
  11408. }
  11409. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  11410. {
  11411. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  11412. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  11413. if ($existingKey !== $generatedKey) {
  11414. return true;
  11415. }
  11416. // 比较 description 是否变化
  11417. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  11418. return true;
  11419. }
  11420. // 比较 pic_prompt 是否变化
  11421. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  11422. }
  11423. private function normalizeEpisodeResourceKey($value): string
  11424. {
  11425. $value = trim((string)$value);
  11426. if ($value === '') {
  11427. return '';
  11428. }
  11429. return strtolower((string)preg_replace('/\s+/u', '', $value));
  11430. }
  11431. // 生成全局角色图片
  11432. private function batchSetGlobalRoleImg($data, $is_force=false) {
  11433. $anime_id = getProp($data, 'anime_id');
  11434. if (!$anime_id) Utils::throwError('1002:请选择对话');
  11435. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11436. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11437. $art_style = getProp($anime, 'art_style');
  11438. $update_flag = false;
  11439. foreach ($roles as &$role) {
  11440. $role_name = getProp($role, 'role');
  11441. if ($role_name == '旁白') continue;
  11442. // 优先使用 pic_prompt,如果没有则使用 description
  11443. $pic_prompt = getProp($role, 'pic_prompt');
  11444. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  11445. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  11446. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  11447. // 参考图地址
  11448. $ref_img_url = getProp($role, 'url');
  11449. if (!$is_force && $ref_img_url) continue;
  11450. $update_flag = true;
  11451. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  11452. try {
  11453. $params = [
  11454. 'prompt' => $description,
  11455. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  11456. 'ref_img_urls' => []
  11457. ];
  11458. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11459. $task_id = $task->id;
  11460. if (!$task_id) {
  11461. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  11462. }
  11463. $role['task_id'] = $task_id;
  11464. $role['task_status'] = 'processing';
  11465. } catch (\Exception $e) {
  11466. Utils::throwError("20003:" . $e->getMessage());
  11467. }
  11468. }
  11469. if (!$update_flag) return true;
  11470. // 保存角色信息
  11471. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  11472. 'roles' => json_encode($roles, 256),
  11473. 'generate_status' => '执行中',
  11474. 'generate_at' => date('Y-m-d H:i:s'),
  11475. 'updated_at' => date('Y-m-d H:i:s')
  11476. ]);
  11477. if (!$boolen) {
  11478. Utils::throwError('20003:保存角色信息失败');
  11479. }
  11480. return $boolen;
  11481. }
  11482. // 生成全局场景图片
  11483. private function batchSetGlobalSceneImg($data, $is_force=false) {
  11484. $anime_id = getProp($data, 'anime_id');
  11485. if (!$anime_id) Utils::throwError('1002:请选择对话');
  11486. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11487. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11488. $art_style = getProp($anime, 'art_style');
  11489. $update_flag = false;
  11490. foreach ($scenes as &$scene) {
  11491. $scene_name = getProp($scene, 'scene');
  11492. // 优先使用 pic_prompt,如果没有则使用 description
  11493. $pic_prompt = getProp($scene, 'pic_prompt');
  11494. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  11495. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  11496. // 参考图地址
  11497. $ref_img_url = getProp($scene, 'url');
  11498. if (!$is_force && $ref_img_url) continue;
  11499. $update_flag = true;
  11500. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  11501. try {
  11502. $params = [
  11503. 'prompt' => $description,
  11504. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  11505. 'ref_img_urls' => []
  11506. ];
  11507. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11508. $task_id = $task->id;
  11509. if (!$task_id) {
  11510. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  11511. }
  11512. $scene['task_id'] = $task_id;
  11513. $scene['task_status'] = 'processing';
  11514. } catch (\Exception $e) {
  11515. Utils::throwError("20003:" . $e->getMessage());
  11516. }
  11517. }
  11518. if (!$update_flag) return true;
  11519. // 保存角色信息
  11520. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  11521. 'scenes' => json_encode($scenes, 256),
  11522. 'generate_status' => '执行中',
  11523. 'generate_at' => date('Y-m-d H:i:s'),
  11524. 'updated_at' => date('Y-m-d H:i:s')
  11525. ]);
  11526. if (!$boolen) {
  11527. Utils::throwError('20003:保存角色信息失败');
  11528. }
  11529. return $boolen;
  11530. }
  11531. // 生成分镜主体、场景和道具图片
  11532. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  11533. $character_prefix = '';
  11534. $scene_prefix = '';
  11535. $prop_prefix = '';
  11536. if ($art_style_type) {
  11537. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  11538. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  11539. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  11540. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  11541. }
  11542. $update_flag = false;
  11543. // 获取上一集的roles、scenes和props数据
  11544. $prev_roles = [];
  11545. $prev_scenes = [];
  11546. $prev_props = [];
  11547. if ($episode_number > 1) {
  11548. $prev_episode = DB::table('mp_anime_episodes')
  11549. ->where('anime_id', $anime_id)
  11550. ->where('episode_number', $episode_number - 1)
  11551. ->where('is_default', 1)
  11552. ->first();
  11553. if ($prev_episode) {
  11554. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  11555. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  11556. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  11557. dLog('deepseek')->info("获取上一集数据成功", [
  11558. 'anime_id' => $anime_id,
  11559. 'prev_episode_number' => $episode_number - 1,
  11560. 'prev_roles_count' => count($prev_roles),
  11561. 'prev_scenes_count' => count($prev_scenes),
  11562. 'prev_props_count' => count($prev_props)
  11563. ]);
  11564. }
  11565. }
  11566. // 处理角色图片生成
  11567. foreach ($roles as &$role) {
  11568. $role_name = getProp($role, 'role');
  11569. if ($role_name == '旁白') continue;
  11570. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  11571. if (isset($ref_products[$role_name])) {
  11572. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  11573. if ($role['url']) continue;
  11574. }
  11575. $role_description = getProp($role, 'description');
  11576. $role_pic_prompt = getProp($role, 'pic_prompt');
  11577. $role_url = getProp($role, 'url');
  11578. // 检查是否可以从上一集继承
  11579. $inherited = false;
  11580. if (!$is_force && !empty($prev_roles)) {
  11581. foreach ($prev_roles as $prev_role) {
  11582. $prev_role_name = getProp($prev_role, 'role');
  11583. $prev_description = getProp($prev_role, 'description');
  11584. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  11585. $prev_url = getProp($prev_role, 'url');
  11586. $prev_task_id = getProp($prev_role, 'task_id');
  11587. $prev_task_status = getProp($prev_role, 'task_status');
  11588. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  11589. if ($role_name == $prev_role_name
  11590. && $role_description == $prev_description
  11591. && $role_pic_prompt == $prev_pic_prompt
  11592. && !empty($prev_url)) {
  11593. $role['task_id'] = $prev_task_id;
  11594. $role['task_status'] = $prev_task_status;
  11595. $role['url'] = $prev_url;
  11596. $inherited = true;
  11597. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  11598. 'anime_id' => $anime_id,
  11599. 'episode_number' => $episode_number,
  11600. 'task_id' => $prev_task_id,
  11601. 'url' => $prev_url
  11602. ]);
  11603. break;
  11604. }
  11605. }
  11606. }
  11607. // 如果已继承或已有url,跳过生成
  11608. if ($inherited || (!$is_force && $role_url)) {
  11609. continue;
  11610. }
  11611. // 优先使用 pic_prompt,如果没有则使用 description
  11612. $pic_prompt = getProp($role, 'pic_prompt');
  11613. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  11614. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11615. $update_flag = true;
  11616. // 调用AIImageGenerationService的生成图片任务接口
  11617. try {
  11618. $params = [
  11619. 'prompt' => $description,
  11620. 'ref_img_urls' => []
  11621. ];
  11622. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11623. $task_id = $task->id;
  11624. if (!$task_id) {
  11625. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  11626. continue; // 不中断,继续处理其他角色
  11627. }
  11628. $role['task_id'] = $task_id;
  11629. $role['task_status'] = 'processing';
  11630. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  11631. 'anime_id' => $anime_id,
  11632. 'episode_number' => $episode_number,
  11633. 'task_id' => $task_id
  11634. ]);
  11635. } catch (\Exception $e) {
  11636. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  11637. // 不抛出异常,继续处理其他角色
  11638. }
  11639. }
  11640. // 处理场景图片生成
  11641. foreach ($scenes as &$scene) {
  11642. $scene_name = getProp($scene, 'scene');
  11643. $scene_description = getProp($scene, 'description');
  11644. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  11645. $scene_url = getProp($scene, 'url');
  11646. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  11647. if (isset($ref_products[$scene_name])) {
  11648. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  11649. if ($scene['url']) continue;
  11650. }
  11651. // 检查是否可以从上一集继承
  11652. $inherited = false;
  11653. if (!$is_force && !empty($prev_scenes)) {
  11654. foreach ($prev_scenes as $prev_scene) {
  11655. $prev_scene_name = getProp($prev_scene, 'scene');
  11656. $prev_description = getProp($prev_scene, 'description');
  11657. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  11658. $prev_url = getProp($prev_scene, 'url');
  11659. $prev_task_id = getProp($prev_scene, 'task_id');
  11660. $prev_task_status = getProp($prev_scene, 'task_status');
  11661. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  11662. if ($scene_name == $prev_scene_name
  11663. && $scene_description == $prev_description
  11664. && $scene_pic_prompt == $prev_pic_prompt
  11665. && !empty($prev_url)) {
  11666. $scene['task_id'] = $prev_task_id;
  11667. $scene['task_status'] = $prev_task_status;
  11668. $scene['url'] = $prev_url;
  11669. $inherited = true;
  11670. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  11671. 'anime_id' => $anime_id,
  11672. 'episode_number' => $episode_number,
  11673. 'task_id' => $prev_task_id,
  11674. 'url' => $prev_url
  11675. ]);
  11676. break;
  11677. }
  11678. }
  11679. }
  11680. // 如果已继承或已有url,跳过生成
  11681. if ($inherited || (!$is_force && $scene_url)) {
  11682. continue;
  11683. }
  11684. // 优先使用 pic_prompt,如果没有则使用 description
  11685. $pic_prompt = getProp($scene, 'pic_prompt');
  11686. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  11687. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11688. $update_flag = true;
  11689. // 调用AIImageGenerationService的生成图片任务接口
  11690. try {
  11691. $params = [
  11692. 'prompt' => $description,
  11693. 'ref_img_urls' => []
  11694. ];
  11695. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11696. $task_id = $task->id;
  11697. if (!$task_id) {
  11698. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  11699. continue; // 不中断,继续处理其他场景
  11700. }
  11701. $scene['task_id'] = $task_id;
  11702. $scene['task_status'] = 'processing';
  11703. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  11704. 'anime_id' => $anime_id,
  11705. 'episode_number' => $episode_number,
  11706. 'task_id' => $task_id
  11707. ]);
  11708. } catch (\Exception $e) {
  11709. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  11710. // 不抛出异常,继续处理其他场景
  11711. }
  11712. }
  11713. // 处理道具图片生成(逻辑与场景一致)
  11714. foreach ($props as &$prop) {
  11715. $prop_name = getProp($prop, 'prop');
  11716. $prop_description = getProp($prop, 'description');
  11717. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  11718. $prop_url = getProp($prop, 'url');
  11719. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  11720. if (isset($ref_products[$prop_name])) {
  11721. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  11722. if ($prop['url']) continue;
  11723. }
  11724. // 检查是否可以从上一集继承
  11725. $inherited = false;
  11726. if (!$is_force && !empty($prev_props)) {
  11727. foreach ($prev_props as $prev_prop) {
  11728. $prev_prop_name = getProp($prev_prop, 'prop');
  11729. $prev_description = getProp($prev_prop, 'description');
  11730. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  11731. $prev_url = getProp($prev_prop, 'url');
  11732. $prev_task_id = getProp($prev_prop, 'task_id');
  11733. $prev_task_status = getProp($prev_prop, 'task_status');
  11734. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  11735. if ($prop_name == $prev_prop_name
  11736. && $prop_description == $prev_description
  11737. && $prop_pic_prompt == $prev_pic_prompt
  11738. && !empty($prev_url)) {
  11739. $prop['task_id'] = $prev_task_id;
  11740. $prop['task_status'] = $prev_task_status;
  11741. $prop['url'] = $prev_url;
  11742. $inherited = true;
  11743. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  11744. 'anime_id' => $anime_id,
  11745. 'episode_number' => $episode_number,
  11746. 'task_id' => $prev_task_id,
  11747. 'url' => $prev_url
  11748. ]);
  11749. break;
  11750. }
  11751. }
  11752. }
  11753. // 如果已继承或已有url,跳过生成
  11754. if ($inherited || (!$is_force && $prop_url)) {
  11755. continue;
  11756. }
  11757. // 优先使用 pic_prompt,如果没有则使用 description
  11758. $pic_prompt = getProp($prop, 'pic_prompt');
  11759. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  11760. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11761. $update_flag = true;
  11762. // 调用AIImageGenerationService的生成图片任务接口
  11763. try {
  11764. $params = [
  11765. 'prompt' => $description,
  11766. 'ref_img_urls' => []
  11767. ];
  11768. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11769. $task_id = $task->id;
  11770. if (!$task_id) {
  11771. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  11772. continue; // 不中断,继续处理其他道具
  11773. }
  11774. $prop['task_id'] = $task_id;
  11775. $prop['task_status'] = 'processing';
  11776. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  11777. 'anime_id' => $anime_id,
  11778. 'episode_number' => $episode_number,
  11779. 'task_id' => $task_id
  11780. ]);
  11781. } catch (\Exception $e) {
  11782. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  11783. // 不抛出异常,继续处理其他道具
  11784. }
  11785. }
  11786. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11787. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  11788. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  11789. // // 保存剧集的角色和场景信息
  11790. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  11791. // 'roles' => json_encode($roles, 256),
  11792. // 'scenes' => json_encode($scenes, 256),
  11793. // 'generate_status' => '执行中',
  11794. // 'generate_at' => date('Y-m-d H:i:s'),
  11795. // 'updated_at' => date('Y-m-d H:i:s')
  11796. // ]);
  11797. // if (!$boolen) {
  11798. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  11799. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  11800. // }
  11801. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  11802. // 'episode_id' => $episode_id,
  11803. 'roles_count' => count($roles),
  11804. 'scenes_count' => count($scenes),
  11805. 'props_count' => count($props)
  11806. ]);
  11807. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11808. }
  11809. /**
  11810. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  11811. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  11812. *
  11813. * @param int $anime_id 动漫对话ID
  11814. * @param array $episode_roles 剧集角色数据
  11815. * @param array $episode_scenes 剧集场景数据
  11816. * @param array $episode_props 剧集道具数据
  11817. * @return bool
  11818. */
  11819. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  11820. // 获取全局数据
  11821. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11822. if (!$anime) {
  11823. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  11824. return false;
  11825. }
  11826. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11827. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11828. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  11829. $roles_added = false;
  11830. $roles_updated = false;
  11831. $scenes_added = false;
  11832. $props_added = false;
  11833. // 处理角色同步
  11834. foreach ($episode_roles as $episode_role) {
  11835. $episode_role_name = getProp($episode_role, 'role');
  11836. $episode_description = getProp($episode_role, 'description');
  11837. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  11838. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  11839. // 跳过旁白
  11840. if ($episode_role_name == '旁白') {
  11841. continue;
  11842. }
  11843. // 检查全局中是否已存在相同的角色
  11844. $exists = false;
  11845. $global_role_index = -1;
  11846. foreach ($global_roles as $index => $global_role) {
  11847. $global_role_name = getProp($global_role, 'role');
  11848. $global_description = getProp($global_role, 'description');
  11849. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  11850. // 如果role、description、pic_prompt三项都一致,则认为已存在
  11851. if ($episode_role_name == $global_role_name
  11852. && $episode_description == $global_description
  11853. && $episode_pic_prompt == $global_pic_prompt) {
  11854. $exists = true;
  11855. $global_role_index = $index;
  11856. break;
  11857. }
  11858. }
  11859. // 如果不存在,则添加到全局
  11860. if (!$exists) {
  11861. $global_roles[] = $episode_role;
  11862. $roles_added = true;
  11863. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  11864. 'anime_id' => $anime_id,
  11865. 'role' => $episode_role_name
  11866. ]);
  11867. } else {
  11868. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  11869. if (!empty($episode_voice_prompt)) {
  11870. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  11871. // 如果全局没有voice_prompt或与剧集不一致,则更新
  11872. if ($global_voice_prompt !== $episode_voice_prompt) {
  11873. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  11874. $roles_updated = true;
  11875. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  11876. 'anime_id' => $anime_id,
  11877. 'role' => $episode_role_name,
  11878. 'voice_prompt' => $episode_voice_prompt
  11879. ]);
  11880. }
  11881. }
  11882. }
  11883. }
  11884. // 处理场景同步
  11885. foreach ($episode_scenes as $episode_scene) {
  11886. $episode_scene_name = getProp($episode_scene, 'scene');
  11887. $episode_description = getProp($episode_scene, 'description');
  11888. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  11889. // 检查全局中是否已存在相同的场景
  11890. $exists = false;
  11891. foreach ($global_scenes as $global_scene) {
  11892. $global_scene_name = getProp($global_scene, 'scene');
  11893. $global_description = getProp($global_scene, 'description');
  11894. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  11895. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  11896. if ($episode_scene_name == $global_scene_name
  11897. && $episode_description == $global_description
  11898. && $episode_pic_prompt == $global_pic_prompt) {
  11899. $exists = true;
  11900. break;
  11901. }
  11902. }
  11903. // 如果不存在,则添加到全局
  11904. if (!$exists) {
  11905. $global_scenes[] = $episode_scene;
  11906. $scenes_added = true;
  11907. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  11908. 'anime_id' => $anime_id,
  11909. 'scene' => $episode_scene_name
  11910. ]);
  11911. }
  11912. }
  11913. // 处理道具同步(逻辑与场景一致)
  11914. foreach ($episode_props as $episode_prop) {
  11915. $episode_prop_name = getProp($episode_prop, 'prop');
  11916. $episode_description = getProp($episode_prop, 'description');
  11917. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  11918. // 检查全局中是否已存在相同的道具
  11919. $exists = false;
  11920. foreach ($global_props as $global_prop) {
  11921. $global_prop_name = getProp($global_prop, 'prop');
  11922. $global_description = getProp($global_prop, 'description');
  11923. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  11924. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  11925. if ($episode_prop_name == $global_prop_name
  11926. && $episode_description == $global_description
  11927. && $episode_pic_prompt == $global_pic_prompt) {
  11928. $exists = true;
  11929. break;
  11930. }
  11931. }
  11932. // 如果不存在,则添加到全局
  11933. if (!$exists) {
  11934. $global_props[] = $episode_prop;
  11935. $props_added = true;
  11936. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  11937. 'anime_id' => $anime_id,
  11938. 'prop' => $episode_prop_name
  11939. ]);
  11940. }
  11941. }
  11942. // 如果有新增或更新,则更新全局数据
  11943. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  11944. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  11945. if ($roles_added || $roles_updated) {
  11946. $update_data['roles'] = json_encode($global_roles, 256);
  11947. }
  11948. if ($scenes_added) {
  11949. $update_data['scenes'] = json_encode($global_scenes, 256);
  11950. }
  11951. if ($props_added) {
  11952. $update_data['props'] = json_encode($global_props, 256);
  11953. }
  11954. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11955. dLog('deepseek')->info('剧集数据同步到全局完成', [
  11956. 'anime_id' => $anime_id,
  11957. 'roles_added' => $roles_added,
  11958. 'roles_updated' => $roles_updated,
  11959. 'scenes_added' => $scenes_added,
  11960. 'props_added' => $props_added,
  11961. 'global_roles_count' => count($global_roles),
  11962. 'global_scenes_count' => count($global_scenes),
  11963. 'global_props_count' => count($global_props)
  11964. ]);
  11965. }
  11966. return true;
  11967. }
  11968. /**
  11969. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  11970. *
  11971. * @param int $anime_id 动漫对话ID
  11972. * @param int $episode_id 分集ID
  11973. * @return bool
  11974. */
  11975. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  11976. // 获取全局角色和场景数据
  11977. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11978. if (!$anime) {
  11979. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  11980. return false;
  11981. }
  11982. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11983. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11984. // 获取指定的分集
  11985. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  11986. if (!$episode) {
  11987. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  11988. return false;
  11989. }
  11990. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  11991. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  11992. $roles_updated = false;
  11993. $scenes_updated = false;
  11994. // 继承角色的task_id、task_status和url
  11995. foreach ($episode_roles as &$episode_role) {
  11996. $episode_role_name = getProp($episode_role, 'role');
  11997. $episode_description = getProp($episode_role, 'description');
  11998. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  11999. $episode_url = getProp($episode_role, 'url');
  12000. // 跳过旁白角色
  12001. if ($episode_role_name == '旁白') {
  12002. continue;
  12003. }
  12004. // 如果剧集中已有URL,跳过
  12005. if (!empty($episode_url)) {
  12006. continue;
  12007. }
  12008. // 遍历全局角色数据,查找匹配的角色
  12009. foreach ($global_roles as $global_role) {
  12010. $global_role_name = getProp($global_role, 'role');
  12011. $global_description = getProp($global_role, 'description');
  12012. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  12013. $global_url = getProp($global_role, 'url');
  12014. $global_task_id = getProp($global_role, 'task_id');
  12015. $global_task_status = getProp($global_role, 'task_status');
  12016. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12017. if ($episode_role_name == $global_role_name
  12018. && $episode_description == $global_description
  12019. && $episode_pic_prompt == $global_pic_prompt) {
  12020. // 继承 task_id、task_status 和 url
  12021. if (!empty($global_task_id)) {
  12022. $episode_role['task_id'] = $global_task_id;
  12023. $episode_role['task_status'] = $global_task_status;
  12024. $roles_updated = true;
  12025. dLog('deepseek')->info('剧集角色继承全局task_id', [
  12026. 'episode_id' => $episode_id,
  12027. 'role' => $episode_role_name,
  12028. 'task_id' => $global_task_id,
  12029. 'task_status' => $global_task_status
  12030. ]);
  12031. }
  12032. if (!empty($global_url)) {
  12033. $episode_role['url'] = $global_url;
  12034. $roles_updated = true;
  12035. dLog('deepseek')->info('剧集角色继承全局url', [
  12036. 'episode_id' => $episode_id,
  12037. 'role' => $episode_role_name,
  12038. 'url' => $global_url
  12039. ]);
  12040. }
  12041. break;
  12042. }
  12043. }
  12044. }
  12045. // 继承场景的task_id、task_status和url
  12046. foreach ($episode_scenes as &$episode_scene) {
  12047. $episode_scene_name = getProp($episode_scene, 'scene');
  12048. $episode_description = getProp($episode_scene, 'description');
  12049. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  12050. $episode_url = getProp($episode_scene, 'url');
  12051. // 如果剧集中已有URL,跳过
  12052. if (!empty($episode_url)) {
  12053. continue;
  12054. }
  12055. // 遍历全局场景数据,查找匹配的场景
  12056. foreach ($global_scenes as $global_scene) {
  12057. $global_scene_name = getProp($global_scene, 'scene');
  12058. $global_description = getProp($global_scene, 'description');
  12059. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  12060. $global_url = getProp($global_scene, 'url');
  12061. $global_task_id = getProp($global_scene, 'task_id');
  12062. $global_task_status = getProp($global_scene, 'task_status');
  12063. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12064. if ($episode_scene_name == $global_scene_name
  12065. && $episode_description == $global_description
  12066. && $episode_pic_prompt == $global_pic_prompt) {
  12067. // 继承 task_id、task_status 和 url
  12068. if (!empty($global_task_id)) {
  12069. $episode_scene['task_id'] = $global_task_id;
  12070. $episode_scene['task_status'] = $global_task_status;
  12071. $scenes_updated = true;
  12072. dLog('deepseek')->info('剧集场景继承全局task_id', [
  12073. 'episode_id' => $episode_id,
  12074. 'scene' => $episode_scene_name,
  12075. 'task_id' => $global_task_id,
  12076. 'task_status' => $global_task_status
  12077. ]);
  12078. }
  12079. if (!empty($global_url)) {
  12080. $episode_scene['url'] = $global_url;
  12081. $scenes_updated = true;
  12082. dLog('deepseek')->info('剧集场景继承全局url', [
  12083. 'episode_id' => $episode_id,
  12084. 'scene' => $episode_scene_name,
  12085. 'url' => $global_url
  12086. ]);
  12087. }
  12088. break;
  12089. }
  12090. }
  12091. }
  12092. // 如果有更新,则保存到数据库
  12093. if ($roles_updated || $scenes_updated) {
  12094. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  12095. if ($roles_updated) {
  12096. $update_data['roles'] = json_encode($episode_roles, 256);
  12097. }
  12098. if ($scenes_updated) {
  12099. $update_data['scenes'] = json_encode($episode_scenes, 256);
  12100. }
  12101. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  12102. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  12103. 'episode_id' => $episode_id,
  12104. 'roles_updated' => $roles_updated,
  12105. 'scenes_updated' => $scenes_updated
  12106. ]);
  12107. }
  12108. return true;
  12109. }
  12110. public function chatChangeImg($data) {
  12111. $segment = getProp($data, 'segment');
  12112. $segment_content = getProp($segment, 'segment_content');
  12113. $prompt = getProp($data, 'prompt');
  12114. $ref_img = getProp($data, 'ref_img');
  12115. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  12116. // 处理文本模型
  12117. $model = getProp($data, 'model');
  12118. if (!$model) {
  12119. // 用户没有输入,从anime表获取
  12120. $segment_id = getProp($segment, 'segment_id');
  12121. if ($segment_id) {
  12122. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  12123. if ($episode_id) {
  12124. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  12125. if ($anime_id) {
  12126. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  12127. }
  12128. }
  12129. }
  12130. if (!$model) {
  12131. // anime表也没有,使用默认值
  12132. $model = 'doubao-seed-2-0-mini-260215';
  12133. }
  12134. }
  12135. // 验证模型是否在可用模型表中
  12136. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  12137. $model = 'doubao-seed-2-0-mini-260215';
  12138. }
  12139. $messages[] =
  12140. [
  12141. 'role' => 'user',
  12142. 'content' => $question
  12143. ];
  12144. $post_data = [
  12145. 'model' => $model,
  12146. 'messages' => $messages,
  12147. // 'max_tokens' => 8192,
  12148. 'temperature' => 0.7,
  12149. 'frequency_penalty' => 0,
  12150. 'presence_penalty' => 0,
  12151. 'response_format' => ['type' => 'text'],
  12152. 'stream' => false // 是否启用流式输出
  12153. ];
  12154. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  12155. // DeepSeek 官方模型使用 DeepSeek API
  12156. $chatResult = $this->chatOnly($post_data);
  12157. } else if (in_array($model, $this->gpt_text_models)) {
  12158. // GPT-5.4 模型使用 TokenRouter API
  12159. $chatResult = $this->gpt54ChatOnly($post_data);
  12160. } else {
  12161. // 其他模型使用火山引擎API
  12162. $chatResult = $this->volcEngineChatCompletion($post_data);
  12163. }
  12164. if (is_array($chatResult)) {
  12165. extract($chatResult);
  12166. }else {
  12167. Utils::throwError('20003: 接口调用失败!');
  12168. }
  12169. return [
  12170. 'type' => 'done',
  12171. // 'episode' => $episode,
  12172. 'answer' => $fullContent,
  12173. 'reasoning' => $fullReasoningContent,
  12174. 'usage' => $usage
  12175. ];
  12176. }
  12177. /**
  12178. * 仅调用 deepseek 对话接口(非流式)
  12179. *
  12180. * @param array $post_data
  12181. * @param int $timeout
  12182. * @return array
  12183. */
  12184. private function chatOnly($post_data, $timeout = 1800) {
  12185. $post_data['max_tokens'] = 300000;
  12186. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  12187. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  12188. $response = $result->getBody()->getContents();
  12189. $response_arr = json_decode($response, true);
  12190. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  12191. $fullContent = '';
  12192. $fullReasoningContent = [];
  12193. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  12194. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  12195. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  12196. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  12197. }
  12198. return [
  12199. 'fullContent' => $fullContent,
  12200. 'fullReasoningContent' => $fullReasoningContent,
  12201. 'usage' => $usage
  12202. ];
  12203. }
  12204. /**
  12205. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  12206. *
  12207. * @param string $errorMessage
  12208. * @return string|null
  12209. */
  12210. public function analyzeErrorMessage($errorMessage)
  12211. {
  12212. try {
  12213. $post_data = [
  12214. 'model' => 'deepseek-v4-flash',
  12215. 'messages' => [
  12216. [
  12217. 'role' => 'system',
  12218. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  12219. ],
  12220. [
  12221. 'role' => 'user',
  12222. 'content' => (string)$errorMessage,
  12223. ],
  12224. ],
  12225. 'temperature' => 0.3,
  12226. 'frequency_penalty' => 0,
  12227. 'presence_penalty' => 0,
  12228. 'response_format' => ['type' => 'text'],
  12229. 'stream' => false,
  12230. ];
  12231. $result = $this->chatOnly($post_data, 8);
  12232. $content = trim((string)($result['fullContent'] ?? ''));
  12233. if ($content === '') {
  12234. return null;
  12235. }
  12236. return mb_substr($content, 0, 50);
  12237. } catch (\Exception $e) {
  12238. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  12239. 'error_message' => $errorMessage
  12240. ]);
  12241. return null;
  12242. }
  12243. }
  12244. // 仅调用 GPT-5.4 对话接口(非流式)
  12245. private function gpt54ChatOnly($post_data) {
  12246. $apiKey = env('GPT_54_API_KEY');
  12247. if (empty($apiKey)) {
  12248. Utils::throwError('20003:GPT-5.4 API Key未配置');
  12249. }
  12250. // 先探活,服务不可用时自动重试
  12251. $this->ensureGptServiceAvailable();
  12252. $client = new Client(['timeout' => 1800, 'verify' => false]);
  12253. $headers = [
  12254. 'Authorization' => 'Bearer ' . $apiKey,
  12255. 'Content-Type' => 'application/json'
  12256. ];
  12257. // 移除 thinking 参数,GPT-5.4 不支持
  12258. if (isset($post_data['thinking'])) {
  12259. unset($post_data['thinking']);
  12260. }
  12261. if (isset($post_data['reasoning_effort'])) {
  12262. unset($post_data['reasoning_effort']);
  12263. }
  12264. $post_data['max_completion_tokens'] = 100000;
  12265. // 确保 stream 为 false
  12266. $post_data['stream'] = false;
  12267. $maxRetries = $this->gptRetryTimes();
  12268. $interval = $this->gptRetryInterval();
  12269. $attempt = 0;
  12270. while (true) {
  12271. try {
  12272. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  12273. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  12274. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  12275. 'json' => $post_data,
  12276. 'headers' => $headers
  12277. ]);
  12278. $response = $result->getBody()->getContents();
  12279. $response_arr = json_decode($response, true);
  12280. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  12281. $fullContent = '';
  12282. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  12283. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  12284. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  12285. }
  12286. return [
  12287. 'fullContent' => $fullContent,
  12288. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  12289. 'usage' => $usage
  12290. ];
  12291. } catch (\Exception $e) {
  12292. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  12293. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  12294. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  12295. throw $e;
  12296. }
  12297. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  12298. 'retry' => $attempt + 1,
  12299. 'max_retries' => $maxRetries,
  12300. 'error' => $e->getMessage()
  12301. ]);
  12302. sleep($interval);
  12303. $attempt++;
  12304. }
  12305. }
  12306. }
  12307. private function splitContent($content) {
  12308. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  12309. $chapters = [];
  12310. // 匹配章节标题格式:
  12311. // 1. 标题可能独占一行,也可能在正文末尾或中间
  12312. // 2. 格式支持:
  12313. // - **第一集**
  12314. // - 第一集:
  12315. // - ###第1章 重生
  12316. // - ##第2章 相救
  12317. // - 第三章 共处一室
  12318. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  12319. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  12320. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  12321. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  12322. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  12323. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  12324. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  12325. // 先在每个标题前插入换行符(如果前面不是换行的话)
  12326. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  12327. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  12328. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  12329. // 用正则找出所有章节标题的位置
  12330. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  12331. $titleCount = count($matches[0]);
  12332. for ($i = 0; $i < $titleCount; $i++) {
  12333. // 获取当前章节标题
  12334. $titleLine = trim($matches[0][$i][0]);
  12335. // 去除标题开头的特殊符号
  12336. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/u', '', $titleLine);
  12337. // 去除标题结尾的冒号和特殊符号
  12338. $cleanTitle = preg_replace('/[#*·::\s]+$/u', '', $cleanTitle);
  12339. $cleanTitle = trim($cleanTitle);
  12340. // 获取当前标题的结束位置
  12341. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  12342. // 获取下一个章节标题的开始位置(如果存在)
  12343. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  12344. // 提取章节内容(从标题结束到下一个标题开始)
  12345. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  12346. // 清理内容:去除前后空白和分隔线
  12347. $chapterContent = trim($chapterContent);
  12348. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  12349. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  12350. if (!empty($cleanTitle) && !empty($chapterContent)) {
  12351. $chapters[] = [
  12352. 'title' => $cleanTitle,
  12353. 'content' => $chapterContent
  12354. ];
  12355. }
  12356. }
  12357. } else {
  12358. // 如果没有匹配到章节,返回整个内容
  12359. $chapters[] = [
  12360. 'title' => '',
  12361. 'content' => $content
  12362. ];
  12363. }
  12364. return $chapters;
  12365. }
  12366. public function getContentByBid($bid) {
  12367. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  12368. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  12369. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  12370. $content = '';
  12371. foreach ($chapters as $chapter) {
  12372. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  12373. }
  12374. return $content;
  12375. }
  12376. public function getContentByScriptId($script_id) {
  12377. $content = '';
  12378. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  12379. if ($contents) {
  12380. $content = implode(PHP_EOL, $contents);
  12381. }else {
  12382. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  12383. }
  12384. return $content;
  12385. }
  12386. /**
  12387. * 根据文件类型提取文本内容
  12388. *
  12389. * @param mixed $file 文件对象或文件路径
  12390. * @return string
  12391. */
  12392. public function extractFileContent($file) {
  12393. // 获取文件路径和扩展名
  12394. if (is_string($file)) {
  12395. $filePath = $file;
  12396. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  12397. } else {
  12398. // Laravel UploadedFile 对象
  12399. $filePath = $file->getRealPath();
  12400. $extension = strtolower($file->getClientOriginalExtension());
  12401. }
  12402. $content = '';
  12403. switch ($extension) {
  12404. case 'txt':
  12405. $content = $this->extractTxtContent($filePath);
  12406. break;
  12407. case 'pdf':
  12408. $content = $this->extractPdfContent($filePath);
  12409. break;
  12410. case 'doc':
  12411. case 'docx':
  12412. $content = $this->extractWordContent($filePath);
  12413. break;
  12414. // case 'jpg':
  12415. // case 'jpeg':
  12416. // case 'png':
  12417. // case 'gif':
  12418. // case 'bmp':
  12419. // case 'webp':
  12420. // $content = $this->extractImageContent($filePath);
  12421. // break;
  12422. default:
  12423. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  12424. }
  12425. // 移除非法 UTF-8 字节,避免后续 JSON 编码或正则解析异常
  12426. if (!mb_check_encoding($content, 'UTF-8')) {
  12427. $cleaned = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
  12428. $content = $cleaned === false ? $content : $cleaned;
  12429. }
  12430. return $content;
  12431. }
  12432. /**
  12433. * 提取 TXT 文件内容
  12434. */
  12435. private function extractTxtContent($filePath) {
  12436. if (!file_exists($filePath)) {
  12437. Utils::throwError('20003:文件不存在');
  12438. }
  12439. $content = file_get_contents($filePath);
  12440. // 尝试检测并转换编码
  12441. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  12442. if ($encoding && $encoding !== 'UTF-8') {
  12443. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  12444. }
  12445. return trim($content);
  12446. }
  12447. /**
  12448. * 提取 PDF 文件内容
  12449. */
  12450. private function extractPdfContent($filePath) {
  12451. if (!file_exists($filePath)) {
  12452. Utils::throwError('20003:文件不存在');
  12453. }
  12454. try {
  12455. $parser = new PdfParser();
  12456. $pdf = $parser->parseFile($filePath);
  12457. $content = $pdf->getText();
  12458. return trim($content);
  12459. } catch (\Exception $e) {
  12460. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  12461. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  12462. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  12463. }
  12464. }
  12465. /**
  12466. * 提取 Word 文件内容(支持 doc 和 docx)
  12467. */
  12468. private function extractWordContent($filePath) {
  12469. if (!file_exists($filePath)) {
  12470. Utils::throwError('20003:文件不存在');
  12471. }
  12472. try {
  12473. $phpWord = WordIOFactory::load($filePath);
  12474. $content = '';
  12475. foreach ($phpWord->getSections() as $section) {
  12476. foreach ($section->getElements() as $element) {
  12477. $content .= $this->extractWordElementText($element);
  12478. }
  12479. }
  12480. return trim($content);
  12481. } catch (\Exception $e) {
  12482. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  12483. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  12484. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  12485. }
  12486. }
  12487. /**
  12488. * 递归提取 Word 元素中的文本
  12489. */
  12490. private function extractWordElementText($element) {
  12491. $text = '';
  12492. if (method_exists($element, 'getText')) {
  12493. $text .= $element->getText() . "\n";
  12494. } elseif (method_exists($element, 'getElements')) {
  12495. foreach ($element->getElements() as $childElement) {
  12496. $text .= $this->extractWordElementText($childElement);
  12497. }
  12498. }
  12499. return $text;
  12500. }
  12501. /**
  12502. * 提取图片内容(使用火山引擎 OCR)
  12503. */
  12504. private function extractImageContent($filePath) {
  12505. if (!file_exists($filePath)) {
  12506. Utils::throwError('20003:文件不存在');
  12507. }
  12508. try {
  12509. // 读取图片并转换为 base64
  12510. $imageData = file_get_contents($filePath);
  12511. $base64Image = base64_encode($imageData);
  12512. // 调用火山引擎 OCR 服务
  12513. $content = $this->callVolcEngineOCR($base64Image);
  12514. return trim($content);
  12515. } catch (\Exception $e) {
  12516. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  12517. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  12518. Utils::throwError('20003:图片识别失败');
  12519. }
  12520. }
  12521. /**
  12522. * 调用火山引擎 OCR 服务识别图片文字
  12523. *
  12524. * @param string $base64Image base64 编码的图片数据
  12525. * @return string 识别的文字内容
  12526. */
  12527. private function callVolcEngineOCR($base64Image) {
  12528. $method = 'POST';
  12529. $service = 'cv';
  12530. $host = 'visual.volcengineapi.com';
  12531. $region = env('VOLC_REGION', 'cn-north-1');
  12532. $access_key = env('VOLC_AK');
  12533. $secret_key = env('VOLC_SK');
  12534. $action = 'OCRNormal';
  12535. $version = '2020-08-26';
  12536. if (!$access_key || !$secret_key) {
  12537. Utils::throwError('20003:请配置火山引擎 AK/SK');
  12538. }
  12539. // 请求体
  12540. $body = json_encode([
  12541. 'image_base64' => $base64Image
  12542. ]);
  12543. // 生成签名
  12544. $headers = $this->getVolcEngineSignHeaders(
  12545. $method, $service, $host, $region,
  12546. "Action={$action}&Version={$version}",
  12547. $access_key, $secret_key, $body
  12548. );
  12549. $client = new Client(['timeout' => 1800, 'verify' => false]);
  12550. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  12551. 'headers' => $headers,
  12552. 'body' => $body
  12553. ]);
  12554. $response_arr = json_decode($response->getBody()->getContents(), true);
  12555. // 提取识别的文字
  12556. $textLines = [];
  12557. if (isset($response_arr['data']['line_texts'])) {
  12558. $textLines = $response_arr['data']['line_texts'];
  12559. } elseif (isset($response_arr['data']['ocr_infos'])) {
  12560. foreach ($response_arr['data']['ocr_infos'] as $info) {
  12561. if (isset($info['text'])) {
  12562. $textLines[] = $info['text'];
  12563. }
  12564. }
  12565. }
  12566. if (empty($textLines)) {
  12567. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  12568. return '';
  12569. }
  12570. return implode("\n", $textLines);
  12571. }
  12572. /**
  12573. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  12574. */
  12575. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  12576. $contentType = 'application/json';
  12577. $accept = 'application/json';
  12578. // 获取当前UTC时间
  12579. $t = new DateTime('now', new DateTimeZone('UTC'));
  12580. $xDate = $t->format('Ymd\THis\Z');
  12581. $dateStamp = $t->format('Ymd');
  12582. // 计算 body 的 sha256 哈希
  12583. $payloadHash = hash('sha256', $body);
  12584. // 1. 拼接规范请求串
  12585. $canonicalUri = '/';
  12586. $canonicalQueryString = $queryString;
  12587. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  12588. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  12589. $canonicalRequest = implode("\n", [
  12590. $method,
  12591. $canonicalUri,
  12592. $canonicalQueryString,
  12593. $canonicalHeaders,
  12594. $signedHeaders,
  12595. $payloadHash
  12596. ]);
  12597. // 2. 拼接待签名字符串
  12598. $algorithm = 'HMAC-SHA256';
  12599. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  12600. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  12601. $stringToSign = implode("\n", [
  12602. $algorithm,
  12603. $xDate,
  12604. $credentialScope,
  12605. $hashedCanonicalRequest
  12606. ]);
  12607. // 3. 计算签名
  12608. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  12609. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  12610. // 4. 添加签名到请求头
  12611. $authorizationHeader = sprintf(
  12612. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  12613. $algorithm,
  12614. $access_key,
  12615. $credentialScope,
  12616. $signedHeaders,
  12617. $signature
  12618. );
  12619. return [
  12620. 'Accept' => $accept,
  12621. 'Content-Type' => $contentType,
  12622. 'Host' => $host,
  12623. 'X-Date' => $xDate,
  12624. 'X-Content-Sha256'=> $payloadHash,
  12625. 'Authorization' => $authorizationHeader
  12626. ];
  12627. }
  12628. public function generateScriptWords($cid, $model = 'r1') {
  12629. ini_set('max_execution_time', 0);
  12630. if (!$cid) Utils::throwError('20003: 请选择章节!');
  12631. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  12632. // 模型兼容性处理和思考模式设置
  12633. $thinkingMode = 'disabled';
  12634. $reasoningEffort = 'high';
  12635. if ($model == 'r1') {
  12636. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  12637. $thinkingMode = 'enabled';
  12638. } else {
  12639. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  12640. $thinkingMode = 'disabled';
  12641. }
  12642. $messages = [
  12643. [
  12644. 'role' => 'system',
  12645. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  12646. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  12647. 2.非对话部分请全部用旁白角色代替
  12648. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  12649. ],
  12650. [
  12651. 'role' => 'user',
  12652. 'content' => $content
  12653. ]
  12654. ];
  12655. $post_data = [
  12656. 'model' => $model,
  12657. 'messages' => $messages,
  12658. // 'max_tokens' => 8192,
  12659. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  12660. 'frequency_penalty' => 0,
  12661. 'presence_penalty' => 0,
  12662. 'thinking' => ['type' => $thinkingMode],
  12663. 'response_format' => [
  12664. 'type' => 'text'
  12665. ],
  12666. 'stream' => false
  12667. ];
  12668. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  12669. // 根据模型类型选择调用方法
  12670. $fullContent = '';
  12671. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  12672. // DeepSeek 官方模型使用 DeepSeek API
  12673. $chatResult = $this->chatOnly($post_data);
  12674. } else if (in_array($model, $this->gpt_text_models)) {
  12675. // GPT-5.4 模型使用 TokenRouter API
  12676. $chatResult = $this->gpt54ChatOnly($post_data);
  12677. } else {
  12678. // 其他模型使用火山引擎API
  12679. $chatResult = $this->volcEngineChatCompletion($post_data);
  12680. }
  12681. if (is_array($chatResult)) {
  12682. $fullContent = $chatResult['fullContent'];
  12683. }
  12684. return $fullContent;
  12685. }
  12686. /**
  12687. * 智能化解析集数信息
  12688. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  12689. *
  12690. * @param string $prompt 用户输入的提示词
  12691. * @return int|null 解析出的集数,如果没有找到则返回null
  12692. */
  12693. private function extractEpisodeNumber($prompt)
  12694. {
  12695. if (empty($prompt)) {
  12696. return null;
  12697. }
  12698. // 定义各种可能的表达模式
  12699. $patterns = [
  12700. // 基本模式:改成N集、调整成N集、修改成N集
  12701. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  12702. // 扩展模式:分成N集、拆分成N集、分割成N集
  12703. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  12704. // 数量模式:N集、共N集、总共N集
  12705. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  12706. // 制作模式:制作N集、生成N集、创建N集
  12707. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  12708. // 计划模式:计划N集、预计N集、打算N集
  12709. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  12710. // 需要模式:需要N集、要N集
  12711. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  12712. // 中文数字模式:改成三集、调整成五集等
  12713. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  12714. // 英文数字模式
  12715. '/(?: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',
  12716. ];
  12717. // 中文数字转阿拉伯数字的映射
  12718. $chineseNumbers = [
  12719. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  12720. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  12721. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  12722. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  12723. ];
  12724. // 逐个尝试匹配模式
  12725. foreach ($patterns as $pattern) {
  12726. if (preg_match($pattern, $prompt, $matches)) {
  12727. $number = trim($matches[1]);
  12728. // 如果是中文数字,转换为阿拉伯数字
  12729. if (isset($chineseNumbers[$number])) {
  12730. return $chineseNumbers[$number];
  12731. }
  12732. // 如果是阿拉伯数字,直接返回
  12733. if (is_numeric($number)) {
  12734. $episodeNum = intval($number);
  12735. // 合理性检查:集数应该在1-100之间
  12736. if ($episodeNum >= 1 && $episodeNum <= 100) {
  12737. return $episodeNum;
  12738. }
  12739. }
  12740. }
  12741. }
  12742. return null;
  12743. }
  12744. /**
  12745. * 调用火山引擎对话(Chat) API
  12746. *
  12747. * @param array $params 包含以下参数:
  12748. * - model: 模型ID(必填)
  12749. * - messages: 消息列表(必填)
  12750. * - stream: 是否流式输出(可选,默认false)
  12751. * - max_tokens: 最大输出token数(可选)
  12752. * - temperature: 采样温度(可选,默认1)
  12753. * - top_p: 核采样概率(可选,默认0.7)
  12754. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  12755. * - presence_penalty: 存在惩罚系数(可选,默认0)
  12756. * - stop: 停止词(可选)
  12757. * - tools: 工具列表(可选)
  12758. * @return array|Generator 非流式返回数组,流式返回生成器
  12759. */
  12760. public function volcEngineChatCompletion(array $params)
  12761. {
  12762. $apiKey = env('VOLC_AI_API_KEY');
  12763. if (empty($apiKey)) {
  12764. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  12765. }
  12766. // 构建请求参数
  12767. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  12768. $requestData = [
  12769. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  12770. 'messages' => $params['messages'] ?? [],
  12771. ];
  12772. if (!in_array($originalModel, $this->valid_text_models)) {
  12773. Utils::throwError('20003:该模型不支持!');
  12774. }
  12775. // 添加可选参数
  12776. if (isset($params['stream'])) {
  12777. $requestData['stream'] = $params['stream'];
  12778. }
  12779. if (isset($params['stream_options'])) {
  12780. $requestData['stream_options'] = $params['stream_options'];
  12781. }
  12782. if (isset($params['max_tokens'])) {
  12783. $requestData['max_tokens'] = $params['max_tokens'];
  12784. }else if (isset($params['max_completion_tokens'])) {
  12785. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  12786. }else {
  12787. $requestData['max_completion_tokens'] = 100000;
  12788. }
  12789. if (isset($params['temperature'])) {
  12790. $requestData['temperature'] = $params['temperature'];
  12791. }
  12792. if (isset($params['top_p'])) {
  12793. $requestData['top_p'] = $params['top_p'];
  12794. }
  12795. if (isset($params['frequency_penalty'])) {
  12796. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  12797. }
  12798. if (isset($params['presence_penalty'])) {
  12799. $requestData['presence_penalty'] = $params['presence_penalty'];
  12800. }
  12801. if (isset($params['stop'])) {
  12802. $requestData['stop'] = $params['stop'];
  12803. }
  12804. if (isset($params['tools'])) {
  12805. $requestData['tools'] = $params['tools'];
  12806. }
  12807. if (isset($params['tool_choice'])) {
  12808. $requestData['tool_choice'] = $params['tool_choice'];
  12809. }
  12810. if (isset($params['response_format'])) {
  12811. $requestData['response_format'] = $params['response_format'];
  12812. }
  12813. if (isset($params['thinking'])) {
  12814. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  12815. if (is_array($params['thinking'])) {
  12816. $requestData['thinking'] = $params['thinking'];
  12817. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  12818. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  12819. }
  12820. } else {
  12821. $requestData['thinking'] = ['type' => $params['thinking']];
  12822. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  12823. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  12824. }
  12825. }
  12826. } else {
  12827. $requestData['thinking'] = ['type' => 'disabled'];
  12828. }
  12829. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  12830. $client = new Client(['verify' => false, 'timeout' => 1800]);
  12831. try {
  12832. // 判断是否为流式输出
  12833. $isStream = isset($params['stream']) && $params['stream'] === true;
  12834. if ($isStream) {
  12835. // 流式输出
  12836. // 流式请求默认声明返回 usage(未显式传参时)
  12837. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  12838. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  12839. } else {
  12840. // 非流式输出
  12841. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  12842. 'headers' => [
  12843. 'Authorization' => 'Bearer ' . $apiKey,
  12844. 'Content-Type' => 'application/json',
  12845. ],
  12846. 'json' => $requestData
  12847. ]);
  12848. $responseData = json_decode($response->getBody(), true);
  12849. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  12850. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  12851. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  12852. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  12853. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  12854. }
  12855. return [
  12856. 'fullContent' => $fullContent,
  12857. 'fullReasoningContent' => $fullReasoningContent,
  12858. 'usage' => $usage
  12859. ];
  12860. }
  12861. } catch (\Exception $e) {
  12862. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  12863. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  12864. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  12865. }
  12866. }
  12867. /**
  12868. * 火山引擎对话API流式输出
  12869. *
  12870. * @param Client $client HTTP客户端
  12871. * @param string $apiKey API密钥
  12872. * @param array $requestData 请求数据
  12873. * @return Generator
  12874. */
  12875. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  12876. {
  12877. try {
  12878. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  12879. 'headers' => [
  12880. 'Authorization' => 'Bearer ' . $apiKey,
  12881. 'Content-Type' => 'application/json',
  12882. ],
  12883. 'json' => $requestData,
  12884. 'stream' => true
  12885. ]);
  12886. $body = $response->getBody();
  12887. $buffer = '';
  12888. $fullContent = '';
  12889. $fullReasoningContent = '';
  12890. $usage = [];
  12891. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  12892. // 逐行读取流式响应
  12893. while (!$body->eof()) {
  12894. $chunk = $body->read(1024);
  12895. $buffer .= $chunk;
  12896. // 按行分割
  12897. $lines = explode("\n", $buffer);
  12898. $buffer = array_pop($lines);
  12899. foreach ($lines as $line) {
  12900. $line = trim($line);
  12901. if (empty($line)) {
  12902. continue;
  12903. }
  12904. // 检查是否是SSE数据行
  12905. if (strpos($line, 'data: ') !== 0) {
  12906. continue;
  12907. }
  12908. $data = substr($line, 6);
  12909. if ($data === '[DONE]') {
  12910. dLog('deepseek')->info('收到结束标记');
  12911. break 2;
  12912. }
  12913. try {
  12914. $json = json_decode($data, true);
  12915. if (json_last_error() !== JSON_ERROR_NONE) {
  12916. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  12917. continue;
  12918. }
  12919. if (isset($json['choices'][0]['delta'])) {
  12920. $delta = $json['choices'][0]['delta'];
  12921. // 处理思维链内容
  12922. if (isset($delta['reasoning_content'])) {
  12923. $fullReasoningContent .= $delta['reasoning_content'];
  12924. yield [
  12925. 'type' => 'reasoning',
  12926. 'content' => $delta['reasoning_content'],
  12927. 'full_reasoning' => $fullReasoningContent
  12928. ];
  12929. }
  12930. // 处理回答内容
  12931. if (isset($delta['content'])) {
  12932. $fullContent .= $delta['content'];
  12933. yield [
  12934. 'type' => 'content',
  12935. 'content' => $delta['content'],
  12936. ];
  12937. }
  12938. }
  12939. // 获取使用统计信息
  12940. if (isset($json['usage'])) {
  12941. $usage = $json['usage'];
  12942. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  12943. }
  12944. } catch (\Exception $e) {
  12945. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  12946. continue;
  12947. }
  12948. }
  12949. }
  12950. dLog('deepseek')->info('流式读取完成', [
  12951. 'content_length' => strlen($fullContent),
  12952. 'reasoning_length' => strlen($fullReasoningContent)
  12953. ]);
  12954. yield [
  12955. 'type' => 'done',
  12956. 'full_content' => $fullContent,
  12957. 'full_reasoning' => $fullReasoningContent,
  12958. 'usage' => $usage
  12959. ];
  12960. } catch (\Exception $e) {
  12961. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  12962. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  12963. throw $e;
  12964. }
  12965. }
  12966. /**
  12967. * 检查并创建图片生成任务
  12968. *
  12969. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  12970. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  12971. * @param string $nameKey 资源名称字段('role' 或 'scene')
  12972. * @param string $art_style 美术风格
  12973. * @return array 更新后的资源列表
  12974. */
  12975. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  12976. {
  12977. // 确保参数为数组
  12978. $merged_items = is_array($merged_items) ? $merged_items : [];
  12979. $global_items = is_array($global_items) ? $global_items : [];
  12980. // 构建全局资源映射表,用于快速查找
  12981. $global_map = [];
  12982. foreach ($global_items as $item) {
  12983. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  12984. if ($itemKey === '') {
  12985. continue;
  12986. }
  12987. $global_map[$itemKey] = $item;
  12988. }
  12989. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  12990. foreach ($merged_items as &$item) {
  12991. $item_name = getProp($item, $nameKey);
  12992. $item_description = getProp($item, 'description');
  12993. // $item_url = getProp($item, 'url');
  12994. // // 如果已有图片URL,跳过
  12995. // if (!empty($item_url)) {
  12996. // continue;
  12997. // }
  12998. // 如果是旁白角色,跳过
  12999. if ($nameKey === 'role' && $item_name === '旁白') {
  13000. continue;
  13001. }
  13002. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  13003. if ($itemKey === '') {
  13004. continue;
  13005. }
  13006. $need_create_task = false;
  13007. // 条件1:在全局资源中找不到匹配的名称
  13008. if (!isset($global_map[$itemKey])) {
  13009. $need_create_task = true;
  13010. } else {
  13011. // 条件2:名称匹配但描述或 pic_prompt 不一致
  13012. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  13013. $current_description = trim((string)$item_description);
  13014. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  13015. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  13016. // 如果 description 或 pic_prompt 有变化,需要重新生成
  13017. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  13018. $need_create_task = true;
  13019. }
  13020. }
  13021. // 如果需要创建任务,调用图片生成服务
  13022. if ($need_create_task) {
  13023. try {
  13024. // 优先使用 pic_prompt,如果没有则使用 description
  13025. $pic_prompt = getProp($item, 'pic_prompt');
  13026. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  13027. // 添加美术风格前缀
  13028. if ($art_style) {
  13029. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  13030. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  13031. $description = "{$prefix}:{$description}";
  13032. }
  13033. $params = [
  13034. 'prompt' => $description,
  13035. 'ref_img_urls' => []
  13036. ];
  13037. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13038. $task_id = $task->id;
  13039. if ($task_id) {
  13040. $item['task_id'] = $task_id;
  13041. $item['task_status'] = 'processing';
  13042. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13043. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  13044. }
  13045. } catch (\Exception $e) {
  13046. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13047. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  13048. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  13049. // 不抛出异常,继续处理其他资源
  13050. }
  13051. }
  13052. }
  13053. return $merged_items;
  13054. }
  13055. /**
  13056. * 同步新出现的主体和场景到全局
  13057. *
  13058. * @param int $anime_id 动漫ID
  13059. * @param array $merged_roles 合并后的角色列表
  13060. * @param array $merged_scenes 合并后的场景列表
  13061. * @param array $global_roles 全局角色列表
  13062. * @param array $global_scenes 全局场景列表
  13063. * @return void
  13064. */
  13065. private function syncNewResourcesToGlobal(
  13066. int $anime_id,
  13067. array $merged_roles,
  13068. array $merged_scenes,
  13069. array $global_roles,
  13070. array $global_scenes
  13071. ): void {
  13072. // 构建全局角色映射表
  13073. $global_role_map = [];
  13074. foreach ($global_roles as $role) {
  13075. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  13076. if ($roleKey !== '') {
  13077. $global_role_map[$roleKey] = $role;
  13078. }
  13079. }
  13080. // 构建全局场景映射表
  13081. $global_scene_map = [];
  13082. foreach ($global_scenes as $scene) {
  13083. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  13084. if ($sceneKey !== '') {
  13085. $global_scene_map[$sceneKey] = $scene;
  13086. }
  13087. }
  13088. $need_update = false;
  13089. $new_global_roles = $global_roles;
  13090. $new_global_scenes = $global_scenes;
  13091. // 检查并添加新角色到全局
  13092. foreach ($merged_roles as $role) {
  13093. $role_name = getProp($role, 'role');
  13094. // 跳过旁白
  13095. if ($role_name === '旁白') {
  13096. continue;
  13097. }
  13098. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  13099. if ($roleKey === '') {
  13100. continue;
  13101. }
  13102. // 如果全局中不存在该角色,添加到全局
  13103. if (!isset($global_role_map[$roleKey])) {
  13104. $new_global_roles[] = [
  13105. 'role' => $role_name,
  13106. 'description' => getProp($role, 'description', ''),
  13107. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  13108. 'voice_name' => getProp($role, 'voice_name', ''),
  13109. 'voice_type' => getProp($role, 'voice_type', ''),
  13110. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  13111. 'url' => getProp($role, 'url', ''),
  13112. 'task_id' => getProp($role, 'task_id', ''),
  13113. 'task_status' => getProp($role, 'task_status', ''),
  13114. ];
  13115. $global_role_map[$roleKey] = true; // 标记已添加
  13116. $need_update = true;
  13117. dLog('deepseek')->info("新角色同步到全局", [
  13118. 'anime_id' => $anime_id,
  13119. 'role' => $role_name,
  13120. 'task_id' => getProp($role, 'task_id', ''),
  13121. ]);
  13122. }
  13123. // else {
  13124. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  13125. // $global_role = $global_role_map[$roleKey];
  13126. // if (is_array($global_role)) {
  13127. // $updated = false;
  13128. // $update_fields = [];
  13129. // // 检查描述是否更新
  13130. // $current_description = trim((string)getProp($role, 'description'));
  13131. // $global_description = trim((string)getProp($global_role, 'description'));
  13132. // if ($current_description !== '' && $current_description !== $global_description) {
  13133. // $updated = true;
  13134. // $update_fields[] = 'description';
  13135. // }
  13136. // // 检查pic_prompt是否更新
  13137. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  13138. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  13139. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  13140. // $updated = true;
  13141. // $update_fields[] = 'pic_prompt';
  13142. // }
  13143. // // 检查图片任务信息是否更新
  13144. // $current_task_id = getProp($role, 'task_id');
  13145. // $global_task_id = getProp($global_role, 'task_id');
  13146. // if ($current_task_id && $current_task_id !== $global_task_id) {
  13147. // $updated = true;
  13148. // $update_fields[] = 'task_id';
  13149. // }
  13150. // // 如果有更新,同步到全局
  13151. // if ($updated) {
  13152. // foreach ($new_global_roles as &$global_role_item) {
  13153. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  13154. // if ($global_role_key === $roleKey) {
  13155. // if (in_array('description', $update_fields)) {
  13156. // $global_role_item['description'] = $current_description;
  13157. // }
  13158. // if (in_array('pic_prompt', $update_fields)) {
  13159. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  13160. // }
  13161. // if (in_array('task_id', $update_fields)) {
  13162. // $global_role_item['task_id'] = $current_task_id;
  13163. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  13164. // $global_role_item['url'] = getProp($role, 'url', '');
  13165. // }
  13166. // break;
  13167. // }
  13168. // }
  13169. // $need_update = true;
  13170. // dLog('deepseek')->info("角色信息更新到全局", [
  13171. // 'anime_id' => $anime_id,
  13172. // 'role' => $role_name,
  13173. // 'update_fields' => implode(',', $update_fields),
  13174. // ]);
  13175. // }
  13176. // }
  13177. // }
  13178. }
  13179. // 检查并添加新场景到全局
  13180. foreach ($merged_scenes as $scene) {
  13181. $scene_name = getProp($scene, 'scene');
  13182. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  13183. if ($sceneKey === '') {
  13184. continue;
  13185. }
  13186. // 如果全局中不存在该场景,添加到全局
  13187. if (!isset($global_scene_map[$sceneKey])) {
  13188. $new_global_scenes[] = [
  13189. 'scene' => $scene_name,
  13190. 'description' => getProp($scene, 'description', ''),
  13191. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  13192. 'url' => getProp($scene, 'url', ''),
  13193. 'task_id' => getProp($scene, 'task_id', ''),
  13194. 'task_status' => getProp($scene, 'task_status', ''),
  13195. ];
  13196. $global_scene_map[$sceneKey] = true; // 标记已添加
  13197. $need_update = true;
  13198. dLog('deepseek')->info("新场景同步到全局", [
  13199. 'anime_id' => $anime_id,
  13200. 'scene' => $scene_name,
  13201. 'task_id' => getProp($scene, 'task_id', ''),
  13202. ]);
  13203. }
  13204. // else {
  13205. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  13206. // $global_scene = $global_scene_map[$sceneKey];
  13207. // if (is_array($global_scene)) {
  13208. // $updated = false;
  13209. // $update_fields = [];
  13210. // // 检查描述是否更新
  13211. // $current_description = trim((string)getProp($scene, 'description'));
  13212. // $global_description = trim((string)getProp($global_scene, 'description'));
  13213. // if ($current_description !== '' && $current_description !== $global_description) {
  13214. // $updated = true;
  13215. // $update_fields[] = 'description';
  13216. // }
  13217. // // 检查pic_prompt是否更新
  13218. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  13219. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  13220. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  13221. // $updated = true;
  13222. // $update_fields[] = 'pic_prompt';
  13223. // }
  13224. // // 检查图片任务信息是否更新
  13225. // $current_task_id = getProp($scene, 'task_id');
  13226. // $global_task_id = getProp($global_scene, 'task_id');
  13227. // if ($current_task_id && $current_task_id !== $global_task_id) {
  13228. // $updated = true;
  13229. // $update_fields[] = 'task_id';
  13230. // }
  13231. // // 如果有更新,同步到全局
  13232. // if ($updated) {
  13233. // foreach ($new_global_scenes as &$global_scene_item) {
  13234. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  13235. // if ($global_scene_key === $sceneKey) {
  13236. // if (in_array('description', $update_fields)) {
  13237. // $global_scene_item['description'] = $current_description;
  13238. // }
  13239. // if (in_array('pic_prompt', $update_fields)) {
  13240. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  13241. // }
  13242. // if (in_array('task_id', $update_fields)) {
  13243. // $global_scene_item['task_id'] = $current_task_id;
  13244. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  13245. // $global_scene_item['url'] = getProp($scene, 'url', '');
  13246. // }
  13247. // break;
  13248. // }
  13249. // }
  13250. // $need_update = true;
  13251. // dLog('deepseek')->info("场景信息更新到全局", [
  13252. // 'anime_id' => $anime_id,
  13253. // 'scene' => $scene_name,
  13254. // 'update_fields' => implode(',', $update_fields),
  13255. // ]);
  13256. // }
  13257. // }
  13258. // }
  13259. }
  13260. // 如果有新增或更新,更新数据库
  13261. if ($need_update) {
  13262. $update_data = [
  13263. 'roles' => json_encode($new_global_roles, 256),
  13264. 'scenes' => json_encode($new_global_scenes, 256),
  13265. 'updated_at' => date('Y-m-d H:i:s'),
  13266. ];
  13267. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  13268. if ($result !== false) {
  13269. dLog('deepseek')->info("全局角色和场景更新成功", [
  13270. 'anime_id' => $anime_id,
  13271. 'roles_count' => count($new_global_roles),
  13272. 'scenes_count' => count($new_global_scenes),
  13273. ]);
  13274. } else {
  13275. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  13276. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  13277. }
  13278. }
  13279. }
  13280. }