DeepSeekService.php 778 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299
  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. // 如果没有提供messages,则根据system_prompt、content和images构建
  131. if (empty($messages)) {
  132. $messages = [];
  133. // 添加系统提示词
  134. if (!empty($systemPrompt)) {
  135. $messages[] = [
  136. 'role' => 'system',
  137. 'content' => $systemPrompt
  138. ];
  139. }
  140. // 构建用户消息内容(支持文本+图片)
  141. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  142. $userMessage = [
  143. 'role' => 'user',
  144. 'content' => []
  145. ];
  146. // 添加文本内容
  147. if (!empty($prompt)) {
  148. $userMessage['content'][] = [
  149. 'type' => 'text',
  150. 'text' => $prompt
  151. ];
  152. }
  153. // 处理上传的图片文件
  154. if (!empty($images)) {
  155. if (!is_array($images)) {
  156. $images = [$images];
  157. }
  158. foreach ($images as $image) {
  159. $imageBase64 = $this->processImageToBase64($image);
  160. if ($imageBase64) {
  161. $userMessage['content'][] = [
  162. 'type' => 'image_url',
  163. 'image_url' => [
  164. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  165. ]
  166. ];
  167. }
  168. }
  169. }
  170. // 处理图片URL
  171. if (!empty($imageUrls)) {
  172. if (!is_array($imageUrls)) {
  173. $imageUrls = [$imageUrls];
  174. }
  175. foreach ($imageUrls as $url) {
  176. if (!empty($url)) {
  177. $userMessage['content'][] = [
  178. 'type' => 'image_url',
  179. 'image_url' => [
  180. 'url' => $url
  181. ]
  182. ];
  183. }
  184. }
  185. }
  186. // 处理上传的视频文件(仅 Gemini)
  187. if (!empty($videos) && $isGeminiModel) {
  188. if (!is_array($videos)) {
  189. $videos = [$videos];
  190. }
  191. foreach ($videos as $video) {
  192. $inlineData = $this->processMediaToInlineData($video);
  193. if ($inlineData) {
  194. $userMessage['content'][] = [
  195. 'type' => 'video',
  196. 'inline_data' => $inlineData
  197. ];
  198. }
  199. }
  200. }
  201. // 处理视频URL(仅 Gemini)
  202. if (!empty($videoUrls) && $isGeminiModel) {
  203. if (!is_array($videoUrls)) {
  204. $videoUrls = [$videoUrls];
  205. }
  206. foreach ($videoUrls as $url) {
  207. if (!empty($url)) {
  208. $userMessage['content'][] = [
  209. 'type' => 'video_url',
  210. 'video_url' => ['url' => $url]
  211. ];
  212. }
  213. }
  214. }
  215. // 如果只有文本内容,简化为字符串格式
  216. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  217. $userMessage['content'] = $userMessage['content'][0]['text'];
  218. }
  219. $messages[] = $userMessage;
  220. }
  221. }
  222. // 验证messages不为空
  223. if (empty($messages)) {
  224. Utils::throwError('20003:请提供有效的对话内容');
  225. }
  226. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  227. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  228. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  229. if ($model === 'deepseek-chat') {
  230. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  231. $model = 'deepseek-v4-flash';
  232. $thinkingMode = 'disabled';
  233. } elseif ($model === 'deepseek-reasoner') {
  234. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  235. $model = 'deepseek-v4-flash';
  236. $thinkingMode = 'enabled';
  237. }
  238. // 构建请求参数
  239. $post_data = [
  240. 'model' => $model,
  241. 'messages' => $messages,
  242. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  243. 'temperature' => getProp($data, 'temperature', 1),
  244. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  245. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  246. 'thinking' => ['type' => $thinkingMode],
  247. 'stream' => true // 启用流式输出
  248. ];
  249. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  250. // 添加可选参数
  251. if (isset($data['top_p'])) {
  252. $post_data['top_p'] = $data['top_p'];
  253. }
  254. if (isset($data['response_format'])) {
  255. $post_data['response_format'] = $data['response_format'];
  256. }
  257. // 根据模型类型选择调用方法
  258. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  259. // DeepSeek 官方模型使用 DeepSeek API
  260. return $this->deepSeekStreamResponse($post_data);
  261. } else if (in_array($model, $this->gpt_text_models)) {
  262. // GPT 模型使用 TokenRouter API
  263. return $this->gpt54StreamResponse($post_data);
  264. } else if (in_array($model, $this->gemini_text_models)) {
  265. // Gemini 模型使用 Gemini API
  266. return $this->geminiStreamResponse($post_data, $model);
  267. } else if (in_array($model, $this->valid_text_models)) {
  268. // 火山引擎支持的模型使用火山引擎 API
  269. return $this->volcEngineChatCompletion($post_data);
  270. } else {
  271. Utils::throwError('20003:不支持的模型: ' . $model);
  272. }
  273. }
  274. public function createGenerateText($data) {
  275. $file = getProp($data, 'file');
  276. $uid = Site::getUid();
  277. $cpid = Site::getCpid();
  278. if (!$file) {
  279. Utils::throwError('20003:请上传文件');
  280. }
  281. // 提取文件内容
  282. $content = $this->extractFileContent($file);
  283. if (!$content) {
  284. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  285. }
  286. // 获取原始文件名(不含扩展名)作为script_name
  287. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  288. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  289. // 字节安全剥离,不依赖服务器locale设置
  290. $originalName = $file->getClientOriginalName();
  291. $extension = $file->getClientOriginalExtension();
  292. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  293. ? substr($originalName, 0, -strlen($extension) - 1)
  294. : $originalName;
  295. if ($script_name === '') {
  296. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  297. }
  298. // 如果同一用户的剧本名存在则提示
  299. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  300. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  301. }
  302. // 插入数据到mp_scripts表
  303. $script_id = DB::table('mp_scripts')->insertGetId([
  304. 'script_name' => $script_name,
  305. 'user_id' => $uid,
  306. 'cpid' => $cpid,
  307. 'content' => $content,
  308. 'created_at' => date('Y-m-d H:i:s'),
  309. 'updated_at' => date('Y-m-d H:i:s')
  310. ]);
  311. return [
  312. 'script_id' => $script_id,
  313. 'script_name' => $script_name
  314. ];
  315. }
  316. /**
  317. * AI对话调用成功后的积分扣费(返回结果前调用)
  318. *
  319. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  320. *
  321. * @param int $uid
  322. * @param int $tokens
  323. * @param array $chargeInfo
  324. * @return void
  325. */
  326. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo): void
  327. {
  328. $result = $this->pointsService->recordChatCharge(
  329. $uid,
  330. PointsService::CHAT_CHARGE_POINTS,
  331. $tokens,
  332. $chargeInfo
  333. );
  334. if (empty($result['charged'])) {
  335. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  336. }
  337. }
  338. /**
  339. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  340. *
  341. * @param array $data 请求参数
  342. * @return array 返回结果数组
  343. */
  344. public function newGenerateText($data) {
  345. // 获取请求参数
  346. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  347. $messages = getProp($data, 'messages', []);
  348. $systemPrompt = getProp($data, 'system_prompt', '');
  349. $prompt = getProp($data, 'prompt', '');
  350. $images = getProp($data, 'images', []); // 支持多张图片
  351. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  352. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  353. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  354. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  355. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  356. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  357. $generateTaskId = 0;
  358. $uid = Site::getUid();
  359. if ($script_id > 0) {
  360. $existingTask = DB::table('mp_script_generate_tasks')
  361. ->where('uid', $uid)
  362. ->where('script_id', $script_id)
  363. ->orderByDesc('id')
  364. ->first();
  365. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  366. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  367. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  368. }
  369. }
  370. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  371. $originalContent = '';
  372. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  373. if ($script_id > 0) {
  374. $script = DB::table('mp_scripts')
  375. ->where('id', $script_id)
  376. ->where('is_deleted', 0)
  377. ->first();
  378. if (!$script) {
  379. Utils::throwError('20003:剧本不存在或已删除');
  380. }
  381. $originalContent = $script->content ?? '';
  382. if (empty($originalContent)) {
  383. Utils::throwError('20003:剧本内容为空');
  384. }
  385. $hasValidScript = true;
  386. // 将剧本内容添加到提示词前面
  387. if (!empty($originalContent)) {
  388. if (!empty($prompt)) {
  389. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  390. } else {
  391. $prompt = "原文内容:\n" . $originalContent;
  392. }
  393. }
  394. }
  395. // 新增: 如果提供了template_id,从数据库获取template_prompt
  396. if ($templateId > 0) {
  397. $template = DB::table('mp_prompt_templates')
  398. ->where('id', $templateId)
  399. ->where('is_deleted', 0)
  400. ->first();
  401. if (!$template) {
  402. Utils::throwError('20003:模板不存在或已删除');
  403. }
  404. $templatePrompt = $template->template_prompt ?? '';
  405. // 将模板提示词和用户输入的prompt组合
  406. // 模板为准,用户输入作为补充要求
  407. if (!empty($templatePrompt)) {
  408. if (!empty($prompt)) {
  409. $prompt = $templatePrompt . "\n\n" . $prompt;
  410. } else {
  411. $prompt = $templatePrompt;
  412. }
  413. }
  414. }
  415. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  416. if (empty($messages)) {
  417. $messages = [];
  418. // 添加系统提示词
  419. if (!empty($systemPrompt)) {
  420. $messages[] = [
  421. 'role' => 'system',
  422. 'content' => $systemPrompt
  423. ];
  424. }
  425. // 构建用户消息内容(支持文本+图片)
  426. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  427. $userMessage = [
  428. 'role' => 'user',
  429. 'content' => []
  430. ];
  431. // 添加文本内容
  432. if (!empty($prompt)) {
  433. $userMessage['content'][] = [
  434. 'type' => 'text',
  435. 'text' => $prompt
  436. ];
  437. }
  438. // 处理上传的图片文件
  439. if (!empty($images)) {
  440. if (!is_array($images)) {
  441. $images = [$images];
  442. }
  443. foreach ($images as $image) {
  444. $imageBase64 = $this->processImageToBase64($image);
  445. if ($imageBase64) {
  446. $userMessage['content'][] = [
  447. 'type' => 'image_url',
  448. 'image_url' => [
  449. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  450. ]
  451. ];
  452. }
  453. }
  454. }
  455. // 处理图片URL
  456. if (!empty($imageUrls)) {
  457. if (!is_array($imageUrls)) {
  458. $imageUrls = [$imageUrls];
  459. }
  460. foreach ($imageUrls as $url) {
  461. if (!empty($url)) {
  462. $userMessage['content'][] = [
  463. 'type' => 'image_url',
  464. 'image_url' => [
  465. 'url' => $url
  466. ]
  467. ];
  468. }
  469. }
  470. }
  471. // 如果只有文本内容,简化为字符串格式
  472. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  473. $userMessage['content'] = $userMessage['content'][0]['text'];
  474. }
  475. $messages[] = $userMessage;
  476. }
  477. }
  478. // 验证messages不为空
  479. if (empty($messages)) {
  480. Utils::throwError('20003:请提供有效的对话内容');
  481. }
  482. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  483. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  484. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  485. if ($model === 'deepseek-chat') {
  486. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  487. $model = 'deepseek-v4-flash';
  488. $thinkingMode = 'disabled';
  489. } elseif ($model === 'deepseek-reasoner') {
  490. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  491. $model = 'deepseek-v4-flash';
  492. $thinkingMode = 'enabled';
  493. }
  494. // 构建请求参数(非流式)
  495. $post_data = [
  496. 'model' => $model,
  497. 'messages' => $messages,
  498. 'temperature' => getProp($data, 'temperature', 1),
  499. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  500. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  501. 'thinking' => ['type' => $thinkingMode],
  502. 'stream' => false // 非流式输出
  503. ];
  504. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  505. // 添加可选参数
  506. if (isset($data['top_p'])) {
  507. $post_data['top_p'] = $data['top_p'];
  508. }
  509. // 新增: 根据response_format设置响应格式
  510. if ($responseFormat === 'json') {
  511. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  512. $hasJsonKeyword = false;
  513. foreach ($post_data['messages'] as $message) {
  514. if (isset($message['content'])) {
  515. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  516. if (stripos($content, 'json') !== false) {
  517. $hasJsonKeyword = true;
  518. break;
  519. }
  520. }
  521. }
  522. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  523. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  524. if (!$hasJsonKeyword) {
  525. $lastMessageIndex = count($post_data['messages']) - 1;
  526. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  527. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  528. // 如果content是字符串,直接追加
  529. if (is_string($lastContent)) {
  530. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  531. }
  532. // 如果content是数组(包含文本和图片),在文本部分追加
  533. else if (is_array($lastContent)) {
  534. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  535. if ($contentPart['type'] === 'text') {
  536. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  537. break;
  538. }
  539. }
  540. }
  541. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  542. }
  543. }
  544. // 设置response_format参数(所有支持的模型)
  545. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  546. // DeepSeek模型
  547. $post_data['response_format'] = ['type' => 'json_object'];
  548. } else if (in_array($model, $this->gpt_text_models)) {
  549. // GPT模型
  550. $post_data['response_format'] = ['type' => 'json_object'];
  551. } else if (in_array($model, $this->valid_text_models)) {
  552. // 火山引擎模型
  553. $post_data['response_format'] = ['type' => 'json_object'];
  554. }
  555. }
  556. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  557. if ($script_id > 0) {
  558. $uid = Site::getUid();
  559. // 创建新的生成任务
  560. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  561. 'uid' => $uid,
  562. 'script_id' => $script_id,
  563. 'sequence' => $sequence,
  564. 'status' => 'processing',
  565. 'prompt' => getProp($data, 'prompt', ''),
  566. 'started_at' => date('Y-m-d H:i:s'),
  567. 'created_at' => date('Y-m-d H:i:s'),
  568. 'updated_at' => date('Y-m-d H:i:s')
  569. ]);
  570. }
  571. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  572. if ($hasValidScript) {
  573. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  574. }
  575. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  576. try {
  577. $aiResult = null;
  578. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  579. // DeepSeek 官方模型使用现有的 chatOnly 方法
  580. $result = $this->chatOnly($post_data);
  581. // 记录实际使用的模型
  582. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  583. $aiResult = [
  584. 'content' => $result['fullContent'],
  585. 'reasoning_content' => $result['fullReasoningContent'],
  586. 'usage' => $result['usage'],
  587. 'model' => $model,
  588. 'finish_reason' => 'stop'
  589. ];
  590. } else if (in_array($model, $this->gpt_text_models)) {
  591. // GPT 模型使用现有的 gpt54ChatOnly 方法
  592. $result = $this->gpt54ChatOnly($post_data);
  593. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  594. $aiResult = [
  595. 'content' => $result['fullContent'],
  596. 'reasoning_content' => '',
  597. 'usage' => $result['usage'],
  598. 'model' => $model,
  599. 'finish_reason' => 'stop'
  600. ];
  601. } else if (in_array($model, $this->gemini_text_models)) {
  602. // Gemini 模型使用 Gemini API(非流式)
  603. $result = $this->geminiChatOnly($post_data, $model);
  604. dLog('deepseek')->info('newGenerateText使用Gemini模型', ['requested_model' => $model]);
  605. $aiResult = [
  606. 'content' => $result['fullContent'],
  607. 'reasoning_content' => $result['fullReasoningContent'] ?? '',
  608. 'usage' => $result['usage'],
  609. 'model' => $model,
  610. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  611. ];
  612. } else if (in_array($model, $this->valid_text_models)) {
  613. // 火山引擎支持的模型使用火山引擎 API(非流式)
  614. $post_data['stream'] = false;
  615. $result = $this->volcEngineChatCompletion($post_data);
  616. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  617. 'requested_model' => $model,
  618. 'result_keys' => array_keys($result),
  619. 'has_fullContent' => isset($result['fullContent']),
  620. 'has_content' => isset($result['content'])
  621. ]);
  622. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  623. $aiResult = [
  624. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  625. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  626. 'usage' => $result['usage'] ?? [],
  627. 'model' => $model,
  628. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  629. ];
  630. } else {
  631. Utils::throwError('20003:不支持的模型: ' . $model);
  632. }
  633. } catch (\Exception $e) {
  634. // 生成失败,更新任务状态
  635. if ($generateTaskId) {
  636. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  637. 'status' => 'failed',
  638. 'error_message' => $e->getMessage(),
  639. 'completed_at' => date('Y-m-d H:i:s'),
  640. 'updated_at' => date('Y-m-d H:i:s')
  641. ]);
  642. }
  643. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  644. }
  645. // 生成成功,更新任务状态
  646. if ($generateTaskId && $aiResult) {
  647. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  648. 'status' => 'success',
  649. 'result' => getProp($aiResult, 'content', ''),
  650. 'completed_at' => date('Y-m-d H:i:s'),
  651. 'updated_at' => date('Y-m-d H:i:s')
  652. ]);
  653. $aiResult['generate_task_id'] = $generateTaskId;
  654. }
  655. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  656. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  657. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  658. 'model' => $model,
  659. 'script_id' => $script_id,
  660. 'sequence' => $sequence,
  661. 'source' => 'newGenerateText',
  662. ]);
  663. }
  664. // 新增: 如果提供了script_id,保存对话记录
  665. if ($script_id > 0 && $aiResult) {
  666. try {
  667. $uid = Site::getUid();
  668. $now = now();
  669. // 获取用户原始的prompt(不包含剧本内容)
  670. $originalPrompt = getProp($data, 'prompt', '');
  671. $recordsToInsert = [
  672. [
  673. 'uid' => $uid,
  674. 'script_id' => $script_id,
  675. 'sequence' => $sequence,
  676. 'role' => 'user',
  677. 'content' => $originalPrompt,
  678. 'created_at' => $now,
  679. 'updated_at' => $now,
  680. ],
  681. [
  682. 'uid' => $uid,
  683. 'script_id' => $script_id,
  684. 'sequence' => $sequence,
  685. 'role' => 'assistant',
  686. 'content' => $aiResult['content'],
  687. 'created_at' => $now,
  688. 'updated_at' => $now,
  689. ]
  690. ];
  691. DB::table('mp_script_records')->insert($recordsToInsert);
  692. // 获取刚插入的记录ID(假设按插入顺序返回)
  693. $insertedRecords = DB::table('mp_script_records')
  694. ->where('uid', $uid)
  695. ->where('script_id', $script_id)
  696. ->where('sequence', $sequence)
  697. ->orderBy('id', 'desc')
  698. ->limit(2)
  699. ->get()
  700. ->map(function ($record) {
  701. return [
  702. 'rid' => $record->id,
  703. 'script_id' => $record->script_id,
  704. 'sequence' => $record->sequence,
  705. 'role' => $record->role,
  706. 'content' => $record->content,
  707. 'created_at' => $record->created_at,
  708. ];
  709. })
  710. ->reverse()
  711. ->values()
  712. ->toArray();
  713. // 将记录信息添加到返回结果中
  714. $aiResult['records'] = $insertedRecords;
  715. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  716. } catch (\Exception $e) {
  717. // 记录错误但不影响主流程
  718. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  719. }
  720. }
  721. return $aiResult;
  722. }
  723. /**
  724. * 通用 Gemini 文生文方法(支持流式和非流式)
  725. *
  726. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  727. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  728. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  729. * system_prompt 系统提示词(可选)
  730. * prompt 用户提示词(可选)
  731. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  732. * image_urls 图片/视频URL列表(可选,同上)
  733. * temperature 温度(可选,默认 1)
  734. * top_p 核采样(可选)
  735. * max_tokens 最大输出 token(可选,默认 8192)
  736. * response_format text/json(可选)
  737. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  738. * thinking_budget 思考预算(可选,默认 20)
  739. * stream 是否流式(可选,默认 false)
  740. *
  741. * @param array $data 请求参数
  742. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  743. */
  744. public function geminiGenerateText($data) {
  745. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  746. $isStream = (bool)getProp($data, 'stream', false);
  747. if (!in_array($model, $this->gemini_text_models)) {
  748. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  749. }
  750. $requestData = $this->buildGeminiRequestBody($data, $model);
  751. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  752. if ($isStream) {
  753. // 流式返回生成器
  754. return $this->geminiStreamResponse($requestData, $model);
  755. }
  756. // 非流式
  757. return $this->geminiChatOnly($requestData, $model);
  758. }
  759. /**
  760. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  761. */
  762. private function geminiMediaMaxBytes() {
  763. return 14 * 1024 * 1024;
  764. }
  765. /**
  766. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  767. */
  768. private function buildGeminiRequestBody($data, $model) {
  769. $messages = getProp($data, 'messages', []);
  770. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  771. if (empty($messages)) {
  772. $systemPrompt = getProp($data, 'system_prompt', '');
  773. $prompt = getProp($data, 'prompt', '');
  774. $images = getProp($data, 'images', []);
  775. $imageUrls = getProp($data, 'image_urls', []);
  776. $messages = [];
  777. if (!empty($systemPrompt)) {
  778. $messages[] = [
  779. 'role' => 'system',
  780. 'content' => $systemPrompt
  781. ];
  782. }
  783. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  784. $userMessage = ['role' => 'user', 'content' => []];
  785. if (!empty($prompt)) {
  786. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  787. }
  788. if (!empty($images)) {
  789. if (!is_array($images)) {
  790. $images = [$images];
  791. }
  792. foreach ($images as $image) {
  793. $inlineData = $this->processMediaToInlineData($image);
  794. if ($inlineData) {
  795. $userMessage['content'][] = [
  796. 'type' => 'image',
  797. 'inline_data' => $inlineData
  798. ];
  799. }
  800. }
  801. }
  802. if (!empty($imageUrls)) {
  803. if (!is_array($imageUrls)) {
  804. $imageUrls = [$imageUrls];
  805. }
  806. foreach ($imageUrls as $url) {
  807. if (!empty($url)) {
  808. $inlineData = $this->processMediaToInlineData($url);
  809. if ($inlineData) {
  810. $userMessage['content'][] = [
  811. 'type' => 'image',
  812. 'inline_data' => $inlineData
  813. ];
  814. }
  815. }
  816. }
  817. }
  818. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  819. $userMessage['content'] = $userMessage['content'][0]['text'];
  820. }
  821. $messages[] = $userMessage;
  822. }
  823. }
  824. if (empty($messages)) {
  825. Utils::throwError('20003:请提供有效的对话内容');
  826. }
  827. // 转换为 Gemini contents 格式
  828. $systemInstruction = '';
  829. $contents = [];
  830. foreach ($messages as $message) {
  831. $role = getProp($message, 'role', 'user');
  832. $content = getProp($message, 'content', '');
  833. if ($role === 'system') {
  834. if (is_array($content)) {
  835. $systemInstruction = $this->extractGeminiTextFromParts($content);
  836. } else {
  837. $systemInstruction = (string)$content;
  838. }
  839. continue;
  840. }
  841. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  842. $parts = [];
  843. if (is_array($content)) {
  844. foreach ($content as $part) {
  845. $partType = getProp($part, 'type', 'text');
  846. if ($partType === 'text') {
  847. $text = (string)getProp($part, 'text', '');
  848. if ($text !== '') {
  849. $parts[] = ['text' => $text];
  850. }
  851. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  852. if (in_array($partType, ['image_url', 'video_url'])) {
  853. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  854. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  855. } elseif (isset($part['inline_data'])) {
  856. // 已处理过的 inline_data 直接使用
  857. $parts[] = ['inline_data' => $part['inline_data']];
  858. continue;
  859. } else {
  860. $url = '';
  861. }
  862. $inlineData = $this->processMediaToInlineData($url);
  863. if ($inlineData) {
  864. $parts[] = ['inline_data' => $inlineData];
  865. }
  866. }
  867. }
  868. } else {
  869. $text = (string)$content;
  870. if ($text !== '') {
  871. $parts[] = ['text' => $text];
  872. }
  873. }
  874. if (!empty($parts)) {
  875. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  876. }
  877. }
  878. if (empty($contents)) {
  879. Utils::throwError('20003:请提供有效的对话内容');
  880. }
  881. // 构建生成配置
  882. $generationConfig = [];
  883. if (getProp($data, 'temperature', null) !== null) {
  884. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  885. }
  886. if (getProp($data, 'top_p', null) !== null) {
  887. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  888. }
  889. if (getProp($data, 'frequency_penalty', null) !== null) {
  890. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  891. }
  892. if (getProp($data, 'presence_penalty', null) !== null) {
  893. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  894. }
  895. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  896. if ($maxOutputTokens <= 0) {
  897. $maxOutputTokens = 8192;
  898. }
  899. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  900. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  901. $maxOutputTokens = 32768;
  902. }
  903. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  904. // response_format 映射:text -> text/plain,json -> application/json
  905. $responseFormat = getProp($data, 'response_format', 'text');
  906. if (is_array($responseFormat)) {
  907. $responseFormat = getProp($responseFormat, 'type', 'text');
  908. }
  909. if (in_array($responseFormat, ['json', 'json_object'])) {
  910. $generationConfig['responseMimeType'] = 'application/json';
  911. } else {
  912. $generationConfig['responseMimeType'] = 'text/plain';
  913. }
  914. $requestData = [
  915. 'contents' => $contents,
  916. 'generationConfig' => $generationConfig,
  917. ];
  918. if ($systemInstruction !== '') {
  919. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  920. }
  921. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  922. $thinkingMode = getProp($data, 'thinking', null);
  923. if (is_array($thinkingMode)) {
  924. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  925. }
  926. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  927. if ($thinkingMode === null) {
  928. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  929. }
  930. if ($thinkingMode === 'enabled') {
  931. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  932. if ($thinkingBudget <= 0) {
  933. $thinkingBudget = 20;
  934. }
  935. $requestData['generationConfig']['thinkingConfig'] = [
  936. 'thinkingBudget' => $thinkingBudget
  937. ];
  938. } elseif ($defaultThinking) {
  939. // 该模型仅支持思考模式,传 0 会返回 400
  940. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  941. } else {
  942. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  943. }
  944. return $requestData;
  945. }
  946. /**
  947. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  948. *
  949. * 模型名 -> env 变量名映射:
  950. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  951. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  952. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  953. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  954. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  955. */
  956. private function getGeminiApiKey($model) {
  957. $map = [
  958. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  959. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  960. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  961. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  962. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  963. ];
  964. if (isset($map[$model])) {
  965. $key = env($map[$model]);
  966. if (!empty($key)) {
  967. return $key;
  968. }
  969. }
  970. return env('GEMINI_API_KEY', '');
  971. }
  972. /**
  973. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  974. */
  975. private function geminiChatOnly($requestData, $model) {
  976. $apiKey = $this->getGeminiApiKey($model);
  977. if (empty($apiKey)) {
  978. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  979. }
  980. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  981. if (isset($requestData['messages'])) {
  982. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  983. }
  984. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  985. . '/models/' . $model . ':generateContent';
  986. $client = new Client(['timeout' => 1800, 'verify' => false]);
  987. $headers = [
  988. 'Authorization' => 'Bearer ' . $apiKey,
  989. 'Content-Type' => 'application/json'
  990. ];
  991. $maxRetries = $this->gptRetryTimes();
  992. $interval = $this->gptRetryInterval();
  993. $attempt = 0;
  994. while (true) {
  995. try {
  996. $response = $client->post($url, [
  997. 'json' => $requestData,
  998. 'headers' => $headers
  999. ]);
  1000. $responseArr = json_decode($response->getBody()->getContents(), true);
  1001. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1002. $fullContent = $this->extractGeminiContent($responseArr);
  1003. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1004. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1005. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1006. ? $responseArr['candidates'][0]['finishReason']
  1007. : '';
  1008. return [
  1009. 'fullContent' => $fullContent,
  1010. 'fullReasoningContent' => $fullReasoningContent,
  1011. 'usage' => $usage,
  1012. 'finish_reason' => $finishReason
  1013. ];
  1014. } catch (\Exception $e) {
  1015. $retryable = true;
  1016. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1017. $status = $e->getResponse()->getStatusCode();
  1018. $retryable = $status >= 500 || $status == 429;
  1019. }
  1020. if (!$retryable || $attempt >= $maxRetries) {
  1021. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1022. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1023. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1024. }
  1025. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1026. 'retry' => $attempt + 1,
  1027. 'max_retries' => $maxRetries,
  1028. 'error' => $e->getMessage()
  1029. ]);
  1030. sleep($interval);
  1031. $attempt++;
  1032. }
  1033. }
  1034. }
  1035. /**
  1036. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1037. */
  1038. private function geminiStreamResponse($requestData, $model) {
  1039. $apiKey = $this->getGeminiApiKey($model);
  1040. if (empty($apiKey)) {
  1041. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1042. }
  1043. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1044. if (isset($requestData['messages'])) {
  1045. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1046. }
  1047. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1048. . '/models/' . $model . ':generateContent?alt=sse';
  1049. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1050. $headers = [
  1051. 'Authorization' => 'Bearer ' . $apiKey,
  1052. 'Content-Type' => 'application/json'
  1053. ];
  1054. try {
  1055. $response = $client->post($url, [
  1056. 'json' => $requestData,
  1057. 'headers' => $headers,
  1058. 'stream' => true
  1059. ]);
  1060. $body = $response->getBody();
  1061. $fullContent = '';
  1062. $fullReasoningContent = '';
  1063. $usage = [];
  1064. $buffer = '';
  1065. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1066. while (!$body->eof()) {
  1067. $chunk = $body->read(1024);
  1068. $buffer .= $chunk;
  1069. $lines = explode("\n", $buffer);
  1070. $buffer = array_pop($lines);
  1071. foreach ($lines as $line) {
  1072. $line = trim($line);
  1073. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1074. continue;
  1075. }
  1076. $data = substr($line, 6);
  1077. if ($data === '[DONE]') {
  1078. break 2;
  1079. }
  1080. try {
  1081. $json = json_decode($data, true);
  1082. if (json_last_error() !== JSON_ERROR_NONE) {
  1083. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1084. continue;
  1085. }
  1086. // 思考内容(thoughts)
  1087. $thoughts = $this->extractGeminiThoughts($json);
  1088. if ($thoughts !== '') {
  1089. $fullReasoningContent .= $thoughts;
  1090. yield [
  1091. 'type' => 'reasoning',
  1092. 'content' => $thoughts,
  1093. 'full_reasoning' => $fullReasoningContent
  1094. ];
  1095. }
  1096. // 回答内容
  1097. $partText = $this->extractGeminiContent($json);
  1098. if ($partText !== '') {
  1099. $fullContent .= $partText;
  1100. yield [
  1101. 'type' => 'content',
  1102. 'content' => $partText,
  1103. ];
  1104. }
  1105. // 使用统计
  1106. if (isset($json['usageMetadata'])) {
  1107. $usage = $json['usageMetadata'];
  1108. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  1109. }
  1110. } catch (\Exception $e) {
  1111. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1112. continue;
  1113. }
  1114. }
  1115. }
  1116. dLog('deepseek')->info('Gemini流式读取完成', [
  1117. 'content_length' => strlen($fullContent),
  1118. 'reasoning_length' => strlen($fullReasoningContent)
  1119. ]);
  1120. yield [
  1121. 'type' => 'done',
  1122. 'full_content' => $fullContent,
  1123. 'full_reasoning' => $fullReasoningContent,
  1124. 'usage' => $usage
  1125. ];
  1126. } catch (\Exception $e) {
  1127. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  1128. yield [
  1129. 'type' => 'error',
  1130. 'msg' => $e->getMessage(),
  1131. 'code' => $e->getCode()
  1132. ];
  1133. }
  1134. }
  1135. /**
  1136. * 从 Gemini 响应中提取回答文本
  1137. */
  1138. private function extractGeminiContent($responseArr) {
  1139. $text = '';
  1140. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  1141. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  1142. if (isset($part['text'])) {
  1143. $text .= $part['text'];
  1144. }
  1145. }
  1146. }
  1147. return $text;
  1148. }
  1149. /**
  1150. * 从 Gemini 响应中提取思考内容
  1151. */
  1152. private function extractGeminiReasoningContent($responseArr) {
  1153. $reasoning = '';
  1154. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1155. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1156. if (isset($thought['text'])) {
  1157. $reasoning .= $thought['text'];
  1158. }
  1159. }
  1160. }
  1161. return $reasoning;
  1162. }
  1163. /**
  1164. * 从 Gemini 流式响应中提取本次增量思考内容
  1165. */
  1166. private function extractGeminiThoughts($responseArr) {
  1167. $thoughts = '';
  1168. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1169. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1170. if (isset($thought['text'])) {
  1171. $thoughts .= $thought['text'];
  1172. }
  1173. }
  1174. }
  1175. return $thoughts;
  1176. }
  1177. /**
  1178. * 提取消息数组中的纯文本
  1179. */
  1180. private function extractGeminiTextFromParts($parts) {
  1181. $text = '';
  1182. if (is_array($parts)) {
  1183. foreach ($parts as $part) {
  1184. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  1185. $text .= (string)getProp($part, 'text', '');
  1186. }
  1187. }
  1188. }
  1189. return $text;
  1190. }
  1191. /**
  1192. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  1193. *
  1194. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  1195. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  1196. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  1197. *
  1198. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  1199. * @return array|null ['mime_type' => string, 'data' => string]
  1200. */
  1201. private function processMediaToInlineData($media) {
  1202. if (empty($media)) {
  1203. return null;
  1204. }
  1205. $localPath = null;
  1206. $isTempFile = false;
  1207. try {
  1208. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  1209. if (is_string($media) && strpos($media, 'data:') === 0) {
  1210. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  1211. return [
  1212. 'mime_type' => $matches[1],
  1213. 'data' => $matches[2]
  1214. ];
  1215. }
  1216. return null;
  1217. }
  1218. // 2. 获取本地文件路径
  1219. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  1220. $localPath = $this->downloadMediaToTemp($media);
  1221. $isTempFile = true;
  1222. } elseif (is_string($media)) {
  1223. $localPath = $media;
  1224. } else {
  1225. // Laravel UploadedFile 对象
  1226. $localPath = $media->getRealPath();
  1227. }
  1228. if (!$localPath || !file_exists($localPath)) {
  1229. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  1230. return null;
  1231. }
  1232. $fileSize = filesize($localPath);
  1233. $maxBytes = $this->geminiMediaMaxBytes();
  1234. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  1235. $mimeType = $this->detectMediaMime($localPath);
  1236. $isVideo = strpos($mimeType, 'video/') === 0;
  1237. $needCompress = $fileSize > $maxBytes;
  1238. $duration = 0;
  1239. if ($isVideo) {
  1240. $duration = $this->getMediaDuration($localPath);
  1241. if ($duration > 300) {
  1242. $needCompress = true;
  1243. }
  1244. }
  1245. $finalPath = $localPath;
  1246. $compressedPath = null;
  1247. if ($needCompress && $this->ffmpegAvailable()) {
  1248. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  1249. if ($compressed && file_exists($compressed)) {
  1250. $compressedPath = $compressed;
  1251. if (filesize($compressed) < $fileSize || $isVideo) {
  1252. $finalPath = $compressed;
  1253. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  1254. } else {
  1255. @unlink($compressed);
  1256. $compressedPath = null;
  1257. }
  1258. }
  1259. }
  1260. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  1261. $finalSize = filesize($finalPath);
  1262. if ($finalSize > $maxBytes) {
  1263. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  1264. 'path' => $localPath,
  1265. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  1266. 'limit_mb' => 14
  1267. ]);
  1268. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  1269. }
  1270. // 兜底校验:视频时长超过5分钟且未能压缩成功
  1271. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  1272. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  1273. }
  1274. $data = base64_encode(file_get_contents($finalPath));
  1275. return [
  1276. 'mime_type' => $mimeType,
  1277. 'data' => $data
  1278. ];
  1279. } catch (\App\Exceptions\ApiException $e) {
  1280. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  1281. throw $e;
  1282. } catch (\Exception $e) {
  1283. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  1284. return null;
  1285. } finally {
  1286. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  1287. @unlink($compressedPath);
  1288. }
  1289. if ($isTempFile && $localPath && file_exists($localPath)) {
  1290. @unlink($localPath);
  1291. }
  1292. }
  1293. }
  1294. /**
  1295. * 下载远程多媒体到临时目录
  1296. *
  1297. * @return string|null 本地临时文件路径
  1298. */
  1299. private function downloadMediaToTemp($url) {
  1300. try {
  1301. $tempDir = storage_path('app/temp/gemini');
  1302. if (!is_dir($tempDir)) {
  1303. mkdir($tempDir, 0775, true);
  1304. }
  1305. $extension = 'tmp';
  1306. $pathInfo = parse_url($url, PHP_URL_PATH);
  1307. if ($pathInfo) {
  1308. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  1309. if ($ext && strlen($ext) <= 10) {
  1310. $extension = strtolower($ext);
  1311. }
  1312. }
  1313. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  1314. $client = new Client(['timeout' => 300, 'verify' => false]);
  1315. $response = $client->get($url, ['sink' => $tmpFile]);
  1316. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  1317. @unlink($tmpFile);
  1318. return null;
  1319. }
  1320. return $tmpFile;
  1321. } catch (\Exception $e) {
  1322. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  1323. return null;
  1324. }
  1325. }
  1326. /**
  1327. * 检测多媒体文件 MIME 类型
  1328. */
  1329. private function detectMediaMime($filePath) {
  1330. $imageInfo = @getimagesize($filePath);
  1331. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  1332. return $imageInfo['mime'];
  1333. }
  1334. // 视频按扩展名粗略判断
  1335. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  1336. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  1337. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  1338. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  1339. if (isset($videoExts[$ext])) {
  1340. return $videoExts[$ext];
  1341. }
  1342. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  1343. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  1344. if (isset($imageExts[$ext])) {
  1345. return $imageExts[$ext];
  1346. }
  1347. return 'application/octet-stream';
  1348. }
  1349. /**
  1350. * 获取多媒体时长(秒),非视频或失败返回 0
  1351. */
  1352. private function getMediaDuration($filePath) {
  1353. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  1354. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  1355. $output = trim((string)shell_exec($cmd));
  1356. $duration = (float)$output;
  1357. return $duration > 0 ? $duration : 0;
  1358. }
  1359. /**
  1360. * 检查 ffmpeg 是否可用
  1361. */
  1362. private function ffmpegAvailable() {
  1363. static $available = null;
  1364. if ($available !== null) {
  1365. return $available;
  1366. }
  1367. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1368. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  1369. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  1370. $available = false;
  1371. return $available;
  1372. }
  1373. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  1374. $output = shell_exec($cmd);
  1375. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  1376. return $available;
  1377. }
  1378. /**
  1379. * 使用 ffmpeg 压缩多媒体文件
  1380. *
  1381. * @param string $inputFile 输入文件路径
  1382. * @param bool $isVideo 是否为视频
  1383. * @param float $duration 视频时长(秒),非视频传 0
  1384. * @return string|null 压缩后的文件路径,失败返回 null
  1385. */
  1386. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  1387. try {
  1388. $tempDir = storage_path('app/temp/gemini');
  1389. if (!is_dir($tempDir)) {
  1390. mkdir($tempDir, 0775, true);
  1391. }
  1392. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1393. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  1394. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  1395. if ($isVideo) {
  1396. // 视频:时长超过5分钟则加速压缩到5分钟以内
  1397. $speedFactor = 1.0;
  1398. if ($duration > 300) {
  1399. $speedFactor = $duration / 300;
  1400. }
  1401. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  1402. $finalDuration = $duration / max(1.0, $speedFactor);
  1403. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  1404. $targetBitrate = max(300, min(6000, $targetBitrate));
  1405. $filters = [];
  1406. $filters[] = 'scale=min(1280,iw):-2';
  1407. $filters[] = 'fps=24';
  1408. if ($speedFactor > 1.0) {
  1409. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  1410. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  1411. $fullCount = (int)ceil($speedFactor / 2.0);
  1412. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1413. if ($lastTempo < 0.5) {
  1414. $fullCount++;
  1415. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1416. }
  1417. for ($i = 0; $i < $fullCount; $i++) {
  1418. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  1419. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  1420. }
  1421. }
  1422. $filterStr = implode(',', $filters);
  1423. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  1424. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  1425. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  1426. } else {
  1427. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  1428. $imageInfo = @getimagesize($inputFile);
  1429. $scaleW = 2048;
  1430. $scaleH = 2048;
  1431. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  1432. if ($imageInfo[0] >= $imageInfo[1]) {
  1433. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  1434. $scaleW = 2048;
  1435. } else {
  1436. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  1437. $scaleH = 2048;
  1438. }
  1439. }
  1440. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  1441. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  1442. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  1443. }
  1444. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  1445. $output = shell_exec($cmd);
  1446. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  1447. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  1448. 'input' => $inputFile,
  1449. 'output' => $output
  1450. ]);
  1451. @unlink($outputFile);
  1452. return null;
  1453. }
  1454. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  1455. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  1456. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  1457. ]);
  1458. return $outputFile;
  1459. } catch (\Exception $e) {
  1460. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  1461. return null;
  1462. }
  1463. }
  1464. /**
  1465. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  1466. *
  1467. * @param array $data
  1468. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1469. */
  1470. public function getScriptGenerateTasks($data) {
  1471. $uid = Site::getUid();
  1472. return DB::table('mp_script_generate_tasks as t')
  1473. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  1474. ->where('t.uid', $uid)
  1475. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  1476. ->orderByDesc('t.id')
  1477. ->paginate(15);
  1478. }
  1479. public function saveScriptChatHistory($data) {
  1480. $uid = Site::getUid();
  1481. $rid = getProp($data, 'rid');
  1482. $script_id = getProp($data, 'script_id');
  1483. $sequence = getProp($data, 'sequence', 0);
  1484. $content = getProp($data, 'content');
  1485. if (!$rid) {
  1486. Utils::throwError('20003:请选择对话记录ID');
  1487. }
  1488. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  1489. if (!$record) {
  1490. Utils::throwError('20003:对话记录不存在');
  1491. }
  1492. if (!$script_id) {
  1493. Utils::throwError('20003:请选择剧本');
  1494. }
  1495. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  1496. if (!$script) {
  1497. Utils::throwError('20003:剧本不存在');
  1498. }
  1499. // 批量插入数据
  1500. return DB::table('mp_script_records')->where('id', $rid)->update([
  1501. 'content' => $content,
  1502. 'updated_at' => date('Y-m-d H:i:s')
  1503. ]);
  1504. }
  1505. /**
  1506. * 获取剧本的历史对话记录
  1507. *
  1508. * @param array $data 请求参数
  1509. * @return array 返回历史记录数组
  1510. */
  1511. public function getScriptChatHistory($data) {
  1512. $uid = Site::getUid();
  1513. $script_id = getProp($data, 'script_id');
  1514. $rid = getProp($data, 'rid');
  1515. $sequence = getProp($data, 'sequence', null);
  1516. if (!$script_id) {
  1517. Utils::throwError('20003:请提供剧本ID');
  1518. }
  1519. // 验证剧本是否存在
  1520. $script = DB::table('mp_scripts')
  1521. ->where('id', $script_id)
  1522. ->where('is_deleted', 0)
  1523. ->first();
  1524. if (!$script) {
  1525. Utils::throwError('20003:剧本不存在');
  1526. }
  1527. // 构建查询
  1528. $query = DB::table('mp_script_records')
  1529. ->where('script_id', $script_id);
  1530. // ->where('uid', $uid);
  1531. // 如果提供了 sequence,则过滤指定剧集
  1532. if ($sequence !== null) {
  1533. $query->where('sequence', $sequence);
  1534. }
  1535. // 记录ID筛选
  1536. if ($rid) {
  1537. $query->where('id', $rid);
  1538. }
  1539. // 查询记录并按 id 正序排序
  1540. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  1541. ->orderBy('created_at', 'asc')
  1542. ->orderBy('id', 'asc')
  1543. ->get()
  1544. ->map(function ($record) {
  1545. return [
  1546. 'rid' => $record->id,
  1547. 'script_id' => $record->script_id,
  1548. 'sequence' => $record->sequence,
  1549. 'role' => $record->role,
  1550. 'content' => $record->content,
  1551. 'products' => $record->products ? json_decode($record->products) : [],
  1552. 'created_at' => $record->created_at,
  1553. ];
  1554. })
  1555. ->toArray();
  1556. return $records;
  1557. }
  1558. /**
  1559. * 处理图片转换为base64
  1560. *
  1561. * @param mixed $image 图片文件对象或文件路径
  1562. * @return string|null base64编码的图片数据
  1563. */
  1564. private function processImageToBase64($image) {
  1565. try {
  1566. // 获取文件路径
  1567. if (is_string($image)) {
  1568. $filePath = $image;
  1569. } else {
  1570. // Laravel UploadedFile 对象
  1571. $filePath = $image->getRealPath();
  1572. }
  1573. if (!file_exists($filePath)) {
  1574. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  1575. return null;
  1576. }
  1577. // 验证是否为图片文件
  1578. $imageInfo = @getimagesize($filePath);
  1579. if ($imageInfo === false) {
  1580. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  1581. return null;
  1582. }
  1583. // 读取图片并转换为base64
  1584. $imageData = file_get_contents($filePath);
  1585. $base64Image = base64_encode($imageData);
  1586. dLog('deepseek')->info('图片转换成功', [
  1587. 'size' => strlen($imageData),
  1588. 'type' => $imageInfo['mime']
  1589. ]);
  1590. return $base64Image;
  1591. } catch (\Exception $e) {
  1592. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  1593. return null;
  1594. }
  1595. }
  1596. private function getArtStylePromptMappings($art_style='')
  1597. {
  1598. $arr = [
  1599. '唯美真人风格' => [
  1600. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1601. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  1602. ],
  1603. '真人古风风格' => [
  1604. 'aliases' => ['真人古风风格', '真人古风'],
  1605. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  1606. ],
  1607. '日系动漫风格' => [
  1608. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1609. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  1610. ],
  1611. '国漫风格' => [
  1612. 'aliases' => ['国漫风格', '国漫'],
  1613. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  1614. ],
  1615. 'Q版卡通风格' => [
  1616. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1617. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  1618. ],
  1619. '简约扁平风格' => [
  1620. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1621. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  1622. ],
  1623. '武侠风格' => [
  1624. 'aliases' => ['武侠风格', '武侠'],
  1625. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  1626. ],
  1627. '古风仙侠风格' => [
  1628. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1629. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  1630. ],
  1631. '新中式水墨风格' => [
  1632. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  1633. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  1634. ],
  1635. '写实插画风格' => [
  1636. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  1637. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  1638. ],
  1639. '3D卡通风格' => [
  1640. 'aliases' => ['3D卡通风格', '3D卡通'],
  1641. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  1642. ],
  1643. '条漫风格' => [
  1644. 'aliases' => ['条漫风格', '条漫'],
  1645. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  1646. ],
  1647. '赛博朋克风格' => [
  1648. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1649. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  1650. ],
  1651. '暗黑悬疑风格' => [
  1652. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1653. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  1654. ],
  1655. '治愈清新风格' => [
  1656. 'aliases' => ['治愈清新风格', '治愈清新'],
  1657. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  1658. ],
  1659. '3D真人风格' => [
  1660. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  1661. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  1662. ],
  1663. ];
  1664. if($art_style) {
  1665. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  1666. }
  1667. return $arr;
  1668. $arr = [
  1669. '唯美真人风格' => [
  1670. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1671. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  1672. 2. 色彩色调
  1673. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  1674. 3. 画质精度
  1675. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  1676. 4. 画面观感
  1677. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  1678. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  1679. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  1680. ],
  1681. '真人古风风格' => [
  1682. 'aliases' => ['真人古风风格', '真人古风'],
  1683. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  1684. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  1685. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  1686. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  1687. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  1688. ],
  1689. '日系动漫风格' => [
  1690. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1691. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  1692. 正向提示词(中文)
  1693. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  1694. 必须遵守规则
  1695. • 全程保持日系动漫风格,不混入其他画风
  1696. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  1697. • 画面适配所选画面比例,构图居中,主体突出
  1698. • 线条干净、色彩统一,不杂乱、不突兀
  1699. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  1700. ],
  1701. '国漫风格' => [
  1702. 'aliases' => ['国漫风格', '国漫'],
  1703. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  1704. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  1705. 必须遵守规则
  1706. • 严格保持国漫画风,不串风格、不混画风
  1707. • 角色形象统一,不随意改变五官、身材、服饰
  1708. • 画面构图稳定,适合漫剧叙事展示
  1709. • 色调统一,不出现脏色、杂色
  1710. 禁止/避免词汇
  1711. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  1712. ],
  1713. 'Q版卡通风格' => [
  1714. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1715. 'prompt' => "风格说明
  1716. 头大身小,造型可爱圆润,简约干净
  1717. 正向提示词(中文)
  1718. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  1719. 必须遵守规则
  1720. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  1721. • 角色造型统一,表情可爱,不诡异
  1722. • 画面简洁清爽,无多余复杂元素
  1723. • 色彩明亮柔和,不刺眼
  1724. 禁止/避免词汇
  1725. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  1726. ],
  1727. '简约扁平风格' => [
  1728. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1729. 'prompt' => "风格说明
  1730. 色块简洁、无复杂渐变,现代极简风
  1731. 正向提示词(中文)
  1732. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  1733. 必须遵守规则
  1734. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  1735. • 构图简洁,主体突出,无多余装饰
  1736. • 色彩统一、干净,不杂乱
  1737. 禁止/避免词汇
  1738. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  1739. ],
  1740. '武侠风格' => [
  1741. 'aliases' => ['武侠风格', '武侠'],
  1742. 'prompt' => "风格说明
  1743. 江湖气息,线条硬朗,动作感强
  1744. 正向提示词(中文)
  1745. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  1746. 必须遵守规则
  1747. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  1748. • 角色形象、服饰、身材比例统一
  1749. • 画面动作自然,不扭曲、不畸形
  1750. 禁止/避免词汇
  1751. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  1752. ],
  1753. '古风仙侠风格' => [
  1754. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1755. 'prompt' => "风格说明
  1756. 飘逸汉服、云雾仙气、唯美空灵
  1757. 正向提示词(中文)
  1758. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  1759. 必须遵守规则
  1760. • 保持古风仙侠统一画风,不混入现代、科幻元素
  1761. • 角色服饰、发型、形象前后一致
  1762. • 场景仙气飘逸,色调清雅统一
  1763. • 画面唯美柔和,不阴暗、不诡异
  1764. 禁止/避免词汇
  1765. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  1766. ],
  1767. '新中式水墨风格' => [
  1768. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  1769. 'prompt' => "风格说明
  1770. 淡墨渲染,毛笔笔触,留白意境
  1771. 正向提示词(中文)
  1772. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  1773. 必须遵守规则
  1774. • 严格保持水墨质感,不混入厚涂、写实、卡通
  1775. • 色调淡雅统一,不浓艳杂乱
  1776. • 画面干净有意境,不堆砌元素
  1777. 禁止/避免词汇
  1778. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  1779. ],
  1780. '写实插画风格' => [
  1781. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  1782. 'prompt' => "风格说明
  1783. 接近真人比例,光影真实,质感细腻
  1784. 正向提示词(中文)
  1785. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  1786. 必须遵守规则
  1787. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  1788. • 角色五官、身材、服饰高度统一
  1789. • 画面清晰、光影自然、不扭曲
  1790. 禁止/避免词汇
  1791. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  1792. ],
  1793. '3D卡通风格' => [
  1794. 'aliases' => ['3D卡通风格', '3D卡通'],
  1795. 'prompt' => "风格说明
  1796. 3D建模质感,柔和渲染,圆润可爱
  1797. 正向提示词(中文)
  1798. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  1799. 必须遵守规则
  1800. • 保持3D卡通统一质感,不出现2D杂乱线条
  1801. • 角色模型、比例、形象前后一致
  1802. • 画面干净,不模糊、不穿模
  1803. 禁止/避免词汇
  1804. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  1805. ],
  1806. '条漫风格' => [
  1807. 'aliases' => ['条漫风格', '条漫'],
  1808. 'prompt' => "风格说明
  1809. 纵向分镜,上下滑动阅读,轻量化
  1810. 正向提示词(中文)
  1811. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  1812. 必须遵守规则
  1813. • 保持条漫纵向阅读逻辑,构图简洁
  1814. • 画风统一,不混写实、3D、水墨
  1815. • 画面干净,不杂乱
  1816. 禁止/避免词汇
  1817. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  1818. ],
  1819. '赛博朋克风格' => [
  1820. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1821. 'prompt' => "风格说明
  1822. 霓虹灯光、未来都市、暗色调、科技机械
  1823. 正向提示词(中文)
  1824. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  1825. 必须遵守规则
  1826. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  1827. • 色调以暗调+霓虹为主,色彩统一
  1828. • 画面科技感强,不杂乱
  1829. 禁止/避免词汇
  1830. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  1831. ],
  1832. '暗黑悬疑风格' => [
  1833. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1834. 'prompt' => "风格说明
  1835. 低饱和、冷色调、阴影重、神秘压抑
  1836. 正向提示词(中文)
  1837. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  1838. 必须遵守规则
  1839. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  1840. • 画面氛围压抑神秘,但不低俗、不血腥
  1841. • 角色形象统一,不崩坏
  1842. 禁止/避免词汇
  1843. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  1844. ],
  1845. '治愈清新风格' => [
  1846. 'aliases' => ['治愈清新风格', '治愈清新'],
  1847. 'prompt' => "风格说明
  1848. 马卡龙色系、柔光、温暖干净
  1849. 正向提示词(中文)
  1850. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  1851. 必须遵守规则
  1852. • 保持治愈清新统一色调,不阴暗、不诡异
  1853. • 画面柔和干净,无杂乱元素
  1854. • 角色形象柔和可爱,不狰狞
  1855. 禁止/避免词汇
  1856. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  1857. ],
  1858. ];
  1859. return $arr;
  1860. }
  1861. public function getArtStylePromptByInput($inputArtStyle): string
  1862. {
  1863. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  1864. if ($normalizedInput === '') {
  1865. return '';
  1866. }
  1867. return $this->getArtStylePromptMappings($normalizedInput);
  1868. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  1869. // foreach ($mapping['aliases'] as $alias) {
  1870. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  1871. // if ($normalizedAlias === '') {
  1872. // continue;
  1873. // }
  1874. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  1875. // return $mapping['prompt'];
  1876. // }
  1877. // }
  1878. // }
  1879. return '';
  1880. }
  1881. public function getArtStyleShortPromptByInput($inputArtStyle) {
  1882. $stylePrefixes = [
  1883. '唯美真人风格' => [
  1884. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  1885. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  1886. ],
  1887. '真人古风风格' => [
  1888. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  1889. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  1890. ],
  1891. '日系动漫风格' => [
  1892. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  1893. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  1894. ],
  1895. '国漫风格' => [
  1896. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  1897. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  1898. ],
  1899. 'Q版卡通风格' => [
  1900. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  1901. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  1902. ],
  1903. '简约扁平风格' => [
  1904. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  1905. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  1906. ],
  1907. '武侠风格' => [
  1908. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  1909. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  1910. ],
  1911. '古风仙侠风格' => [
  1912. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  1913. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  1914. ],
  1915. '新中式水墨风格' => [
  1916. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1917. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1918. ],
  1919. '写实插画风格' => [
  1920. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1921. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1922. ],
  1923. '3D卡通风格' => [
  1924. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1925. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  1926. ],
  1927. '条漫风格' => [
  1928. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  1929. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  1930. ],
  1931. '赛博朋克风格' => [
  1932. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  1933. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  1934. ],
  1935. '暗黑悬疑风格' => [
  1936. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  1937. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  1938. ],
  1939. '治愈清新风格' => [
  1940. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1941. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1942. ]
  1943. ];
  1944. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1945. }
  1946. private function normalizeArtStyleInput($value): string
  1947. {
  1948. $value = trim((string)$value);
  1949. if ($value === '') {
  1950. return '';
  1951. }
  1952. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1953. return mb_strtolower($value, 'UTF-8');
  1954. }
  1955. private function replaceArtStyleSection(string $content, string $artStyle): string
  1956. {
  1957. if ($content === '' || $artStyle === '') {
  1958. return $content;
  1959. }
  1960. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1961. if (!preg_match($pattern, $content)) {
  1962. return $content;
  1963. }
  1964. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1965. }
  1966. /**
  1967. * DeepSeek流式输出处理方法
  1968. *
  1969. * @param array $post_data DeepSeek API请求参数
  1970. * @return \Generator 返回生成器,用于流式输出
  1971. */
  1972. private function deepSeekStreamResponse($post_data) {
  1973. // 设置最大输出tokens
  1974. $post_data['max_tokens'] = 300000;
  1975. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  1976. $post_data['stream_options'] = ['include_usage' => true];
  1977. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1978. $response = $client->post($this->url, [
  1979. 'json' => $post_data,
  1980. 'headers' => $this->headers,
  1981. 'stream' => true // 启用流式响应
  1982. ]);
  1983. $body = $response->getBody();
  1984. $fullContent = '';
  1985. $fullReasoningContent = '';
  1986. $usage = [];
  1987. $buffer = '';
  1988. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1989. // 逐行读取流式响应
  1990. while (!$body->eof()) {
  1991. $chunk = $body->read(1024); // 每次读取 1KB
  1992. $buffer .= $chunk;
  1993. // 按行分割
  1994. $lines = explode("\n", $buffer);
  1995. // 保留最后一个不完整的行
  1996. $buffer = array_pop($lines);
  1997. foreach ($lines as $line) {
  1998. $line = trim($line);
  1999. // 跳过空行
  2000. if (empty($line)) {
  2001. continue;
  2002. }
  2003. // 检查是否是 SSE 数据行
  2004. if (strpos($line, 'data: ') !== 0) {
  2005. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2006. continue;
  2007. }
  2008. $data = substr($line, 6); // 移除 "data: " 前缀
  2009. if ($data === '[DONE]') {
  2010. dLog('deepseek')->info('收到结束标记');
  2011. break 2; // 跳出两层循环
  2012. }
  2013. try {
  2014. $json = json_decode($data, true);
  2015. if (json_last_error() !== JSON_ERROR_NONE) {
  2016. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2017. continue;
  2018. }
  2019. if (isset($json['choices'][0]['delta'])) {
  2020. $delta = $json['choices'][0]['delta'];
  2021. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2022. if (isset($delta['reasoning_content'])) {
  2023. $fullReasoningContent .= $delta['reasoning_content'];
  2024. yield [
  2025. 'type' => 'reasoning',
  2026. 'content' => $delta['reasoning_content'],
  2027. 'full_reasoning' => $fullReasoningContent
  2028. ];
  2029. }
  2030. // 处理最终回答内容
  2031. if (isset($delta['content'])) {
  2032. $fullContent .= $delta['content'];
  2033. yield [
  2034. 'type' => 'content',
  2035. 'content' => $delta['content'],
  2036. ];
  2037. }
  2038. }
  2039. // 获取使用统计信息
  2040. if (isset($json['usage'])) {
  2041. $usage = $json['usage'];
  2042. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2043. }
  2044. } catch (\Exception $e) {
  2045. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2046. continue;
  2047. }
  2048. }
  2049. }
  2050. dLog('deepseek')->info('流式读取完成', [
  2051. 'content_length' => strlen($fullContent),
  2052. 'reasoning_length' => strlen($fullReasoningContent)
  2053. ]);
  2054. yield [
  2055. 'type' => 'done',
  2056. 'full_content' => $fullContent,
  2057. 'full_reasoning' => $fullReasoningContent,
  2058. 'usage' => $usage
  2059. ];
  2060. }
  2061. /**
  2062. * GPT 重试次数(env 可配置,默认 5 次)
  2063. */
  2064. private function gptRetryTimes()
  2065. {
  2066. return (int)env('GPT_RETRY_TIMES', 5);
  2067. }
  2068. /**
  2069. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  2070. */
  2071. private function gptRetryInterval()
  2072. {
  2073. return (int)env('GPT_RETRY_INTERVAL', 10);
  2074. }
  2075. /**
  2076. * 判断 GPT 请求异常是否可重试
  2077. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  2078. */
  2079. private function isGptRetryableException(\Exception $e)
  2080. {
  2081. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  2082. return false;
  2083. }
  2084. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  2085. $status = $e->getResponse()->getStatusCode();
  2086. return $status >= 500 || $status == 429;
  2087. }
  2088. return true;
  2089. }
  2090. /**
  2091. * GPT 中转站探活:GET /v1/models,5 秒短超时
  2092. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  2093. */
  2094. private function checkGptServiceAvailable()
  2095. {
  2096. $apiKey = env('GPT_54_API_KEY');
  2097. if (empty($apiKey)) {
  2098. return false;
  2099. }
  2100. try {
  2101. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  2102. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  2103. 'headers' => [
  2104. 'Authorization' => 'Bearer ' . $apiKey,
  2105. 'Content-Type' => 'application/json'
  2106. ]
  2107. ]);
  2108. $status = $response->getStatusCode();
  2109. return $status < 500 && $status != 429;
  2110. } catch (\Exception $e) {
  2111. return false;
  2112. }
  2113. }
  2114. /**
  2115. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  2116. * 全部失败抛出友好错误
  2117. */
  2118. private function ensureGptServiceAvailable()
  2119. {
  2120. $maxRetries = $this->gptRetryTimes();
  2121. $interval = $this->gptRetryInterval();
  2122. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  2123. if ($this->checkGptServiceAvailable()) {
  2124. return;
  2125. }
  2126. if ($attempt < $maxRetries) {
  2127. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  2128. 'retry' => $attempt + 1,
  2129. 'max_retries' => $maxRetries
  2130. ]);
  2131. sleep($interval);
  2132. }
  2133. }
  2134. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  2135. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  2136. 'max_retries' => $maxRetries,
  2137. 'interval' => $interval
  2138. ]);
  2139. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  2140. }
  2141. /**
  2142. * GPT 流式输出处理方法
  2143. *
  2144. * @param array $post_data GPT API请求参数
  2145. * @return \Generator 返回生成器,用于流式输出
  2146. */
  2147. private function gpt54StreamResponse($post_data) {
  2148. $apiKey = env('GPT_54_API_KEY');
  2149. if (empty($apiKey)) {
  2150. Utils::throwError('20003:GPT API Key未配置');
  2151. }
  2152. // 先探活,服务不可用时自动重试
  2153. $this->ensureGptServiceAvailable();
  2154. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2155. $headers = [
  2156. 'Authorization' => 'Bearer ' . $apiKey,
  2157. 'Content-Type' => 'application/json'
  2158. ];
  2159. // 移除 thinking 参数,GPT-5.4 不支持
  2160. if (isset($post_data['thinking'])) {
  2161. unset($post_data['thinking']);
  2162. }
  2163. if (isset($post_data['reasoning_effort'])) {
  2164. unset($post_data['reasoning_effort']);
  2165. }
  2166. $post_data['max_completion_tokens'] = 100000;
  2167. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2168. $post_data['stream_options'] = ['include_usage' => true];
  2169. $maxRetries = $this->gptRetryTimes();
  2170. $interval = $this->gptRetryInterval();
  2171. $attempt = 0;
  2172. while (true) {
  2173. $fullContent = '';
  2174. $usage = [];
  2175. $buffer = '';
  2176. try {
  2177. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  2178. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  2179. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  2180. 'json' => $post_data,
  2181. 'headers' => $headers,
  2182. 'stream' => true // 启用流式响应
  2183. ]);
  2184. $body = $response->getBody();
  2185. dLog('deepseek')->info('开始读取 GPT 流式响应');
  2186. // 逐行读取流式响应
  2187. while (!$body->eof()) {
  2188. $chunk = $body->read(1024); // 每次读取 1KB
  2189. $buffer .= $chunk;
  2190. // 按行分割
  2191. $lines = explode("\n", $buffer);
  2192. // 保留最后一个不完整的行
  2193. $buffer = array_pop($lines);
  2194. foreach ($lines as $line) {
  2195. $line = trim($line);
  2196. // 跳过空行
  2197. if (empty($line)) {
  2198. continue;
  2199. }
  2200. // 检查是否是 SSE 数据行
  2201. if (strpos($line, 'data: ') !== 0) {
  2202. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2203. continue;
  2204. }
  2205. $data = substr($line, 6); // 移除 "data: " 前缀
  2206. if ($data === '[DONE]') {
  2207. dLog('deepseek')->info('收到结束标记');
  2208. break 2; // 跳出 foreach 和流读取循环
  2209. }
  2210. try {
  2211. $json = json_decode($data, true);
  2212. if (json_last_error() !== JSON_ERROR_NONE) {
  2213. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2214. continue;
  2215. }
  2216. if (isset($json['choices'][0]['delta'])) {
  2217. $delta = $json['choices'][0]['delta'];
  2218. // 处理回答内容
  2219. if (isset($delta['content'])) {
  2220. $fullContent .= $delta['content'];
  2221. yield [
  2222. 'type' => 'content',
  2223. 'content' => $delta['content'],
  2224. ];
  2225. }
  2226. }
  2227. // 获取使用统计信息
  2228. if (isset($json['usage'])) {
  2229. $usage = $json['usage'];
  2230. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2231. }
  2232. } catch (\Exception $e) {
  2233. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2234. continue;
  2235. }
  2236. }
  2237. }
  2238. dLog('deepseek')->info('流式读取完成', [
  2239. 'content_length' => strlen($fullContent)
  2240. ]);
  2241. yield [
  2242. 'type' => 'done',
  2243. 'full_content' => $fullContent,
  2244. 'full_reasoning' => '',
  2245. 'usage' => $usage
  2246. ];
  2247. return;
  2248. } catch (\Exception $e) {
  2249. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  2250. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  2251. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  2252. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  2253. throw $e;
  2254. }
  2255. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  2256. 'retry' => $attempt + 1,
  2257. 'max_retries' => $maxRetries,
  2258. 'error' => $e->getMessage()
  2259. ]);
  2260. sleep($interval);
  2261. $attempt++;
  2262. }
  2263. }
  2264. }
  2265. // 与推理模型对话
  2266. public function chatWithReasoner($data) {
  2267. $content = getProp($data, 'content');
  2268. $model = getProp($data, 'model', 'r1');
  2269. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2270. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2271. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2272. if ($model == 'r1') {
  2273. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  2274. $thinkingMode = 'disabled';
  2275. } else {
  2276. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  2277. $thinkingMode = 'disabled';
  2278. }
  2279. // 获取可选情感(根据音色可支持情感选)
  2280. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  2281. $emotion_list = [];
  2282. foreach ($timbre_emotion as $emotion) {
  2283. $tmp = explode(',', $emotion);
  2284. $emotion_list = array_merge($emotion_list, $tmp);
  2285. }
  2286. $emotion_list = array_unique($emotion_list);
  2287. $emotion_str = implode('、', $emotion_list);
  2288. // // 获取可选情感
  2289. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  2290. // $emotion_str = implode('、', $emotion_list);
  2291. // 是否启用情感
  2292. $enable_emotion = getProp($data, 'enable_emotion', 0);
  2293. if ($enable_emotion) {
  2294. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  2295. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2296. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  2297. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  2298. }else {
  2299. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  2300. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2301. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  2302. }
  2303. $messages = [
  2304. [
  2305. 'role' => 'system',
  2306. 'content' => $sys_content
  2307. ],
  2308. [
  2309. 'role' => 'user',
  2310. 'content' => $content
  2311. ]
  2312. ];
  2313. $post_data = [
  2314. 'model' => $model,
  2315. 'messages' => $messages,
  2316. // 'max_tokens' => 8192,
  2317. 'temperature' => 1,
  2318. 'frequency_penalty' => 0,
  2319. 'presence_penalty' => 0,
  2320. 'thinking' => ['type' => $thinkingMode],
  2321. 'response_format' => [
  2322. 'type' => 'text'
  2323. ],
  2324. 'stream' => false
  2325. ];
  2326. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2327. // 根据模型类型选择调用方法
  2328. $fullContent = '';
  2329. $usage = [];
  2330. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2331. // DeepSeek 官方模型使用 DeepSeek API
  2332. $chatResult = $this->chatOnly($post_data);
  2333. } else if (in_array($model, $this->gpt_text_models)) {
  2334. // GPT-5.4 模型使用 TokenRouter API
  2335. $chatResult = $this->gpt54ChatOnly($post_data);
  2336. } else {
  2337. // 其他模型使用火山引擎API
  2338. $chatResult = $this->volcEngineChatCompletion($post_data);
  2339. }
  2340. if (is_array($chatResult)) {
  2341. $fullContent = $chatResult['fullContent'];
  2342. $usage = $chatResult['usage'];
  2343. }
  2344. // 处理获取到的剧本数据
  2345. $script_content = handleScriptWords($fullContent, $enable_emotion);
  2346. $result = [
  2347. 'origin_content' => $fullContent,
  2348. 'roles' => getProp($script_content, 'roles'),
  2349. 'words' => getProp($script_content, 'words'),
  2350. ];
  2351. return $result;
  2352. }
  2353. public function resetParagraphAudio($data) {
  2354. $bid = getProp($data, 'bid');
  2355. $cid = getProp($data, 'cid');
  2356. $version_id = getProp($data, 'version_id');
  2357. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  2358. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  2359. 'generate_status' => '待制作',
  2360. 'updated_at' => date('Y-m-d H:i:s')
  2361. ]);
  2362. }
  2363. public function saveParagraphAudio($data) {
  2364. $bid = getProp($data, 'bid');
  2365. $cid = getProp($data, 'cid');
  2366. $version_id = getProp($data, 'version_id');
  2367. $sequence = getProp($data, 'sequence');
  2368. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  2369. // 获取所有情感
  2370. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2371. $emotion_list = array_flip($emotion_list);
  2372. // 获取音色支持情感
  2373. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  2374. $timbre_emotion = explode(',', $timbre_emotion);
  2375. $emotion = getProp($data, 'emotion');
  2376. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  2377. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  2378. $list = [
  2379. 'bid' => $bid,
  2380. 'cid' => $cid,
  2381. 'version_id' => $version_id,
  2382. 'sequence' => $sequence,
  2383. 'role' => getProp($data, 'role'),
  2384. 'gender' => getProp($data, 'gender'),
  2385. 'text' => trim(getProp($data, 'text')),
  2386. 'emotion' => $emotion,
  2387. 'emotion_type' => $emotion_type,
  2388. 'voice_type' => getProp($data, 'voice_type'),
  2389. 'voice_name' => getProp($data, 'voice_name'),
  2390. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  2391. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  2392. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  2393. 'pitch' => getProp($data, 'pitch', 0),
  2394. // 'paragraph_audio_url' => '',
  2395. 'generate_status' => '制作中',
  2396. 'error_msg' => '',
  2397. 'updated_at' => date('Y-m-d H:i:s')
  2398. ];
  2399. $continue = false;
  2400. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  2401. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  2402. $list['generate_status'] = '制作成功';
  2403. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2404. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  2405. $continue = true;
  2406. }
  2407. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  2408. if ($id) {
  2409. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  2410. }else {
  2411. $list['created_at'] = date('Y-m-d H:i:s');
  2412. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  2413. $boolen = $id ? true : false;
  2414. }
  2415. // 如果更新成功则加入查询队列
  2416. if ($boolen) {
  2417. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  2418. Redis::sadd($redis_key, $id);
  2419. }
  2420. if ($boolen && !$continue) {
  2421. $boolen = false;
  2422. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2423. // 根据ID通过API通知合成音频
  2424. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  2425. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  2426. $response = $result->getBody()->getContents();
  2427. $response_arr = json_decode($response, true);
  2428. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2429. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2430. Log::info('通知火山生成段落音频失败: '.$error_msg);
  2431. Utils::throwError('20003:通知火山生成段落音频失败');
  2432. }
  2433. $boolen = true;
  2434. }
  2435. return $boolen;
  2436. }
  2437. public function insertAudioEffect($data) {
  2438. $audio_id = getProp($data, 'audio_id');
  2439. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2440. $bid = getProp($chapter_audio, 'bid');
  2441. $version_id = getProp($chapter_audio, 'version_id');
  2442. $cid = getProp($chapter_audio, 'cid');
  2443. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2444. $audio_effect_json = getProp($data, 'audio_effect_json');
  2445. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  2446. try {
  2447. DB::beginTransaction();
  2448. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2449. if (!$count) {
  2450. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2451. }else {
  2452. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2453. }
  2454. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2455. 'audio_effect_status' => '添加中',
  2456. 'audio_effect_json' => $audio_effect_json,
  2457. 'updated_at' => date('Y-m-d H:i:s')
  2458. ]);
  2459. if (!$boolen1) {
  2460. DB::rollBack();
  2461. Utils::throwError('20003:更新生成数据失败');
  2462. }
  2463. $id = DB::table('mp_audio_tasks')->insertGetId([
  2464. 'audio_id' => $audio_id,
  2465. 'generate_status' => '执行中',
  2466. 'generate_json' => json_encode([], 256),
  2467. 'bid' => $bid,
  2468. 'book_name' => getProp($chapter_audio, 'book_name'),
  2469. 'version_id' => $version_id,
  2470. 'version_name' => getProp($chapter_audio, 'version_name'),
  2471. 'cid' => $cid,
  2472. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2473. 'task_name' => $task_name,
  2474. 'created_at' => date('Y-m-d H:i:s'),
  2475. 'updated_at' => date('Y-m-d H:i:s')
  2476. ]);
  2477. if (!$id) {
  2478. DB::rollBack();
  2479. Utils::throwError('20003:创建任务失败');
  2480. }
  2481. }catch (\Exception $e) {
  2482. DB::rollBack();
  2483. Utils::throwError('20003:'.$e->getMessage());
  2484. }
  2485. DB::commit();
  2486. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2487. // 根据ID通过API通知合成音频
  2488. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2489. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2490. $response = $result->getBody()->getContents();
  2491. $response_arr = json_decode($response, true);
  2492. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2493. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2494. Log::info('通知火山插入音效失败: '.$error_msg);
  2495. Utils::throwError('20003:通知火山插入音效失败');
  2496. }
  2497. return true;
  2498. }
  2499. public function insertBgm($data) {
  2500. $audio_id = getProp($data, 'audio_id');
  2501. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2502. $bid = getProp($chapter_audio, 'bid');
  2503. $version_id = getProp($chapter_audio, 'version_id');
  2504. $cid = getProp($chapter_audio, 'cid');
  2505. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2506. $bgm_json = getProp($data, 'bgm_json');
  2507. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2508. if (!$bgm_json) {
  2509. $bgm_json = getProp($data, 'audio_effect_json');
  2510. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2511. }
  2512. try {
  2513. DB::beginTransaction();
  2514. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2515. if (!$count) {
  2516. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2517. }else {
  2518. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2519. }
  2520. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2521. 'bgm_status' => '添加中',
  2522. 'bgm_json' => $bgm_json,
  2523. 'updated_at' => date('Y-m-d H:i:s')
  2524. ]);
  2525. if (!$boolen1) {
  2526. DB::rollBack();
  2527. Utils::throwError('20003:更新生成数据失败');
  2528. }
  2529. $id = DB::table('mp_audio_tasks')->insertGetId([
  2530. 'audio_id' => $audio_id,
  2531. 'generate_status' => '执行中',
  2532. 'generate_json' => json_encode([], 256),
  2533. 'bid' => $bid,
  2534. 'book_name' => getProp($chapter_audio, 'book_name'),
  2535. 'version_id' => $version_id,
  2536. 'version_name' => getProp($chapter_audio, 'version_name'),
  2537. 'cid' => $cid,
  2538. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2539. 'task_name' => $task_name,
  2540. 'created_at' => date('Y-m-d H:i:s'),
  2541. 'updated_at' => date('Y-m-d H:i:s')
  2542. ]);
  2543. if (!$id) {
  2544. DB::rollBack();
  2545. Utils::throwError('20003:创建任务失败');
  2546. }
  2547. }catch (\Exception $e) {
  2548. DB::rollBack();
  2549. Utils::throwError('20003:'.$e->getMessage());
  2550. }
  2551. DB::commit();
  2552. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2553. // 根据ID通过API通知合成音频
  2554. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2555. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2556. $response = $result->getBody()->getContents();
  2557. $response_arr = json_decode($response, true);
  2558. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2559. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2560. Log::info('通知火山插入bgm失败: '.$error_msg);
  2561. Utils::throwError('20003:通知火山插入bgm失败');
  2562. }
  2563. return true;
  2564. }
  2565. public function getParagraphAudios($data) {
  2566. $bid = getProp($data, 'bid');
  2567. $cid = getProp($data, 'cid');
  2568. $version_id = getProp($data, 'version_id');
  2569. $sequence = getProp($data, 'sequence');
  2570. // 获取已生成的音频
  2571. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  2572. if ($sequence) $query->where('sequence', $sequence);
  2573. $paragraph_audios = $query->orderBy('sequence')->get();
  2574. $result = [];
  2575. foreach($paragraph_audios as $item) {
  2576. $result[] = [
  2577. 'sequence' => getProp($item, 'sequence'),
  2578. 'role' => getProp($item, 'role'),
  2579. 'gender' => getProp($item, 'gender'),
  2580. 'text' => trim(getProp($item, 'text')),
  2581. 'emotion' => getProp($item, 'emotion'),
  2582. 'emotion_type' => getProp($item, 'emotion_type'),
  2583. 'voice_type' => getProp($item, 'voice_type'),
  2584. 'voice_name' => getProp($item, 'voice_name'),
  2585. 'speed_ratio' => getProp($item, 'speed_ratio'),
  2586. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  2587. 'emotion_scale' => getProp($item, 'emotion_scale'),
  2588. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  2589. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  2590. ];
  2591. }
  2592. return $result;
  2593. }
  2594. // 新增合成任务
  2595. public function addGenerateTask($data) {
  2596. $bid = getProp($data, 'bid');
  2597. $cid = getProp($data, 'cid');
  2598. $version_id = getProp($data, 'version_id');
  2599. $generate_json = getProp($data, 'generate_json');
  2600. // 获取已生成的音频
  2601. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  2602. $paragraph_list = [];
  2603. foreach($paragraph_audios as $item) {
  2604. $paragraph_list[getProp($item, 'sequence')] = [
  2605. 'role' => getProp($item, 'role'),
  2606. 'gender' => getProp($item, 'gender'),
  2607. 'text' => trim(getProp($item, 'text')),
  2608. 'emotion' => getProp($item, 'emotion'),
  2609. 'emotion_type' => getProp($item, 'emotion_type'),
  2610. 'voice_type' => getProp($item, 'voice_type'),
  2611. 'voice_name' => getProp($item, 'voice_name'),
  2612. 'speed_ratio' => getProp($item, 'speed_ratio'),
  2613. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  2614. 'emotion_scale' => getProp($item, 'emotion_scale'),
  2615. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  2616. ];
  2617. }
  2618. // 更新角色-音色信息
  2619. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  2620. $existed_role_info = json_decode($existed_role_info, true);
  2621. if (!$existed_role_info) $existed_role_info = [];
  2622. // 获取情感信息
  2623. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2624. $emotion_list = array_flip($emotion_list);
  2625. // 获取音色对应情感组
  2626. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  2627. $timbre_emotion_list = [];
  2628. foreach($timbre_emotions as $item) {
  2629. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  2630. }
  2631. // 构造生成音频的json
  2632. $words = json_decode($generate_json, true);
  2633. // 最终合成前的参数组
  2634. $mp_chapter_paragraph_audios = [];
  2635. $sequence = 1;
  2636. $complete_paragraph_sequences = [];
  2637. foreach($words as &$word) {
  2638. 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:参数格式有误');
  2639. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  2640. $role = getProp($word, 'role');
  2641. $word['gender'] = (int)$word['gender'];
  2642. // 判断音色对应情感是否支持,不支持则调整为中性
  2643. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  2644. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  2645. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  2646. if (isset($emotion_list[getProp($word, 'emotion')])) {
  2647. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  2648. }else {
  2649. $word['emotion'] = '中性';
  2650. $word['emotion_type'] = 'neutral';
  2651. }
  2652. $existed_role_info[$role] = [
  2653. 'timbre_type' => $word['voice_type'],
  2654. 'timbre_name' => $word['voice_name'],
  2655. 'emotion' => $word['emotion'],
  2656. 'emotion_type' => $word['emotion_type'],
  2657. 'speed_ratio' => $word['speed_ratio'],
  2658. 'loudness_ratio'=> $word['loudness_ratio'],
  2659. 'emotion_scale' => $word['emotion_scale'],
  2660. 'pitch' => $word['pitch']
  2661. ];
  2662. $word['paragraph_audio_url'] = '';
  2663. // 判断生成参数是否相同,相同则直接使用已生成的音频
  2664. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  2665. // 如果音频存在并且参数都未改变则使用已生成的音频
  2666. if (getProp($paragraph, 'paragraph_audio_url')) {
  2667. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  2668. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  2669. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  2670. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  2671. // {
  2672. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  2673. // }
  2674. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  2675. }
  2676. $tmp = $word;
  2677. // 组装章节分句音频数据
  2678. // $tmp['sequence'] = getProp($word, 'sequence');
  2679. // $tmp['text'] = getProp($word, 'text');
  2680. // $tmp['emotion'] = getProp($word, 'emotion');
  2681. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  2682. // $tmp['voice_name'] = getProp($word, 'voice_name');
  2683. // $tmp['voice_type'] = getProp($word, 'voice_type');
  2684. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  2685. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  2686. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  2687. $tmp['bid'] = $bid;
  2688. $tmp['version_id'] = $version_id;
  2689. $tmp['cid'] = $cid;
  2690. $tmp['sequence'] = $sequence;
  2691. $tmp['created_at'] = date('Y-m-d H:i:s');
  2692. $tmp['updated_at'] = date('Y-m-d H:i:s');
  2693. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  2694. $mp_chapter_paragraph_audios[] = $tmp;
  2695. $complete_paragraph_sequences[] = $sequence;
  2696. $sequence++;
  2697. }
  2698. $generate_json = json_encode($words, 256);
  2699. // 判断是否有未生成字幕的段落
  2700. $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();
  2701. if ($no_subtitle_sequences) {
  2702. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  2703. }
  2704. try {
  2705. DB::beginTransaction();
  2706. $role_info = json_encode($existed_role_info, 256);
  2707. $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')]);
  2708. if (!$boolen) {
  2709. DB::rollBack();
  2710. Utils::throwError('20003:更新角色信息失败');
  2711. }
  2712. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  2713. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  2714. if (!$count) {
  2715. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2716. }else {
  2717. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2718. }
  2719. $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')]);
  2720. if (!$boolen1) {
  2721. DB::rollBack();
  2722. Utils::throwError('20003:更新生成数据失败');
  2723. }
  2724. $id = DB::table('mp_audio_tasks')->insertGetId([
  2725. 'audio_id' => getProp($chapter_audio, 'id'),
  2726. 'generate_status' => '执行中',
  2727. 'generate_json' => $generate_json,
  2728. 'bid' => $bid,
  2729. 'book_name' => getProp($chapter_audio, 'book_name'),
  2730. 'version_id' => $version_id,
  2731. 'version_name' => getProp($chapter_audio, 'version_name'),
  2732. 'cid' => $cid,
  2733. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2734. 'task_name' => $task_name,
  2735. 'created_at' => date('Y-m-d H:i:s'),
  2736. 'updated_at' => date('Y-m-d H:i:s')
  2737. ]);
  2738. if (!$id) {
  2739. DB::rollBack();
  2740. Utils::throwError('20003:创建任务失败');
  2741. }
  2742. // 删除不在段落序号范围内的其他数据
  2743. if ($complete_paragraph_sequences) {
  2744. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  2745. }
  2746. // // 删除章节分句音频数据并重新插入
  2747. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  2748. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  2749. // if (!$boolen3) {
  2750. // DB::rollBack();
  2751. // Utils::throwError('20003:更新章节分句音频失败');
  2752. // }
  2753. } catch (\Exception $e) {
  2754. DB::rollBack();
  2755. Utils::throwError('20003:'.$e->getMessage());
  2756. }
  2757. DB::commit();
  2758. // 通知火山生成音频
  2759. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2760. // 根据ID通过API通知合成音频
  2761. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  2762. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  2763. $response = $result->getBody()->getContents();
  2764. $response_arr = json_decode($response, true);
  2765. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2766. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2767. Log::info('通知火山生成音频失败: '.$error_msg);
  2768. Utils::throwError('20003:通知火山生成音频失败');
  2769. }
  2770. return true;
  2771. }
  2772. public function timbreList($data) {
  2773. $gender = getProp($data, 'gender');
  2774. $timbre_name = getProp($data, 'voice_name');
  2775. $category_id = getProp($data, 'category_id');
  2776. $age_stage = getProp($data, 'age_stage');
  2777. $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');
  2778. if ($gender) {
  2779. $query->where('gender', $gender);
  2780. }
  2781. if ($timbre_name) {
  2782. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  2783. }
  2784. if ($category_id) {
  2785. $query->where(function ($query) use ($category_id) {
  2786. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  2787. });
  2788. }
  2789. if ($age_stage) {
  2790. $query->where('age_stage', $age_stage);
  2791. }
  2792. $list = $query->get()->map(function ($value) {
  2793. $value = (array)$value;
  2794. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  2795. return $value;
  2796. })->toArray();
  2797. return $list;
  2798. }
  2799. // 生成火山临时token
  2800. public function setStsToken() {
  2801. // ************* 配置参数 *************
  2802. $method = 'GET';
  2803. $service = 'sts';
  2804. $host = 'open.volcengineapi.com';
  2805. $region = env('VOLC_REGION');
  2806. $endpoint = 'https://open.volcengineapi.com';
  2807. // $endpoint = 'https://tos-cn-beijing.volces.com';
  2808. $access_key = env('VOLC_AK');
  2809. $secret_key = env('VOLC_SK');
  2810. // 获取缓存中的token,如果没有则请求接口
  2811. $token = Redis::get('volc_sts_token');
  2812. if (!$token) {
  2813. // 查询参数
  2814. $query_parameters = [
  2815. 'Action' => 'AssumeRole',
  2816. 'RoleSessionName' => 'user@zw',
  2817. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  2818. 'Version' => '2018-01-01'
  2819. ];
  2820. // 生成URL编码的查询字符串
  2821. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  2822. // 获取签名头信息
  2823. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  2824. // 构建完整URL
  2825. $request_url = $endpoint . '?' . $request_parameters;
  2826. $client = new Client(['verify' => false]);
  2827. $response = $client->get($request_url, ['headers' => $headers]);
  2828. $response_arr = json_decode($response->getBody()->getContents(), true);
  2829. $result = [
  2830. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  2831. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  2832. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  2833. 'Region' => env('VOLC_REGION'),
  2834. 'Endpoint' => env('VOLC_END_POINT'),
  2835. 'Bucket' => env('VOLC_BUCKET'),
  2836. ];
  2837. // 缓存token
  2838. Redis::setex('volc_sts_token', 3000, json_encode($result));
  2839. return $result;
  2840. } else {
  2841. return json_decode($token, true);
  2842. }
  2843. // $response = $response['Response'];
  2844. // $access_key = $response['Credentials']['AccessKeyId'];
  2845. // $secret_key = $response['Credentials']['AccessKeySecret'];
  2846. // $security_token = $response['Credentials']['SecurityToken'];
  2847. // $expiration = $response['Credentials']['Expiration'];
  2848. // dd($response_arr);
  2849. }
  2850. public function emotionGroups($data) {
  2851. $id = getProp($data, 'group_id');
  2852. $group_name = getProp($data, 'group_name');
  2853. $voice_type = getProp($data, 'voice_type');
  2854. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  2855. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  2856. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  2857. if ($group_name) {
  2858. $query->where('group_name', 'like', "%{$group_name}%");
  2859. }
  2860. if ($id) {
  2861. $query->where('id', $id);
  2862. }
  2863. if ($voice_type) {
  2864. $query->where('voice_type', $voice_type);
  2865. }
  2866. return $query->orderBy('id')->get()->map(function ($value) {
  2867. return (array)$value;
  2868. })->toArray();
  2869. }
  2870. private function sign($key, $msg) {
  2871. return hash_hmac('sha256', $msg, $key, true);
  2872. }
  2873. // 生成签名密钥
  2874. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  2875. $kDate = $this->sign($key, $dateStamp);
  2876. $kRegion = $this->sign($kDate, $regionName);
  2877. $kService = $this->sign($kRegion, $serviceName);
  2878. $kSigning = $this->sign($kService, 'request');
  2879. return $kSigning;
  2880. }
  2881. // 获取签名头信息
  2882. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  2883. $contenttype = 'application/x-www-form-urlencoded';
  2884. $accept = 'application/json';
  2885. // 获取当前UTC时间
  2886. $t = new DateTime('now', new DateTimeZone('UTC'));
  2887. $xdate = $t->format('Ymd\THis\Z');
  2888. $datestamp = $t->format('Ymd');
  2889. // 1. 拼接规范请求串
  2890. $canonical_uri = '/';
  2891. $canonical_querystring = $request_parameters;
  2892. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  2893. $signed_headers = 'content-type;host;x-date';
  2894. // 空请求体的SHA256哈希
  2895. $payload_hash = hash('sha256', '');
  2896. $canonical_request = implode("\n", [
  2897. $method,
  2898. $canonical_uri,
  2899. $canonical_querystring,
  2900. $canonical_headers,
  2901. $signed_headers,
  2902. $payload_hash
  2903. ]);
  2904. // 2. 拼接待签名字符串
  2905. $algorithm = 'HMAC-SHA256';
  2906. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  2907. $hashed_canonical_request = hash('sha256', $canonical_request);
  2908. $string_to_sign = implode("\n", [
  2909. $algorithm,
  2910. $xdate,
  2911. $credential_scope,
  2912. $hashed_canonical_request
  2913. ]);
  2914. // 3. 计算签名
  2915. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  2916. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  2917. // 4. 添加签名到请求头
  2918. $authorization_header = sprintf(
  2919. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2920. $algorithm,
  2921. $access_key,
  2922. $credential_scope,
  2923. $signed_headers,
  2924. $signature
  2925. );
  2926. return [
  2927. 'Accept' => $accept,
  2928. 'Content-Type' => $contenttype,
  2929. 'X-Date' => $xdate,
  2930. 'Authorization' => $authorization_header
  2931. ];
  2932. }
  2933. // 文字合成语音(火山引擎)
  2934. public function tts($data) {
  2935. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  2936. $headers = [
  2937. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  2938. 'Content-Type' => 'application/json; charset=UTF-8'
  2939. ];
  2940. $post_data = [
  2941. 'app' => [
  2942. 'appid' => env('VOLC_APPID'),
  2943. 'token' => env('VOLC_TOKEN'),
  2944. 'cluster' => 'volcano_tts'
  2945. ],
  2946. 'user' => [
  2947. 'uid' => 'mp_audio'
  2948. ],
  2949. // 'audio' => [
  2950. // 'voice_type' =>
  2951. // ],
  2952. ];
  2953. }
  2954. public function scriptList($data) {
  2955. $uid = Site::getUid();
  2956. $script_id = getProp($data, 'script_id');
  2957. $script_name = getProp($data, 'script_name');
  2958. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  2959. if ($script_id) {
  2960. $query->where('id', $script_id);
  2961. }
  2962. if ($script_name) {
  2963. $query->where('script_name', 'like', "%{$script_name}%");
  2964. }
  2965. return $query->orderBy('created_at', 'desc')->paginate(12);
  2966. }
  2967. public function scripts($data) {
  2968. $uid = Site::getUid();
  2969. $script_id = getProp($data, 'script_id');
  2970. $script_name = getProp($data, 'script_name');
  2971. $is_products = getProp($data, 'is_products');
  2972. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  2973. if ($script_id) {
  2974. $query->where('id', $script_id);
  2975. }
  2976. if ($is_products !== '') {
  2977. $query->where('is_products', $is_products);
  2978. }
  2979. if ($script_name) {
  2980. $query->where('script_name', 'like', "%{$script_name}%");
  2981. }
  2982. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  2983. return (array)$value;
  2984. })->toArray();
  2985. }
  2986. public function scriptInfo($data) {
  2987. $uid = Site::getUid();
  2988. $script_id = getProp($data, 'script_id');
  2989. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  2990. // ->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();
  2991. ->selectRaw('id as script_id, script_name')->first();
  2992. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2993. $script = (array)$script;
  2994. // 获取分集组信息
  2995. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  2996. ->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')
  2997. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  2998. $value = (array)$value;
  2999. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  3000. return (array)$value;
  3001. })->toArray();
  3002. $script['group'] = $groups;
  3003. return $script;
  3004. }
  3005. public function createScript($data) {
  3006. $script_name = getProp($data, 'script_name');
  3007. $uid = Site::getUid(); // 获取当前用户ID
  3008. $cpid = Site::getCpid(); // 获取当前公司组ID
  3009. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  3010. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  3011. $script_name .= '_'.date('YmdHis');
  3012. }
  3013. return DB::table('mp_scripts')->insertGetId([
  3014. 'script_name' => $script_name,
  3015. 'user_id' => $uid,
  3016. 'cpid' => $cpid,
  3017. 'created_at' => date('Y-m-d H:i:s'),
  3018. 'updated_at' => date('Y-m-d H:i:s')
  3019. ]);
  3020. }
  3021. public function editScript($data) {
  3022. $script_id = getProp($data, 'script_id');
  3023. $script_name = getProp($data, 'script_name');
  3024. $uid = Site::getUid(); // 获取当前用户ID
  3025. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  3026. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  3027. if ($id && (int)$id !== (int)$script_id) {
  3028. $script_name .= '_'.date('YmdHis');
  3029. }
  3030. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3031. 'script_name' => $script_name,
  3032. 'updated_at' => date('Y-m-d H:i:s')
  3033. ]);
  3034. }
  3035. public function delScript($data) {
  3036. $script_id = getProp($data, 'script_id');
  3037. $uid = Site::getUid(); // 获取当前用户ID
  3038. if (!$script_id) Utils::throwError('20003:请选择剧本');
  3039. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3040. 'is_deleted' => 1,
  3041. 'updated_at' => date('Y-m-d H:i:s')
  3042. ]);
  3043. }
  3044. public function createEpisode($data) {
  3045. $script_id = getProp($data, 'script_id');
  3046. $group_name = getProp($data, 'group_name');
  3047. $remark = getProp($data, 'remark');
  3048. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  3049. $uid = Site::getUid(); // 获取当前用户ID
  3050. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  3051. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  3052. $group_name .= '_'.date('YmdHis');
  3053. }
  3054. return DB::table('mp_script_episode_group')->insertGetId([
  3055. 'script_id' => $script_id,
  3056. 'group_name' => $group_name,
  3057. 'user_id' => $uid,
  3058. 'remark' => $remark,
  3059. 'created_at' => date('Y-m-d H:i:s'),
  3060. 'updated_at' => date('Y-m-d H:i:s')
  3061. ]);
  3062. }
  3063. public function editEpisode($data) {
  3064. $group_id = getProp($data, 'group_id');
  3065. $start_episode_number = getProp($data, 'start_episode_number');
  3066. $end_episode_number = getProp($data, 'end_episode_number');
  3067. $group_name = getProp($data, 'group_name');
  3068. $uid = Site::getUid(); // 获取当前用户ID
  3069. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  3070. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  3071. if ($id && (int)$id !== (int)$group_id) {
  3072. $group_name .= '_'.date('YmdHis');
  3073. }
  3074. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3075. 'group_name' => $group_name,
  3076. 'start_episode_number' => $start_episode_number,
  3077. 'end_episode_number' => $end_episode_number,
  3078. 'updated_at' => date('Y-m-d H:i:s')
  3079. ]);
  3080. }
  3081. public function delEpisode($data) {
  3082. $group_id = getProp($data, 'group_id');
  3083. $uid = Site::getUid(); // 获取当前用户ID
  3084. if (!$group_id) Utils::throwError('20003:请选择分集');
  3085. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3086. 'is_deleted' => 1,
  3087. 'updated_at' => date('Y-m-d H:i:s')
  3088. ]);
  3089. }
  3090. /**
  3091. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3092. *
  3093. * @param array $data 包含以下参数:
  3094. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3095. * - question: 用户问题(可选)
  3096. * - model: 使用的模型(r1 或 v3,默认 v3)
  3097. * @return \Generator 返回生成器,用于流式输出
  3098. */
  3099. public function generateEpisodes($data) {
  3100. $script_id = getProp($data, 'script_id');
  3101. $group_id = getProp($data, 'group_id');
  3102. // $file = getProp($data, 'file');
  3103. $file = '';
  3104. $content = getProp($data, 'content', '');
  3105. // $bid = getProp($data, 'bid', 0);
  3106. $bid = 0;
  3107. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3108. if (!$group) {
  3109. Utils::throwError('20003:剧本分集不存在');
  3110. }
  3111. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  3112. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  3113. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  3114. $prompt = getProp($data, 'prompt');
  3115. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  3116. $model = getProp($data, 'model');
  3117. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3118. Utils::throwError('20003:该模型不存在!');
  3119. }
  3120. // 检查是否存在重叠的剧集序号范围
  3121. $exists_groups = DB::table('mp_script_episode_group')
  3122. ->where('script_id', $script_id)
  3123. ->where('id', '<>', $group_id) // 排除当前组
  3124. ->where('is_deleted', 0)
  3125. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3126. // 检查新范围是否与现有范围重叠
  3127. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3128. // 新范围的开始在现有范围内
  3129. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3130. ->where('end_episode_number', '>=', $start_episode_sequence);
  3131. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3132. // 新范围的结束在现有范围内
  3133. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3134. ->where('end_episode_number', '>=', $end_episode_sequence);
  3135. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3136. // 新范围完全包含现有范围
  3137. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3138. ->where('end_episode_number', '<=', $end_episode_sequence);
  3139. });
  3140. })
  3141. ->select('start_episode_number', 'end_episode_number')
  3142. ->get();
  3143. if ($exists_groups->isNotEmpty()) {
  3144. $conflict_ranges = [];
  3145. foreach ($exists_groups as $group) {
  3146. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3147. }
  3148. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3149. }
  3150. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3151. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3152. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3153. if ($model === 'deepseek-chat') {
  3154. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3155. $model = 'deepseek-v4-flash';
  3156. $thinkingMode = 'disabled';
  3157. } elseif ($model === 'deepseek-reasoner') {
  3158. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3159. $model = 'deepseek-v4-flash';
  3160. $thinkingMode = 'enabled';
  3161. }
  3162. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3163. if (!$script) {
  3164. Utils::throwError('20003:剧本不存在');
  3165. }
  3166. $content = getProp($group, 'content');
  3167. if (!$file && !$content && !$bid) {
  3168. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3169. }
  3170. // 提取文件内容
  3171. if ($file) {
  3172. $content = $this->extractFileContent($file);
  3173. if (!$content) {
  3174. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3175. }
  3176. } elseif ($bid) {
  3177. $content = $this->getContentByBid($bid);
  3178. if (!$content) {
  3179. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3180. }
  3181. } elseif ($content) {
  3182. $content = filterContent($content);
  3183. } elseif ($prompt) {
  3184. $content = filterContent($prompt);
  3185. } else {
  3186. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3187. }
  3188. // 构建消息
  3189. $messages = [
  3190. $this->sys_message,
  3191. [
  3192. 'role' => 'user',
  3193. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3194. ]
  3195. ];
  3196. $post_data = [
  3197. 'model' => $model,
  3198. 'messages' => $messages,
  3199. // 'max_tokens' => 8192,
  3200. 'temperature' => 0.7,
  3201. 'frequency_penalty' => 0,
  3202. 'presence_penalty' => 0,
  3203. 'thinking' => ['type' => $thinkingMode],
  3204. 'response_format' => ['type' => 'text'],
  3205. 'stream' => true
  3206. ];
  3207. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3208. // 根据模型类型选择调用方法
  3209. $fullContent = '';
  3210. $fullReasoningContent = '';
  3211. $usage = [];
  3212. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3213. // DeepSeek 官方模型使用 DeepSeek API
  3214. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3215. } else if (in_array($model, $this->gpt_text_models)) {
  3216. // GPT-5.4 模型使用 TokenRouter API
  3217. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3218. } else if (in_array($model, $this->gemini_text_models)) {
  3219. // Gemini 模型使用 Gemini API
  3220. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3221. } else {
  3222. // 其他模型使用火山引擎API
  3223. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3224. }
  3225. // 处理流式输出
  3226. foreach ($streamGenerator as $chunk) {
  3227. if (isset($chunk['type'])) {
  3228. if ($chunk['type'] === 'done') {
  3229. // 最终结果
  3230. $fullContent = $chunk['full_content'];
  3231. $fullReasoningContent = $chunk['full_reasoning'];
  3232. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3233. } else {
  3234. // 逐块yield数据
  3235. yield $chunk;
  3236. }
  3237. }
  3238. }
  3239. dLog('deepseek')->info('完整内容: '.$fullContent);
  3240. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3241. // 处理完整内容并返回最终结果
  3242. $script_arr = [];
  3243. if ($fullContent) {
  3244. $script_arr = extractScriptContent($fullContent);
  3245. }
  3246. logDB('deepseek', 'info', '解析内容', $script_arr);
  3247. if (!$script_arr['episodes']) {
  3248. Utils::throwError('20003:未生成剧本相关信息');
  3249. // yield [
  3250. // 'type' => 'done',
  3251. // 'script' => $script_arr,
  3252. // 'msg' => '未生成剧本相关信息',
  3253. // 'answer' => $fullContent,
  3254. // 'reasoning' => $fullReasoningContent,
  3255. // 'usage' => $usage
  3256. // ];
  3257. // return ;
  3258. }
  3259. try {
  3260. DB::beginTransaction();
  3261. // // 返回前保存剧本内容
  3262. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3263. // 'content' => $content,
  3264. // 'updated_at' => date('Y-m-d H:i:s')
  3265. // ]);
  3266. // if (!$boolen) {
  3267. // Utils::throwError('20003:保存剧本内容失败');
  3268. // }
  3269. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3270. // 'start_episode_number' => $start_episode_sequence,
  3271. // 'end_episode_number' => $end_episode_sequence,
  3272. // 'updated_at' => date('Y-m-d H:i:s')
  3273. // ]);
  3274. // if (!$boolen1) {
  3275. // Utils::throwError('20003:保存分集失败');
  3276. // }
  3277. $episode_content = '';
  3278. $episodes = [];
  3279. foreach ($script_arr['episodes'] as $item) {
  3280. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  3281. // $episodes[] = [
  3282. // 'script_id' => $script_id,
  3283. // 'episode_number' => $item['episode_number'],
  3284. // 'episode_name' => $item['episode_name'],
  3285. // 'episode_content' => $item['episode_content'],
  3286. // 'created_at' => date('Y-m-d H:i:s'),
  3287. // 'updated_at' => date('Y-m-d H:i:s'),
  3288. // ];
  3289. }
  3290. if ($episode_content) {
  3291. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3292. 'episode_content' => $episode_content,
  3293. 'updated_at' => date('Y-m-d H:i:s')
  3294. ]);
  3295. if (!$boolen2) {
  3296. Utils::throwError('20003:保存分集内容失败');
  3297. }
  3298. }else {
  3299. Utils::throwError('20003:分集剧本解析失败');
  3300. }
  3301. }catch (\Exception $e) {
  3302. DB::rollBack();
  3303. Utils::throwError('20003:'.$e->getMessage());
  3304. }
  3305. DB::commit();
  3306. yield [
  3307. 'type' => 'done',
  3308. 'script' => $script_arr,
  3309. 'episode_content' => $episode_content,
  3310. 'answer' => $fullContent,
  3311. 'reasoning' => $fullReasoningContent,
  3312. 'usage' => $usage
  3313. ];
  3314. }
  3315. public function chatWithFileStream($data) {
  3316. $script_id = getProp($data, 'script_id');
  3317. $group_id = getProp($data, 'group_id');
  3318. $file = getProp($data, 'file');
  3319. $content = getProp($data, 'content', '');
  3320. $bid = getProp($data, 'bid', 0);
  3321. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3322. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3323. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  3324. $prompt = getProp($data, 'prompt');
  3325. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3326. if (!empty($prompt)) {
  3327. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3328. }
  3329. $question = getProp($data, 'question', $baseQuestion);
  3330. $model = getProp($data, 'model');
  3331. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3332. Utils::throwError('20003:该模型不存在!');
  3333. }
  3334. // 检查是否存在重叠的剧集序号范围
  3335. $exists_groups = DB::table('mp_script_episode_group')
  3336. ->where('script_id', $script_id)
  3337. ->where('id', '<>', $group_id)
  3338. ->where('is_deleted', 0)
  3339. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3340. // 检查新范围是否与现有范围重叠
  3341. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3342. // 新范围的开始在现有范围内
  3343. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3344. ->where('end_episode_number', '>=', $start_episode_sequence);
  3345. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3346. // 新范围的结束在现有范围内
  3347. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3348. ->where('end_episode_number', '>=', $end_episode_sequence);
  3349. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3350. // 新范围完全包含现有范围
  3351. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3352. ->where('end_episode_number', '<=', $end_episode_sequence);
  3353. });
  3354. })
  3355. ->select('start_episode_number', 'end_episode_number')
  3356. ->get();
  3357. if ($exists_groups->isNotEmpty()) {
  3358. $conflict_ranges = [];
  3359. foreach ($exists_groups as $group) {
  3360. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3361. }
  3362. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3363. }
  3364. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3365. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3366. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3367. if ($model === 'deepseek-chat') {
  3368. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3369. $model = 'deepseek-v4-flash';
  3370. $thinkingMode = 'disabled';
  3371. } elseif ($model === 'deepseek-reasoner') {
  3372. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3373. $model = 'deepseek-v4-flash';
  3374. $thinkingMode = 'enabled';
  3375. }
  3376. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3377. if (!$script) {
  3378. Utils::throwError('20003:剧本不存在');
  3379. }
  3380. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3381. if (!$group) {
  3382. Utils::throwError('20003:剧本分集不存在');
  3383. }
  3384. if (!$file && !$content && !$bid) {
  3385. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3386. }
  3387. // 提取文件内容
  3388. if ($file) {
  3389. $content = $this->extractFileContent($file);
  3390. if (!$content) {
  3391. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3392. }
  3393. } elseif ($bid) {
  3394. $content = $this->getContentByBid($bid);
  3395. if (!$content) {
  3396. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3397. }
  3398. } elseif ($content) {
  3399. $content = filterContent($content);
  3400. } elseif ($prompt) {
  3401. $content = filterContent($prompt);
  3402. } else {
  3403. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3404. }
  3405. // 构建消息
  3406. $messages = [
  3407. [
  3408. 'role' => 'system',
  3409. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3410. 强制要求:\n
  3411. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3412. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  3413. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  3414. 普通要求:\n
  3415. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  3416. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  3417. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  3418. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  3419. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  3420. 示例如下:\n
  3421. ###剧本名:西昆仑
  3422. ###故事梗概
  3423. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3424. ###剧本亮点
  3425. 亮点1:绝境奇药,生死一线
  3426. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3427. 亮点2:结拜兄妹,化解尴尬
  3428. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3429. 亮点3:纤发夺命,情愫暗涌
  3430. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3431. ###人物关系
  3432. 阿雪与梁萧之间存在兄妹之情。
  3433. ###核心矛盾
  3434. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3435. ###主体列表
  3436. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3437. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3438. 阴阳球:天地异宝,能化生精气,救人于危难。
  3439. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3440. ###美术风格
  3441. 基础画风风格词:厚涂古风
  3442. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3443. ###场景列表
  3444. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  3445. [
  3446. 'role' => 'user',
  3447. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3448. ]
  3449. ];
  3450. $post_data = [
  3451. 'model' => $model,
  3452. 'messages' => $messages,
  3453. // 'max_tokens' => 8192,
  3454. 'temperature' => 0.7,
  3455. 'frequency_penalty' => 0,
  3456. 'presence_penalty' => 0,
  3457. 'thinking' => ['type' => $thinkingMode],
  3458. 'response_format' => ['type' => 'text'],
  3459. 'stream' => true
  3460. ];
  3461. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3462. // 根据模型类型选择调用方法
  3463. $fullContent = '';
  3464. $fullReasoningContent = '';
  3465. $usage = [];
  3466. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3467. // DeepSeek 官方模型使用 DeepSeek API
  3468. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3469. } else if (in_array($model, $this->gpt_text_models)) {
  3470. // GPT-5.4 模型使用 TokenRouter API
  3471. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3472. } else if (in_array($model, $this->gemini_text_models)) {
  3473. // Gemini 模型使用 Gemini API
  3474. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3475. } else {
  3476. // 其他模型使用火山引擎API
  3477. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3478. }
  3479. // 处理流式输出
  3480. foreach ($streamGenerator as $chunk) {
  3481. if (isset($chunk['type'])) {
  3482. if ($chunk['type'] === 'done') {
  3483. // 最终结果
  3484. $fullContent = $chunk['full_content'];
  3485. $fullReasoningContent = $chunk['full_reasoning'];
  3486. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3487. } else {
  3488. // 逐块yield数据
  3489. yield $chunk;
  3490. }
  3491. }
  3492. }
  3493. dLog('deepseek')->info('完整内容: '.$fullContent);
  3494. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3495. // 处理完整内容并返回最终结果
  3496. $script_arr = [];
  3497. if ($fullContent) {
  3498. $script_arr = extractScriptContent($fullContent);
  3499. }
  3500. logDB('deepseek', 'info', '解析内容', $script_arr);
  3501. if (!$script_arr['roles']) {
  3502. Utils::throwError('20003:未生成剧本相关信息');
  3503. // yield [
  3504. // 'type' => 'done',
  3505. // 'script' => $script_arr,
  3506. // 'msg' => '未生成剧本相关信息',
  3507. // 'answer' => $fullContent,
  3508. // 'reasoning' => $fullReasoningContent,
  3509. // 'usage' => $usage
  3510. // ];
  3511. }
  3512. try {
  3513. DB::beginTransaction();
  3514. // // 返回前保存剧本内容
  3515. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3516. // 'content' => $content,
  3517. // 'status' => '解析完成',
  3518. // 'updated_at' => date('Y-m-d H:i:s')
  3519. // ]);
  3520. // if (!$boolen) {
  3521. // Utils::throwError('20003:保存剧本内容失败');
  3522. // }
  3523. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3524. 'start_episode_number' => $start_episode_sequence,
  3525. 'end_episode_number' => $end_episode_sequence,
  3526. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3527. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3528. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3529. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3530. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3531. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3532. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3533. 'status' => '解析完成',
  3534. 'content' => $content,
  3535. 'updated_at' => date('Y-m-d H:i:s')
  3536. ]);
  3537. if (!$boolen1) {
  3538. Utils::throwError('20003:保存分集失败');
  3539. }
  3540. // $episodes = [];
  3541. // foreach ($script_arr['episodes'] as $item) {
  3542. // $episodes[] = [
  3543. // 'script_id' => $script_id,
  3544. // 'episode_number' => $item['episode_number'],
  3545. // 'episode_name' => $item['episode_name'],
  3546. // 'episode_content' => $item['episode_content'],
  3547. // 'created_at' => date('Y-m-d H:i:s'),
  3548. // 'updated_at' => date('Y-m-d H:i:s'),
  3549. // ];
  3550. // }
  3551. // if ($episodes) {
  3552. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  3553. // if (!$boolen2) {
  3554. // Utils::throwError('20003:保存分集内容失败');
  3555. // }
  3556. // }else {
  3557. // Utils::throwError('20003:分集剧本解析失败');
  3558. // }
  3559. }catch (\Exception $e) {
  3560. DB::rollBack();
  3561. Utils::throwError('20003:'.$e->getMessage());
  3562. }
  3563. DB::commit();
  3564. yield [
  3565. 'type' => 'done',
  3566. 'script' => $script_arr,
  3567. 'answer' => $fullContent,
  3568. 'reasoning' => $fullReasoningContent,
  3569. 'usage' => $usage
  3570. ];
  3571. }
  3572. /**
  3573. * 上传文件识别文字内容并与 DeepSeek 进行对话
  3574. *
  3575. * @param array $data 包含以下参数:
  3576. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3577. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  3578. * - model: 使用的模型(r1 或 v3,默认 v3)
  3579. * @return array
  3580. */
  3581. public function chatWithFile($data) {
  3582. $script_id = getProp($data, 'script_id');
  3583. $file = getProp($data, 'file');
  3584. $content = getProp($data, 'content', '');
  3585. $bid = getProp($data, 'bid', 0);
  3586. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3587. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3588. $prompt = getProp($data, 'prompt');
  3589. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3590. if (!empty($prompt)) {
  3591. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3592. }
  3593. $question = getProp($data, 'question', $baseQuestion);
  3594. // 处理文本模型
  3595. $model = getProp($data, 'model');
  3596. if (!$model) {
  3597. // 用户没有输入,使用默认值
  3598. $model = 'doubao-seed-2-0-mini-260215';
  3599. }
  3600. // 验证模型是否在可用模型表中
  3601. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3602. $model = 'doubao-seed-2-0-mini-260215';
  3603. }
  3604. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3605. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3606. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3607. if ($model === 'deepseek-chat') {
  3608. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3609. $model = 'deepseek-v4-flash';
  3610. $thinkingMode = 'disabled';
  3611. } elseif ($model === 'deepseek-reasoner') {
  3612. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3613. $model = 'deepseek-v4-flash';
  3614. $thinkingMode = 'enabled';
  3615. }
  3616. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3617. if (!$script) {
  3618. Utils::throwError('20003:剧本不存在');
  3619. }
  3620. if (!$file && !$content && !$bid) {
  3621. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3622. }
  3623. // 提取文件内容
  3624. if ($file) {
  3625. $content = $this->extractFileContent($file);
  3626. if (!$content) {
  3627. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3628. }
  3629. } elseif ($bid) {
  3630. $content = $this->getContentByBid($bid);
  3631. if (!$content) {
  3632. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3633. }
  3634. } elseif ($content) {
  3635. $content = filterContent($content);
  3636. } elseif ($prompt) {
  3637. $content = filterContent($prompt);
  3638. } else {
  3639. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3640. }
  3641. // 构建消息
  3642. $messages = [
  3643. $this->sys_message,
  3644. [
  3645. 'role' => 'user',
  3646. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3647. ]
  3648. ];
  3649. $post_data = [
  3650. 'model' => $model,
  3651. 'messages' => $messages,
  3652. // 'max_tokens' => 8192,
  3653. 'temperature' => 0.7,
  3654. 'frequency_penalty' => 0,
  3655. 'presence_penalty' => 0,
  3656. 'thinking' => ['type' => $thinkingMode],
  3657. 'response_format' => ['type' => 'text'],
  3658. 'stream' => false
  3659. ];
  3660. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3661. // 根据模型类型选择调用方法
  3662. $fullContent = '';
  3663. $usage = [];
  3664. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3665. // DeepSeek 官方模型使用 DeepSeek API
  3666. $chatResult = $this->chatOnly($post_data);
  3667. } else if (in_array($model, $this->gpt_text_models)) {
  3668. // GPT-5.4 模型使用 TokenRouter API
  3669. $chatResult = $this->gpt54ChatOnly($post_data);
  3670. } else {
  3671. // 其他模型使用火山引擎API
  3672. $chatResult = $this->volcEngineChatCompletion($post_data);
  3673. }
  3674. if (is_array($chatResult)) {
  3675. $fullContent = $chatResult['fullContent'];
  3676. $usage = $chatResult['usage'];
  3677. }
  3678. $script_arr = [];
  3679. // 处理结果
  3680. if ($fullContent) {
  3681. $script_arr = extractScriptContent($fullContent);
  3682. }
  3683. // 返回前保存剧本内容
  3684. DB::table('mp_scripts')->where('id', $script_id)->update([
  3685. 'content' => $content,
  3686. 'updated_at' => date('Y-m-d H:i:s')
  3687. ]);
  3688. return [
  3689. 'script' => $script_arr,
  3690. 'answer' => $fullContent,
  3691. 'usage' => $usage
  3692. ];
  3693. }
  3694. public function getEpisodeContent($data) {
  3695. $group_id = getProp($data, 'group_id');
  3696. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  3697. }
  3698. public function saveEpisodeContent($data) {
  3699. $script_id = getProp($data, 'script_id');
  3700. $group_id = getProp($data, 'group_id');
  3701. $start_episode_sequence = getProp($data, 'start_episode_number');
  3702. $end_episode_sequence = getProp($data, 'end_episode_number');
  3703. // 检查是否存在重叠的剧集序号范围
  3704. $exists_groups = DB::table('mp_script_episode_group')
  3705. ->where('script_id', $script_id)
  3706. ->where('id', '<>', $group_id) // 排除当前组
  3707. ->where('is_deleted', 0)
  3708. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3709. // 检查新范围是否与现有范围重叠
  3710. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3711. // 新范围的开始在现有范围内
  3712. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3713. ->where('end_episode_number', '>=', $start_episode_sequence);
  3714. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3715. // 新范围的结束在现有范围内
  3716. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3717. ->where('end_episode_number', '>=', $end_episode_sequence);
  3718. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3719. // 新范围完全包含现有范围
  3720. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3721. ->where('end_episode_number', '<=', $end_episode_sequence);
  3722. });
  3723. })
  3724. ->select('start_episode_number', 'end_episode_number')
  3725. ->get();
  3726. if ($exists_groups->isNotEmpty()) {
  3727. $conflict_ranges = [];
  3728. foreach ($exists_groups as $group) {
  3729. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3730. }
  3731. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3732. }
  3733. $episode_content = getProp($data, 'episode_content');
  3734. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  3735. 'content' => $episode_content,
  3736. 'start_episode_number' => $start_episode_sequence,
  3737. 'end_episode_number' => $end_episode_sequence,
  3738. 'updated_at' => date('Y-m-d H:i:s')
  3739. ]);
  3740. $script_arr =getProp($data, 'script', []);
  3741. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  3742. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3743. $script_id = getProp($data, 'script_id');
  3744. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  3745. try {
  3746. DB::beginTransaction();
  3747. $update_data = [
  3748. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3749. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3750. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3751. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3752. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3753. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3754. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3755. 'status' => 3,
  3756. 'start_episode_sequence' => $start_episode_sequence,
  3757. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  3758. 'episode_num' => count($script_arr['episodes']),
  3759. 'updated_at' => date('Y-m-d H:i:s')
  3760. ];
  3761. // 保存剧本内容
  3762. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  3763. if (!$boolen) {
  3764. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  3765. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  3766. Utils::throwError('20003:剧本内容保存失败');
  3767. }
  3768. // 保存分集内容
  3769. // 删除历史分集内容
  3770. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  3771. $episodes = [];
  3772. $sequence = 1;
  3773. foreach ($script_arr['episodes'] as $episode) {
  3774. $segment_number = 1;
  3775. foreach($episode['segments'] as $segment) {
  3776. $episodes[] = [
  3777. 'script_id' => $script_id,
  3778. 'episode_number' => $episode['episode_number'],
  3779. 'title' => $episode['title'],
  3780. // 'content' => $episode['content'],
  3781. 'content' => '',
  3782. 'segment_number' => $segment_number,
  3783. 'segment_content' => $segment['segment_content'],
  3784. 'sequence' => $sequence,
  3785. 'created_at' => date('Y-m-d H:i:s'),
  3786. 'updated_at' => date('Y-m-d H:i:s')
  3787. ];
  3788. $sequence++;
  3789. $segment_number++;
  3790. }
  3791. }
  3792. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  3793. if (!$boolen2) {
  3794. dLog('deepseek')->info('分集内容保存失败', $episodes);
  3795. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  3796. Utils::throwError('20003:分集内容保存失败');
  3797. }
  3798. } catch (\Exception $e) {
  3799. DB::rollBack();
  3800. Utils::throwError('20003:'.$e->getMessage());
  3801. }
  3802. DB::commit();
  3803. return true;
  3804. }
  3805. public function getBookContent($data) {
  3806. $bid = getProp($data, 'bid');
  3807. $start_sequence = getProp($data, 'start_sequence');
  3808. $end_sequence = getProp($data, 'end_sequence');
  3809. $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])
  3810. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  3811. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  3812. return $return_content;
  3813. }
  3814. public function exportScript($data) {
  3815. $filename = getProp($data, 'filename');
  3816. $script_id = getProp($data, 'script_id');
  3817. $group_id = getProp($data, 'group_id');
  3818. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  3819. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  3820. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3821. $script = (array)$script;
  3822. // 获取分集组信息
  3823. if ($group_id) {
  3824. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3825. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3826. ->get()->map(function($value) {
  3827. return (array)$value;
  3828. })->toArray();
  3829. }else {
  3830. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3831. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3832. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  3833. return (array)$value;
  3834. })->toArray();
  3835. }
  3836. if (!$groups) Utils::throwError('20003:分集不存在');
  3837. $script['group'] = $groups;
  3838. $export_type = getProp($data, 'export_type', 'txt');
  3839. // 生成文件名
  3840. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  3841. // 根据导出类型生成不同格式的文件
  3842. switch ($export_type) {
  3843. case 'txt':
  3844. return $this->exportScriptAsTxt($script, $filename);
  3845. case 'pdf':
  3846. return $this->exportScriptAsPdf($script, $filename);
  3847. default:
  3848. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  3849. }
  3850. }
  3851. /**
  3852. * 导出剧本为TXT格式
  3853. */
  3854. private function exportScriptAsTxt($script, $filename) {
  3855. // 构建TXT内容
  3856. $content = $this->buildScriptContent($script);
  3857. // 设置响应头,直接下载
  3858. header('Content-Type: text/plain; charset=utf-8');
  3859. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  3860. header('Content-Length: ' . strlen($content));
  3861. // 输出内容并结束
  3862. echo $content;
  3863. exit();
  3864. }
  3865. /**
  3866. * 导出剧本为PDF格式
  3867. */
  3868. private function exportScriptAsPdf($script, $filename) {
  3869. // 使用HTML转PDF的方式来更好地支持中文
  3870. $htmlContent = $this->buildScriptHtmlForPdf($script);
  3871. // 创建PDF实例
  3872. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  3873. // 设置文档信息
  3874. $pdf->SetCreator('剧本导出系统');
  3875. $pdf->SetAuthor('系统');
  3876. $pdf->SetTitle($script['script_name']);
  3877. $pdf->SetSubject('剧本导出');
  3878. // 设置边距
  3879. $pdf->SetMargins(15, 15, 15);
  3880. $pdf->SetAutoPageBreak(TRUE, 15);
  3881. // 添加页面
  3882. $pdf->AddPage();
  3883. // 注册并使用 simsun.ttf 字体
  3884. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  3885. // 使用HTML内容生成PDF
  3886. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  3887. // 直接输出PDF文件供下载
  3888. header('Content-Type: application/pdf');
  3889. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  3890. // 直接输出PDF内容
  3891. $pdf->Output($filename . '.pdf', 'D');
  3892. exit();
  3893. }
  3894. /**
  3895. * 构建用于PDF的HTML内容
  3896. */
  3897. private function buildScriptHtmlForPdf($script) {
  3898. $html = '<style>
  3899. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  3900. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  3901. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  3902. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  3903. .info { margin-bottom: 8px; }
  3904. .group { margin-bottom: 30px; page-break-inside: avoid; }
  3905. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  3906. .segment { margin-bottom: 10px; margin-left: 20px; }
  3907. .episode-content { white-space: pre-wrap; }
  3908. </style>';
  3909. // 标题
  3910. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  3911. // 处理分组数据
  3912. if (!empty($script['group']) && is_array($script['group'])) {
  3913. $groups = (array)$script['group'];
  3914. foreach ($groups as $group) {
  3915. $html .= '<div class="group">';
  3916. // 分组标题
  3917. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  3918. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  3919. // 故事梗概
  3920. if (!empty($group['intro'])) {
  3921. $html .= '<h3>故事梗概</h3>';
  3922. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  3923. }
  3924. // 剧本亮点
  3925. if (!empty($group['highlights'])) {
  3926. $html .= '<h3>剧本亮点</h3>';
  3927. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  3928. }
  3929. // 人物关系
  3930. if (!empty($group['role_relationship'])) {
  3931. $html .= '<h3>人物关系</h3>';
  3932. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  3933. }
  3934. // 核心矛盾
  3935. if (!empty($group['core_contradiction'])) {
  3936. $html .= '<h3>核心矛盾</h3>';
  3937. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  3938. }
  3939. // 主体列表
  3940. if (!empty($group['roles']) && is_array($group['roles'])) {
  3941. $html .= '<h3>主体列表</h3>';
  3942. $html .= '<ul>';
  3943. foreach ($group['roles'] as $role) {
  3944. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  3945. }
  3946. $html .= '</ul>';
  3947. }
  3948. // 美术风格
  3949. if (!empty($group['art_style'])) {
  3950. $html .= '<h3>美术风格</h3>';
  3951. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  3952. }
  3953. // 场景列表
  3954. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3955. $html .= '<h3>场景列表</h3>';
  3956. $html .= '<ul>';
  3957. foreach ($group['scenes'] as $scene) {
  3958. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  3959. }
  3960. $html .= '</ul>';
  3961. }
  3962. // 分集剧本
  3963. if (!empty($group['episode_content'])) {
  3964. $html .= '<h3>分集剧本</h3>';
  3965. // 去除零宽字符和其他不可见字符
  3966. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  3967. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  3968. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  3969. }
  3970. $html .= '</div>';
  3971. }
  3972. }
  3973. return $html;
  3974. }
  3975. /**
  3976. * 构建PDF内容
  3977. */
  3978. private function buildPdfContent($pdf, $script) {
  3979. // 标题
  3980. $pdf->SetFont('dejavusans', 'B', 18);
  3981. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  3982. $pdf->Ln(5);
  3983. // 基本信息
  3984. $pdf->SetFont('dejavusans', '', 12);
  3985. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  3986. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  3987. $pdf->Ln(5);
  3988. // 剧本简介
  3989. if (!empty($script['intro'])) {
  3990. $pdf->SetFont('dejavusans', 'B', 14);
  3991. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  3992. $pdf->SetFont('dejavusans', '', 12);
  3993. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  3994. $pdf->Ln(3);
  3995. }
  3996. // 亮点
  3997. if (!empty($script['highlights'])) {
  3998. $pdf->SetFont('dejavusans', 'B', 14);
  3999. $pdf->Cell(0, 10, '亮点', 0, 1);
  4000. $pdf->SetFont('dejavusans', '', 12);
  4001. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  4002. $pdf->Ln(3);
  4003. }
  4004. // 核心矛盾
  4005. if (!empty($script['core_contradiction'])) {
  4006. $pdf->SetFont('dejavusans', 'B', 14);
  4007. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  4008. $pdf->SetFont('dejavusans', '', 12);
  4009. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  4010. $pdf->Ln(3);
  4011. }
  4012. // 艺术风格
  4013. if (!empty($script['art_style'])) {
  4014. $pdf->SetFont('dejavusans', 'B', 14);
  4015. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  4016. $pdf->SetFont('dejavusans', '', 12);
  4017. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  4018. $pdf->Ln(3);
  4019. }
  4020. // 备注
  4021. if (!empty($script['remark'])) {
  4022. $pdf->SetFont('dejavusans', 'B', 14);
  4023. $pdf->Cell(0, 10, '备注', 0, 1);
  4024. $pdf->SetFont('dejavusans', '', 12);
  4025. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  4026. $pdf->Ln(3);
  4027. }
  4028. // 角色列表
  4029. if (!empty($script['roles']) && is_array($script['roles'])) {
  4030. $pdf->SetFont('dejavusans', 'B', 14);
  4031. $pdf->Cell(0, 10, '角色列表', 0, 1);
  4032. $pdf->SetFont('dejavusans', '', 12);
  4033. foreach ($script['roles'] as $index => $role) {
  4034. if (is_array($role) || is_object($role)) {
  4035. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  4036. } else {
  4037. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  4038. }
  4039. }
  4040. $pdf->Ln(3);
  4041. }
  4042. // 角色关系
  4043. if (!empty($script['role_relationship'])) {
  4044. $pdf->SetFont('dejavusans', 'B', 14);
  4045. $pdf->Cell(0, 10, '角色关系', 0, 1);
  4046. $pdf->SetFont('dejavusans', '', 12);
  4047. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  4048. $pdf->Ln(3);
  4049. }
  4050. // 场景列表
  4051. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  4052. $pdf->SetFont('dejavusans', 'B', 14);
  4053. $pdf->Cell(0, 10, '场景列表', 0, 1);
  4054. $pdf->SetFont('dejavusans', '', 12);
  4055. foreach ($script['scenes'] as $index => $scene) {
  4056. if (is_array($scene) || is_object($scene)) {
  4057. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  4058. } else {
  4059. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  4060. }
  4061. }
  4062. $pdf->Ln(5);
  4063. }
  4064. // 分集内容
  4065. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  4066. $pdf->SetFont('dejavusans', 'B', 16);
  4067. $pdf->Cell(0, 12, '分集内容', 0, 1);
  4068. $pdf->Ln(3);
  4069. foreach ($script['episodes'] as $episode) {
  4070. // 检查是否需要新页面
  4071. if ($pdf->GetY() > 250) {
  4072. $pdf->AddPage();
  4073. }
  4074. $pdf->SetFont('dejavusans', 'B', 14);
  4075. $episodeTitle = '第' . $episode['episode_number'] . '集';
  4076. if (!empty($episode['title'])) {
  4077. $episodeTitle .= ':' . $episode['title'];
  4078. }
  4079. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  4080. // 处理分段内容
  4081. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  4082. $pdf->SetFont('dejavusans', '', 12);
  4083. foreach ($episode['segments'] as $segment) {
  4084. if (!empty($segment['segment_content'])) {
  4085. // 如果有分段编号,显示分段标题
  4086. if (!empty($segment['segment_number'])) {
  4087. $pdf->SetFont('dejavusans', 'B', 12);
  4088. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  4089. $pdf->SetFont('dejavusans', '', 12);
  4090. }
  4091. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  4092. $pdf->Ln(2);
  4093. }
  4094. }
  4095. }
  4096. $pdf->Ln(5);
  4097. }
  4098. }
  4099. }
  4100. /**
  4101. * 构建剧本文本内容
  4102. */
  4103. private function buildScriptContent($script) {
  4104. $content = '';
  4105. $groups = $script['group'];
  4106. $groups = (array)$groups;
  4107. foreach ($groups as $group) {
  4108. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  4109. // 剧本基本信息
  4110. if (!empty($group['intro'])) {
  4111. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  4112. }
  4113. if (!empty($group['highlights'])) {
  4114. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  4115. }
  4116. if (!empty($group['role_relationship'])) {
  4117. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  4118. }
  4119. if (!empty($group['core_contradiction'])) {
  4120. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  4121. }
  4122. if (!empty($group['roles']) && is_array($group['roles'])) {
  4123. $content .= "###主体列表\n";
  4124. foreach ($group['roles'] as $role) {
  4125. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  4126. }
  4127. $content .= "\n\n";
  4128. }
  4129. if (!empty($group['art_style'])) {
  4130. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  4131. }
  4132. // 场景信息
  4133. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4134. $content .= "###场景列表\n";
  4135. foreach ($group['scenes'] as $scene) {
  4136. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  4137. }
  4138. $content .= "\n\n";
  4139. }
  4140. // 分集内容
  4141. if (!empty($group['episode_content'])) {
  4142. $content .= "###分集剧本\n";
  4143. $content .= $group['episode_content'];
  4144. // foreach ($script['episodes'] as $episode) {
  4145. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  4146. // // if (!empty($episode['episode_name'])) {
  4147. // // $content .= ":" . $episode['episode_name'];
  4148. // // }
  4149. // // $content .= "\n";
  4150. // $content .= $episode['episode_content'] . "\n\n";
  4151. // }
  4152. }
  4153. }
  4154. return $content;
  4155. }
  4156. /**
  4157. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4158. *
  4159. * @param array $data 包含以下参数:
  4160. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4161. * - question: 用户问题(可选)
  4162. * - model: 使用的模型(r1 或 v3,默认 v3)
  4163. * @return \Generator 返回生成器,用于流式输出
  4164. */
  4165. public function addChat($data) {
  4166. $uid = Site::getUid();
  4167. $anime_id = getProp($data, 'anime_id');
  4168. if (!$anime_id) Utils::throwError('20003:请选择对话');
  4169. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4170. if (!$anime) Utils::throwError('20003:对话不存在');
  4171. $file = getProp($data, 'file');
  4172. $content = getProp($data, 'content', '');
  4173. $bid = getProp($data, 'bid', 0);
  4174. $script_id = getProp($data, 'script_id', 0);
  4175. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  4176. $prompt = getProp($data, 'prompt');
  4177. $user_anime_name = getProp($anime, 'anime_name');
  4178. // 处理文本模型
  4179. $model = getProp($data, 'model');
  4180. if (!$model) {
  4181. // 用户没有输入,从anime表获取
  4182. $model = getProp($anime, 'model');
  4183. if (!$model) {
  4184. // anime表也没有,使用默认值
  4185. $model = 'doubao-seed-2-0-mini-260215';
  4186. }
  4187. }
  4188. // 验证模型是否在可用模型表中
  4189. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4190. $model = 'doubao-seed-2-0-mini-260215';
  4191. }
  4192. $is_multi = getProp($anime, 'is_multi');
  4193. $is_single = (int)$is_multi !== 1;
  4194. // 积分余额预检(仅单剧集模式收费)
  4195. if ($is_single) {
  4196. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  4197. }
  4198. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4199. if ($prompt) {
  4200. $question .= "本次修改要求如下:\n{$prompt}";
  4201. }
  4202. // if (!$file && !$content && !$bid) {
  4203. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4204. // }
  4205. // 提取文件内容
  4206. if ($file) {
  4207. $content = $this->extractFileContent($file);
  4208. if (!$content) {
  4209. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4210. }
  4211. } elseif ($script_id) {
  4212. $content = $this->getContentByScriptId($script_id);
  4213. if (!$content) {
  4214. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4215. }
  4216. } elseif ($bid) {
  4217. $content = $this->getContentByBid($bid);
  4218. if (!$content) {
  4219. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4220. }
  4221. } elseif ($content) {
  4222. $content = filterContent($content);
  4223. } else {
  4224. $content = getProp($anime, 'content');
  4225. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4226. $need_generate_content = true;
  4227. }
  4228. }
  4229. // 美术风格
  4230. $input_art_style = getProp($data, 'art_style');
  4231. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4232. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4233. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4234. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4235. 中年女:邻居阿姨
  4236. 老年男:幽默大爷
  4237. 老年女:婆婆
  4238. 萌娃:奶气萌娃";
  4239. // 判断是否需要生成原文内容
  4240. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4241. // 如果需要生成原文内容,添加额外的要求
  4242. $content_generation_requirement = $need_generate_content
  4243. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4244. : "";
  4245. // 美术风格
  4246. if (!$mappedArtStyle) {
  4247. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4248. }else {
  4249. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4250. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4251. }else {
  4252. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4253. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4254. }
  4255. }
  4256. $systemPrompt = $is_single
  4257. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4258. 强制要求:
  4259. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4260. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4261. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4262. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4263. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4264. 普通要求:
  4265. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4266. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4267. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  4268. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4269. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4270. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4271. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4272. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4273. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4274. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4275. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4276. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4277. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4278. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4279. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4280. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4281. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4282. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4283. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4284. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4285. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4286. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4287. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4288. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4289. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4290. 5.{$mappedArtStyle_prompt}\n\n
  4291. 示例如下:\n
  4292. ###剧本名:西昆仑
  4293. ###故事梗概
  4294. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4295. ###剧本亮点
  4296. 亮点1:绝境奇药,生死一线
  4297. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4298. 亮点2:结拜兄妹,化解尴尬
  4299. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4300. 亮点3:纤发夺命,情愫暗涌
  4301. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4302. ###人物关系
  4303. 阿雪与梁萧之间存在兄妹之情。
  4304. ###核心矛盾
  4305. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4306. ###主体列表
  4307. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4308. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4309. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4310. 姿态:站立。}{{甜心小美}}
  4311. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4312. 全景,正面拍摄,青年女性,亚洲人。
  4313. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4314. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4315. 姿态:站立。}{{阳光青年}}
  4316. ###美术风格
  4317. 基础画风风格词:厚涂古风
  4318. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4319. ###场景列表
  4320. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4321. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4322. 无人物。}
  4323. ###分镜剧本
  4324. ##第1幕:徐家老旧厨房 白天 室内
  4325. 分镜1
  4326. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4327. 场景:徐家老旧厨房
  4328. 构图设计:全景,低角度仰视
  4329. 运镜调度:手持拍摄
  4330. 配音角色:旁白
  4331. 出镜角色:许芸-校服装、徐母
  4332. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4333. 画面类型:普通画面
  4334. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4335. 分镜2
  4336. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4337. 场景:徐家老旧厨房
  4338. 构图设计:近景,徐母面部特写
  4339. 运镜调度:固定镜头
  4340. 配音角色:徐母
  4341. 出镜角色:徐母
  4342. 台词内容:问我夜不归宿死哪儿去了。
  4343. 画面类型:对口型
  4344. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4345. ##第2幕:徐家简陋客厅 黄昏 室内
  4346. 分镜3
  4347. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4348. 场景:徐家简陋客厅
  4349. 构图设计:全景,景深虚化
  4350. 运镜调度:固定镜头
  4351. 配音角色:旁白
  4352. 出镜角色:无
  4353. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4354. 画面类型:普通画面
  4355. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4356. 分镜4
  4357. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4358. 场景:徐家简陋客厅
  4359. 构图设计:特写,火车票
  4360. 运镜调度:固定镜头
  4361. 配音角色:旁白
  4362. 出镜角色:无
  4363. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4364. 画面类型:普通画面
  4365. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4366. "
  4367. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4368. 强制要求:\n
  4369. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4370. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4371. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4372. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4373. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4374. 普通要求:\n
  4375. 1.剧本名(必须生成)必须与文档内容高度相关
  4376. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4377. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4378. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4379. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4380. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4381. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4382. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4383. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4384. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4385. 4.{$mappedArtStyle_prompt}\n\n
  4386. 示例如下:\n
  4387. ###剧本名:西昆仑
  4388. ###故事梗概
  4389. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4390. ###剧本亮点
  4391. 亮点1:绝境奇药,生死一线
  4392. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4393. 亮点2:结拜兄妹,化解尴尬
  4394. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4395. 亮点3:纤发夺命,情愫暗涌
  4396. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4397. ###人物关系
  4398. 阿雪与梁萧之间存在兄妹之情。
  4399. ###核心矛盾
  4400. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4401. ###主体列表
  4402. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4403. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4404. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4405. 姿态:站立。}{{甜心小美}}
  4406. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4407. 全景,正面拍摄,青年女性,亚洲人。
  4408. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4409. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4410. 姿态:站立。}{{阳光青年}}
  4411. ###美术风格
  4412. 基础画风风格词:厚涂古风
  4413. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4414. ###场景列表
  4415. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4416. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4417. 无人物。}";
  4418. // 构建消息
  4419. $messages = [
  4420. [
  4421. 'role' => 'system',
  4422. 'content' => $systemPrompt
  4423. ],
  4424. [
  4425. 'role' => 'user',
  4426. 'content' => "以下是文档内容:
  4427. {$content}
  4428. 用户问题:
  4429. {$question}"
  4430. ]
  4431. ];
  4432. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4433. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4434. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4435. if ($model === 'deepseek-chat') {
  4436. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4437. $model = 'deepseek-v4-flash';
  4438. $thinkingMode = 'disabled';
  4439. } elseif ($model === 'deepseek-reasoner') {
  4440. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4441. $model = 'deepseek-v4-flash';
  4442. $thinkingMode = 'enabled';
  4443. }
  4444. $post_data = [
  4445. 'model' => $model,
  4446. 'messages' => $messages,
  4447. // 'max_tokens' => 8192,
  4448. 'temperature' => 0.7,
  4449. 'frequency_penalty' => 0,
  4450. 'presence_penalty' => 0,
  4451. 'response_format' => ['type' => 'text'],
  4452. 'thinking' => ['type'=>$thinkingMode],
  4453. 'stream' => true // 启用流式输出
  4454. ];
  4455. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4456. // 根据模型类型选择调用方法
  4457. $fullContent = '';
  4458. $fullReasoningContent = '';
  4459. $usage = [];
  4460. try {
  4461. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4462. // DeepSeek 官方模型使用 DeepSeek API
  4463. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4464. } else if (in_array($model, $this->gpt_text_models)) {
  4465. // GPT-5.4 模型使用 TokenRouter API
  4466. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4467. } else if (in_array($model, $this->gemini_text_models)) {
  4468. // Gemini 模型使用 Gemini API
  4469. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4470. } else {
  4471. // 其他模型使用火山引擎API
  4472. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4473. }
  4474. // 验证返回值类型
  4475. if (!is_iterable($streamGenerator)) {
  4476. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4477. dLog('deepseek')->error('addChat流式生成器无效', [
  4478. 'generator_type' => $errorType,
  4479. 'model' => $model,
  4480. 'anime_id' => $anime_id
  4481. ]);
  4482. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  4483. 'type' => $errorType,
  4484. 'model' => $model
  4485. ]);
  4486. yield [
  4487. 'type' => 'error',
  4488. 'script' => [],
  4489. 'episode' => [],
  4490. 'answer' => '',
  4491. 'reasoning' => '',
  4492. 'usage' => [],
  4493. 'error' => '接口返回数据异常,请重新请求'
  4494. ];
  4495. return;
  4496. }
  4497. // 处理流式输出
  4498. foreach ($streamGenerator as $chunk) {
  4499. if (isset($chunk['type'])) {
  4500. if ($chunk['type'] === 'done') {
  4501. // 最终结果
  4502. $fullContent = $chunk['full_content'];
  4503. $fullReasoningContent = $chunk['full_reasoning'];
  4504. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4505. } else {
  4506. // 逐块yield数据
  4507. yield $chunk;
  4508. }
  4509. }
  4510. }
  4511. } catch (\Exception $e) {
  4512. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  4513. 'model' => $model,
  4514. 'anime_id' => $anime_id,
  4515. 'trace' => $e->getTraceAsString()
  4516. ]);
  4517. logDB('deepseek', 'error', 'addChat流式处理失败', [
  4518. 'error' => $e->getMessage(),
  4519. 'model' => $model
  4520. ]);
  4521. yield [
  4522. 'type' => 'error',
  4523. 'script' => [],
  4524. 'episode' => [],
  4525. 'answer' => '',
  4526. 'reasoning' => '',
  4527. 'usage' => [],
  4528. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4529. ];
  4530. return;
  4531. }
  4532. dLog('deepseek')->info('完整内容: '.$fullContent);
  4533. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4534. // 处理完整内容并返回最终结果
  4535. $script_arr = [];
  4536. if ($fullContent) {
  4537. $script_arr = handleScriptContent($fullContent);
  4538. dLog('deepseek')->info('解析内容', $script_arr);
  4539. logDB('deepseek', 'info', '解析内容', $script_arr);
  4540. }
  4541. if (empty($script_arr['roles'])) {
  4542. // 未生成剧本相关内容,保存对话记录并返回提示
  4543. dLog('deepseek')->info('未生成剧本相关的内容');
  4544. try {
  4545. DB::beginTransaction();
  4546. $now = date('Y-m-d H:i:s');
  4547. // 保存对话记录
  4548. $records = [
  4549. [
  4550. 'uid' => $uid,
  4551. 'anime_id' => $anime_id,
  4552. 'sequence' => 0,
  4553. 'role' => 'user',
  4554. 'content' => $prompt,
  4555. 'created_at' => $now,
  4556. 'updated_at' => $now
  4557. ],
  4558. [
  4559. 'uid' => $uid,
  4560. 'anime_id' => $anime_id,
  4561. 'sequence' => 0,
  4562. 'role' => 'assistant',
  4563. // 'content' => $fullContent,
  4564. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  4565. 'created_at' => $now,
  4566. 'updated_at' => $now
  4567. ]
  4568. ];
  4569. DB::table('mp_anime_records')->insert($records);
  4570. DB::commit();
  4571. } catch (\Exception $e) {
  4572. DB::rollBack();
  4573. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4574. }
  4575. yield [
  4576. 'type' => 'done',
  4577. 'script' => [],
  4578. 'episode' => [],
  4579. 'answer' => $fullContent,
  4580. 'reasoning' => $fullReasoningContent,
  4581. 'usage' => $usage,
  4582. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4583. ];
  4584. return;
  4585. }
  4586. // 如果需要生成原文内容,从script_arr中提取
  4587. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4588. $content = $script_arr['content'];
  4589. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  4590. if (!$content) {
  4591. yield [
  4592. 'type' => 'done',
  4593. 'script' => [],
  4594. 'episode' => [],
  4595. 'answer' => $fullContent,
  4596. 'reasoning' => $fullReasoningContent,
  4597. 'usage' => $usage,
  4598. 'error' => '未生成剧本内容,请调整提示词再试'
  4599. ];
  4600. return;
  4601. }
  4602. }
  4603. // 替换美术风格
  4604. if ($mappedArtStyle !== '') {
  4605. $script_arr['art_style'] = $mappedArtStyle;
  4606. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4607. }
  4608. // 新建动漫
  4609. if ($user_anime_name == '新剧本策划') {
  4610. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  4611. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  4612. // if (!$anime_name) {
  4613. // // 未识别到剧本名,保存对话记录并返回提示
  4614. // dLog('deepseek')->info('未能识别到剧本名称');
  4615. // try {
  4616. // DB::beginTransaction();
  4617. // $now = date('Y-m-d H:i:s');
  4618. // // 保存对话记录
  4619. // $records = [
  4620. // [
  4621. // 'uid' => $uid,
  4622. // 'anime_id' => $anime_id,
  4623. // 'sequence' => 0,
  4624. // 'role' => 'user',
  4625. // 'content' => $prompt,
  4626. // 'created_at' => $now,
  4627. // 'updated_at' => $now
  4628. // ],
  4629. // [
  4630. // 'uid' => $uid,
  4631. // 'anime_id' => $anime_id,
  4632. // 'sequence' => 0,
  4633. // 'role' => 'assistant',
  4634. // 'content' => '未能生成剧本名称,请重试',
  4635. // 'created_at' => $now,
  4636. // 'updated_at' => $now
  4637. // ]
  4638. // ];
  4639. // DB::table('mp_anime_records')->insert($records);
  4640. // DB::commit();
  4641. // } catch (\Exception $e) {
  4642. // DB::rollBack();
  4643. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4644. // }
  4645. // yield [
  4646. // 'type' => 'done',
  4647. // 'script' => [],
  4648. // 'episode' => [],
  4649. // 'answer' => $fullContent,
  4650. // 'reasoning' => $fullReasoningContent,
  4651. // 'usage' => $usage,
  4652. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  4653. // ];
  4654. // return;
  4655. // }
  4656. // 确认对话名称唯一性
  4657. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4658. $anime_name = $anime_name . '_' . date('YmdHis');
  4659. }
  4660. }else {
  4661. $anime_name = $user_anime_name;
  4662. }
  4663. $table_data = [
  4664. 'user_id' => $uid,
  4665. 'anime_name' => $anime_name,
  4666. 'model' => $model,
  4667. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4668. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4669. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4670. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4671. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4672. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4673. 'art_style_type' => $input_art_style,
  4674. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4675. 'status' => '解析完成',
  4676. 'content' => $content,
  4677. 'is_multi' => $is_multi,
  4678. 'ace_mode' => $ace_mode,
  4679. 'generate_status' => '待执行',
  4680. 'updated_at' => date('Y-m-d H:i:s')
  4681. ];
  4682. if ($table_data['content']) {
  4683. $chapters = splitContent($table_data['content']);
  4684. $chapter_count = count($chapters);
  4685. if ($chapter_count > 0) {
  4686. $table_data['start_episode_sequence'] = 1;
  4687. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4688. }
  4689. }
  4690. // 如果有剧本ID则进行绑定
  4691. if ($script_id) {
  4692. $table_data['script_id'] = $script_id;
  4693. }
  4694. $single_episode = [];
  4695. try {
  4696. DB::beginTransaction();
  4697. $now = date('Y-m-d H:i:s');
  4698. // 更新动漫大纲
  4699. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4700. if (!$boolen) {
  4701. dLog('deepseek')->info('动漫保存失败', $table_data);
  4702. Utils::throwError('20003:动漫保存失败');
  4703. }
  4704. // 保存对话记录
  4705. $records = [
  4706. [
  4707. 'uid' => $uid,
  4708. 'anime_id' => $anime_id,
  4709. 'sequence' => 0,
  4710. 'role' => 'user',
  4711. 'content' => $prompt,
  4712. 'created_at' => date('Y-m-d H:i:s'),
  4713. 'updated_at' => date('Y-m-d H:i:s')
  4714. ],
  4715. [
  4716. 'uid' => $uid,
  4717. 'anime_id' => $anime_id,
  4718. 'sequence' => 0,
  4719. 'role' => 'assistant',
  4720. 'content' => $fullContent,
  4721. 'created_at' => date('Y-m-d H:i:s'),
  4722. 'updated_at' => date('Y-m-d H:i:s')
  4723. ]
  4724. ];
  4725. // 保存对话记录
  4726. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4727. if (!$boolen3) {
  4728. Utils::throwError('20003:对话记录保存失败');
  4729. }
  4730. if ($is_single) {
  4731. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4732. if (empty($episode_arr['acts'])) {
  4733. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4734. }
  4735. $saveResult = $this->saveEpisodeVersionData(
  4736. $anime_id,
  4737. 1,
  4738. $episode_arr,
  4739. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4740. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4741. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4742. null,
  4743. null,
  4744. false,
  4745. $content,
  4746. $now
  4747. );
  4748. $single_episode = $saveResult['episode'];
  4749. $episode_id = $saveResult['episode_id'];
  4750. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4751. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4752. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4753. 'props' => json_encode($saveResult['merged_props'], 256),
  4754. 'updated_at' => $now
  4755. ]);
  4756. if ($boolen5 === false) {
  4757. Utils::throwError('20003:单剧集主表资源同步失败');
  4758. }
  4759. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4760. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4761. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4762. $episode_record_content = '确认分镜大纲';
  4763. if ($content !== '') {
  4764. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4765. }
  4766. $episode_records = [
  4767. [
  4768. 'uid' => $uid,
  4769. 'anime_id' => $anime_id,
  4770. 'role' => 'user',
  4771. 'content' => $episode_record_content,
  4772. 'sequence' => 1,
  4773. 'episode_id' => $episode_id,
  4774. 'created_at' => $now,
  4775. 'updated_at' => $now
  4776. ],
  4777. [
  4778. 'uid' => $uid,
  4779. 'anime_id' => $anime_id,
  4780. 'role' => 'assistant',
  4781. 'content' => $fullContent,
  4782. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4783. 'sequence' => 1,
  4784. 'episode_id' => $episode_id,
  4785. 'created_at' => $now,
  4786. 'updated_at' => $now
  4787. ]
  4788. ];
  4789. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4790. if (!$boolen4) {
  4791. Utils::throwError('20003:单剧集分镜记录保存失败');
  4792. }
  4793. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  4794. if ($is_single && !empty($single_episode)) {
  4795. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4796. 'anime_id' => $anime_id,
  4797. 'episode_id' => $episode_id ?? 0,
  4798. ]);
  4799. }
  4800. }
  4801. }catch (\Exception $e) {
  4802. DB::rollBack();
  4803. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  4804. yield [
  4805. 'type' => 'done',
  4806. 'answer' => $fullContent,
  4807. 'reasoning' => $fullReasoningContent,
  4808. 'usage' => $usage,
  4809. 'error' => $e->getMessage(),
  4810. ];
  4811. return;
  4812. }
  4813. DB::commit();
  4814. dLog('deepseek')->info('保存完毕');
  4815. if ($is_single && !empty($single_episode)) {
  4816. // $this->batchSetGlobalRoleImg([
  4817. // 'anime_id' => $anime_id,
  4818. // ]);
  4819. // $this->batchSetGlobalSceneImg([
  4820. // 'anime_id' => $anime_id,
  4821. // ]);
  4822. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4823. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4824. }
  4825. $table_data['anime_id'] = $anime_id;
  4826. $table_data['roles'] = json_decode($table_data['roles'], true);
  4827. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4828. // $table_data['episodes'] = $script_arr['episodes'];
  4829. unset($table_data['created_at']);
  4830. unset($table_data['updated_at']);
  4831. unset($table_data['status']);
  4832. dLog('deepseek')->info('开始返回');
  4833. yield [
  4834. 'type' => 'done',
  4835. 'script' => $table_data,
  4836. 'episode' => $single_episode,
  4837. 'answer' => $fullContent,
  4838. 'reasoning' => $fullReasoningContent,
  4839. 'usage' => $usage
  4840. ];
  4841. }
  4842. public function reGenerateAnime($data) {
  4843. $uid = Site::getUid();
  4844. $file = getProp($data, 'file');
  4845. $content = getProp($data, 'content', '');
  4846. $bid = getProp($data, 'bid', 0);
  4847. $script_id = getProp($data, 'script_id', 0);
  4848. $anime_id = getProp($data, 'anime_id');
  4849. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4850. if (!$anime) {
  4851. Utils::throwError('20003:该对话不存在');
  4852. }
  4853. $user_anime_name = getProp($anime, 'anime_name');
  4854. $prompt = getProp($data, 'prompt');
  4855. // 处理文本模型
  4856. $model = getProp($data, 'model');
  4857. if (!$model) {
  4858. // 用户没有输入,从anime表获取
  4859. $model = getProp($anime, 'model');
  4860. if (!$model) {
  4861. // anime表也没有,使用默认值
  4862. $model = 'doubao-seed-2-0-mini-260215';
  4863. }
  4864. }
  4865. // 验证模型是否在可用模型表中
  4866. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4867. $model = 'doubao-seed-2-0-mini-260215';
  4868. }
  4869. $is_multi = getProp($anime, 'is_multi', 1);
  4870. $is_single = (int)$is_multi !== 1;
  4871. // 积分余额预检(仅单剧集模式收费)
  4872. if ($is_single) {
  4873. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  4874. }
  4875. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  4876. if ($is_single) {
  4877. $episode_exists = DB::table('mp_anime_episodes')
  4878. ->where('anime_id', $anime_id)
  4879. ->where('sequence', 1)
  4880. ->exists();
  4881. if ($episode_exists) {
  4882. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  4883. }
  4884. }
  4885. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4886. if ($prompt) {
  4887. $question .= "本次修改要求如下:\n{$prompt}";
  4888. }
  4889. // 提取文件内容
  4890. if ($file) {
  4891. $content = $this->extractFileContent($file);
  4892. if (!$content) {
  4893. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4894. }
  4895. } elseif ($script_id) {
  4896. $content = $this->getContentByScriptId($script_id);
  4897. if (!$content) {
  4898. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4899. }
  4900. } elseif ($bid) {
  4901. $content = $this->getContentByBid($bid);
  4902. if (!$content) {
  4903. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4904. }
  4905. } elseif ($content) {
  4906. $content = filterContent($content);
  4907. }else {
  4908. $content = filterContent(getProp($anime, 'content'));
  4909. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4910. $need_generate_content = true;
  4911. }
  4912. }
  4913. // 判断是否需要生成原文内容
  4914. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4915. // 如果需要生成原文内容,添加额外的要求
  4916. $content_generation_requirement = $need_generate_content
  4917. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4918. : "";
  4919. // 美术风格
  4920. $input_art_style = getProp($anime, 'art_style');
  4921. if (!$input_art_style) {
  4922. $input_art_style = getProp($data, 'art_style');
  4923. }
  4924. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4925. // 美术风格
  4926. if (!$mappedArtStyle) {
  4927. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4928. }else {
  4929. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4930. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4931. }else {
  4932. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4933. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4934. }
  4935. }
  4936. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4937. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4938. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4939. 中年女:邻居阿姨
  4940. 老年男:幽默大爷
  4941. 老年女:婆婆
  4942. 萌娃:奶气萌娃";
  4943. $system_message = ['role'=>'system', 'content'=>$is_single
  4944. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4945. 强制要求:
  4946. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4947. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4948. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4949. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4950. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4951. 普通要求:
  4952. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4953. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4954. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4955. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4956. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4957. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4958. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4959. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4960. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4961. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4962. 3.$mappedArtStyle_prompt\n\n
  4963. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4964. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4965. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4966. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4967. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4968. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4969. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4970. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4971. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4972. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4973. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4974. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4975. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4976. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4977. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4978. 示例如下:\n
  4979. ###剧本名:西昆仑
  4980. ###故事梗概
  4981. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4982. ###剧本亮点
  4983. 亮点1:绝境奇药,生死一线
  4984. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4985. 亮点2:结拜兄妹,化解尴尬
  4986. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4987. 亮点3:纤发夺命,情愫暗涌
  4988. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4989. ###人物关系
  4990. 阿雪与梁萧之间存在兄妹之情。
  4991. ###核心矛盾
  4992. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4993. ###主体列表
  4994. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4995. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4996. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4997. 姿态:站立。}{{甜心小美}}
  4998. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4999. 全景,正面拍摄,青年女性,亚洲人。
  5000. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5001. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5002. 姿态:站立。}{{阳光青年}}
  5003. ###美术风格
  5004. 基础画风风格词:厚涂古风
  5005. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5006. ###场景列表
  5007. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5008. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5009. 无人物。}
  5010. ###分镜剧本
  5011. ##第1幕:徐家老旧厨房 白天 室内
  5012. 分镜1
  5013. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5014. 场景:徐家老旧厨房
  5015. 构图设计:全景,低角度仰视
  5016. 运镜调度:手持拍摄
  5017. 配音角色:旁白
  5018. 出镜角色:许芸-校服装、徐母
  5019. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5020. 画面类型:普通画面
  5021. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5022. 分镜2
  5023. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5024. 场景:徐家老旧厨房
  5025. 构图设计:近景,徐母面部特写
  5026. 运镜调度:固定镜头
  5027. 配音角色:徐母
  5028. 出镜角色:徐母
  5029. 台词内容:问我夜不归宿死哪儿去了。
  5030. 画面类型:对口型
  5031. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5032. ##第2幕:徐家简陋客厅 黄昏 室内
  5033. 分镜3
  5034. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5035. 场景:徐家简陋客厅
  5036. 构图设计:全景,景深虚化
  5037. 运镜调度:固定镜头
  5038. 配音角色:旁白
  5039. 出镜角色:无
  5040. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5041. 画面类型:普通画面
  5042. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5043. 分镜4
  5044. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5045. 场景:徐家简陋客厅
  5046. 构图设计:特写,火车票
  5047. 运镜调度:固定镜头
  5048. 配音角色:旁白
  5049. 出镜角色:无
  5050. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5051. 画面类型:普通画面
  5052. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5053. "
  5054. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5055. 强制要求:\n
  5056. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5057. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5058. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5059. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5060. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5061. 普通要求:\n
  5062. 1.剧本名(必须生成)必须与文档内容高度相关
  5063. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5064. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5065. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5066. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5067. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5068. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5069. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5070. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5071. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5072. 4.$mappedArtStyle_prompt\n\n
  5073. 示例如下:\n
  5074. ###剧本名:西昆仑
  5075. ###故事梗概
  5076. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5077. ###剧本亮点
  5078. 亮点1:绝境奇药,生死一线
  5079. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5080. 亮点2:结拜兄妹,化解尴尬
  5081. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5082. 亮点3:纤发夺命,情愫暗涌
  5083. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5084. ###人物关系
  5085. 阿雪与梁萧之间存在兄妹之情。
  5086. ###核心矛盾
  5087. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5088. ###主体列表
  5089. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5090. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5091. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5092. 姿态:站立。}{{甜心小美}}
  5093. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5094. 全景,正面拍摄,青年女性,亚洲人。
  5095. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5096. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5097. 姿态:站立。}{{阳光青年}}
  5098. ###美术风格
  5099. 基础画风风格词:厚涂古风
  5100. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5101. ###场景列表
  5102. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5103. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5104. 无人物。}"];
  5105. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  5106. $episode_count = $this->extractEpisodeNumber($prompt);
  5107. if ((int)getProp($anime, 'is_multi') !== 1) {
  5108. yield [
  5109. 'type' => 'done',
  5110. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  5111. 'reasoning' => '',
  5112. 'usage' => []
  5113. ];
  5114. return;
  5115. }
  5116. if ($episode_count) {
  5117. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  5118. $system_message = [
  5119. 'role' => 'system',
  5120. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5121. 强制要求:\n
  5122. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5123. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5124. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5125. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5126. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5127. 普通要求:\n
  5128. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5129. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5130. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5131. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5132. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5133. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5134. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5135. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5136. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5137. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  5138. 示例如下:\n
  5139. ###剧本名:西昆仑
  5140. ###故事梗概
  5141. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5142. ###剧本亮点
  5143. 亮点1:绝境奇药,生死一线
  5144. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5145. 亮点2:结拜兄妹,化解尴尬
  5146. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5147. 亮点3:纤发夺命,情愫暗涌
  5148. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5149. ###人物关系
  5150. 阿雪与梁萧之间存在兄妹之情。
  5151. ###核心矛盾
  5152. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5153. ###主体列表
  5154. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5155. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5156. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5157. 姿态:站立。}{{甜心小美}}
  5158. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5159. 全景,正面拍摄,青年女性,亚洲人。
  5160. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5161. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5162. 姿态:站立。}{{阳光青年}}
  5163. ###美术风格
  5164. 基础画风风格词:厚涂古风
  5165. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5166. ###场景列表
  5167. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5168. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5169. 无人物。}
  5170. ###分集详细内容
  5171. ##第1章 重生
  5172. 我重生了。
  5173. 源于一个男人偏执的暗恋。
  5174. ##第2章 相救
  5175. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  5176. 我眼睛扫向站在锅炉后的卞大伟。"
  5177. ];
  5178. // 构建消息
  5179. $messages = [
  5180. $system_message,
  5181. [
  5182. 'role' => 'user',
  5183. 'content' => "以下是文档内容:
  5184. {$content}
  5185. 用户问题:
  5186. {$question}"
  5187. ]
  5188. ];
  5189. }else {
  5190. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  5191. // 构建消息
  5192. $messages = [
  5193. $system_message,
  5194. [
  5195. 'role' => 'user',
  5196. 'content' => "以下是文档内容:
  5197. {$content}
  5198. 用户问题:
  5199. {$question}"
  5200. ]
  5201. ];
  5202. }else {
  5203. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  5204. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  5205. return (array)$value;
  5206. })->toArray();
  5207. array_unshift($messages, $system_message);
  5208. $messages[] = [
  5209. 'role' => 'user',
  5210. 'content' => $prompt
  5211. ];
  5212. }
  5213. }
  5214. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5215. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5216. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5217. if ($model === 'deepseek-chat') {
  5218. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5219. $model = 'deepseek-v4-flash';
  5220. $thinkingMode = 'disabled';
  5221. } elseif ($model === 'deepseek-reasoner') {
  5222. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5223. $model = 'deepseek-v4-flash';
  5224. $thinkingMode = 'enabled';
  5225. }
  5226. $post_data = [
  5227. 'model' => $model,
  5228. 'messages' => $messages,
  5229. // 'max_tokens' => 8192,
  5230. 'temperature' => 0.7,
  5231. 'frequency_penalty' => 0,
  5232. 'presence_penalty' => 0,
  5233. 'response_format' => ['type' => 'text'],
  5234. 'thinking' => ['type' => $thinkingMode],
  5235. 'stream' => true // 启用流式输出
  5236. ];
  5237. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5238. // 根据模型类型选择调用方法
  5239. $fullContent = '';
  5240. $fullReasoningContent = '';
  5241. $usage = [];
  5242. // dd($post_data);
  5243. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  5244. try {
  5245. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5246. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5247. } else if (in_array($model, $this->gpt_text_models)) {
  5248. // GPT-5.4 模型使用 TokenRouter API
  5249. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5250. } else if (in_array($model, $this->gemini_text_models)) {
  5251. // Gemini 模型使用 Gemini API
  5252. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5253. } else {
  5254. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5255. }
  5256. // 验证返回值类型
  5257. if (!is_iterable($streamGenerator)) {
  5258. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5259. dLog('deepseek')->error('方法名流式生成器无效', [
  5260. 'generator_type' => $errorType,
  5261. 'model' => $model,
  5262. // 添加其他上下文信息
  5263. ]);
  5264. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  5265. 'type' => $errorType,
  5266. 'model' => $model
  5267. ]);
  5268. yield [
  5269. 'type' => 'error',
  5270. // 根据方法返回相应的空数据结构
  5271. 'answer' => '',
  5272. 'reasoning' => '',
  5273. 'usage' => [],
  5274. 'error' => '接口返回数据异常,请重新请求'
  5275. ];
  5276. return;
  5277. }
  5278. // 处理流式输出
  5279. foreach ($streamGenerator as $chunk) {
  5280. if (isset($chunk['type'])) {
  5281. if ($chunk['type'] === 'done') {
  5282. $fullContent = $chunk['full_content'];
  5283. $fullReasoningContent = $chunk['full_reasoning'];
  5284. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5285. } else {
  5286. yield $chunk;
  5287. }
  5288. }
  5289. }
  5290. } catch (\Exception $e) {
  5291. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  5292. 'model' => $model,
  5293. 'trace' => $e->getTraceAsString()
  5294. ]);
  5295. logDB('deepseek', 'error', '方法名流式处理失败', [
  5296. 'error' => $e->getMessage(),
  5297. 'model' => $model
  5298. ]);
  5299. yield [
  5300. 'type' => 'error',
  5301. // 根据方法返回相应的空数据结构
  5302. 'answer' => '',
  5303. 'reasoning' => '',
  5304. 'usage' => [],
  5305. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5306. ];
  5307. return;
  5308. }
  5309. dLog('deepseek')->info('完整内容: '.$fullContent);
  5310. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5311. // 处理完整内容并返回最终结果
  5312. $script_arr = [];
  5313. if ($fullContent) {
  5314. $script_arr = handleScriptContent($fullContent);
  5315. dLog('deepseek')->info('解析内容', $script_arr);
  5316. logDB('deepseek', 'info', '解析内容', $script_arr);
  5317. }
  5318. if (empty($script_arr['roles'])) {
  5319. // 未生成剧本相关内容,保存对话记录并返回提示
  5320. dLog('deepseek')->info('未生成剧本相关的内容');
  5321. try {
  5322. $now = date('Y-m-d H:i:s');
  5323. // 保存对话记录
  5324. $records = [
  5325. [
  5326. 'uid' => $uid,
  5327. 'anime_id' => $anime_id,
  5328. 'sequence' => 0,
  5329. 'role' => 'user',
  5330. 'content' => $prompt,
  5331. 'created_at' => $now,
  5332. 'updated_at' => $now
  5333. ],
  5334. [
  5335. 'uid' => $uid,
  5336. 'anime_id' => $anime_id,
  5337. 'sequence' => 0,
  5338. 'role' => 'assistant',
  5339. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  5340. 'created_at' => $now,
  5341. 'updated_at' => $now
  5342. ]
  5343. ];
  5344. DB::table('mp_anime_records')->insert($records);
  5345. } catch (\Exception $e) {
  5346. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5347. }
  5348. yield [
  5349. 'type' => 'done',
  5350. 'script' => [],
  5351. 'episode' => [],
  5352. 'answer' => $fullContent,
  5353. 'reasoning' => $fullReasoningContent,
  5354. 'usage' => $usage,
  5355. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5356. ];
  5357. return;
  5358. }
  5359. // 替换美术风格
  5360. if ($mappedArtStyle !== '') {
  5361. $script_arr['art_style'] = $mappedArtStyle;
  5362. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5363. }
  5364. if ($user_anime_name != '新剧本策划') {
  5365. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5366. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5367. // 确认对话名称唯一性
  5368. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5369. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  5370. }
  5371. }else {
  5372. $anime_name = $user_anime_name;
  5373. }
  5374. $table_data = [
  5375. 'user_id' => $uid,
  5376. 'model' => $model,
  5377. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5378. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5379. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5380. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5381. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5382. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5383. 'art_style_type' => $input_art_style,
  5384. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5385. 'status' => '解析完成',
  5386. 'generate_status' => '待执行',
  5387. 'updated_at' => date('Y-m-d H:i:s')
  5388. ];
  5389. if ($anime_name) $table_data['anime_name'] = $anime_name;
  5390. // 如果是修改集数,则将content内容更新(会改变原文)
  5391. if (isset($episode_count) && $episode_count > 0) {
  5392. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  5393. $table_data['start_episode_sequence'] = 1;
  5394. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  5395. }else {
  5396. // 如果需要生成原文内容,从script_arr中提取
  5397. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5398. $table_data['content'] = $script_arr['content'];
  5399. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  5400. if (!$table_data['content']) {
  5401. yield [
  5402. 'type' => 'done',
  5403. 'script' => [],
  5404. 'episode' => [],
  5405. 'answer' => $fullContent,
  5406. 'reasoning' => $fullReasoningContent,
  5407. 'usage' => $usage,
  5408. 'error' => '未生成剧本内容,请调整提示词再试'
  5409. ];
  5410. return;
  5411. }
  5412. }
  5413. if (isset($table_data['content']) && $table_data['content']) {
  5414. $chapters = splitContent($table_data['content']);
  5415. $chapter_count = count($chapters);
  5416. if ($chapter_count > 0) {
  5417. $table_data['start_episode_sequence'] = 1;
  5418. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5419. }
  5420. }
  5421. }
  5422. $single_episode = [];
  5423. try {
  5424. DB::beginTransaction();
  5425. $now = date('Y-m-d H:i:s');
  5426. // 更新动漫大纲
  5427. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5428. if (!$boolen) {
  5429. dLog('deepseek')->info('对话修改失败', $table_data);
  5430. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  5431. Utils::throwError('20003:对话修改失败');
  5432. }
  5433. // 保存对话记录
  5434. $records = [
  5435. [
  5436. 'uid' => $uid,
  5437. 'anime_id' => $anime_id,
  5438. 'sequence' => 0,
  5439. 'role' => 'user',
  5440. 'content' => $prompt,
  5441. 'created_at' => $now,
  5442. 'updated_at' => $now
  5443. ],
  5444. [
  5445. 'uid' => $uid,
  5446. 'anime_id' => $anime_id,
  5447. 'sequence' => 0,
  5448. 'role' => 'assistant',
  5449. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5450. 'content' => $fullContent,
  5451. 'created_at' => $now,
  5452. 'updated_at' => $now
  5453. ]
  5454. ];
  5455. // 保存对话记录
  5456. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5457. if (!$boolen3) {
  5458. Utils::throwError('20003:对话记录保存失败');
  5459. }
  5460. // 单剧集模式:生成并保存剧集信息
  5461. if ($is_single) {
  5462. $anime_name = getProp($anime, 'anime_name', '未命名');
  5463. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5464. if (empty($episode_arr['acts'])) {
  5465. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5466. }
  5467. $saveResult = $this->saveEpisodeVersionData(
  5468. $anime_id,
  5469. 1,
  5470. $episode_arr,
  5471. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5472. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5473. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5474. null,
  5475. null,
  5476. false,
  5477. $content,
  5478. $now
  5479. );
  5480. $single_episode = $saveResult['episode'];
  5481. $episode_id = $saveResult['episode_id'];
  5482. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5483. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5484. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5485. 'props' => json_encode($saveResult['merged_props'], 256),
  5486. 'updated_at' => $now
  5487. ]);
  5488. if ($boolen5 === false) {
  5489. Utils::throwError('20003:单剧集主表资源同步失败');
  5490. }
  5491. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5492. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5493. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5494. $episode_record_content = '确认分镜大纲';
  5495. if ($content !== '') {
  5496. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5497. }
  5498. $episode_records = [
  5499. [
  5500. 'uid' => $uid,
  5501. 'anime_id' => $anime_id,
  5502. 'role' => 'user',
  5503. 'content' => $episode_record_content,
  5504. 'sequence' => 1,
  5505. 'episode_id' => $episode_id,
  5506. 'created_at' => $now,
  5507. 'updated_at' => $now
  5508. ],
  5509. [
  5510. 'uid' => $uid,
  5511. 'anime_id' => $anime_id,
  5512. 'role' => 'assistant',
  5513. 'content' => $fullContent,
  5514. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5515. 'sequence' => 1,
  5516. 'episode_id' => $episode_id,
  5517. 'created_at' => $now,
  5518. 'updated_at' => $now
  5519. ]
  5520. ];
  5521. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5522. if (!$boolen4) {
  5523. Utils::throwError('20003:单剧集分镜记录保存失败');
  5524. }
  5525. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  5526. if ($is_single && !empty($single_episode)) {
  5527. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5528. 'anime_id' => $anime_id,
  5529. 'episode_id' => $episode_id ?? 0,
  5530. ]);
  5531. }
  5532. }
  5533. }catch (\Exception $e) {
  5534. DB::rollBack();
  5535. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  5536. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  5537. yield [
  5538. 'type' => 'done',
  5539. 'answer' => $fullContent,
  5540. 'reasoning' => $fullReasoningContent,
  5541. 'usage' => $usage,
  5542. 'error' => $e->getMessage(),
  5543. ];
  5544. return;
  5545. }
  5546. DB::commit();
  5547. dLog('deepseek')->info('保存完毕');
  5548. if ($is_single && !empty($single_episode)) {
  5549. // $this->batchSetGlobalRoleImg([
  5550. // 'anime_id' => $anime_id,
  5551. // ]);
  5552. // $this->batchSetGlobalSceneImg([
  5553. // 'anime_id' => $anime_id,
  5554. // ]);
  5555. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5556. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5557. }
  5558. $table_data['anime_id'] = $anime_id;
  5559. $table_data['roles'] = json_decode($table_data['roles'], true);
  5560. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5561. unset($table_data['updated_at']);
  5562. unset($table_data['status']);
  5563. yield [
  5564. 'type' => 'done',
  5565. 'script' => $table_data,
  5566. 'episode' => $single_episode,
  5567. 'answer' => $fullContent,
  5568. 'reasoning' => $fullReasoningContent,
  5569. 'usage' => $usage
  5570. ];
  5571. }
  5572. public function chat($data) {
  5573. $uid = Site::getUid();
  5574. // 积分余额预检(不足直接报错)
  5575. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  5576. $anime_id = getProp($data, 'anime_id');
  5577. $file = getProp($data, 'file');
  5578. $content = getProp($data, 'content', '');
  5579. $bid = getProp($data, 'bid', 0);
  5580. $script_id = getProp($data, 'script_id', 0);
  5581. $episode_number = getProp($data, 'episode_number', 1);
  5582. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5583. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5584. if (!$anime) Utils::throwError('20003:该对话不存在!');
  5585. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  5586. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  5587. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  5588. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  5589. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  5590. $roles = is_array($roles) ? $roles : [];
  5591. $scenes = is_array($scenes) ? $scenes : [];
  5592. // 获取最后一集序号
  5593. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  5594. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  5595. // 转换主体列表和场景列表的格式
  5596. // 获取参考主体或场景
  5597. if ((int)$episode_number === 1) {
  5598. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  5599. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  5600. }else {
  5601. $prev_episode_number = $episode_number - 1;
  5602. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  5603. }
  5604. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  5605. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  5606. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  5607. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  5608. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5609. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5610. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5611. 中年女:邻居阿姨
  5612. 老年男:幽默大爷
  5613. 老年女:婆婆
  5614. 萌娃:奶气萌娃";
  5615. if ($roles_content) {
  5616. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  5617. 主体范围:\n {$roles_content}\n
  5618. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  5619. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5620. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  5621. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5622. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  5623. }else {
  5624. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5625. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5626. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  5627. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5628. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  5629. }
  5630. if ($scenes_content) {
  5631. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  5632. 场景范围:\n {$scenes_content}\n
  5633. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  5634. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5635. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5636. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  5637. }else {
  5638. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5639. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5640. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5641. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  5642. }
  5643. // 提取文件内容
  5644. if ($file) {
  5645. $uploaded_content = $this->extractFileContent($file);
  5646. if (!$uploaded_content) {
  5647. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5648. }
  5649. } elseif ($script_id) {
  5650. $uploaded_content = $this->getContentByScriptId($script_id);
  5651. if (!$uploaded_content) {
  5652. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5653. }
  5654. } elseif ($bid) {
  5655. $uploaded_content = $this->getContentByBid($bid);
  5656. if (!$uploaded_content) {
  5657. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5658. }
  5659. } elseif ($content) {
  5660. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  5661. }
  5662. // elseif ($prompt) {
  5663. // $uploaded_content = filterContent($prompt);
  5664. // }
  5665. else {
  5666. $uploaded_content = '';
  5667. }
  5668. $input_art_style = getProp($anime, 'art_style');
  5669. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5670. // 美术风格
  5671. if (!$mappedArtStyle) {
  5672. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5673. }else {
  5674. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5675. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5676. }else {
  5677. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5678. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5679. }
  5680. }
  5681. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5682. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5683. // 强制要求:
  5684. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5685. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5686. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5687. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  5688. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  5689. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  5690. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  5691. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  5692. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  5693. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  5694. // - 分镜要和场景列表、人物主体保持一致\n
  5695. // 普通要求:
  5696. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  5697. // {$role_demo}
  5698. // {$scene_demo}
  5699. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5700. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5701. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5702. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5703. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  5704. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5705. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5706. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5707. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5708. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5709. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5710. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5711. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5712. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5713. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  5714. // 5.$mappedArtStyle_prompt\n\n
  5715. // 示例格式:\n
  5716. // 第1集:隐形的守护者
  5717. // ###故事梗概
  5718. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5719. // ###美术风格
  5720. // 基础画风风格词:韩漫二次元
  5721. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  5722. // ###主体列表
  5723. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  5724. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  5725. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  5726. // ###场景列表
  5727. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  5728. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5729. // 无人物。}
  5730. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  5731. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  5732. // 无人物。}
  5733. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  5734. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5735. // 无人物。}
  5736. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5737. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5738. // 无人物。}
  5739. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5740. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5741. // 无人物。}
  5742. // ###分镜剧本
  5743. // ##第1幕:徐家老旧厨房 白天 室内
  5744. // 分镜1
  5745. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5746. // 场景:徐家老旧厨房
  5747. // 构图设计:全景,低角度仰视
  5748. // 运镜调度:手持拍摄
  5749. // 配音角色:旁白
  5750. // 出镜角色:许芸-校服装、徐母
  5751. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5752. // 画面类型:普通画面
  5753. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5754. // 分镜2
  5755. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5756. // 场景:徐家老旧厨房
  5757. // 构图设计:近景,徐母面部特写
  5758. // 运镜调度:固定镜头
  5759. // 配音角色:徐母
  5760. // 出镜角色:徐母
  5761. // 台词内容:问我夜不归宿死哪儿去了。
  5762. // 画面类型:对口型
  5763. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5764. // ##第2幕:徐家简陋客厅 黄昏 室内
  5765. // 分镜3
  5766. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5767. // 场景:徐家简陋客厅
  5768. // 构图设计:全景,景深虚化
  5769. // 运镜调度:固定镜头
  5770. // 配音角色:旁白
  5771. // 出镜角色:无
  5772. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5773. // 画面类型:普通画面
  5774. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5775. // 分镜4
  5776. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5777. // 场景:徐家简陋客厅
  5778. // 构图设计:特写,火车票
  5779. // 运镜调度:固定镜头
  5780. // 配音角色:旁白
  5781. // 出镜角色:无
  5782. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5783. // 画面类型:普通画面
  5784. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5785. // \n\n";
  5786. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  5787. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  5788. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  5789. 普通要求:
  5790. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  5791. {$role_demo}
  5792. {$scene_demo}
  5793. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5794. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5795. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5796. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  5797. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  5798. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5799. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5800. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5801. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5802. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5803. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5804. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5805. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5806. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5807. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  5808. 5.$mappedArtStyle_prompt
  5809. 6.《情绪-视听语言映射表》:
  5810. 6.1 场景空间与时间心理学 (Scene & Temporality)
  5811. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  5812. -----|---------|------------|----------------
  5813. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  5814. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  5815. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  5816. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  5817. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  5818. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  5819. -----|---------|------------|----------------
  5820. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  5821. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  5822. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  5823. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  5824. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  5825. --------|---------|--------------|-------------
  5826. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  5827. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  5828. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  5829. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  5830. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  5831. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  5832. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  5833. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  5834. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  5835. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  5836. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  5837. -----|---------|------------|------------
  5838. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  5839. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  5840. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  5841. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  5842. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  5843. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  5844. --------|---------|--------------|----------
  5845. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  5846. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  5847. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  5848. 6.6 声音设计与潜意识影响 (Soundscape)
  5849. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  5850. -----|---------|------------|------------------
  5851. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  5852. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  5853. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  5854. 理论基石:
  5855. - The Five C's of Cinematography by Joseph V. Mascelli
  5856. - Film Art: An Introduction by David Bordwell
  5857. - Sight, Sound, Motion by Herbert Zettl
  5858. - Notes on the Cinematograph by Robert Bresson
  5859. \n\n
  5860. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  5861. 示例格式:\n
  5862. 第1集:隐形的守护者
  5863. ###故事梗概
  5864. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5865. ###美术风格
  5866. 基础画风风格词:韩漫二次元
  5867. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  5868. ###主体列表
  5869. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  5870. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  5871. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  5872. ###场景列表
  5873. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  5874. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5875. 无人物。}
  5876. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  5877. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  5878. 无人物。}
  5879. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  5880. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5881. 无人物。}
  5882. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5883. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5884. 无人物。}
  5885. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5886. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5887. 无人物。}
  5888. ###分镜剧本
  5889. ##第1幕:徐家老旧厨房 白天 室内
  5890. 分镜1
  5891. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5892. 场景:徐家老旧厨房
  5893. 构图设计:全景,低角度仰视
  5894. 运镜调度:手持拍摄
  5895. 配音角色:旁白
  5896. 出镜角色:许芸-校服装、徐母
  5897. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5898. 画面类型:普通画面
  5899. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5900. 分镜2
  5901. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5902. 场景:徐家老旧厨房
  5903. 构图设计:近景,徐母面部特写
  5904. 运镜调度:固定镜头
  5905. 配音角色:徐母
  5906. 出镜角色:徐母
  5907. 台词内容:问我夜不归宿死哪儿去了。
  5908. 画面类型:对口型
  5909. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5910. ##第2幕:徐家简陋客厅 黄昏 室内
  5911. 分镜3
  5912. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5913. 场景:徐家简陋客厅
  5914. 构图设计:全景,景深虚化
  5915. 运镜调度:固定镜头
  5916. 配音角色:旁白
  5917. 出镜角色:无
  5918. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5919. 画面类型:普通画面
  5920. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5921. 分镜4
  5922. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5923. 场景:徐家简陋客厅
  5924. 构图设计:特写,火车票
  5925. 运镜调度:固定镜头
  5926. 配音角色:旁白
  5927. 出镜角色:无
  5928. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5929. 画面类型:普通画面
  5930. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5931. \n\n";
  5932. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5933. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  5934. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  5935. $prompt = $origin_prompt;
  5936. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  5937. // 获取章节内容
  5938. $full_content = getProp($anime, 'content');
  5939. if ($uploaded_content) {
  5940. $full_content = $uploaded_content;
  5941. }
  5942. // 根据章节内容拆分章节
  5943. $chapters = splitContent($full_content);
  5944. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  5945. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  5946. $messages = [];
  5947. if ($prompt == '确认分镜大纲') {
  5948. // 暂时保留
  5949. $content = $chapter_content;
  5950. if ($is_single) $content = $full_content; // 单剧集使用全文
  5951. if (!$content) {
  5952. Utils::throwError('20003:章节内容无法获取,请确认');
  5953. }
  5954. $question = $is_single
  5955. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  5956. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  5957. // 构建消息
  5958. $messages[] =
  5959. [
  5960. 'role' => 'user',
  5961. 'content' => $question
  5962. ];
  5963. }else if ($prompt == '继续策划下一集') {
  5964. if ($is_single) {
  5965. Utils::throwError('20003:单剧集不支持继续策划下一集');
  5966. }
  5967. $content = $chapter_content;
  5968. if (!$content) {
  5969. Utils::throwError('20003:章节内容无法获取,请确认');
  5970. }
  5971. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  5972. // 获取上一集最后记录
  5973. $prev_sequence = $episode_number - 1;
  5974. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  5975. // 构建消息
  5976. $messages[] =
  5977. [
  5978. 'role' => 'user',
  5979. 'content' => $question
  5980. ];
  5981. }else {
  5982. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  5983. if (!$content) {
  5984. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  5985. }
  5986. if (!$content) {
  5987. Utils::throwError('20003:章节内容无法获取,请确认');
  5988. }
  5989. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  5990. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  5991. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  5992. if ($origin_prompt) {
  5993. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  5994. }
  5995. $messages[] =
  5996. [
  5997. 'role' => 'user',
  5998. 'content' => $question
  5999. ];
  6000. }
  6001. // 处理文本模型
  6002. $model = getProp($data, 'model');
  6003. if (!$model) {
  6004. // 用户没有输入,从anime表获取
  6005. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6006. $model = getProp($anime, 'model');
  6007. if (!$model) {
  6008. // anime表也没有,使用默认值
  6009. $model = 'doubao-seed-2-0-mini-260215';
  6010. }
  6011. }
  6012. // 验证模型是否在可用模型表中
  6013. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6014. $model = 'doubao-seed-2-0-mini-260215';
  6015. }
  6016. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6017. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6018. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6019. if ($model === 'deepseek-chat') {
  6020. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6021. $model = 'deepseek-v4-flash';
  6022. $thinkingMode = 'disabled';
  6023. } elseif ($model === 'deepseek-reasoner') {
  6024. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6025. $model = 'deepseek-v4-flash';
  6026. $thinkingMode = 'enabled';
  6027. }
  6028. $post_data = [
  6029. 'model' => $model,
  6030. 'messages' => $messages,
  6031. // 'max_tokens' => 8192,
  6032. 'temperature' => 0.2,
  6033. 'frequency_penalty' => 0,
  6034. 'presence_penalty' => 0,
  6035. 'response_format' => ['type' => 'text'],
  6036. 'thinking' => ['type' => $thinkingMode],
  6037. 'stream' => true // 启用流式输出
  6038. ];
  6039. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6040. // 根据模型类型选择调用方法
  6041. $fullContent = '';
  6042. $fullReasoningContent = '';
  6043. $usage = [];
  6044. try {
  6045. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6046. // DeepSeek 官方模型使用 DeepSeek API
  6047. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6048. } else if (in_array($model, $this->gpt_text_models)) {
  6049. // GPT-5.4 模型使用 TokenRouter API
  6050. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6051. } else if (in_array($model, $this->gemini_text_models)) {
  6052. // Gemini 模型使用 Gemini API
  6053. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6054. } else {
  6055. // 其他模型使用火山引擎API
  6056. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6057. }
  6058. // 验证返回值类型
  6059. if (!is_iterable($streamGenerator)) {
  6060. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6061. dLog('deepseek')->error('chat流式生成器无效', [
  6062. 'generator_type' => $errorType,
  6063. 'model' => $model,
  6064. 'anime_id' => $anime_id,
  6065. 'episode_number' => $episode_number
  6066. ]);
  6067. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  6068. 'type' => $errorType,
  6069. 'model' => $model
  6070. ]);
  6071. yield [
  6072. 'type' => 'error',
  6073. 'episode' => [],
  6074. 'answer' => '',
  6075. 'reasoning' => '',
  6076. 'usage' => [],
  6077. 'error' => '接口返回数据异常,请重新请求'
  6078. ];
  6079. return;
  6080. }
  6081. // 处理流式输出
  6082. foreach ($streamGenerator as $chunk) {
  6083. if (isset($chunk['type'])) {
  6084. if ($chunk['type'] === 'done') {
  6085. // 最终结果
  6086. $fullContent = $chunk['full_content'];
  6087. $fullReasoningContent = $chunk['full_reasoning'];
  6088. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6089. } else {
  6090. // 逐块yield数据
  6091. yield $chunk;
  6092. }
  6093. }
  6094. }
  6095. } catch (\Exception $e) {
  6096. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  6097. 'model' => $model,
  6098. 'anime_id' => $anime_id,
  6099. 'episode_number' => $episode_number,
  6100. 'trace' => $e->getTraceAsString()
  6101. ]);
  6102. logDB('deepseek', 'error', 'chat流式处理失败', [
  6103. 'error' => $e->getMessage(),
  6104. 'model' => $model
  6105. ]);
  6106. yield [
  6107. 'type' => 'error',
  6108. 'episode' => [],
  6109. 'answer' => '',
  6110. 'reasoning' => '',
  6111. 'usage' => [],
  6112. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6113. ];
  6114. return;
  6115. }
  6116. dLog('deepseek')->info('完整内容: '.$fullContent);
  6117. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6118. // 处理完整内容并返回最终结果
  6119. $episode_arr = handleEpisodeContent($fullContent);
  6120. logDB('deepseek', 'info', '解析内容', $episode_arr);
  6121. if (empty($episode_arr['acts'])) {
  6122. // 未生成剧本相关内容,保存对话记录并返回提示
  6123. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  6124. try {
  6125. $now = date('Y-m-d H:i:s');
  6126. // 保存对话记录
  6127. $records = [
  6128. [
  6129. 'uid' => $uid,
  6130. 'anime_id' => $anime_id,
  6131. 'sequence' => $episode_number,
  6132. 'role' => 'user',
  6133. 'content' => $prompt,
  6134. 'created_at' => $now,
  6135. 'updated_at' => $now
  6136. ],
  6137. [
  6138. 'uid' => $uid,
  6139. 'anime_id' => $anime_id,
  6140. 'sequence' => $episode_number,
  6141. 'role' => 'assistant',
  6142. 'content' => $fullContent,
  6143. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6144. 'created_at' => $now,
  6145. 'updated_at' => $now
  6146. ]
  6147. ];
  6148. DB::table('mp_anime_records')->insert($records);
  6149. } catch (\Exception $e) {
  6150. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6151. }
  6152. yield [
  6153. 'type' => 'done',
  6154. 'episode' => [],
  6155. 'answer' => $fullContent,
  6156. 'reasoning' => $fullReasoningContent,
  6157. 'usage' => $usage,
  6158. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  6159. ];
  6160. return;
  6161. }
  6162. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  6163. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  6164. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  6165. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  6166. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  6167. $existing_props = is_array($existing_props) ? $existing_props : [];
  6168. $now = date('Y-m-d H:i:s');
  6169. try {
  6170. DB::beginTransaction();
  6171. $saveResult = $this->saveEpisodeVersionData(
  6172. $anime_id,
  6173. $episode_number,
  6174. $episode_arr,
  6175. $existing_roles,
  6176. $existing_scenes,
  6177. $existing_props,
  6178. $current_episode,
  6179. $base_episode,
  6180. $is_regenerate_version,
  6181. $content,
  6182. $now
  6183. );
  6184. $episode = $saveResult['episode'];
  6185. $episode_id = $saveResult['episode_id'];
  6186. $merged_roles = $saveResult['merged_roles'];
  6187. $merged_scenes = $saveResult['merged_scenes'];
  6188. $merged_props = $saveResult['merged_props'];
  6189. $record_content = $origin_prompt;
  6190. if ($uploaded_content !== '') {
  6191. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  6192. }
  6193. $records = [
  6194. [
  6195. 'uid' => $uid,
  6196. 'anime_id' => $anime_id,
  6197. 'role' => 'user',
  6198. 'content' => $record_content,
  6199. 'sequence' => $episode_number,
  6200. 'episode_id' => $episode_id,
  6201. 'created_at' => $now,
  6202. 'updated_at' => $now
  6203. ],
  6204. [
  6205. 'uid' => $uid,
  6206. 'anime_id' => $anime_id,
  6207. 'role' => 'assistant',
  6208. 'content' => $fullContent,
  6209. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6210. 'sequence' => $episode_number,
  6211. 'episode_id' => $episode_id,
  6212. 'created_at' => $now,
  6213. 'updated_at' => $now
  6214. ]
  6215. ];
  6216. $boolen4 = DB::table('mp_anime_records')->insert($records);
  6217. if (!$boolen4) {
  6218. Utils::throwError('20003:对话记录保存失败');
  6219. }
  6220. // 保存模型和内容到anime表
  6221. $update_anime_data = [
  6222. 'model' => $model,
  6223. 'updated_at' => $now
  6224. ];
  6225. if ($uploaded_content) {
  6226. $update_anime_data['content'] = $uploaded_content;
  6227. }
  6228. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  6229. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6230. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6231. 'anime_id' => $anime_id,
  6232. 'episode_number' => $episode_number,
  6233. 'model' => $model,
  6234. ]);
  6235. }catch (\Exception $e) {
  6236. DB::rollBack();
  6237. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6238. yield [
  6239. 'type' => 'done',
  6240. 'answer' => $fullContent,
  6241. 'reasoning' => $fullReasoningContent,
  6242. 'usage' => $usage,
  6243. 'error' => $e->getMessage(),
  6244. ];
  6245. return;
  6246. }
  6247. DB::commit();
  6248. if ($is_global_generate_pics) {
  6249. // // 批量生成全局角色图片
  6250. // $this->batchSetGlobalRoleImg([
  6251. // 'anime_id' => $anime_id,
  6252. // ], true);
  6253. // // 批量生成全局场景图片
  6254. // $this->batchSetGlobalSceneImg([
  6255. // 'anime_id' => $anime_id,
  6256. // ], true);
  6257. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6258. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6259. }
  6260. $episode['episode_id'] = $episode_id;
  6261. $episode['roles'] = $merged_roles;
  6262. $episode['scenes'] = $merged_scenes;
  6263. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  6264. yield [
  6265. 'type' => 'done',
  6266. 'episode' => $episode,
  6267. 'answer' => $fullContent,
  6268. 'reasoning' => $fullReasoningContent,
  6269. 'usage' => $usage
  6270. ];
  6271. }
  6272. public function addChatForAce($data) {
  6273. $uid = Site::getUid();
  6274. $anime_id = getProp($data, 'anime_id');
  6275. if (!$anime_id) Utils::throwError('20003:请选择对话');
  6276. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  6277. if (!$anime) Utils::throwError('20003:对话不存在');
  6278. $file = getProp($data, 'file');
  6279. $content = getProp($data, 'content', '');
  6280. $bid = getProp($data, 'bid', 0);
  6281. $script_id = getProp($data, 'script_id', 0);
  6282. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  6283. $prompt = getProp($data, 'prompt');
  6284. $is_multi = getProp($anime, 'is_multi');
  6285. $is_single = (int)$is_multi !== 1;
  6286. // 积分余额预检(仅单剧集模式收费)
  6287. if ($is_single) {
  6288. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  6289. }
  6290. $extra_products = getProp($data, 'products', []);
  6291. if (!$extra_products) {
  6292. $extra_products = getProp($anime, 'extra_products');
  6293. if ($extra_products) {
  6294. $extra_products = json_decode($extra_products, true);
  6295. }else {
  6296. $extra_products = [];
  6297. }
  6298. }else {
  6299. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6300. }
  6301. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6302. $anime_script_id = getProp($anime, 'script_id');
  6303. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  6304. $cpid = Site::getCpid();
  6305. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6306. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6307. ->where('mapping.script_id', $anime_script_id)
  6308. ->where('product.cpid', $cpid)
  6309. ->where('product.is_deleted', 0);
  6310. $mappings = $script_products_mappings->select(
  6311. 'mapping.product_id',
  6312. 'mapping.episode_number',
  6313. 'product.product_name',
  6314. 'product.type',
  6315. 'product.product',
  6316. 'product.pic_prompt',
  6317. 'product.url',
  6318. 'product.pic_task_id',
  6319. 'product.pic_task_status',
  6320. 'product.three_view_image_url'
  6321. )
  6322. ->get();
  6323. // 按 product_id 分组,合并 episode_number
  6324. $productMap = [];
  6325. foreach ($mappings as $item) {
  6326. $product_id = $item->product_id;
  6327. $product_name = $item->product_name;
  6328. // 处理product_name两边的符号
  6329. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6330. if (!isset($productMap[$product_id])) {
  6331. $productMap[$product_id] = [
  6332. 'product_id' => $product_id,
  6333. 'product_name' => $product_name,
  6334. 'type' => (int)$item->type,
  6335. 'product' => (int)$item->product,
  6336. 'pic_prompt' => $item->pic_prompt,
  6337. 'url' => $item->url,
  6338. 'pic_task_id' => $item->pic_task_id,
  6339. 'pic_task_status' => $item->pic_task_status,
  6340. 'episode_numbers' => [],
  6341. ];
  6342. }
  6343. // 添加 episode_number(去重)
  6344. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6345. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6346. }
  6347. }
  6348. // 将查询到的剧本资产合并到extra_products中
  6349. // 先构建extra_products的索引(以product_id为key,用于去重)
  6350. $extraProductsMap = [];
  6351. foreach ($extra_products as $item) {
  6352. $key = getProp($item, 'product_id');
  6353. if ($key) {
  6354. $extraProductsMap[$key] = $item;
  6355. }
  6356. }
  6357. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6358. foreach ($productMap as $product) {
  6359. $product_id = $product['product_id'];
  6360. // 如果不存在则添加(不带episode_number信息)
  6361. if (!isset($extraProductsMap[$product_id])) {
  6362. $extraProductsMap[$product_id] = [
  6363. 'product_id' => $product['product_id'],
  6364. 'product_name' => $product['product_name'],
  6365. 'type' => $product['type'],
  6366. 'product' => $product['product'],
  6367. 'pic_prompt' => $product['pic_prompt'],
  6368. 'url' => $product['url'],
  6369. 'pic_task_id' => $product['pic_task_id'],
  6370. 'pic_task_status' => $product['pic_task_status'],
  6371. ];
  6372. }
  6373. }
  6374. // 重新赋值给extra_products
  6375. $extra_products = array_values($extraProductsMap);
  6376. }
  6377. $user_anime_name = getProp($anime, 'anime_name');
  6378. // 处理提示词
  6379. if ($prompt && $extra_products) {
  6380. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6381. foreach($extra_products as $item) {
  6382. $product_name = getProp($item, 'product_name');
  6383. if ($product_name) {
  6384. // 替换 {product_name} 为 product_name
  6385. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6386. }
  6387. }
  6388. }
  6389. // 处理文本模型
  6390. $model = getProp($data, 'model');
  6391. if (!$model) {
  6392. // 用户没有输入,从anime表获取
  6393. $model = getProp($anime, 'model');
  6394. if (!$model) {
  6395. // anime表也没有,使用默认值
  6396. $model = 'deepseek-v4-pro';
  6397. }
  6398. }
  6399. // 验证模型是否在可用模型表中
  6400. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6401. $model = 'deepseek-v4-pro';
  6402. }
  6403. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6404. if ($prompt) {
  6405. $question .= "本次修改要求如下:\n{$prompt}";
  6406. }
  6407. // if (!$file && !$content && !$bid) {
  6408. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  6409. // }
  6410. // 提取文件内容
  6411. if ($file) {
  6412. $content = $this->extractFileContent($file);
  6413. if (!$content) {
  6414. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6415. }
  6416. } elseif ($script_id) {
  6417. $content = $this->getContentByScriptId($script_id);
  6418. if (!$content) {
  6419. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6420. }
  6421. } elseif ($bid) {
  6422. $content = $this->getContentByBid($bid);
  6423. if (!$content) {
  6424. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6425. }
  6426. } elseif ($content) {
  6427. $content = filterContent($content);
  6428. } else {
  6429. $content = getProp($anime, 'content');
  6430. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6431. $need_generate_content = true;
  6432. }
  6433. }
  6434. // 美术风格
  6435. $input_art_style = getProp($data, 'art_style');
  6436. if (!$input_art_style) {
  6437. $mappedArtStyle = getProp($anime, 'art_style');
  6438. }else {
  6439. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6440. }
  6441. // 判断是否需要生成原文内容
  6442. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6443. // 如果需要生成原文内容,添加额外的要求
  6444. $content_generation_requirement = $need_generate_content
  6445. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6446. : "";
  6447. // 美术风格
  6448. if (!$mappedArtStyle) {
  6449. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6450. }else {
  6451. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6452. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6453. }else {
  6454. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6455. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6456. }
  6457. }
  6458. // 构建主体、场景和道具提示词
  6459. $extra_role_prompt = "\n";
  6460. $extra_scene_prompt = "\n";
  6461. $extra_prop_prompt = "\n";
  6462. $ref_products = []; // 参考资产
  6463. if ($extra_products) {
  6464. foreach($extra_products as $item) {
  6465. $product = getProp($item, 'product');
  6466. $product_name = getProp($item, 'product_name');
  6467. if ($product_name == '旁白') continue;
  6468. $ref_products[$product_name] = $item;
  6469. $pic_prompt = getProp($item, 'pic_prompt');
  6470. if ((int)$product === 1) {
  6471. // 拼接角色信息
  6472. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6473. } elseif ((int)$product === 2) {
  6474. // 拼接场景信息
  6475. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6476. } elseif ((int)$product === 3) {
  6477. // 拼接道具信息
  6478. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6479. }
  6480. }
  6481. // 优化提示词,融入剧本
  6482. if (!empty(trim($extra_role_prompt))) {
  6483. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6484. }
  6485. if (!empty(trim($extra_scene_prompt))) {
  6486. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6487. }
  6488. if (!empty(trim($extra_prop_prompt))) {
  6489. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6490. }
  6491. }
  6492. if ($anime_script_id && $is_single) {
  6493. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6494. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6495. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6496. }else {
  6497. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6498. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6499. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6500. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6501. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6502. {$extra_role_prompt}";
  6503. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6504. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6505. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6506. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6507. {$extra_scene_prompt}";
  6508. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6509. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6510. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6511. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6512. {$extra_prop_prompt}";
  6513. }
  6514. $systemPrompt = $is_single
  6515. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6516. 强制要求:
  6517. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6518. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6519. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6520. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6521. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6522. 普通要求:
  6523. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6524. $role_demo
  6525. $scene_demo
  6526. $prop_demo
  6527. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6528. 5.1片段分割逻辑(优先级从高到低):
  6529. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6530. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6531. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6532. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6533. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6534. - 片段数量格式为: 片段数量:8
  6535. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6536. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6537. 5.3分镜结构:每个分镜包含以下字段:
  6538. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6539. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6540. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6541. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6542. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6543. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6544. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6545. - 运镜:场景+画面描述+运镜
  6546. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6547. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6548. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6549. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6550. 6.{$mappedArtStyle_prompt}\n\n
  6551. 示例如下:\n
  6552. ###剧本名:西昆仑
  6553. ###故事梗概
  6554. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6555. ###剧本亮点
  6556. 亮点1:绝境奇药,生死一线
  6557. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6558. 亮点2:结拜兄妹,化解尴尬
  6559. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6560. 亮点3:纤发夺命,情愫暗涌
  6561. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6562. ###人物关系
  6563. 阿雪与梁萧之间存在兄妹之情。
  6564. ###核心矛盾
  6565. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6566. ###主体列表
  6567. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6568. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6569. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6570. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6571. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6572. 全景,正面拍摄,青年女性,亚洲人。
  6573. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6574. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6575. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6576. ###美术风格
  6577. 基础画风风格词:厚涂古风
  6578. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6579. ###场景列表
  6580. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6581. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6582. 无人物。}
  6583. ###分段剧本
  6584. 片段数量:8
  6585. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6586. ##片段1
  6587. 时长:12s
  6588. 分镜1
  6589. 出场角色:刀疤脸
  6590. 场景:边境小镇街道
  6591. 出场道具:酒杯-高脚杯
  6592. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6593. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6594. 配音台词:
  6595. 背景音效:
  6596. 分镜2
  6597. 出场角色:刀疤脸
  6598. 场景:悦来酒馆
  6599. 出场道具:酒杯-高脚杯
  6600. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6601. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6602. 配音台词:
  6603. 背景音效:
  6604. 分镜3
  6605. 出场角色:刀疤脸
  6606. 场景:悦来酒馆
  6607. 出场道具:酒杯-高脚杯
  6608. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6609. 运镜:从中景推向令牌特写。
  6610. 配音台词:
  6611. 背景音效:
  6612. 分镜4
  6613. 出场角色:刀疤脸
  6614. 场景:悦来酒馆
  6615. 出场道具:酒杯-高脚杯
  6616. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6617. 运镜:极速推向酒水溅起的瞬间。
  6618. 配音台词:
  6619. 背景音效:
  6620. 分镜5
  6621. 出场角色:刀疤脸
  6622. 场景:悦来酒馆
  6623. 出场道具:酒杯-高脚杯
  6624. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6625. 运镜:固定机位,利用倾斜构图制造压迫感。
  6626. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6627. 背景音效:
  6628. \n\n"
  6629. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6630. 强制要求:\n
  6631. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6632. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6633. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6634. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6635. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6636. 普通要求:\n
  6637. 1.剧本名(必须生成)必须与文档内容高度相关
  6638. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6639. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6640. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6641. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6642. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6643. {$extra_role_prompt}
  6644. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6645. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6646. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6647. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6648. {$extra_scene_prompt}
  6649. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6650. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6651. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6652. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6653. {$extra_prop_prompt}
  6654. 5.{$mappedArtStyle_prompt}\n\n
  6655. 示例如下:\n
  6656. ###剧本名:西昆仑
  6657. ###故事梗概
  6658. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6659. ###剧本亮点
  6660. 亮点1:绝境奇药,生死一线
  6661. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6662. 亮点2:结拜兄妹,化解尴尬
  6663. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6664. 亮点3:纤发夺命,情愫暗涌
  6665. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6666. ###人物关系
  6667. 阿雪与梁萧之间存在兄妹之情。
  6668. ###核心矛盾
  6669. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6670. ###主体列表
  6671. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6672. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6673. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6674. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6675. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6676. 全景,正面拍摄,青年女性,亚洲人。
  6677. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6678. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6679. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6680. ###美术风格
  6681. 基础画风风格词:厚涂古风
  6682. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6683. ###场景列表
  6684. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6685. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6686. 无人物。}
  6687. ###道具列表
  6688. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  6689. // 构建消息
  6690. $messages = [
  6691. [
  6692. 'role' => 'system',
  6693. 'content' => $systemPrompt
  6694. ],
  6695. [
  6696. 'role' => 'user',
  6697. 'content' => "以下是文档内容:
  6698. {$content}
  6699. 用户问题:
  6700. {$question}"
  6701. ]
  6702. ];
  6703. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6704. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6705. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6706. if ($model === 'deepseek-chat') {
  6707. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6708. $model = 'deepseek-v4-flash';
  6709. $thinkingMode = 'disabled';
  6710. } elseif ($model === 'deepseek-reasoner') {
  6711. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6712. $model = 'deepseek-v4-flash';
  6713. $thinkingMode = 'enabled';
  6714. }
  6715. $post_data = [
  6716. 'model' => $model,
  6717. 'messages' => $messages,
  6718. // 'max_tokens' => 8192,
  6719. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  6720. 'frequency_penalty' => 0,
  6721. 'presence_penalty' => 0,
  6722. 'response_format' => ['type' => 'text'],
  6723. 'thinking' => ['type'=>$thinkingMode],
  6724. 'stream' => true // 启用流式输出
  6725. ];
  6726. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6727. // 根据模型类型选择调用方法
  6728. $fullContent = '';
  6729. $fullReasoningContent = '';
  6730. $usage = [];
  6731. try {
  6732. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6733. // DeepSeek 官方模型使用 DeepSeek API
  6734. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6735. } else if (in_array($model, $this->gpt_text_models)) {
  6736. // GPT-5.4 模型使用 TokenRouter API
  6737. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6738. } else if (in_array($model, $this->gemini_text_models)) {
  6739. // Gemini 模型使用 Gemini API
  6740. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6741. } else {
  6742. // 其他模型使用火山引擎API
  6743. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6744. }
  6745. // 验证返回值类型
  6746. if (!is_iterable($streamGenerator)) {
  6747. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6748. dLog('deepseek')->error('addChat流式生成器无效', [
  6749. 'generator_type' => $errorType,
  6750. 'model' => $model,
  6751. 'anime_id' => $anime_id
  6752. ]);
  6753. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  6754. 'type' => $errorType,
  6755. 'model' => $model
  6756. ]);
  6757. yield [
  6758. 'type' => 'error',
  6759. 'script' => [],
  6760. 'episode' => [],
  6761. 'answer' => '',
  6762. 'reasoning' => '',
  6763. 'usage' => [],
  6764. 'error' => '接口返回数据异常,请重新请求'
  6765. ];
  6766. return;
  6767. }
  6768. // 处理流式输出
  6769. foreach ($streamGenerator as $chunk) {
  6770. if (isset($chunk['type'])) {
  6771. if ($chunk['type'] === 'done') {
  6772. // 最终结果
  6773. $fullContent = $chunk['full_content'];
  6774. $fullReasoningContent = $chunk['full_reasoning'];
  6775. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6776. } else {
  6777. // 逐块yield数据
  6778. yield $chunk;
  6779. }
  6780. }
  6781. }
  6782. } catch (\Exception $e) {
  6783. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  6784. 'model' => $model,
  6785. 'anime_id' => $anime_id,
  6786. 'trace' => $e->getTraceAsString()
  6787. ]);
  6788. logDB('deepseek', 'error', 'addChat流式处理失败', [
  6789. 'error' => $e->getMessage(),
  6790. 'model' => $model
  6791. ]);
  6792. yield [
  6793. 'type' => 'error',
  6794. 'script' => [],
  6795. 'episode' => [],
  6796. 'answer' => '',
  6797. 'reasoning' => '',
  6798. 'usage' => [],
  6799. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6800. ];
  6801. return;
  6802. }
  6803. dLog('deepseek')->info('完整内容: '.$fullContent);
  6804. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6805. // 处理完整内容并返回最终结果
  6806. $script_arr = [];
  6807. if ($fullContent) {
  6808. $script_arr = handleScriptContentForAce($fullContent);
  6809. dLog('deepseek')->info('解析内容', $script_arr);
  6810. logDB('deepseek', 'info', '解析内容', $script_arr);
  6811. }
  6812. if (empty($script_arr['roles'])) {
  6813. // 未生成剧本相关内容,保存对话记录并返回提示
  6814. dLog('deepseek')->info('未生成剧本相关的内容');
  6815. try {
  6816. DB::beginTransaction();
  6817. $now = date('Y-m-d H:i:s');
  6818. // 保存对话记录
  6819. $records = [
  6820. [
  6821. 'uid' => $uid,
  6822. 'anime_id' => $anime_id,
  6823. 'sequence' => 0,
  6824. 'role' => 'user',
  6825. 'content' => $prompt,
  6826. 'created_at' => $now,
  6827. 'updated_at' => $now
  6828. ],
  6829. [
  6830. 'uid' => $uid,
  6831. 'anime_id' => $anime_id,
  6832. 'sequence' => 0,
  6833. 'role' => 'assistant',
  6834. // 'content' => $fullContent,
  6835. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  6836. 'created_at' => $now,
  6837. 'updated_at' => $now
  6838. ]
  6839. ];
  6840. DB::table('mp_anime_records')->insert($records);
  6841. DB::commit();
  6842. } catch (\Exception $e) {
  6843. DB::rollBack();
  6844. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6845. }
  6846. yield [
  6847. 'type' => 'done',
  6848. 'script' => [],
  6849. 'episode' => [],
  6850. 'answer' => $fullContent,
  6851. 'reasoning' => $fullReasoningContent,
  6852. 'usage' => $usage,
  6853. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6854. ];
  6855. return;
  6856. }
  6857. // 如果需要生成原文内容,从script_arr中提取
  6858. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6859. $content = $script_arr['content'];
  6860. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  6861. if (!$content) {
  6862. yield [
  6863. 'type' => 'done',
  6864. 'script' => [],
  6865. 'episode' => [],
  6866. 'answer' => $fullContent,
  6867. 'reasoning' => $fullReasoningContent,
  6868. 'usage' => $usage,
  6869. 'error' => '未生成剧本内容,请调整提示词再试'
  6870. ];
  6871. return;
  6872. }
  6873. }
  6874. // 替换美术风格
  6875. if ($mappedArtStyle !== '') {
  6876. $script_arr['art_style'] = $mappedArtStyle;
  6877. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6878. }
  6879. // 新建动漫
  6880. if ($user_anime_name == '新剧本策划') {
  6881. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6882. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6883. // if (!$anime_name) {
  6884. // // 未识别到剧本名,保存对话记录并返回提示
  6885. // dLog('deepseek')->info('未能识别到剧本名称');
  6886. // try {
  6887. // DB::beginTransaction();
  6888. // $now = date('Y-m-d H:i:s');
  6889. // // 保存对话记录
  6890. // $records = [
  6891. // [
  6892. // 'uid' => $uid,
  6893. // 'anime_id' => $anime_id,
  6894. // 'sequence' => 0,
  6895. // 'role' => 'user',
  6896. // 'content' => $prompt,
  6897. // 'created_at' => $now,
  6898. // 'updated_at' => $now
  6899. // ],
  6900. // [
  6901. // 'uid' => $uid,
  6902. // 'anime_id' => $anime_id,
  6903. // 'sequence' => 0,
  6904. // 'role' => 'assistant',
  6905. // 'content' => '未能生成剧本名称,请重试',
  6906. // 'created_at' => $now,
  6907. // 'updated_at' => $now
  6908. // ]
  6909. // ];
  6910. // DB::table('mp_anime_records')->insert($records);
  6911. // DB::commit();
  6912. // } catch (\Exception $e) {
  6913. // DB::rollBack();
  6914. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6915. // }
  6916. // yield [
  6917. // 'type' => 'done',
  6918. // 'script' => [],
  6919. // 'episode' => [],
  6920. // 'answer' => $fullContent,
  6921. // 'reasoning' => $fullReasoningContent,
  6922. // 'usage' => $usage,
  6923. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6924. // ];
  6925. // return;
  6926. // }
  6927. // 确认对话名称唯一性
  6928. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6929. $anime_name = $anime_name . '_' . date('YmdHis');
  6930. }
  6931. }else {
  6932. $anime_name = $user_anime_name;
  6933. }
  6934. $table_data = [
  6935. 'user_id' => $uid,
  6936. 'anime_name' => $anime_name,
  6937. 'model' => $model,
  6938. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6939. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6940. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6941. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6942. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6943. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6944. 'art_style_type' => $input_art_style,
  6945. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6946. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6947. 'status' => '解析完成',
  6948. 'content' => $content,
  6949. 'is_multi' => $is_multi,
  6950. 'ace_mode' => $ace_mode,
  6951. 'generate_status' => '待执行',
  6952. 'updated_at' => date('Y-m-d H:i:s')
  6953. ];
  6954. if ($table_data['content']) {
  6955. $chapters = splitContent($table_data['content']);
  6956. $chapter_count = count($chapters);
  6957. if ($chapter_count > 0) {
  6958. $table_data['start_episode_sequence'] = 1;
  6959. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6960. }
  6961. }
  6962. if ($extra_products) {
  6963. $table_data['extra_products'] = json_encode($extra_products, 256);
  6964. }
  6965. // 如果有剧本ID则进行绑定
  6966. if ($script_id) {
  6967. $table_data['script_id'] = $script_id;
  6968. }
  6969. $single_episode = [];
  6970. try {
  6971. DB::beginTransaction();
  6972. $now = date('Y-m-d H:i:s');
  6973. // 更新动漫大纲
  6974. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6975. if (!$boolen) {
  6976. dLog('deepseek')->info('动漫保存失败', $table_data);
  6977. Utils::throwError('20003:动漫保存失败');
  6978. }
  6979. // 保存对话记录
  6980. $records = [
  6981. [
  6982. 'uid' => $uid,
  6983. 'anime_id' => $anime_id,
  6984. 'sequence' => 0,
  6985. 'role' => 'user',
  6986. 'content' => $prompt,
  6987. 'created_at' => date('Y-m-d H:i:s'),
  6988. 'updated_at' => date('Y-m-d H:i:s')
  6989. ],
  6990. [
  6991. 'uid' => $uid,
  6992. 'anime_id' => $anime_id,
  6993. 'sequence' => 0,
  6994. 'role' => 'assistant',
  6995. 'content' => $fullContent,
  6996. 'created_at' => date('Y-m-d H:i:s'),
  6997. 'updated_at' => date('Y-m-d H:i:s')
  6998. ]
  6999. ];
  7000. // 保存对话记录
  7001. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7002. if (!$boolen3) {
  7003. Utils::throwError('20003:对话记录保存失败');
  7004. }
  7005. if ($is_single) {
  7006. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7007. if (empty($episode_arr['acts'])) {
  7008. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7009. }
  7010. $saveResult = $this->saveEpisodeVersionData(
  7011. $anime_id,
  7012. 1,
  7013. $episode_arr,
  7014. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7015. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7016. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7017. null,
  7018. null,
  7019. false,
  7020. $content,
  7021. $now,
  7022. $ref_products
  7023. );
  7024. $single_episode = $saveResult['episode'];
  7025. $episode_id = $saveResult['episode_id'];
  7026. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7027. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7028. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7029. 'props' => json_encode($saveResult['merged_props'], 256),
  7030. 'updated_at' => $now
  7031. ]);
  7032. if ($boolen5 === false) {
  7033. Utils::throwError('20003:单剧集主表资源同步失败');
  7034. }
  7035. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7036. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7037. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7038. $episode_record_content = '确认分镜大纲';
  7039. if ($content !== '') {
  7040. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7041. }
  7042. $episode_records = [
  7043. [
  7044. 'uid' => $uid,
  7045. 'anime_id' => $anime_id,
  7046. 'role' => 'user',
  7047. 'content' => $episode_record_content,
  7048. 'sequence' => 1,
  7049. 'episode_id' => $episode_id,
  7050. 'created_at' => $now,
  7051. 'updated_at' => $now
  7052. ],
  7053. [
  7054. 'uid' => $uid,
  7055. 'anime_id' => $anime_id,
  7056. 'role' => 'assistant',
  7057. 'content' => $fullContent,
  7058. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7059. 'sequence' => 1,
  7060. 'episode_id' => $episode_id,
  7061. 'created_at' => $now,
  7062. 'updated_at' => $now
  7063. ]
  7064. ];
  7065. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7066. if (!$boolen4) {
  7067. Utils::throwError('20003:单剧集分镜记录保存失败');
  7068. }
  7069. }
  7070. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7071. if ($is_single && !empty($single_episode)) {
  7072. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7073. 'anime_id' => $anime_id,
  7074. 'episode_id' => $episode_id ?? 0,
  7075. ]);
  7076. }
  7077. }catch (\Exception $e) {
  7078. DB::rollBack();
  7079. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7080. yield [
  7081. 'type' => 'done',
  7082. 'answer' => $fullContent,
  7083. 'reasoning' => $fullReasoningContent,
  7084. 'usage' => $usage,
  7085. 'error' => $e->getMessage(),
  7086. ];
  7087. return;
  7088. }
  7089. DB::commit();
  7090. dLog('deepseek')->info('保存完毕');
  7091. if ($is_single && !empty($single_episode)) {
  7092. // $this->batchSetGlobalRoleImg([
  7093. // 'anime_id' => $anime_id,
  7094. // ]);
  7095. // $this->batchSetGlobalSceneImg([
  7096. // 'anime_id' => $anime_id,
  7097. // ]);
  7098. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7099. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7100. }
  7101. $table_data['anime_id'] = $anime_id;
  7102. $table_data['roles'] = json_decode($table_data['roles'], true);
  7103. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7104. // $table_data['episodes'] = $script_arr['episodes'];
  7105. unset($table_data['created_at']);
  7106. unset($table_data['updated_at']);
  7107. unset($table_data['status']);
  7108. dLog('deepseek')->info('开始返回');
  7109. yield [
  7110. 'type' => 'done',
  7111. 'script' => $table_data,
  7112. 'episode' => $single_episode,
  7113. 'answer' => $fullContent,
  7114. 'reasoning' => $fullReasoningContent,
  7115. 'usage' => $usage
  7116. ];
  7117. }
  7118. public function reGenerateAnimeForAce($data) {
  7119. $uid = Site::getUid();
  7120. $file = getProp($data, 'file');
  7121. $content = getProp($data, 'content', '');
  7122. $bid = getProp($data, 'bid', 0);
  7123. $script_id = getProp($data, 'script_id', 0);
  7124. $anime_id = getProp($data, 'anime_id');
  7125. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7126. if (!$anime) {
  7127. Utils::throwError('20003:该对话不存在');
  7128. }
  7129. $is_multi = getProp($anime, 'is_multi', 1);
  7130. $is_single = (int)$is_multi !== 1;
  7131. // 积分余额预检(仅单剧集模式收费)
  7132. if ($is_single) {
  7133. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  7134. }
  7135. $extra_products = getProp($data, 'products', []);
  7136. if (!$extra_products) {
  7137. $extra_products = getProp($anime, 'extra_products');
  7138. if ($extra_products) {
  7139. $extra_products = json_decode($extra_products, true);
  7140. }else {
  7141. $extra_products = [];
  7142. }
  7143. }else {
  7144. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7145. }
  7146. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7147. $anime_script_id = getProp($anime, 'script_id');
  7148. if ($anime_script_id && $is_single) {
  7149. $cpid = Site::getCpid();
  7150. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7151. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7152. ->where('mapping.script_id', $anime_script_id)
  7153. ->where('product.cpid', $cpid)
  7154. ->where('product.is_deleted', 0);
  7155. $mappings = $script_products_mappings->select(
  7156. 'mapping.product_id',
  7157. 'mapping.episode_number',
  7158. 'product.product_name',
  7159. 'product.type',
  7160. 'product.product',
  7161. 'product.pic_prompt',
  7162. 'product.url',
  7163. 'product.pic_task_id',
  7164. 'product.pic_task_status',
  7165. 'product.three_view_image_url'
  7166. )
  7167. ->get();
  7168. // 按 product_id 分组,合并 episode_number
  7169. $productMap = [];
  7170. foreach ($mappings as $item) {
  7171. $product_id = $item->product_id;
  7172. $product_name = $item->product_name;
  7173. // 处理product_name两边的符号
  7174. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7175. if (!isset($productMap[$product_id])) {
  7176. $productMap[$product_id] = [
  7177. 'product_id' => $product_id,
  7178. 'product_name' => $product_name,
  7179. 'type' => (int)$item->type,
  7180. 'product' => (int)$item->product,
  7181. 'pic_prompt' => $item->pic_prompt,
  7182. 'url' => $item->url,
  7183. 'pic_task_id' => $item->pic_task_id,
  7184. 'pic_task_status' => $item->pic_task_status,
  7185. 'episode_numbers' => [],
  7186. ];
  7187. }
  7188. // 添加 episode_number(去重)
  7189. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7190. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7191. }
  7192. }
  7193. // 将查询到的剧本资产合并到extra_products中
  7194. // 先构建extra_products的索引(以product_id为key,用于去重)
  7195. $extraProductsMap = [];
  7196. foreach ($extra_products as $item) {
  7197. $key = getProp($item, 'product_id');
  7198. if ($key) {
  7199. $extraProductsMap[$key] = $item;
  7200. }
  7201. }
  7202. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7203. foreach ($productMap as $product) {
  7204. $product_id = $product['product_id'];
  7205. // 如果不存在则添加(不带episode_number信息)
  7206. if (!isset($extraProductsMap[$product_id])) {
  7207. $extraProductsMap[$product_id] = [
  7208. 'product_id' => $product['product_id'],
  7209. 'product_name' => $product['product_name'],
  7210. 'type' => $product['type'],
  7211. 'product' => $product['product'],
  7212. 'pic_prompt' => $product['pic_prompt'],
  7213. 'url' => $product['url'],
  7214. 'pic_task_id' => $product['pic_task_id'],
  7215. 'pic_task_status' => $product['pic_task_status'],
  7216. ];
  7217. }
  7218. }
  7219. // 重新赋值给extra_products
  7220. $extra_products = array_values($extraProductsMap);
  7221. }
  7222. $user_anime_name = getProp($anime, 'anime_name');
  7223. $prompt = getProp($data, 'prompt');
  7224. // 处理提示词
  7225. if ($prompt && $extra_products) {
  7226. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7227. foreach($extra_products as $item) {
  7228. $product_name = getProp($item, 'product_name');
  7229. if ($product_name) {
  7230. // 替换 {product_name} 为 product_name
  7231. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7232. }
  7233. }
  7234. }
  7235. // 处理文本模型
  7236. $model = getProp($data, 'model');
  7237. if (!$model) {
  7238. // 用户没有输入,从anime表获取
  7239. $model = getProp($anime, 'model');
  7240. if (!$model) {
  7241. // anime表也没有,使用默认值
  7242. $model = 'deepseek-v4-pro';
  7243. }
  7244. }
  7245. // 验证模型是否在可用模型表中
  7246. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7247. $model = 'deepseek-v4-pro';
  7248. }
  7249. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  7250. if ($is_single) {
  7251. $episode_exists = DB::table('mp_anime_episodes')
  7252. ->where('anime_id', $anime_id)
  7253. ->where('sequence', 1)
  7254. ->exists();
  7255. if ($episode_exists) {
  7256. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  7257. }
  7258. }
  7259. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7260. if ($prompt) {
  7261. $question .= "本次修改要求如下:\n{$prompt}";
  7262. }
  7263. // 提取文件内容
  7264. if ($file) {
  7265. $content = $this->extractFileContent($file);
  7266. if (!$content) {
  7267. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7268. }
  7269. } elseif ($script_id) {
  7270. $content = $this->getContentByScriptId($script_id);
  7271. if (!$content) {
  7272. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7273. }
  7274. } elseif ($bid) {
  7275. $content = $this->getContentByBid($bid);
  7276. if (!$content) {
  7277. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7278. }
  7279. } elseif ($content) {
  7280. $content = filterContent($content);
  7281. }else {
  7282. $content = filterContent(getProp($anime, 'content'));
  7283. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7284. $need_generate_content = true;
  7285. }
  7286. }
  7287. // 判断是否需要生成原文内容
  7288. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7289. // 如果需要生成原文内容,添加额外的要求
  7290. $content_generation_requirement = $need_generate_content
  7291. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7292. : "";
  7293. // 美术风格
  7294. $input_art_style = getProp($data, 'art_style');
  7295. if (!$input_art_style) {
  7296. $mappedArtStyle = getProp($anime, 'art_style');
  7297. }else {
  7298. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7299. }
  7300. if (!$mappedArtStyle) {
  7301. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7302. }else {
  7303. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7304. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7305. }else {
  7306. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7307. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7308. }
  7309. }
  7310. // 构建主体、场景和道具提示词
  7311. $extra_role_prompt = "\n";
  7312. $extra_scene_prompt = "\n";
  7313. $extra_prop_prompt = "\n";
  7314. $ref_products = []; // 参考资产
  7315. if ($extra_products) {
  7316. foreach($extra_products as $item) {
  7317. $product = getProp($item, 'product');
  7318. $product_name = getProp($item, 'product_name');
  7319. if ($product_name == '旁白') continue;
  7320. $ref_products[$product_name] = $item;
  7321. $pic_prompt = getProp($item, 'pic_prompt');
  7322. if ((int)$product === 1) {
  7323. // 拼接角色信息
  7324. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7325. } elseif ((int)$product === 2) {
  7326. // 拼接场景信息
  7327. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7328. } elseif ((int)$product === 3) {
  7329. // 拼接道具信息
  7330. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7331. }
  7332. }
  7333. // 优化提示词,融入剧本
  7334. if (!empty(trim($extra_role_prompt))) {
  7335. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7336. }
  7337. if (!empty(trim($extra_scene_prompt))) {
  7338. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7339. }
  7340. if (!empty(trim($extra_prop_prompt))) {
  7341. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7342. }
  7343. }
  7344. if ($anime_script_id && $is_single) {
  7345. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7346. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7347. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7348. }else {
  7349. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7350. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7351. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7352. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7353. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7354. {$extra_role_prompt}";
  7355. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7356. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7357. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7358. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7359. {$extra_scene_prompt}";
  7360. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7361. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7362. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7363. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7364. {$extra_prop_prompt}";
  7365. }
  7366. $system_message = ['role'=>'system', 'content'=>$is_single
  7367. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7368. 强制要求:
  7369. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7370. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7371. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7372. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7373. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7374. 普通要求:
  7375. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7376. $role_demo
  7377. $scene_demo
  7378. $prop_demo
  7379. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7380. 5.1片段分割逻辑(优先级从高到低):
  7381. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7382. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7383. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7384. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7385. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7386. - 片段数量格式为: 片段数量:8
  7387. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7388. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7389. 5.3分镜结构:每个分镜包含以下字段:
  7390. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7391. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7392. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7393. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7394. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7395. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7396. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7397. - 运镜:场景+画面描述+运镜
  7398. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7399. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7400. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7401. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7402. 6.{$mappedArtStyle_prompt}\n\n
  7403. 示例如下:\n
  7404. ###剧本名:西昆仑
  7405. ###故事梗概
  7406. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7407. ###剧本亮点
  7408. 亮点1:绝境奇药,生死一线
  7409. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7410. 亮点2:结拜兄妹,化解尴尬
  7411. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7412. 亮点3:纤发夺命,情愫暗涌
  7413. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7414. ###人物关系
  7415. 阿雪与梁萧之间存在兄妹之情。
  7416. ###核心矛盾
  7417. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7418. ###主体列表
  7419. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7420. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7421. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7422. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7423. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7424. 全景,正面拍摄,青年女性,亚洲人。
  7425. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7426. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7427. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7428. ###美术风格
  7429. 基础画风风格词:厚涂古风
  7430. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7431. ###场景列表
  7432. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7433. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7434. 无人物。}
  7435. ###分段剧本
  7436. 片段数量:8
  7437. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7438. ##片段1
  7439. 时长:12s
  7440. 分镜1
  7441. 出场角色:刀疤脸
  7442. 场景:边境小镇街道
  7443. 出场道具:酒杯-高脚杯
  7444. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7445. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7446. 配音台词:
  7447. 背景音效:
  7448. 分镜2
  7449. 出场角色:刀疤脸
  7450. 场景:悦来酒馆
  7451. 出场道具:酒杯-高脚杯
  7452. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7453. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7454. 配音台词:
  7455. 背景音效:
  7456. 分镜3
  7457. 出场角色:刀疤脸
  7458. 场景:悦来酒馆
  7459. 出场道具:酒杯-高脚杯
  7460. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7461. 运镜:从中景推向令牌特写。
  7462. 配音台词:
  7463. 背景音效:
  7464. 分镜4
  7465. 出场角色:刀疤脸
  7466. 场景:悦来酒馆
  7467. 出场道具:酒杯-高脚杯
  7468. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7469. 运镜:极速推向酒水溅起的瞬间。
  7470. 配音台词:
  7471. 背景音效:
  7472. 分镜5
  7473. 出场角色:刀疤脸
  7474. 场景:悦来酒馆
  7475. 出场道具:酒杯-高脚杯
  7476. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7477. 运镜:固定机位,利用倾斜构图制造压迫感。
  7478. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7479. 背景音效:
  7480. \n\n"
  7481. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7482. 强制要求:\n
  7483. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7484. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7485. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7486. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7487. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7488. 普通要求:\n
  7489. 1.剧本名(必须生成)必须与文档内容高度相关
  7490. $role_demo
  7491. $scene_demo
  7492. $prop_demo
  7493. 5.{$mappedArtStyle_prompt}\n\n
  7494. 示例如下:\n
  7495. ###剧本名:西昆仑
  7496. ###故事梗概
  7497. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7498. ###剧本亮点
  7499. 亮点1:绝境奇药,生死一线
  7500. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7501. 亮点2:结拜兄妹,化解尴尬
  7502. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7503. 亮点3:纤发夺命,情愫暗涌
  7504. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7505. ###人物关系
  7506. 阿雪与梁萧之间存在兄妹之情。
  7507. ###核心矛盾
  7508. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7509. ###主体列表
  7510. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7511. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7512. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7513. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7514. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7515. 全景,正面拍摄,青年女性,亚洲人。
  7516. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7517. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7518. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7519. ###美术风格
  7520. 基础画风风格词:厚涂古风
  7521. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7522. ###场景列表
  7523. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7524. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7525. 无人物。}
  7526. ###道具列表
  7527. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  7528. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  7529. $episode_count = $this->extractEpisodeNumber($prompt);
  7530. if ((int)getProp($anime, 'is_multi') !== 1) {
  7531. yield [
  7532. 'type' => 'done',
  7533. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  7534. 'reasoning' => '',
  7535. 'usage' => []
  7536. ];
  7537. return;
  7538. }
  7539. if ($episode_count) {
  7540. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  7541. $system_message = [
  7542. 'role' => 'system',
  7543. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7544. 强制要求:\n
  7545. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7546. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7547. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7548. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7549. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7550. 普通要求:\n
  7551. 1.<故事梗概>控制在200-300字左右
  7552. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7553. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7554. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7555. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7556. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7557. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7558. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7559. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7560. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7561. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  7562. 示例如下:\n
  7563. ###剧本名:西昆仑
  7564. ###故事梗概
  7565. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7566. ###剧本亮点
  7567. 亮点1:绝境奇药,生死一线
  7568. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7569. 亮点2:结拜兄妹,化解尴尬
  7570. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7571. 亮点3:纤发夺命,情愫暗涌
  7572. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7573. ###人物关系
  7574. 阿雪与梁萧之间存在兄妹之情。
  7575. ###核心矛盾
  7576. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7577. ###主体列表
  7578. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7579. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7580. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7581. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7582. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7583. 全景,正面拍摄,青年女性,亚洲人。
  7584. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7585. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7586. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7587. ###美术风格
  7588. 基础画风风格词:厚涂古风
  7589. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7590. ###场景列表
  7591. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7592. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7593. 无人物。}
  7594. ###分集详细内容
  7595. ##第1章 重生
  7596. 我重生了。
  7597. 源于一个男人偏执的暗恋。
  7598. ##第2章 相救
  7599. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  7600. 我眼睛扫向站在锅炉后的卞大伟。"
  7601. ];
  7602. // 构建消息
  7603. $messages = [
  7604. $system_message,
  7605. [
  7606. 'role' => 'user',
  7607. 'content' => "以下是文档内容:
  7608. {$content}
  7609. 用户问题:
  7610. {$question}"
  7611. ]
  7612. ];
  7613. }else {
  7614. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  7615. // 构建消息
  7616. $messages = [
  7617. $system_message,
  7618. [
  7619. 'role' => 'user',
  7620. 'content' => "以下是文档内容:
  7621. {$content}
  7622. 用户问题:
  7623. {$question}"
  7624. ]
  7625. ];
  7626. }else {
  7627. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  7628. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  7629. return (array)$value;
  7630. })->toArray();
  7631. array_unshift($messages, $system_message);
  7632. $messages[] = [
  7633. 'role' => 'user',
  7634. 'content' => $prompt
  7635. ];
  7636. }
  7637. }
  7638. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7639. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7640. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7641. if ($model === 'deepseek-chat') {
  7642. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7643. $model = 'deepseek-v4-flash';
  7644. $thinkingMode = 'disabled';
  7645. } elseif ($model === 'deepseek-reasoner') {
  7646. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7647. $model = 'deepseek-v4-flash';
  7648. $thinkingMode = 'enabled';
  7649. }
  7650. $post_data = [
  7651. 'model' => $model,
  7652. 'messages' => $messages,
  7653. // 'max_tokens' => 8192,
  7654. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7655. 'frequency_penalty' => 0,
  7656. 'presence_penalty' => 0,
  7657. 'response_format' => ['type' => 'text'],
  7658. 'thinking' => ['type' => $thinkingMode],
  7659. 'stream' => true // 启用流式输出
  7660. ];
  7661. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7662. // 根据模型类型选择调用方法
  7663. $fullContent = '';
  7664. $fullReasoningContent = '';
  7665. $usage = [];
  7666. // dd($post_data);
  7667. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  7668. try {
  7669. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7670. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7671. } else if (in_array($model, $this->gpt_text_models)) {
  7672. // GPT-5.4 模型使用 TokenRouter API
  7673. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7674. } else if (in_array($model, $this->gemini_text_models)) {
  7675. // Gemini 模型使用 Gemini API
  7676. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  7677. } else {
  7678. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7679. }
  7680. // 验证返回值类型
  7681. if (!is_iterable($streamGenerator)) {
  7682. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7683. dLog('deepseek')->error('方法名流式生成器无效', [
  7684. 'generator_type' => $errorType,
  7685. 'model' => $model,
  7686. // 添加其他上下文信息
  7687. ]);
  7688. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  7689. 'type' => $errorType,
  7690. 'model' => $model
  7691. ]);
  7692. yield [
  7693. 'type' => 'error',
  7694. // 根据方法返回相应的空数据结构
  7695. 'answer' => '',
  7696. 'reasoning' => '',
  7697. 'usage' => [],
  7698. 'error' => '接口返回数据异常,请重新请求'
  7699. ];
  7700. return;
  7701. }
  7702. // 处理流式输出
  7703. foreach ($streamGenerator as $chunk) {
  7704. if (isset($chunk['type'])) {
  7705. if ($chunk['type'] === 'done') {
  7706. $fullContent = $chunk['full_content'];
  7707. $fullReasoningContent = $chunk['full_reasoning'];
  7708. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7709. } else {
  7710. yield $chunk;
  7711. }
  7712. }
  7713. }
  7714. } catch (\Exception $e) {
  7715. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  7716. 'model' => $model,
  7717. 'trace' => $e->getTraceAsString()
  7718. ]);
  7719. logDB('deepseek', 'error', '方法名流式处理失败', [
  7720. 'error' => $e->getMessage(),
  7721. 'model' => $model
  7722. ]);
  7723. yield [
  7724. 'type' => 'error',
  7725. // 根据方法返回相应的空数据结构
  7726. 'answer' => '',
  7727. 'reasoning' => '',
  7728. 'usage' => [],
  7729. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7730. ];
  7731. return;
  7732. }
  7733. dLog('deepseek')->info('完整内容: '.$fullContent);
  7734. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7735. // 处理完整内容并返回最终结果
  7736. $script_arr = [];
  7737. if ($fullContent) {
  7738. $script_arr = handleScriptContentForAce($fullContent);
  7739. dLog('deepseek')->info('解析内容', $script_arr);
  7740. logDB('deepseek', 'info', '解析内容', $script_arr);
  7741. }
  7742. if (empty($script_arr['roles'])) {
  7743. // 未生成剧本相关内容,保存对话记录并返回提示
  7744. dLog('deepseek')->info('未生成剧本相关的内容');
  7745. try {
  7746. $now = date('Y-m-d H:i:s');
  7747. // 保存对话记录
  7748. $records = [
  7749. [
  7750. 'uid' => $uid,
  7751. 'anime_id' => $anime_id,
  7752. 'sequence' => 0,
  7753. 'role' => 'user',
  7754. 'content' => $prompt,
  7755. 'created_at' => $now,
  7756. 'updated_at' => $now
  7757. ],
  7758. [
  7759. 'uid' => $uid,
  7760. 'anime_id' => $anime_id,
  7761. 'sequence' => 0,
  7762. 'role' => 'assistant',
  7763. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  7764. 'created_at' => $now,
  7765. 'updated_at' => $now
  7766. ]
  7767. ];
  7768. DB::table('mp_anime_records')->insert($records);
  7769. } catch (\Exception $e) {
  7770. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7771. }
  7772. yield [
  7773. 'type' => 'done',
  7774. 'script' => [],
  7775. 'episode' => [],
  7776. 'answer' => $fullContent,
  7777. 'reasoning' => $fullReasoningContent,
  7778. 'usage' => $usage,
  7779. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7780. ];
  7781. return;
  7782. }
  7783. // 替换美术风格
  7784. if ($mappedArtStyle !== '') {
  7785. $script_arr['art_style'] = $mappedArtStyle;
  7786. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7787. }
  7788. if ($user_anime_name != '新剧本策划') {
  7789. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7790. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7791. // 确认对话名称唯一性
  7792. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7793. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  7794. }
  7795. }else {
  7796. $anime_name = $user_anime_name;
  7797. }
  7798. $table_data = [
  7799. 'user_id' => $uid,
  7800. 'model' => $model,
  7801. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7802. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7803. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7804. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7805. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7806. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7807. 'art_style_type' => $input_art_style,
  7808. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7809. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7810. 'status' => '解析完成',
  7811. 'generate_status' => '待执行',
  7812. 'updated_at' => date('Y-m-d H:i:s')
  7813. ];
  7814. if ($anime_name) $table_data['anime_name'] = $anime_name;
  7815. // 如果是修改集数,则将content内容更新(会改变原文)
  7816. if (isset($episode_count) && $episode_count > 0) {
  7817. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  7818. $table_data['start_episode_sequence'] = 1;
  7819. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  7820. }else {
  7821. // 如果需要生成原文内容,从script_arr中提取
  7822. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7823. $table_data['content'] = $script_arr['content'];
  7824. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  7825. if (!$table_data['content']) {
  7826. yield [
  7827. 'type' => 'done',
  7828. 'script' => [],
  7829. 'episode' => [],
  7830. 'answer' => $fullContent,
  7831. 'reasoning' => $fullReasoningContent,
  7832. 'usage' => $usage,
  7833. 'error' => '未生成剧本内容,请调整提示词再试'
  7834. ];
  7835. return;
  7836. }
  7837. }
  7838. if (isset($table_data['content']) && $table_data['content']) {
  7839. $chapters = splitContent($table_data['content']);
  7840. $chapter_count = count($chapters);
  7841. if ($chapter_count > 0) {
  7842. $table_data['start_episode_sequence'] = 1;
  7843. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7844. }
  7845. }
  7846. }
  7847. if ($extra_products) {
  7848. $table_data['extra_products'] = json_encode($extra_products, 256);
  7849. }
  7850. $single_episode = [];
  7851. try {
  7852. DB::beginTransaction();
  7853. $now = date('Y-m-d H:i:s');
  7854. // 更新动漫大纲
  7855. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7856. if (!$boolen) {
  7857. dLog('deepseek')->info('对话修改失败', $table_data);
  7858. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  7859. Utils::throwError('20003:对话修改失败');
  7860. }
  7861. // 保存对话记录
  7862. $records = [
  7863. [
  7864. 'uid' => $uid,
  7865. 'anime_id' => $anime_id,
  7866. 'sequence' => 0,
  7867. 'role' => 'user',
  7868. 'content' => $prompt,
  7869. 'created_at' => $now,
  7870. 'updated_at' => $now
  7871. ],
  7872. [
  7873. 'uid' => $uid,
  7874. 'anime_id' => $anime_id,
  7875. 'sequence' => 0,
  7876. 'role' => 'assistant',
  7877. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7878. 'content' => $fullContent,
  7879. 'created_at' => $now,
  7880. 'updated_at' => $now
  7881. ]
  7882. ];
  7883. // 保存对话记录
  7884. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7885. if (!$boolen3) {
  7886. Utils::throwError('20003:对话记录保存失败');
  7887. }
  7888. // 单剧集模式:生成并保存剧集信息
  7889. if ($is_single) {
  7890. $anime_name = getProp($anime, 'anime_name', '未命名');
  7891. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7892. if (empty($episode_arr['acts'])) {
  7893. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7894. }
  7895. $saveResult = $this->saveEpisodeVersionData(
  7896. $anime_id,
  7897. 1,
  7898. $episode_arr,
  7899. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7900. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7901. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7902. null,
  7903. null,
  7904. false,
  7905. $content,
  7906. $now,
  7907. $ref_products
  7908. );
  7909. $single_episode = $saveResult['episode'];
  7910. $episode_id = $saveResult['episode_id'];
  7911. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7912. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7913. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7914. 'props' => json_encode($saveResult['merged_props'], 256),
  7915. 'updated_at' => $now
  7916. ]);
  7917. if ($boolen5 === false) {
  7918. Utils::throwError('20003:单剧集主表资源同步失败');
  7919. }
  7920. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7921. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7922. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7923. $episode_record_content = '确认分镜大纲';
  7924. if ($content !== '') {
  7925. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7926. }
  7927. $episode_records = [
  7928. [
  7929. 'uid' => $uid,
  7930. 'anime_id' => $anime_id,
  7931. 'role' => 'user',
  7932. 'content' => $episode_record_content,
  7933. 'sequence' => 1,
  7934. 'episode_id' => $episode_id,
  7935. 'created_at' => $now,
  7936. 'updated_at' => $now
  7937. ],
  7938. [
  7939. 'uid' => $uid,
  7940. 'anime_id' => $anime_id,
  7941. 'role' => 'assistant',
  7942. 'content' => $fullContent,
  7943. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7944. 'sequence' => 1,
  7945. 'episode_id' => $episode_id,
  7946. 'created_at' => $now,
  7947. 'updated_at' => $now
  7948. ]
  7949. ];
  7950. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7951. if (!$boolen4) {
  7952. Utils::throwError('20003:单剧集分镜记录保存失败');
  7953. }
  7954. }
  7955. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7956. if ($is_single && !empty($single_episode)) {
  7957. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7958. 'anime_id' => $anime_id,
  7959. 'episode_id' => $episode_id ?? 0,
  7960. ]);
  7961. }
  7962. }catch (\Exception $e) {
  7963. DB::rollBack();
  7964. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  7965. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  7966. yield [
  7967. 'type' => 'done',
  7968. 'answer' => $fullContent,
  7969. 'reasoning' => $fullReasoningContent,
  7970. 'usage' => $usage,
  7971. 'error' => $e->getMessage(),
  7972. ];
  7973. return;
  7974. }
  7975. DB::commit();
  7976. dLog('deepseek')->info('保存完毕');
  7977. if ($is_single && !empty($single_episode)) {
  7978. // $this->batchSetGlobalRoleImg([
  7979. // 'anime_id' => $anime_id,
  7980. // ]);
  7981. // $this->batchSetGlobalSceneImg([
  7982. // 'anime_id' => $anime_id,
  7983. // ]);
  7984. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7985. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7986. }
  7987. $table_data['anime_id'] = $anime_id;
  7988. $table_data['roles'] = json_decode($table_data['roles'], true);
  7989. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7990. $table_data['props'] = json_decode($table_data['props'], true);
  7991. unset($table_data['updated_at']);
  7992. unset($table_data['status']);
  7993. yield [
  7994. 'type' => 'done',
  7995. 'script' => $table_data,
  7996. 'episode' => $single_episode,
  7997. 'answer' => $fullContent,
  7998. 'reasoning' => $fullReasoningContent,
  7999. 'usage' => $usage
  8000. ];
  8001. }
  8002. public function chatForAce($data) {
  8003. $uid = Site::getUid();
  8004. // 积分余额预检(不足直接报错)
  8005. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  8006. $anime_id = getProp($data, 'anime_id');
  8007. $file = getProp($data, 'file');
  8008. $content = getProp($data, 'content', '');
  8009. $bid = getProp($data, 'bid', 0);
  8010. $script_id = getProp($data, 'script_id', 0);
  8011. $episode_number = getProp($data, 'episode_number', 1);
  8012. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8013. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8014. if (!$anime) Utils::throwError('20003:该对话不存在!');
  8015. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  8016. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  8017. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  8018. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  8019. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  8020. $roles = is_array($roles) ? $roles : [];
  8021. $scenes = is_array($scenes) ? $scenes : [];
  8022. $extra_products = getProp($data, 'products', []);
  8023. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8024. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8025. $anime_script_id = getProp($anime, 'script_id');
  8026. if ($anime_script_id) {
  8027. $cpid = Site::getCpid();
  8028. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8029. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8030. ->where('mapping.script_id', $anime_script_id)
  8031. ->where('product.cpid', $cpid)
  8032. ->where('product.is_deleted', 0);
  8033. // 如果提供了 episode_number,则过滤指定集数
  8034. if ($episode_number !== null && $episode_number !== '') {
  8035. $script_products_mappings->where('mapping.episode_number', $episode_number);
  8036. }
  8037. $mappings = $script_products_mappings->select(
  8038. 'mapping.product_id',
  8039. 'mapping.episode_number',
  8040. 'product.product_name',
  8041. 'product.type',
  8042. 'product.product',
  8043. 'product.pic_prompt',
  8044. 'product.url',
  8045. 'product.pic_task_id',
  8046. 'product.pic_task_status',
  8047. 'product.three_view_image_url'
  8048. )
  8049. ->get();
  8050. // 按 product_id 分组,合并 episode_number
  8051. $productMap = [];
  8052. foreach ($mappings as $item) {
  8053. $product_id = $item->product_id;
  8054. $product_name = $item->product_name;
  8055. // 处理product_name两边的符号
  8056. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8057. if (!isset($productMap[$product_id])) {
  8058. $productMap[$product_id] = [
  8059. 'product_id' => $product_id,
  8060. 'product_name' => $product_name,
  8061. 'type' => (int)$item->type,
  8062. 'product' => (int)$item->product,
  8063. 'pic_prompt' => $item->pic_prompt,
  8064. 'url' => $item->url,
  8065. 'pic_task_id' => $item->pic_task_id,
  8066. 'pic_task_status' => $item->pic_task_status,
  8067. 'episode_numbers' => [],
  8068. ];
  8069. }
  8070. // 添加 episode_number(去重)
  8071. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8072. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8073. }
  8074. }
  8075. // 将查询到的剧本资产合并到extra_products中
  8076. // 先构建extra_products的索引(以product_id+episode_number为key)
  8077. $extraProductsMap = [];
  8078. foreach ($extra_products as $item) {
  8079. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  8080. $extraProductsMap[$key] = $item;
  8081. }
  8082. // 合并剧本资产(去重:product_id+episode_number)
  8083. foreach ($productMap as $product) {
  8084. foreach ($product['episode_numbers'] as $ep_num) {
  8085. $key = $product['product_id'] . '_' . $ep_num;
  8086. // 如果不存在则添加
  8087. if (!isset($extraProductsMap[$key])) {
  8088. $extraProductsMap[$key] = [
  8089. 'product_id' => $product['product_id'],
  8090. 'product_name' => $product['product_name'],
  8091. 'type' => $product['type'],
  8092. 'product' => $product['product'],
  8093. 'pic_prompt' => $product['pic_prompt'],
  8094. 'url' => $product['url'],
  8095. 'pic_task_id' => $product['pic_task_id'],
  8096. 'pic_task_status' => $product['pic_task_status'],
  8097. 'episode_number' => $ep_num,
  8098. ];
  8099. }
  8100. }
  8101. }
  8102. // 重新赋值给extra_products
  8103. $extra_products = array_values($extraProductsMap);
  8104. }
  8105. // 处理提示词
  8106. if ($prompt && $extra_products) {
  8107. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8108. foreach($extra_products as $item) {
  8109. $product_name = getProp($item, 'product_name');
  8110. if ($product_name) {
  8111. // 替换 {product_name} 为 product_name
  8112. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8113. }
  8114. }
  8115. }
  8116. // 获取最后一集序号
  8117. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  8118. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  8119. // 转换主体列表和场景列表的格式
  8120. // 获取参考主体或场景
  8121. if ((int)$episode_number === 1) {
  8122. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  8123. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  8124. }else {
  8125. $prev_episode_number = $episode_number - 1;
  8126. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  8127. }
  8128. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  8129. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  8130. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  8131. // 合并anime_products和extra_products(extra_products优先,去重)
  8132. $anime_products = getProp($anime, 'extra_products');
  8133. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  8134. $ref_products = [];
  8135. foreach($anime_products as $item) {
  8136. $product_name = getProp($item, 'product_name');
  8137. $ref_products[$product_name] = $item;
  8138. }
  8139. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  8140. $extra_roles = []; // 从extra_products中提取的角色
  8141. $extra_scenes = []; // 从extra_products中提取的场景
  8142. $extra_props = []; // 从extra_products中提取的道具
  8143. if ($extra_products && is_array($extra_products)) {
  8144. foreach($extra_products as $item) {
  8145. $product = (int)getProp($item, 'product');
  8146. $product_name = getProp($item, 'product_name');
  8147. if ($product_name == '旁白') continue;
  8148. $pic_prompt = getProp($item, 'pic_prompt');
  8149. $ref_products[$product_name] = $item;
  8150. if ($product === 1) {
  8151. // 角色
  8152. $extra_roles[$product_name] = [
  8153. 'role' => $product_name,
  8154. 'pic_prompt' => $pic_prompt,
  8155. 'url' => getProp($item, 'url', ''),
  8156. ];
  8157. } elseif ($product === 2) {
  8158. // 场景
  8159. $extra_scenes[$product_name] = [
  8160. 'scene' => $product_name,
  8161. 'pic_prompt' => $pic_prompt,
  8162. 'url' => getProp($item, 'url', ''),
  8163. ];
  8164. } elseif ($product === 3) {
  8165. // 道具
  8166. $extra_props[$product_name] = [
  8167. 'prop' => $product_name,
  8168. 'pic_prompt' => $pic_prompt,
  8169. 'url' => getProp($item, 'url', ''),
  8170. ];
  8171. }
  8172. }
  8173. }
  8174. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  8175. $merged_roles = [];
  8176. foreach($ref_roles as $role) {
  8177. $role_name = getProp($role, 'role');
  8178. if (!isset($extra_roles[$role_name])) {
  8179. $merged_roles[$role_name] = $role;
  8180. }
  8181. }
  8182. // 添加extra_roles
  8183. foreach($extra_roles as $role_name => $role) {
  8184. $merged_roles[$role_name] = $role;
  8185. }
  8186. $ref_roles = array_values($merged_roles);
  8187. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  8188. $merged_scenes = [];
  8189. foreach($ref_scenes as $scene) {
  8190. $scene_name = getProp($scene, 'scene');
  8191. if (!isset($extra_scenes[$scene_name])) {
  8192. $merged_scenes[$scene_name] = $scene;
  8193. }
  8194. }
  8195. // 添加extra_scenes
  8196. foreach($extra_scenes as $scene_name => $scene) {
  8197. $merged_scenes[$scene_name] = $scene;
  8198. }
  8199. $ref_scenes = array_values($merged_scenes);
  8200. // 合并ref_props和extra_props(extra_props优先,去重)
  8201. $merged_props = [];
  8202. foreach($ref_props as $prop) {
  8203. $prop_name = getProp($prop, 'prop');
  8204. if (!isset($extra_props[$prop_name])) {
  8205. $merged_props[$prop_name] = $prop;
  8206. }
  8207. }
  8208. // 添加extra_props
  8209. foreach($extra_props as $prop_name => $prop) {
  8210. $merged_props[$prop_name] = $prop;
  8211. }
  8212. $ref_props = array_values($merged_props);
  8213. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  8214. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  8215. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  8216. // 构建强制主体、场景和道具提示词
  8217. $forced_roles_prompt = "";
  8218. $forced_scenes_prompt = "";
  8219. $forced_props_prompt = "";
  8220. if (!empty($extra_roles)) {
  8221. $forced_roles_list = "";
  8222. foreach($extra_roles as $role_name => $role) {
  8223. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  8224. }
  8225. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8226. }
  8227. if (!empty($extra_scenes)) {
  8228. $forced_scenes_list = "";
  8229. foreach($extra_scenes as $scene_name => $scene) {
  8230. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  8231. }
  8232. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8233. }
  8234. if (!empty($extra_props)) {
  8235. $forced_props_list = "";
  8236. foreach($extra_props as $prop_name => $prop) {
  8237. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  8238. }
  8239. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8240. }
  8241. if ($anime_script_id) {
  8242. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  8243. }else if ($roles_content) {
  8244. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  8245. 主体范围:\n {$roles_content}\n
  8246. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  8247. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8248. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8249. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8250. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8251. }else {
  8252. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8253. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8254. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8255. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8256. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8257. }
  8258. if ($anime_script_id) {
  8259. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  8260. }else if ($scenes_content) {
  8261. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8262. 场景范围:\n {$scenes_content}\n
  8263. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  8264. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  8265. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8266. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8267. }else {
  8268. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8269. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8270. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8271. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8272. }
  8273. if ($anime_script_id) {
  8274. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  8275. }else if ($props_content) {
  8276. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8277. 道具范围:\n {$props_content}\n
  8278. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  8279. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  8280. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8281. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8282. }else {
  8283. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8284. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  8285. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8286. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8287. }
  8288. // 提取文件内容
  8289. if ($file) {
  8290. $uploaded_content = $this->extractFileContent($file);
  8291. if (!$uploaded_content) {
  8292. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8293. }
  8294. } elseif ($script_id) {
  8295. $uploaded_content = $this->getContentByScriptId($script_id);
  8296. if (!$uploaded_content) {
  8297. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8298. }
  8299. } elseif ($bid) {
  8300. $uploaded_content = $this->getContentByBid($bid);
  8301. if (!$uploaded_content) {
  8302. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8303. }
  8304. } elseif ($content) {
  8305. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  8306. }
  8307. // elseif ($prompt) {
  8308. // $uploaded_content = filterContent($prompt);
  8309. // }
  8310. else {
  8311. $uploaded_content = '';
  8312. }
  8313. // 美术风格
  8314. $input_art_style = getProp($data, 'art_style');
  8315. if (!$input_art_style) {
  8316. $mappedArtStyle = getProp($anime, 'art_style');
  8317. }else {
  8318. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8319. }
  8320. if (!$mappedArtStyle) {
  8321. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8322. }else {
  8323. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8324. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8325. }else {
  8326. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8327. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8328. }
  8329. }
  8330. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8331. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8332. // 强制要求:
  8333. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8334. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8335. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8336. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  8337. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  8338. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  8339. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  8340. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  8341. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  8342. // 10.分镜要和场景列表、人物主体保持一致\n
  8343. // 普通要求:
  8344. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8345. // {$role_demo}
  8346. // {$scene_demo}
  8347. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8348. // 4.1片段分割逻辑(优先级从高到低):
  8349. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8350. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8351. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8352. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8353. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8354. // - 片段数量格式为: 片段数量:8
  8355. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8356. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8357. // 4.3分镜结构:每个分镜包含以下字段:
  8358. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  8359. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  8360. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8361. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  8362. // - 运镜:场景+画面描述+运镜
  8363. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  8364. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8365. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8366. // 5.$mappedArtStyle_prompt\n\n
  8367. // 示例格式:\n
  8368. // 第1集:隐形的守护者
  8369. // ###故事梗概
  8370. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8371. // ###美术风格
  8372. // 基础画风风格词:胡金铨武侠
  8373. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8374. // ###主体列表
  8375. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8376. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8377. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8378. // ###场景列表
  8379. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8380. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8381. // ###分段剧本
  8382. // 片段数量:8
  8383. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8384. // ##片段1
  8385. // 时长:12s
  8386. // 分镜1
  8387. // 场景:边境小镇街道
  8388. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8389. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8390. // 配音台词:
  8391. // 背景音效:
  8392. // 分镜2
  8393. // 场景:悦来酒馆
  8394. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8395. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8396. // 配音台词:
  8397. // 背景音效:
  8398. // 分镜3
  8399. // 场景:悦来酒馆
  8400. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8401. // 运镜:从中景推向令牌特写。
  8402. // 配音台词:
  8403. // 背景音效:
  8404. // 分镜4
  8405. // 场景:悦来酒馆
  8406. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8407. // 运镜:极速推向酒水溅起的瞬间。
  8408. // 配音台词:
  8409. // 背景音效:
  8410. // 分镜5
  8411. // 镜头描述
  8412. // 场景:悦来酒馆
  8413. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8414. // 运镜:固定机位,利用倾斜构图制造压迫感。
  8415. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8416. // 背景音效:
  8417. // \n\n";
  8418. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  8419. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  8420. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  8421. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  8422. 普通要求:
  8423. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8424. {$role_demo}
  8425. {$scene_demo}
  8426. {$prop_demo}
  8427. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8428. 5.1片段分割逻辑(优先级从高到低):
  8429. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8430. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8431. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8432. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8433. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8434. - 片段数量格式为: 片段数量:8
  8435. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8436. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8437. 5.3分镜结构:每个分镜包含以下字段:
  8438. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8439. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8440. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8441. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8442. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8443. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8444. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8445. - 运镜:场景+画面描述+运镜
  8446. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8447. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8448. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8449. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8450. 6.《情绪-视听语言映射表》:
  8451. 6.1 场景空间与时间心理学 (Scene & Temporality)
  8452. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8453. -----|---------|------------|----------------
  8454. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  8455. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  8456. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  8457. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  8458. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  8459. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8460. -----|---------|------------|----------------
  8461. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  8462. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  8463. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  8464. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  8465. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  8466. --------|---------|--------------|-------------
  8467. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  8468. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  8469. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  8470. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  8471. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  8472. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  8473. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  8474. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  8475. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  8476. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  8477. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  8478. -----|---------|------------|------------
  8479. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8480. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8481. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8482. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8483. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8484. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8485. --------|---------|--------------|----------
  8486. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8487. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8488. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8489. 6.6 声音设计与潜意识影响 (Soundscape)
  8490. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8491. -----|---------|------------|------------------
  8492. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8493. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8494. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8495. 理论基石:
  8496. - The Five C's of Cinematography by Joseph V. Mascelli
  8497. - Film Art: An Introduction by David Bordwell
  8498. - Sight, Sound, Motion by Herbert Zettl
  8499. - Notes on the Cinematograph by Robert Bresson
  8500. \n\n
  8501. 7.{$mappedArtStyle_prompt}
  8502. 示例格式:\n
  8503. 第1集:隐形的守护者
  8504. ###故事梗概
  8505. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8506. ###美术风格
  8507. 基础画风风格词:胡金铨武侠
  8508. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8509. ###主体列表
  8510. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8511. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8512. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8513. ###场景列表
  8514. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8515. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8516. ###道具列表
  8517. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  8518. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  8519. ###分段剧本
  8520. 片段数量:8
  8521. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8522. ##片段1
  8523. 时长:12s
  8524. 分镜1
  8525. 出场角色:刀疤脸
  8526. 场景:边境小镇街道
  8527. 出场道具:酒杯-高脚杯
  8528. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8529. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8530. 配音台词:
  8531. 背景音效:
  8532. 分镜2
  8533. 出场角色:刀疤脸
  8534. 场景:悦来酒馆
  8535. 出场道具:酒杯-高脚杯
  8536. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8537. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8538. 配音台词:
  8539. 背景音效:
  8540. 分镜3
  8541. 出场角色:刀疤脸
  8542. 场景:悦来酒馆
  8543. 出场道具:酒杯-高脚杯
  8544. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8545. 运镜:从中景推向令牌特写。
  8546. 配音台词:
  8547. 背景音效:
  8548. 分镜4
  8549. 出场角色:刀疤脸
  8550. 场景:悦来酒馆
  8551. 出场道具:酒杯-高脚杯
  8552. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8553. 运镜:极速推向酒水溅起的瞬间。
  8554. 配音台词:
  8555. 背景音效:
  8556. 分镜5
  8557. 出场角色:刀疤脸
  8558. 场景:悦来酒馆
  8559. 出场道具:酒杯-高脚杯
  8560. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8561. 运镜:固定机位,利用倾斜构图制造压迫感。
  8562. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8563. 背景音效:
  8564. \n\n";
  8565. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8566. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  8567. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  8568. $prompt = $origin_prompt;
  8569. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  8570. // 获取章节内容
  8571. $full_content = getProp($anime, 'content');
  8572. if ($uploaded_content) {
  8573. $full_content = $uploaded_content;
  8574. }
  8575. // 根据章节内容拆分章节
  8576. $chapters = splitContent($full_content);
  8577. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  8578. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  8579. $messages = [];
  8580. if ($prompt == '确认分镜大纲') {
  8581. // 暂时保留
  8582. $content = $chapter_content;
  8583. if ($is_single) $content = $full_content; // 单剧集使用全文
  8584. if (!$content) {
  8585. Utils::throwError('20003:章节内容无法获取,请确认');
  8586. }
  8587. $question = $is_single
  8588. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  8589. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  8590. // 构建消息
  8591. $messages[] =
  8592. [
  8593. 'role' => 'user',
  8594. 'content' => $question
  8595. ];
  8596. }else if ($prompt == '继续策划下一集') {
  8597. if ($is_single) {
  8598. Utils::throwError('20003:单剧集不支持继续策划下一集');
  8599. }
  8600. $content = $chapter_content;
  8601. if (!$content) {
  8602. Utils::throwError('20003:章节内容无法获取,请确认');
  8603. }
  8604. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  8605. // 获取上一集最后记录
  8606. $prev_sequence = $episode_number - 1;
  8607. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  8608. // 构建消息
  8609. $messages[] =
  8610. [
  8611. 'role' => 'user',
  8612. 'content' => $question
  8613. ];
  8614. // dd($messages);
  8615. }else {
  8616. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  8617. if (!$content) {
  8618. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  8619. }
  8620. if (!$content) {
  8621. Utils::throwError('20003:章节内容无法获取,请确认');
  8622. }
  8623. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  8624. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  8625. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  8626. if ($origin_prompt) {
  8627. $question .= "本次修改要求如下:\n{$origin_prompt}";
  8628. }
  8629. $messages[] =
  8630. [
  8631. 'role' => 'user',
  8632. 'content' => $question
  8633. ];
  8634. }
  8635. // 处理文本模型
  8636. $model = getProp($data, 'model');
  8637. if (!$model) {
  8638. // 用户没有输入,从anime表获取
  8639. $model = getProp($anime, 'model');
  8640. if (!$model) {
  8641. // anime表也没有,使用默认值
  8642. $model = 'deepseek-v4-pro';
  8643. }
  8644. }
  8645. // 验证模型是否在可用模型表中
  8646. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8647. $model = 'deepseek-v4-pro';
  8648. }
  8649. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8650. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  8651. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8652. if ($model === 'deepseek-chat') {
  8653. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8654. $model = 'deepseek-v4-flash';
  8655. $thinkingMode = 'disabled';
  8656. } elseif ($model === 'deepseek-reasoner') {
  8657. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8658. $model = 'deepseek-v4-flash';
  8659. $thinkingMode = 'enabled';
  8660. }
  8661. $post_data = [
  8662. 'model' => $model,
  8663. 'messages' => $messages,
  8664. // 'max_tokens' => 8192,
  8665. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8666. 'frequency_penalty' => 0,
  8667. 'presence_penalty' => 0,
  8668. 'response_format' => ['type' => 'text'],
  8669. 'thinking' => ['type' => $thinkingMode],
  8670. 'stream' => true // 启用流式输出
  8671. ];
  8672. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8673. // 根据模型类型选择调用方法
  8674. $fullContent = '';
  8675. $fullReasoningContent = '';
  8676. $usage = [];
  8677. try {
  8678. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8679. // DeepSeek 官方模型使用 DeepSeek API
  8680. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8681. } else if (in_array($model, $this->gpt_text_models)) {
  8682. // GPT-5.4 模型使用 TokenRouter API
  8683. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8684. } else if (in_array($model, $this->gemini_text_models)) {
  8685. // Gemini 模型使用 Gemini API
  8686. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8687. } else {
  8688. // 其他模型使用火山引擎API
  8689. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8690. }
  8691. // 验证返回值类型
  8692. if (!is_iterable($streamGenerator)) {
  8693. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8694. dLog('deepseek')->error('chat流式生成器无效', [
  8695. 'generator_type' => $errorType,
  8696. 'model' => $model,
  8697. 'anime_id' => $anime_id,
  8698. 'episode_number' => $episode_number
  8699. ]);
  8700. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  8701. 'type' => $errorType,
  8702. 'model' => $model
  8703. ]);
  8704. yield [
  8705. 'type' => 'error',
  8706. 'episode' => [],
  8707. 'answer' => '',
  8708. 'reasoning' => '',
  8709. 'usage' => [],
  8710. 'error' => '接口返回数据异常,请重新请求'
  8711. ];
  8712. return;
  8713. }
  8714. // 处理流式输出
  8715. foreach ($streamGenerator as $chunk) {
  8716. if (isset($chunk['type'])) {
  8717. if ($chunk['type'] === 'done') {
  8718. // 最终结果
  8719. $fullContent = $chunk['full_content'];
  8720. $fullReasoningContent = $chunk['full_reasoning'];
  8721. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8722. } else {
  8723. // 逐块yield数据
  8724. yield $chunk;
  8725. }
  8726. }
  8727. }
  8728. } catch (\Exception $e) {
  8729. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  8730. 'model' => $model,
  8731. 'anime_id' => $anime_id,
  8732. 'episode_number' => $episode_number,
  8733. 'trace' => $e->getTraceAsString()
  8734. ]);
  8735. logDB('deepseek', 'error', 'chat流式处理失败', [
  8736. 'error' => $e->getMessage(),
  8737. 'model' => $model
  8738. ]);
  8739. yield [
  8740. 'type' => 'error',
  8741. 'episode' => [],
  8742. 'answer' => '',
  8743. 'reasoning' => '',
  8744. 'usage' => [],
  8745. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8746. ];
  8747. return;
  8748. }
  8749. dLog('deepseek')->info('完整内容: '.$fullContent);
  8750. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8751. // 处理完整内容并返回最终结果
  8752. $episode_arr = handleEpisodeContentForAce($fullContent);
  8753. logDB('deepseek', 'info', '解析内容', $episode_arr);
  8754. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  8755. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  8756. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  8757. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  8758. // }
  8759. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  8760. $max_retries = 3;
  8761. $retry_count = 0;
  8762. $validation_failed = false;
  8763. $validation_error_msg = '';
  8764. // 验证生成的内容
  8765. if ($anime_script_id) {
  8766. // 检查是否有acts数据
  8767. if (empty($episode_arr['acts'])) {
  8768. $validation_failed = true;
  8769. $validation_error_msg = '未生成分镜剧本相关的内容';
  8770. } else {
  8771. // 仅当存在强制主体设定时校验主体列表
  8772. if (!empty($extra_roles)) {
  8773. $generated_roles = array_column($episode_arr['roles'], 'role');
  8774. // 过滤掉"旁白"角色
  8775. $generated_roles = array_filter($generated_roles, function($role) {
  8776. return $role !== '旁白';
  8777. });
  8778. $expected_roles = array_keys($extra_roles);
  8779. // 找出生成的主体中不在预期列表中的主体
  8780. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8781. if (!empty($invalid_roles)) {
  8782. $validation_failed = true;
  8783. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8784. }
  8785. }
  8786. // 仅当存在强制场景设定时校验场景列表
  8787. if (!$validation_failed && !empty($extra_scenes)) {
  8788. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  8789. $expected_scenes = array_keys($extra_scenes);
  8790. // 找出生成的场景中不在预期列表中的场景
  8791. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8792. if (!empty($invalid_scenes)) {
  8793. $validation_failed = true;
  8794. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8795. }
  8796. }
  8797. // 仅当存在强制道具设定时校验道具列表
  8798. if (!$validation_failed && !empty($extra_props)) {
  8799. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8800. $expected_props = array_keys($extra_props);
  8801. // 找出生成的道具中不在预期列表中的道具
  8802. $invalid_props = array_diff($generated_props, $expected_props);
  8803. if (!empty($invalid_props)) {
  8804. $validation_failed = true;
  8805. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8806. }
  8807. }
  8808. }
  8809. } else {
  8810. // 如果没有anime_script_id,只检查是否有acts数据
  8811. if (empty($episode_arr['acts'])) {
  8812. $validation_failed = true;
  8813. $validation_error_msg = '未生成分镜剧本相关的内容';
  8814. }
  8815. }
  8816. // 重试逻辑
  8817. while ($validation_failed && $retry_count < $max_retries) {
  8818. $retry_count++;
  8819. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  8820. 'reason' => $validation_error_msg,
  8821. 'anime_id' => $anime_id,
  8822. 'episode_number' => $episode_number
  8823. ]);
  8824. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  8825. 'reason' => $validation_error_msg,
  8826. 'anime_id' => $anime_id
  8827. ]);
  8828. // 发送流式重试提示
  8829. yield [
  8830. 'type' => 'retry',
  8831. 'retry_count' => $retry_count,
  8832. 'reason' => $validation_error_msg
  8833. ];
  8834. // 构建重试提示词
  8835. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  8836. if ($anime_script_id) {
  8837. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  8838. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  8839. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  8840. } else {
  8841. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  8842. }
  8843. // 添加重试消息到messages
  8844. $messages[] = [
  8845. 'role' => 'assistant',
  8846. 'content' => $fullContent
  8847. ];
  8848. $messages[] = [
  8849. 'role' => 'user',
  8850. 'content' => $retry_prompt
  8851. ];
  8852. // 更新post_data的messages
  8853. $post_data['messages'] = $messages;
  8854. // 重新调用API
  8855. try {
  8856. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8857. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8858. } else if (in_array($model, $this->gpt_text_models)) {
  8859. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8860. } else if (in_array($model, $this->gemini_text_models)) {
  8861. // Gemini 模型使用 Gemini API
  8862. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8863. } else {
  8864. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8865. }
  8866. // 处理流式输出
  8867. $fullContent = '';
  8868. $fullReasoningContent = '';
  8869. foreach ($streamGenerator as $chunk) {
  8870. if (isset($chunk['type'])) {
  8871. if ($chunk['type'] === 'done') {
  8872. $fullContent = $chunk['full_content'];
  8873. $fullReasoningContent = $chunk['full_reasoning'];
  8874. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8875. } else {
  8876. yield $chunk;
  8877. }
  8878. }
  8879. }
  8880. // 重新解析内容
  8881. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  8882. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  8883. $episode_arr = handleEpisodeContentForAce($fullContent);
  8884. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  8885. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  8886. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  8887. // }
  8888. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  8889. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  8890. // 重新验证
  8891. $validation_failed = false;
  8892. $validation_error_msg = '';
  8893. if ($anime_script_id) {
  8894. if (empty($episode_arr['acts'])) {
  8895. $validation_failed = true;
  8896. $validation_error_msg = '未生成分镜剧本相关的内容';
  8897. } else {
  8898. // 仅当存在强制主体设定时校验主体列表
  8899. if (!empty($extra_roles)) {
  8900. $generated_roles = array_column($episode_arr['roles'], 'role');
  8901. // 过滤掉"旁白"角色
  8902. $generated_roles = array_filter($generated_roles, function($role) {
  8903. return $role !== '旁白';
  8904. });
  8905. $expected_roles = array_keys($extra_roles);
  8906. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8907. if (!empty($invalid_roles)) {
  8908. $validation_failed = true;
  8909. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8910. }
  8911. }
  8912. // 仅当存在强制场景设定时校验场景列表
  8913. if (!$validation_failed && !empty($extra_scenes)) {
  8914. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  8915. $expected_scenes = array_keys($extra_scenes);
  8916. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8917. if (!empty($invalid_scenes)) {
  8918. $validation_failed = true;
  8919. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8920. }
  8921. }
  8922. // 仅当存在强制道具设定时校验道具列表
  8923. if (!$validation_failed && !empty($extra_props)) {
  8924. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8925. $expected_props = array_keys($extra_props);
  8926. $invalid_props = array_diff($generated_props, $expected_props);
  8927. if (!empty($invalid_props)) {
  8928. $validation_failed = true;
  8929. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8930. }
  8931. }
  8932. }
  8933. } else {
  8934. if (empty($episode_arr['acts'])) {
  8935. $validation_failed = true;
  8936. $validation_error_msg = '未生成分镜剧本相关的内容';
  8937. }
  8938. }
  8939. } catch (\Exception $e) {
  8940. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  8941. 'trace' => $e->getTraceAsString()
  8942. ]);
  8943. break;
  8944. }
  8945. }
  8946. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  8947. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  8948. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  8949. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  8950. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  8951. if ($validation_failed && $retry_count >= $max_retries) {
  8952. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  8953. 'retry_count' => $retry_count,
  8954. 'last_error' => $validation_error_msg
  8955. ]);
  8956. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  8957. 'error' => $validation_error_msg,
  8958. 'anime_id' => $anime_id
  8959. ]);
  8960. $validation_failed = false;
  8961. $validation_error_msg = '';
  8962. }
  8963. // 如果重试后仍然失败
  8964. if ($validation_failed) {
  8965. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  8966. 'retry_count' => $retry_count,
  8967. 'last_error' => $validation_error_msg
  8968. ]);
  8969. try {
  8970. $now = date('Y-m-d H:i:s');
  8971. $records = [
  8972. [
  8973. 'uid' => $uid,
  8974. 'anime_id' => $anime_id,
  8975. 'sequence' => $episode_number,
  8976. 'role' => 'user',
  8977. 'content' => $prompt,
  8978. 'created_at' => $now,
  8979. 'updated_at' => $now
  8980. ],
  8981. [
  8982. 'uid' => $uid,
  8983. 'anime_id' => $anime_id,
  8984. 'sequence' => $episode_number,
  8985. 'role' => 'assistant',
  8986. 'content' => $fullContent,
  8987. 'created_at' => $now,
  8988. 'updated_at' => $now
  8989. ]
  8990. ];
  8991. DB::table('mp_anime_records')->insert($records);
  8992. } catch (\Exception $e) {
  8993. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8994. }
  8995. yield [
  8996. 'type' => 'done',
  8997. 'episode' => [],
  8998. 'answer' => $fullContent,
  8999. 'reasoning' => $fullReasoningContent,
  9000. 'usage' => $usage,
  9001. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  9002. ];
  9003. return;
  9004. }
  9005. // 验证成功,记录日志
  9006. if ($retry_count > 0) {
  9007. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  9008. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  9009. }
  9010. // 老逻辑
  9011. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  9012. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  9013. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  9014. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  9015. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  9016. $existing_props = is_array($existing_props) ? $existing_props : [];
  9017. $now = date('Y-m-d H:i:s');
  9018. try {
  9019. DB::beginTransaction();
  9020. $saveResult = $this->saveEpisodeVersionData(
  9021. $anime_id,
  9022. $episode_number,
  9023. $episode_arr,
  9024. $existing_roles,
  9025. $existing_scenes,
  9026. $existing_props,
  9027. $current_episode,
  9028. $base_episode,
  9029. $is_regenerate_version,
  9030. $content,
  9031. $now,
  9032. $ref_products
  9033. );
  9034. $episode = $saveResult['episode'];
  9035. $episode_id = $saveResult['episode_id'];
  9036. $merged_roles = $saveResult['merged_roles'];
  9037. $merged_scenes = $saveResult['merged_scenes'];
  9038. $merged_props = $saveResult['merged_props'];
  9039. $record_content = $origin_prompt;
  9040. if ($uploaded_content !== '') {
  9041. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  9042. }
  9043. $records = [
  9044. [
  9045. 'uid' => $uid,
  9046. 'anime_id' => $anime_id,
  9047. 'role' => 'user',
  9048. 'content' => $record_content,
  9049. 'sequence' => $episode_number,
  9050. 'episode_id' => $episode_id,
  9051. 'created_at' => $now,
  9052. 'updated_at' => $now
  9053. ],
  9054. [
  9055. 'uid' => $uid,
  9056. 'anime_id' => $anime_id,
  9057. 'role' => 'assistant',
  9058. 'content' => $fullContent,
  9059. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9060. 'sequence' => $episode_number,
  9061. 'episode_id' => $episode_id,
  9062. 'created_at' => $now,
  9063. 'updated_at' => $now
  9064. ]
  9065. ];
  9066. $boolen4 = DB::table('mp_anime_records')->insert($records);
  9067. if (!$boolen4) {
  9068. Utils::throwError('20003:对话记录保存失败');
  9069. }
  9070. // 保存模型到anime表
  9071. $update_anime_data = [
  9072. 'model' => $model,
  9073. 'updated_at' => $now
  9074. ];
  9075. if ($uploaded_content) {
  9076. $update_anime_data['content'] = $uploaded_content;
  9077. }
  9078. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  9079. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  9080. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  9081. 'anime_id' => $anime_id,
  9082. 'episode_number' => $episode_number,
  9083. 'model' => $model,
  9084. ]);
  9085. }catch (\Exception $e) {
  9086. DB::rollBack();
  9087. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  9088. yield [
  9089. 'type' => 'done',
  9090. 'answer' => $fullContent,
  9091. 'reasoning' => $fullReasoningContent,
  9092. 'usage' => $usage,
  9093. 'error' => $e->getMessage(),
  9094. ];
  9095. return;
  9096. }
  9097. DB::commit();
  9098. if ($is_global_generate_pics) {
  9099. // // 批量生成全局角色图片
  9100. // $this->batchSetGlobalRoleImg([
  9101. // 'anime_id' => $anime_id,
  9102. // ], true);
  9103. // // 批量生成全局场景图片
  9104. // $this->batchSetGlobalSceneImg([
  9105. // 'anime_id' => $anime_id,
  9106. // ], true);
  9107. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  9108. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  9109. }
  9110. $episode['episode_id'] = $episode_id;
  9111. $episode['roles'] = $merged_roles;
  9112. $episode['scenes'] = $merged_scenes;
  9113. $episode['props'] = $merged_props;
  9114. $episode['end_episode_sequence'] = $end_episode_sequence;
  9115. // 获取mp_animes表中的视频参数
  9116. $episode['video_params'] = [
  9117. 'video_model' => getProp($anime, 'video_model'),
  9118. 'video_resolution' => getProp($anime, 'video_resolution'),
  9119. 'ratio' => getProp($anime, 'video_ratio'),
  9120. ];
  9121. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9122. yield [
  9123. 'type' => 'done',
  9124. 'episode' => $episode,
  9125. 'answer' => $fullContent,
  9126. 'reasoning' => $fullReasoningContent,
  9127. 'usage' => $usage
  9128. ];
  9129. }
  9130. /**
  9131. * chatForAce的非流式版本 - 用于定时任务
  9132. * 只获取最终 type=done 的数据,并验证必要字段
  9133. *
  9134. * @param array $data 请求数据
  9135. * @return array 生成结果
  9136. */
  9137. public function chatForAceNonStream($data) {
  9138. $finalResult = null;
  9139. // 调用流式方法,只保存 type=done 的数据
  9140. foreach ($this->chatForAce($data) as $chunk) {
  9141. // 只关注最终结果
  9142. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  9143. $finalResult = $chunk;
  9144. break; // 找到 done 就退出循环
  9145. }
  9146. }
  9147. // 验证最终结果
  9148. if (!$finalResult) {
  9149. return ['error' => '生成失败:未获取到最终结果'];
  9150. }
  9151. // 检查是否有错误
  9152. if (isset($finalResult['error']) && $finalResult['error']) {
  9153. return $finalResult;
  9154. }
  9155. // 验证必要字段
  9156. $episode = $finalResult['episode'] ?? [];
  9157. // 验证 roles
  9158. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  9159. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  9160. }
  9161. // 验证 scenes
  9162. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  9163. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  9164. }
  9165. // 验证 props(道具可以为空,但必须存在且为数组)
  9166. if (!isset($episode['props']) || !is_array($episode['props'])) {
  9167. $episode['props'] = [];
  9168. }
  9169. // 验证 acts(分镜剧本)
  9170. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  9171. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  9172. }
  9173. // 更新验证后的 episode 数据
  9174. $finalResult['episode'] = $episode;
  9175. // 记录验证成功日志
  9176. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  9177. 'roles_count' => count($episode['roles']),
  9178. 'scenes_count' => count($episode['scenes']),
  9179. 'props_count' => count($episode['props']),
  9180. 'acts_count' => count($episode['acts'])
  9181. ]);
  9182. return $finalResult;
  9183. }
  9184. /**
  9185. * 批量生成多个分集
  9186. *
  9187. * @param array $data 请求数据
  9188. * @return array 任务信息
  9189. */
  9190. public function batchGenerateEpisodes($data) {
  9191. $uid = Site::getUid();
  9192. $cpid = Site::getCpid();
  9193. $anime_id = getProp($data, 'anime_id');
  9194. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  9195. if (!$anime_id) {
  9196. Utils::throwError('20003:anime_id参数缺失');
  9197. }
  9198. if ($generate_episode_number < 1) {
  9199. Utils::throwError('20003:生成集数必须大于0');
  9200. }
  9201. // 获取动漫信息
  9202. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9203. if (!$anime) {
  9204. Utils::throwError('20003:该剧集不存在');
  9205. }
  9206. // 检查是否是全能模式
  9207. if ((int)getProp($anime, 'ace_mode') !== 1) {
  9208. Utils::throwError('20003:只有全能模式才支持批量生成');
  9209. }
  9210. // 检查是否是多剧集模式
  9211. if ((int)getProp($anime, 'is_multi') !== 1) {
  9212. Utils::throwError('20003:单剧集不支持批量生成');
  9213. }
  9214. // 获取当前已生成的最大集数
  9215. $currentMaxEpisode = DB::table('mp_anime_episodes')
  9216. ->where('anime_id', $anime_id)
  9217. ->where('is_default', 1)
  9218. ->max('episode_number');
  9219. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  9220. // 确定起始集数
  9221. $startEpisodeNumber = $currentMaxEpisode + 1;
  9222. // 计算结束集数
  9223. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  9224. // 检查是否超过总集数限制
  9225. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  9226. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  9227. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  9228. }
  9229. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  9230. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  9231. ->where('anime_id', $anime_id)
  9232. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  9233. ->whereIn('status', ['pending', 'processing', 'completed'])
  9234. ->count();
  9235. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  9236. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  9237. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  9238. if ($needEpisodeCount > 0) {
  9239. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS * $needEpisodeCount, $uid);
  9240. }
  9241. $now = date('Y-m-d H:i:s');
  9242. $createdTasks = [];
  9243. $skippedTasks = [];
  9244. // 为每一集创建详情记录
  9245. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  9246. // 检查是否已有该集的任务记录
  9247. $existingTask = DB::table('mp_batch_episode_generation_details')
  9248. ->where('anime_id', $anime_id)
  9249. ->where('episode_number', $episodeNumber)
  9250. ->first();
  9251. if ($existingTask) {
  9252. // 如果已存在且未完成,跳过
  9253. if (in_array($existingTask->status, ['pending', 'processing'])) {
  9254. $skippedTasks[] = $episodeNumber;
  9255. continue;
  9256. }
  9257. // 如果是失败状态,可以重新创建(删除旧记录)
  9258. if ($existingTask->status === 'failed') {
  9259. DB::table('mp_batch_episode_generation_details')
  9260. ->where('id', $existingTask->id)
  9261. ->delete();
  9262. }
  9263. // 如果是已完成状态,也跳过
  9264. if ($existingTask->status === 'completed') {
  9265. $skippedTasks[] = $episodeNumber;
  9266. continue;
  9267. }
  9268. }
  9269. // 准备任务数据
  9270. $taskData = [
  9271. 'anime_id' => $anime_id,
  9272. 'uid' => $uid,
  9273. 'cpid' => $cpid,
  9274. 'episode_number' => $episodeNumber,
  9275. 'status' => 'pending',
  9276. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  9277. 'retry_count' => 0,
  9278. 'created_at' => $now,
  9279. 'updated_at' => $now
  9280. ];
  9281. // 创建任务记录
  9282. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  9283. if ($taskId) {
  9284. $createdTasks[] = $episodeNumber;
  9285. }
  9286. }
  9287. if (empty($createdTasks)) {
  9288. if (!empty($skippedTasks)) {
  9289. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  9290. } else {
  9291. Utils::throwError('20003:创建批量生成任务失败');
  9292. }
  9293. }
  9294. return [
  9295. 'anime_id' => $anime_id,
  9296. 'start_episode' => $startEpisodeNumber,
  9297. 'end_episode' => $endEpisodeNumber,
  9298. 'total_episodes' => $generate_episode_number,
  9299. 'created_episodes' => $createdTasks,
  9300. 'skipped_episodes' => $skippedTasks,
  9301. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  9302. "已创建: " . implode(',', $createdTasks) .
  9303. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  9304. ];
  9305. }
  9306. /**
  9307. * 获取批量生成任务状态
  9308. *
  9309. * @param array $data 请求数据
  9310. * @return array 任务状态信息
  9311. */
  9312. public function getBatchGenerationTaskStatus($data) {
  9313. $anime_id = getProp($data, 'anime_id');
  9314. if (!$anime_id) {
  9315. Utils::throwError('20003:anime_id参数缺失');
  9316. }
  9317. // 获取该anime的所有任务
  9318. $tasks = DB::table('mp_batch_episode_generation_details')
  9319. ->where('anime_id', $anime_id)
  9320. ->orderBy('episode_number')
  9321. ->get()
  9322. ->map(function($item) {
  9323. return [
  9324. 'id' => $item->id,
  9325. 'episode_number' => $item->episode_number,
  9326. 'status' => $item->status,
  9327. 'error_message' => $item->error_message,
  9328. 'retry_count' => $item->retry_count,
  9329. 'created_at' => $item->created_at,
  9330. 'updated_at' => $item->updated_at,
  9331. 'completed_at' => $item->completed_at
  9332. ];
  9333. })
  9334. ->toArray();
  9335. if (empty($tasks)) {
  9336. Utils::throwError('20003:该剧集没有批量生成任务');
  9337. }
  9338. // 统计各状态数量
  9339. $totalCount = count($tasks);
  9340. $pendingCount = 0;
  9341. $processingCount = 0;
  9342. $completedCount = 0;
  9343. $failedCount = 0;
  9344. foreach ($tasks as $task) {
  9345. switch ($task['status']) {
  9346. case 'pending':
  9347. $pendingCount++;
  9348. break;
  9349. case 'processing':
  9350. $processingCount++;
  9351. break;
  9352. case 'completed':
  9353. $completedCount++;
  9354. break;
  9355. case 'failed':
  9356. $failedCount++;
  9357. break;
  9358. }
  9359. }
  9360. // 计算进度百分比
  9361. $progress = 0;
  9362. if ($totalCount > 0) {
  9363. $progress = round(($completedCount / $totalCount) * 100, 2);
  9364. }
  9365. // 判断整体状态
  9366. $overallStatus = 'processing';
  9367. if ($completedCount === $totalCount) {
  9368. $overallStatus = 'completed';
  9369. } elseif ($pendingCount === $totalCount) {
  9370. $overallStatus = 'pending';
  9371. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  9372. $overallStatus = 'failed';
  9373. }
  9374. return [
  9375. 'anime_id' => $anime_id,
  9376. 'total_episodes' => $totalCount,
  9377. 'pending_count' => $pendingCount,
  9378. 'processing_count' => $processingCount,
  9379. 'completed_count' => $completedCount,
  9380. 'failed_count' => $failedCount,
  9381. 'progress' => $progress,
  9382. 'overall_status' => $overallStatus,
  9383. 'tasks' => $tasks
  9384. ];
  9385. }
  9386. /**
  9387. * 将生成内容中不在强制列表中的资源合并进强制列表
  9388. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  9389. *
  9390. * @param array $generated 生成内容中的资源列表
  9391. * @param array $forced 强制资源列表(key为资源名称)
  9392. * @param string $type 资源类型:role、scene、prop
  9393. * @return array
  9394. */
  9395. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  9396. {
  9397. foreach ($generated as $item) {
  9398. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  9399. if ($name === null || $name === '') {
  9400. continue;
  9401. }
  9402. if ($name === '旁白') {
  9403. continue;
  9404. }
  9405. if (!isset($forced[$name])) {
  9406. $forced[$name] = $item;
  9407. }
  9408. }
  9409. return $forced;
  9410. }
  9411. /**
  9412. * 智能匹配并替换主体和场景名称
  9413. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  9414. *
  9415. * @param array $episode_arr 解析后的剧集数据
  9416. * @param array $extra_roles 强制主体设定(key为主体名称)
  9417. * @param array $extra_scenes 强制场景设定(key为场景名称)
  9418. * @return array 替换后的剧集数据
  9419. */
  9420. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  9421. $replaced_count = 0;
  9422. // 1. 处理主体列表
  9423. if (!empty($episode_arr['roles'])) {
  9424. foreach ($episode_arr['roles'] as &$role) {
  9425. $generated_role_name = $role['role'] ?? '';
  9426. // 跳过旁白
  9427. if ($generated_role_name === '旁白') {
  9428. continue;
  9429. }
  9430. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  9431. if (!isset($extra_roles[$generated_role_name])) {
  9432. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  9433. if ($matched_role) {
  9434. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  9435. $role['role'] = $matched_role;
  9436. $replaced_count++;
  9437. }
  9438. }
  9439. }
  9440. }
  9441. // 2. 处理场景列表
  9442. if (!empty($episode_arr['scenes'])) {
  9443. foreach ($episode_arr['scenes'] as &$scene) {
  9444. $generated_scene_name = $scene['scene'] ?? '';
  9445. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  9446. if (!isset($extra_scenes[$generated_scene_name])) {
  9447. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  9448. if ($matched_scene) {
  9449. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  9450. $scene['scene'] = $matched_scene;
  9451. $replaced_count++;
  9452. }
  9453. }
  9454. }
  9455. }
  9456. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  9457. if (!empty($episode_arr['acts'])) {
  9458. foreach ($episode_arr['acts'] as &$act) {
  9459. if (!empty($act['segments'])) {
  9460. foreach ($act['segments'] as &$segment) {
  9461. if (!empty($segment['segment_content'])) {
  9462. $original_content = $segment['segment_content'];
  9463. $replaced_content = $original_content;
  9464. // 替换场景名 - 在文本中查找并替换
  9465. foreach (array_keys($extra_scenes) as $full_scene_name) {
  9466. // 尝试找到可能的短名称
  9467. $potential_short_names = [];
  9468. // 提取场景名的主要部分(冒号之前)
  9469. if (mb_strpos($full_scene_name, ':') !== false) {
  9470. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  9471. $potential_short_names[] = $short_name;
  9472. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  9473. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  9474. $potential_short_names[] = $short_name;
  9475. }
  9476. // 替换场景字段中的短名称
  9477. foreach ($potential_short_names as $short_name) {
  9478. if ($short_name !== $full_scene_name) {
  9479. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  9480. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  9481. if ($new_content !== $replaced_content) {
  9482. $replaced_content = $new_content;
  9483. $replaced_count++;
  9484. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  9485. }
  9486. }
  9487. }
  9488. }
  9489. // 替换配音角色名(跳过旁白)
  9490. foreach (array_keys($extra_roles) as $full_role_name) {
  9491. if ($full_role_name === '旁白') {
  9492. continue;
  9493. }
  9494. // 尝试找到可能的短名称
  9495. $potential_short_names = [];
  9496. // 提取角色名的主要部分(短横线之前)
  9497. if (mb_strpos($full_role_name, '-') !== false) {
  9498. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  9499. $potential_short_names[] = $short_name;
  9500. }
  9501. // 替换配音台词中的短名称
  9502. foreach ($potential_short_names as $short_name) {
  9503. if ($short_name !== $full_role_name) {
  9504. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  9505. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  9506. if ($new_content !== $replaced_content) {
  9507. $replaced_content = $new_content;
  9508. $replaced_count++;
  9509. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  9510. }
  9511. }
  9512. }
  9513. }
  9514. // 如果有替换,更新segment_content
  9515. if ($replaced_content !== $original_content) {
  9516. $segment['segment_content'] = $replaced_content;
  9517. }
  9518. }
  9519. }
  9520. }
  9521. }
  9522. }
  9523. if ($replaced_count > 0) {
  9524. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  9525. 'replaced_count' => $replaced_count
  9526. ]);
  9527. }
  9528. return $episode_arr;
  9529. }
  9530. /**
  9531. * 查找匹配的名称
  9532. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  9533. *
  9534. * @param string $generated_name 生成的名称
  9535. * @param array $expected_names 预期的名称列表
  9536. * @return string|null 匹配到的名称,如果没有匹配则返回null
  9537. */
  9538. private function findMatchingName($generated_name, $expected_names) {
  9539. if (empty($generated_name)) {
  9540. return null;
  9541. }
  9542. // 尝试精确匹配
  9543. if (in_array($generated_name, $expected_names)) {
  9544. return $generated_name;
  9545. }
  9546. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  9547. foreach ($expected_names as $expected_name) {
  9548. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  9549. if (mb_strpos($expected_name, $generated_name) === 0) {
  9550. return $expected_name;
  9551. }
  9552. }
  9553. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  9554. // 这样可以处理一些变体,但优先级较低
  9555. foreach ($expected_names as $expected_name) {
  9556. if (mb_strpos($expected_name, $generated_name) !== false) {
  9557. return $expected_name;
  9558. }
  9559. }
  9560. return null;
  9561. }
  9562. /**
  9563. * 重新生成分段剧本
  9564. * @param array $data 包含以下字段:
  9565. * - prompt: string|null 用户修改要求(可选)
  9566. * - template_id: int|null 提示词模板ID(可选)
  9567. * - act_id: int|null 单个片段ID(与episode_id二选一)
  9568. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  9569. * @return array 返回生成结果
  9570. */
  9571. public function regenerateSegmentScript($data) {
  9572. $uid = Site::getUid();
  9573. $prompt = trim((string)getProp($data, 'prompt', ''));
  9574. $template_id = getProp($data, 'template_id', 0);
  9575. $act_id = getProp($data, 'act_id', 0);
  9576. $episode_id = getProp($data, 'episode_id', 0);
  9577. // 验证:prompt和template_id至少提供一个
  9578. if (empty($prompt) && empty($template_id)) {
  9579. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  9580. }
  9581. // 验证:act_id和episode_id二选一
  9582. if (empty($act_id) && empty($episode_id)) {
  9583. Utils::throwError('20003:请提供片段ID或剧集ID');
  9584. }
  9585. if (!empty($act_id) && !empty($episode_id)) {
  9586. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  9587. }
  9588. // 积分余额预检(仅剧集ID模式收费)
  9589. if (!empty($episode_id)) {
  9590. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  9591. }
  9592. // 如果提供了template_id,获取模板提示词
  9593. $template_prompt = '';
  9594. if ($template_id > 0) {
  9595. $template = DB::table('mp_prompt_templates')
  9596. ->where('id', $template_id)
  9597. ->where('is_deleted', 0)
  9598. ->first();
  9599. if (!$template) {
  9600. Utils::throwError('20003:提示词模板不存在或已删除');
  9601. }
  9602. $template_prompt = $template->template_prompt ?? '';
  9603. }
  9604. // 合并用户提示词和模板提示词
  9605. $final_prompt = '';
  9606. if (!empty($template_prompt)) {
  9607. $final_prompt = $template_prompt;
  9608. if (!empty($prompt)) {
  9609. $final_prompt .= "\n\n补充要求:" . $prompt;
  9610. }
  9611. } else {
  9612. $final_prompt = $prompt;
  9613. }
  9614. // 获取需要重新生成的内容参考
  9615. $reference_content = '';
  9616. $target_episode_id = 0;
  9617. $target_anime_id = 0;
  9618. $target_episode_number = 0;
  9619. if ($act_id > 0) {
  9620. // 单个片段模式:获取该片段的内容
  9621. $segment = DB::table('mp_episode_segments')
  9622. ->where('id', $act_id)
  9623. ->first();
  9624. if (!$segment) {
  9625. Utils::throwError('20003:片段不存在');
  9626. }
  9627. $target_episode_id = $segment->episode_id;
  9628. $target_anime_id = $segment->anime_id;
  9629. $target_episode_number = $segment->episode_number;
  9630. $reference_content = $segment->act_content ?? '';
  9631. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  9632. } else {
  9633. // 整个剧集模式:获取所有片段的内容
  9634. $segments = DB::table('mp_episode_segments')
  9635. ->where('episode_id', $episode_id)
  9636. ->orderBy('act_number')
  9637. ->get();
  9638. if ($segments->isEmpty()) {
  9639. Utils::throwError('20003:该剧集没有片段数据');
  9640. }
  9641. $target_episode_id = $episode_id;
  9642. $target_anime_id = $segments[0]->anime_id;
  9643. $target_episode_number = $segments[0]->episode_number;
  9644. // 拼接所有片段内容,保留格式用于AI理解
  9645. $act_contents = [];
  9646. foreach ($segments as $seg) {
  9647. $act_number = $seg->act_number;
  9648. $act_content = $seg->act_content ?? '';
  9649. if (!empty($act_content)) {
  9650. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  9651. }
  9652. }
  9653. $reference_content = implode("\n\n", $act_contents);
  9654. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  9655. if ($episode_content) {
  9656. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  9657. }else {
  9658. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  9659. }
  9660. }
  9661. if (empty($reference_content)) {
  9662. Utils::throwError('20003:没有可参考的片段内容');
  9663. }
  9664. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  9665. $episode = DB::table('mp_anime_episodes')
  9666. ->where('id', $target_episode_id)
  9667. ->first();
  9668. if (!$episode) {
  9669. Utils::throwError('20003:剧集不存在');
  9670. }
  9671. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  9672. $anime_script_id = getProp($anime, 'script_id');
  9673. $intro = $episode->intro ?? '';
  9674. $art_style = $episode->art_style ?? '';
  9675. $roles = json_decode($episode->roles ?? '[]', true);
  9676. $scenes = json_decode($episode->scenes ?? '[]', true);
  9677. $props = json_decode($episode->props ?? '[]', true);
  9678. // 构建提示词中的主体列表和场景列表参考
  9679. $roles_ref = '';
  9680. if (!empty($roles) && is_array($roles)) {
  9681. $roles_list = [];
  9682. foreach ($roles as $role) {
  9683. $role_name = getProp($role, 'role', '');
  9684. $role_desc = getProp($role, 'description', '');
  9685. $pic_prompt = getProp($role, 'pic_prompt', '');
  9686. $voice_prompt = getProp($role, 'voice_prompt', '');
  9687. if (!empty($role_name)) {
  9688. $role_line = $role_name;
  9689. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  9690. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  9691. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  9692. $roles_list[] = $role_line;
  9693. }
  9694. }
  9695. if (!empty($roles_list)) {
  9696. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  9697. }
  9698. }
  9699. $scenes_ref = '';
  9700. if (!empty($scenes) && is_array($scenes)) {
  9701. $scenes_list = [];
  9702. foreach ($scenes as $scene) {
  9703. $scene_name = getProp($scene, 'scene', '');
  9704. $scene_desc = getProp($scene, 'description', '');
  9705. $pic_prompt = getProp($scene, 'pic_prompt', '');
  9706. if (!empty($scene_name)) {
  9707. $scene_line = $scene_name;
  9708. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  9709. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  9710. $scenes_list[] = $scene_line;
  9711. }
  9712. }
  9713. if (!empty($scenes_list)) {
  9714. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  9715. }
  9716. }
  9717. $props_ref = '';
  9718. if (!empty($props) && is_array($props)) {
  9719. $props_list = [];
  9720. foreach ($props as $prop) {
  9721. $prop_name = getProp($prop, 'prop', '');
  9722. $prop_desc = getProp($prop, 'description', '');
  9723. $pic_prompt = getProp($prop, 'pic_prompt', '');
  9724. if (!empty($prop_name)) {
  9725. $prop_line = $prop_name;
  9726. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  9727. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  9728. $props_list[] = $prop_line;
  9729. }
  9730. }
  9731. if (!empty($props_list)) {
  9732. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  9733. }
  9734. }
  9735. // 构建美术风格参考
  9736. $art_style_ref = '';
  9737. if (!empty($art_style)) {
  9738. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  9739. }
  9740. // 构建内容简介参考
  9741. $intro_ref = '';
  9742. if (!empty($intro)) {
  9743. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  9744. }
  9745. // 构建完整的AI提示词
  9746. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  9747. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  9748. $user_prompt .= $intro_ref;
  9749. $user_prompt .= $art_style_ref;
  9750. $user_prompt .= $reference_content;
  9751. // $user_prompt .= $roles_ref;
  9752. // $user_prompt .= $scenes_ref;
  9753. $system_prompt = "\n\n【强制要求】\n";
  9754. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  9755. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  9756. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  9757. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  9758. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  9759. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  9760. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  9761. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  9762. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  9763. ###分段剧本
  9764. 片段数量:8
  9765. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9766. ##片段1
  9767. 时长:12s
  9768. 分镜1
  9769. 出场角色:刀疤脸
  9770. 场景:边境小镇街道
  9771. 出场道具:酒杯-高脚杯
  9772. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9773. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9774. 配音台词:
  9775. 背景音效:
  9776. 分镜2
  9777. 出场角色:刀疤脸
  9778. 场景:悦来酒馆
  9779. 出场道具:酒杯-高脚杯
  9780. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9781. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9782. 配音台词:
  9783. 背景音效:
  9784. 分镜3
  9785. 出场角色:刀疤脸
  9786. 场景:悦来酒馆
  9787. 出场道具:酒杯-高脚杯
  9788. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9789. 运镜:从中景推向令牌特写。
  9790. 配音台词:
  9791. 背景音效:
  9792. 分镜4
  9793. 出场角色:刀疤脸
  9794. 场景:悦来酒馆
  9795. 出场道具:酒杯-高脚杯
  9796. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9797. 运镜:极速推向酒水溅起的瞬间。
  9798. 配音台词:
  9799. 背景音效:
  9800. 分镜5
  9801. 出场角色:刀疤脸
  9802. 场景:悦来酒馆
  9803. 出场道具:酒杯-高脚杯
  9804. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9805. 运镜:固定机位,利用倾斜构图制造压迫感。
  9806. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9807. 背景音效:";
  9808. // 获取模型配置
  9809. $model = getProp($data, 'model');
  9810. if (!$model) {
  9811. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  9812. }
  9813. // 验证模型是否在可用模型表中
  9814. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9815. $model = 'deepseek-v4-pro';
  9816. }
  9817. // 模型兼容性处理
  9818. $thinkingMode = 'disabled';
  9819. $reasoningEffort = 'high';
  9820. if ($model === 'deepseek-chat') {
  9821. $model = 'deepseek-v4-flash';
  9822. $thinkingMode = 'disabled';
  9823. } elseif ($model === 'deepseek-reasoner') {
  9824. $model = 'deepseek-v4-flash';
  9825. $thinkingMode = 'enabled';
  9826. }
  9827. // 构建消息
  9828. $messages = [
  9829. [
  9830. 'role' => 'system',
  9831. 'content' => $system_prompt
  9832. ],
  9833. [
  9834. 'role' => 'user',
  9835. 'content' => $user_prompt
  9836. ]
  9837. ];
  9838. // dd($messages);
  9839. // 构建请求参数
  9840. $post_data = [
  9841. 'model' => $model,
  9842. 'messages' => $messages,
  9843. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9844. 'frequency_penalty' => 0,
  9845. 'presence_penalty' => 0,
  9846. 'response_format' => ['type' => 'text'],
  9847. 'thinking' => ['type' => $thinkingMode],
  9848. 'stream' => false // 非流式输出
  9849. ];
  9850. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9851. // 调用AI生成新的分段剧本
  9852. try {
  9853. $fullContent = '';
  9854. $usage = [];
  9855. // 根据模型类型选择调用方法
  9856. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9857. // DeepSeek 官方模型使用 DeepSeek API
  9858. $chatResult = $this->chatOnly($post_data);
  9859. } else if (in_array($model, $this->gpt_text_models)) {
  9860. // GPT 模型使用 TokenRouter API
  9861. $chatResult = $this->gpt54ChatOnly($post_data);
  9862. } else {
  9863. // 其他模型使用火山引擎API
  9864. $chatResult = $this->volcEngineChatCompletion($post_data);
  9865. }
  9866. if (is_array($chatResult)) {
  9867. $fullContent = $chatResult['fullContent'] ?? '';
  9868. $usage = $chatResult['usage'] ?? [];
  9869. }
  9870. $generated_content = $fullContent;
  9871. if (empty($generated_content)) {
  9872. Utils::throwError('20003:AI生成内容为空,请重试');
  9873. }
  9874. // 解析生成的内容 - 按片段分割
  9875. $parsed_segments = [];
  9876. // 先在开头添加换行符,确保第1片段也能被正确分割
  9877. $normalizedText = "\n" . $generated_content;
  9878. $parts = preg_split('/\n\s*##/', $normalizedText);
  9879. foreach ($parts as $part) {
  9880. $part = trim($part);
  9881. if (empty($part)) continue;
  9882. // 匹配"片段X"格式
  9883. if (!preg_match('/^片段\d+/', $part)) {
  9884. continue;
  9885. }
  9886. // 分离标题和内容
  9887. $lines = explode("\n", $part, 2);
  9888. $actTitle = trim($lines[0]);
  9889. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  9890. // 解析标题,提取序号
  9891. $actNumber = 0;
  9892. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  9893. $actNumber = intval($segmentTitleMatch[1]);
  9894. } else {
  9895. $actNumber = count($parsed_segments) + 1;
  9896. }
  9897. // 提取时长(仅保留数字)
  9898. $actDuration = 0;
  9899. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  9900. $actDurationStr = trim($actDurationMatch[1]);
  9901. // 提取数字部分(支持整数和小数)
  9902. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  9903. $actDuration = (float)$numMatch[1];
  9904. }
  9905. }
  9906. // 清理act_content:去除时长、旁白音色等非分镜内容行
  9907. // 只保留分镜内容,并确保分镜标记使用【】格式
  9908. $cleaned_content = '';
  9909. $content_lines = explode("\n", $actContent);
  9910. $is_capturing = false; // 标记是否开始捕获分镜内容
  9911. $count = 0;
  9912. foreach ($content_lines as $line) {
  9913. $trimmed_line = trim($line);
  9914. // 跳过时长和旁白音色行
  9915. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  9916. continue;
  9917. }
  9918. // 检测是否是分镜开始
  9919. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  9920. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  9921. $count++;
  9922. $is_capturing = true;
  9923. // 如果没有【】,则添加
  9924. if (!preg_match('/^【/u', $trimmed_line)) {
  9925. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  9926. }
  9927. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  9928. }
  9929. // 如果已经开始捕获,则添加该行
  9930. if ($is_capturing && !empty($trimmed_line)) {
  9931. $cleaned_content .= $trimmed_line."\n";
  9932. }
  9933. }
  9934. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  9935. $parsed_segments[] = [
  9936. 'act_number' => $actNumber,
  9937. 'act_title' => $actTitle,
  9938. 'act_duration' => $actDuration,
  9939. 'act_content' => $cleaned_content,
  9940. ];
  9941. }
  9942. if (empty($parsed_segments)) {
  9943. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  9944. }
  9945. // 收集所有资产名称(角色、场景、道具)
  9946. $product_names = [];
  9947. // 收集角色名称
  9948. if (!empty($roles) && is_array($roles)) {
  9949. foreach ($roles as $role) {
  9950. $role_name = getProp($role, 'role', '');
  9951. if (!empty($role_name)) {
  9952. $product_names[] = $role_name;
  9953. }
  9954. }
  9955. }
  9956. // 收集场景名称
  9957. if (!empty($scenes) && is_array($scenes)) {
  9958. foreach ($scenes as $scene) {
  9959. $scene_name = getProp($scene, 'scene', '');
  9960. if (!empty($scene_name)) {
  9961. $product_names[] = $scene_name;
  9962. }
  9963. }
  9964. }
  9965. // 收集道具名称
  9966. if (!empty($props) && is_array($props)) {
  9967. foreach ($props as $prop) {
  9968. $prop_name = getProp($prop, 'prop', '');
  9969. if (!empty($prop_name)) {
  9970. $product_names[] = $prop_name;
  9971. }
  9972. }
  9973. }
  9974. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  9975. $product_names = array_unique($product_names);
  9976. usort($product_names, function($a, $b) {
  9977. return mb_strlen($b) - mb_strlen($a);
  9978. });
  9979. // 处理每个片段的 act_show_content
  9980. foreach ($parsed_segments as &$segment) {
  9981. $act_content = getProp($segment, 'act_content', '');
  9982. if (empty($act_content)) {
  9983. $segment['act_show_content'] = '';
  9984. continue;
  9985. }
  9986. $processed_content = $act_content;
  9987. // 统一替换所有资产名称为 {资产名} 格式
  9988. // 使用占位符避免嵌套替换问题
  9989. $placeholder_map = [];
  9990. $placeholder_index = 0;
  9991. foreach ($product_names as $product_name) {
  9992. // 转义特殊字符
  9993. $escaped_product = preg_quote($product_name, '/');
  9994. // 检查是否匹配且未被 {} 包裹
  9995. $processed_content = preg_replace_callback(
  9996. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  9997. function($matches) use (&$placeholder_map, &$placeholder_index) {
  9998. // 使用唯一占位符
  9999. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  10000. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  10001. $placeholder_index++;
  10002. return $placeholder;
  10003. },
  10004. $processed_content
  10005. );
  10006. }
  10007. // 将所有占位符替换回实际内容
  10008. foreach ($placeholder_map as $placeholder => $replacement) {
  10009. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  10010. }
  10011. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  10012. $shot_counter = 0;
  10013. $processed_content = preg_replace_callback(
  10014. '/【(?:镜头|分镜)(\d+)】/u',
  10015. function($matches) use (&$shot_counter) {
  10016. $shot_counter++;
  10017. return '【镜头' . $shot_counter . '】';
  10018. },
  10019. $processed_content
  10020. );
  10021. $segment['act_show_content'] = $processed_content;
  10022. }
  10023. unset($segment); // 解除引用
  10024. // 保存到数据库
  10025. $now = date('Y-m-d H:i:s');
  10026. $saved_acts = []; // 用于记录保存后的片段信息
  10027. if ($act_id > 0) {
  10028. // 单个片段模式:更新单条记录
  10029. if (count($parsed_segments) > 0) {
  10030. $new_segment = $parsed_segments[0];
  10031. $update_data = [
  10032. 'act_content' => getProp($new_segment, 'act_content', ''),
  10033. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  10034. 'act_title' => getProp($new_segment, 'act_title', ''),
  10035. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  10036. 'updated_at' => $now,
  10037. ];
  10038. DB::table('mp_episode_segments')
  10039. ->where('id', $act_id)
  10040. ->update($update_data);
  10041. // 获取更新后的记录
  10042. $updated_act = DB::table('mp_episode_segments')
  10043. ->where('id', $act_id)
  10044. ->first();
  10045. if ($updated_act) {
  10046. $saved_acts[] = [
  10047. 'act_id' => $updated_act->id,
  10048. 'act_number' => $updated_act->act_number,
  10049. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  10050. 'act_content' => $updated_act->act_content,
  10051. 'act_show_content' => $updated_act->act_show_content,
  10052. 'video_url' => $updated_act->video_url ?? '',
  10053. 'video_duration' => $updated_act->video_duration ?? 0,
  10054. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  10055. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  10056. ];
  10057. }
  10058. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  10059. }
  10060. } else {
  10061. // 整个剧集模式:删除原有记录并批量保存新记录
  10062. DB::beginTransaction();
  10063. try {
  10064. // 删除原有的所有片段记录
  10065. DB::table('mp_episode_segments')
  10066. ->where('episode_id', $target_episode_id)
  10067. ->delete();
  10068. // 批量插入新的片段记录
  10069. $segments_to_insert = [];
  10070. foreach ($parsed_segments as $index => $segment) {
  10071. $act_number = $index + 1;
  10072. $segments_to_insert[] = [
  10073. 'anime_id' => $target_anime_id,
  10074. 'episode_id' => $target_episode_id,
  10075. 'episode_number' => $target_episode_number,
  10076. 'act_number' => $act_number,
  10077. 'act_title' => getProp($segment, 'act_title', ''),
  10078. 'act_duration' => getProp($segment, 'act_duration', 0),
  10079. 'act_content' => getProp($segment, 'act_content', ''),
  10080. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  10081. 'created_at' => $now,
  10082. 'updated_at' => $now,
  10083. ];
  10084. }
  10085. if (!empty($segments_to_insert)) {
  10086. DB::table('mp_episode_segments')->insert($segments_to_insert);
  10087. }
  10088. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  10089. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  10090. 'anime_id' => $target_anime_id,
  10091. 'episode_id' => $target_episode_id,
  10092. ]);
  10093. DB::commit();
  10094. // 查询保存后的所有片段记录
  10095. $saved_segments = DB::table('mp_episode_segments')
  10096. ->where('episode_id', $target_episode_id)
  10097. ->orderBy('act_number')
  10098. ->get();
  10099. foreach ($saved_segments as $saved_segment) {
  10100. $saved_acts[] = [
  10101. 'act_id' => $saved_segment->id,
  10102. 'act_number' => $saved_segment->act_number,
  10103. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  10104. 'act_content' => $saved_segment->act_content,
  10105. 'act_show_content' => $saved_segment->act_show_content,
  10106. 'video_url' => $saved_segment->video_url ?? '',
  10107. 'video_duration' => $saved_segment->video_duration ?? 0,
  10108. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  10109. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  10110. ];
  10111. }
  10112. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  10113. 'episode_id' => $target_episode_id,
  10114. 'segments_count' => count($segments_to_insert)
  10115. ]);
  10116. } catch (\Exception $e) {
  10117. DB::rollBack();
  10118. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  10119. Utils::throwError('20003:保存失败,请重试');
  10120. }
  10121. }
  10122. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  10123. return [
  10124. 'anime_id' => $target_anime_id,
  10125. 'episode_id' => $target_episode_id,
  10126. 'title' => getProp($episode, 'title', ''),
  10127. 'episode_number' => $target_episode_number,
  10128. 'is_generated' => getProp($episode, 'is_generated', 0),
  10129. 'acts' => $saved_acts,
  10130. ];
  10131. } catch (\Exception $e) {
  10132. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  10133. throw $e;
  10134. }
  10135. }
  10136. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  10137. {
  10138. $episode_arr = [
  10139. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  10140. 'intro' => getProp($script_arr, 'intro'),
  10141. 'art_style' => getProp($script_arr, 'art_style'),
  10142. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  10143. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  10144. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  10145. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  10146. ];
  10147. if (empty($episode_arr['acts'])) {
  10148. $fallback_episode_arr = handleEpisodeContent($fullContent);
  10149. if (!empty($fallback_episode_arr['acts'])) {
  10150. $episode_arr = array_merge($fallback_episode_arr, [
  10151. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  10152. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  10153. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  10154. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  10155. ]);
  10156. }
  10157. }
  10158. // if (!getProp($episode_arr, 'episode_title')) {
  10159. // $episode_title = '';
  10160. // $episodes = getProp($script_arr, 'episodes', []);
  10161. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  10162. // $episode_title = '第1集:' . $episodes[0]['title'];
  10163. // }
  10164. // if (!$episode_title) {
  10165. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  10166. // }
  10167. // $episode_arr['episode_title'] = $episode_title;
  10168. // }
  10169. return $episode_arr;
  10170. }
  10171. private function saveEpisodeVersionData(
  10172. int $anime_id,
  10173. int $episode_number,
  10174. array $episode_arr,
  10175. array $existing_roles,
  10176. array $existing_scenes,
  10177. array $existing_props,
  10178. $current_episode,
  10179. $base_episode,
  10180. bool $is_regenerate_version,
  10181. string $content,
  10182. string $now,
  10183. array $ref_products = []
  10184. ): array {
  10185. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  10186. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  10187. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  10188. // 过滤掉关键字段为空的条目
  10189. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  10190. return !empty($item['role'] ?? null);
  10191. }));
  10192. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  10193. return !empty($item['scene'] ?? null);
  10194. }));
  10195. $merged_props = array_values(array_filter($generated_props, function ($item) {
  10196. return !empty($item['prop'] ?? null);
  10197. }));
  10198. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  10199. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  10200. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  10201. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10202. $ace_mode = getProp($anime, 'ace_mode');
  10203. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  10204. $global_roles = json_decode(getProp($anime, 'roles'), true);
  10205. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  10206. $global_roles = is_array($global_roles) ? $global_roles : [];
  10207. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  10208. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  10209. $art_style_type = getProp($anime, 'art_style_type');
  10210. // 检查并创建 roles 的图片生成任务
  10211. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  10212. // 检查并创建 scenes 的图片生成任务
  10213. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  10214. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  10215. if ($arr && is_array($arr)) {
  10216. $merged_roles = $arr['roles'];
  10217. $merged_scenes = $arr['scenes'];
  10218. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  10219. }
  10220. // 确保数据是数组类型
  10221. if (!is_array($merged_roles)) {
  10222. dLog('deepseek')->error('merged_roles不是数组类型', [
  10223. 'type' => gettype($merged_roles),
  10224. 'value' => $merged_roles
  10225. ]);
  10226. $merged_roles = [];
  10227. }
  10228. if (!is_array($merged_scenes)) {
  10229. dLog('deepseek')->error('merged_scenes不是数组类型', [
  10230. 'type' => gettype($merged_scenes),
  10231. 'value' => $merged_scenes
  10232. ]);
  10233. $merged_scenes = [];
  10234. }
  10235. if (!is_array($merged_props)) {
  10236. dLog('deepseek')->error('merged_props不是数组类型', [
  10237. 'type' => gettype($merged_props),
  10238. 'value' => $merged_props
  10239. ]);
  10240. $merged_props = [];
  10241. }
  10242. // 同步新出现的主体和场景到全局
  10243. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  10244. $role_arr = [];
  10245. foreach ($merged_roles as $item) {
  10246. $role_arr[$item['role']] = $item;
  10247. }
  10248. $version_count = DB::table('mp_anime_episodes')
  10249. ->where('anime_id', $anime_id)
  10250. ->where('episode_number', $episode_number)
  10251. ->count('id');
  10252. $episode = [
  10253. 'anime_id' => $anime_id,
  10254. 'episode_number' => $episode_number,
  10255. 'title' => getProp($episode_arr, 'episode_title'),
  10256. 'content' => $content,
  10257. 'intro' => getProp($episode_arr, 'intro'),
  10258. 'art_style' => getProp($episode_arr, 'art_style'),
  10259. 'roles' => json_encode($merged_roles, 256),
  10260. 'scenes' => json_encode($merged_scenes, 256),
  10261. 'props' => json_encode($merged_props, 256),
  10262. 'generate_status' => '待执行',
  10263. 'generate_at' => $now,
  10264. 'is_default' => 1,
  10265. 'updated_at' => $now,
  10266. ];
  10267. $del_flag = false;
  10268. if ($is_regenerate_version) {
  10269. DB::table('mp_anime_episodes')
  10270. ->where('anime_id', $anime_id)
  10271. ->where('episode_number', $episode_number)
  10272. ->update(['is_default' => 0, 'updated_at' => $now]);
  10273. $episode['sequence'] = $version_count + 1;
  10274. $episode['created_at'] = $now;
  10275. $episode['cpid'] = Site::getCpid();
  10276. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  10277. if (!$episode_id) {
  10278. Utils::throwError('20003:创建剧集版本失败');
  10279. }
  10280. } else {
  10281. $target_episode = $current_episode ?: $base_episode;
  10282. if ($target_episode) {
  10283. $episode_id = getProp($target_episode, 'id');
  10284. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  10285. DB::table('mp_anime_episodes')
  10286. ->where('anime_id', $anime_id)
  10287. ->where('episode_number', $episode_number)
  10288. ->where('id', '<>', $episode_id)
  10289. ->update(['is_default' => 0, 'updated_at' => $now]);
  10290. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  10291. if ($boolen === false) {
  10292. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10293. Utils::throwError('20003:分集内容保存失败');
  10294. }
  10295. $del_flag = true;
  10296. } else {
  10297. DB::table('mp_anime_episodes')
  10298. ->where('anime_id', $anime_id)
  10299. ->where('episode_number', $episode_number)
  10300. ->update(['is_default' => 0, 'updated_at' => $now]);
  10301. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  10302. $episode['created_at'] = $now;
  10303. $episode['cpid'] = Site::getCpid();
  10304. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  10305. if (!$episode_id) {
  10306. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  10307. Utils::throwError('20003:分集内容保存失败');
  10308. }
  10309. }
  10310. }
  10311. $segments = [];
  10312. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  10313. // 如果是第2集及以后,获取上一集的主体音色数据
  10314. $previous_roles_voice = [];
  10315. if ($episode_number >= 2) {
  10316. $previous_episode = DB::table('mp_anime_episodes')
  10317. ->where('anime_id', $anime_id)
  10318. ->where('episode_number', $episode_number - 1)
  10319. ->where('is_default', 1)
  10320. ->first();
  10321. if ($previous_episode) {
  10322. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  10323. if (is_array($previous_roles)) {
  10324. foreach ($previous_roles as $prev_role) {
  10325. $role_name = getProp($prev_role, 'role');
  10326. if ($role_name) {
  10327. $previous_roles_voice[$role_name] = [
  10328. 'voice_name' => getProp($prev_role, 'voice_name'),
  10329. 'voice_type' => getProp($prev_role, 'voice_type'),
  10330. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  10331. ];
  10332. $voice_prompt = getProp($prev_role, 'voice_prompt');
  10333. if ($voice_prompt) {
  10334. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  10335. }
  10336. }
  10337. }
  10338. }
  10339. }
  10340. }
  10341. // 将继承的音色数据同步到当前集的主体列表
  10342. if (!empty($previous_roles_voice)) {
  10343. foreach ($merged_roles as &$role) {
  10344. $role_name = getProp($role, 'role');
  10345. if ($role_name && isset($previous_roles_voice[$role_name])) {
  10346. // 强制继承上一集的音色数据
  10347. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  10348. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  10349. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  10350. // 如果上一集有 voice_prompt 则继承,否则跳过
  10351. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  10352. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  10353. }
  10354. }
  10355. }
  10356. unset($role); // 解除引用
  10357. // 更新 role_arr 以便后续使用
  10358. $role_arr = [];
  10359. foreach ($merged_roles as $item) {
  10360. $role_arr[$item['role']] = $item;
  10361. }
  10362. }
  10363. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  10364. $emotion_list = array_flip($emotion_list);
  10365. foreach ($acts as $act) {
  10366. $act_segments = getProp($act, 'segments', []);
  10367. if (!is_array($act_segments)) {
  10368. continue;
  10369. }
  10370. if ((int)$ace_mode === 1) {
  10371. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  10372. $merged_parts = [];
  10373. foreach ($act_segments as $seg) {
  10374. $seg_num = getProp($seg, 'segment_number');
  10375. $seg_content = getProp($seg, 'segment_content');
  10376. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  10377. }
  10378. $act_content = implode("\n", $merged_parts);
  10379. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  10380. $segments[] = [
  10381. 'anime_id' => $anime_id,
  10382. 'episode_id' => $episode_id,
  10383. 'episode_number' => $episode_number,
  10384. 'act_number' => getProp($act, 'act_number'),
  10385. 'act_title' => getProp($act, 'act_title'),
  10386. 'act_duration' => getProp($act, 'act_duration'),
  10387. 'act_content' => $act_content,
  10388. 'created_at' => $now,
  10389. 'updated_at' => $now
  10390. ];
  10391. } else {
  10392. foreach ($act_segments as $segment) {
  10393. $voice_actor = getProp($segment, 'voice_actor');
  10394. // 优先从上一集继承音色数据
  10395. $timbre_info = [];
  10396. if (isset($previous_roles_voice[$voice_actor])) {
  10397. // 从上一集继承音色数据
  10398. $timbre_info = $previous_roles_voice[$voice_actor];
  10399. } elseif (isset($role_arr[$voice_actor])) {
  10400. // 使用当前集的主体音色数据
  10401. $timbre_info = $role_arr[$voice_actor];
  10402. }
  10403. $voice_type = getProp($timbre_info, 'voice_type');
  10404. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  10405. if ($timbre_emotion) {
  10406. $timbre_emotion = explode(',', $timbre_emotion);
  10407. } else {
  10408. $timbre_emotion = [];
  10409. }
  10410. $emotion = getProp($segment, 'emotion', '中性');
  10411. if (!in_array($emotion, $timbre_emotion)) {
  10412. $emotion = '中性';
  10413. }
  10414. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  10415. $segments[] = [
  10416. 'anime_id' => $anime_id,
  10417. 'episode_id' => $episode_id,
  10418. 'episode_number' => $episode_number,
  10419. 'act_number' => getProp($act, 'act_number'),
  10420. 'act_title' => getProp($act, 'act_title'),
  10421. 'act_duration' => getProp($act, 'act_duration'),
  10422. 'segment_id' => getProp($segment, 'segment_id'),
  10423. 'segment_number' => getProp($segment, 'segment_number'),
  10424. 'segment_content' => getProp($segment, 'segment_content'),
  10425. 'description' => getProp($segment, 'description'),
  10426. 'composition' => getProp($segment, 'composition'),
  10427. 'camera_movement' => getProp($segment, 'camera_movement'),
  10428. 'voice_actor' => $voice_actor,
  10429. 'dialogue' => getProp($segment, 'dialogue'),
  10430. 'frame_type' => getProp($segment, 'frame_type'),
  10431. 'scene' => getProp($segment, 'scene'),
  10432. 'characters' => getProp($segment, 'characters'),
  10433. 'tail_frame' => getProp($segment, 'tail_frame'),
  10434. 'voice_name' => getProp($timbre_info, 'voice_name'),
  10435. 'voice_type' => $voice_type,
  10436. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  10437. 'emotion' => $emotion,
  10438. 'emotion_type' => $emotion_type,
  10439. 'gender' => getProp($segment, 'gender', '0'),
  10440. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  10441. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  10442. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  10443. 'pitch' => getProp($segment, 'pitch', 0),
  10444. 'created_at' => $now,
  10445. 'updated_at' => $now
  10446. ];
  10447. }
  10448. }
  10449. }
  10450. if ($segments) {
  10451. if ($del_flag) {
  10452. DB::table('mp_episode_segments')
  10453. ->where('anime_id', $anime_id)
  10454. ->where('episode_id', $episode_id)
  10455. ->delete();
  10456. }
  10457. $boolen = DB::table('mp_episode_segments')->insert($segments);
  10458. if (!$boolen) {
  10459. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  10460. Utils::throwError('20003:分镜内容保存失败');
  10461. }
  10462. }
  10463. dLog('deepseek')->info('segments', $segments);
  10464. // ace_mode=1: acts 返回值按合并格式调整
  10465. if ((int)$ace_mode === 1) {
  10466. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  10467. $act_map = [];
  10468. foreach ($table_act_data as $item) {
  10469. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  10470. }
  10471. $restructured_acts = [];
  10472. foreach ($acts as $act) {
  10473. $act_segments = getProp($act, 'segments', []);
  10474. if (!is_array($act_segments)) {
  10475. continue;
  10476. }
  10477. $merged_parts = [];
  10478. foreach ($act_segments as $seg) {
  10479. $seg_num = getProp($seg, 'segment_number');
  10480. $seg_content = getProp($seg, 'segment_content');
  10481. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  10482. }
  10483. $act_content = implode("\n", $merged_parts);
  10484. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  10485. $restructured_acts[] = [
  10486. 'anime_id' => $anime_id,
  10487. 'episode_id' => $episode_id,
  10488. 'episode_number' => $episode_number,
  10489. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  10490. 'act_number' => getProp($act, 'act_number'),
  10491. 'act_title' => getProp($act, 'act_title'),
  10492. 'act_duration' => getProp($act, 'act_duration'),
  10493. 'act_content' => $act_content,
  10494. 'created_at' => $now,
  10495. 'updated_at' => $now,
  10496. ];
  10497. }
  10498. $acts = $restructured_acts;
  10499. }
  10500. $episode['episode_id'] = $episode_id;
  10501. $episode['roles'] = $merged_roles;
  10502. $episode['scenes'] = $merged_scenes;
  10503. $episode['props'] = $merged_props;
  10504. $episode['acts'] = $acts;
  10505. return [
  10506. 'episode' => $episode,
  10507. 'episode_id' => $episode_id,
  10508. 'merged_roles' => $merged_roles,
  10509. 'merged_scenes' => $merged_scenes,
  10510. 'merged_props' => $merged_props,
  10511. ];
  10512. }
  10513. private function buildEpisodeItemContent(array $items, string $nameKey): string
  10514. {
  10515. $content = '';
  10516. foreach ($items as $item) {
  10517. $name = trim((string)getProp($item, $nameKey));
  10518. if ($name === '' || $name === '旁白') {
  10519. continue;
  10520. }
  10521. $description = trim((string)getProp($item, 'description'));
  10522. $content .= $name . ': ' . $description;
  10523. if ($nameKey == 'role') {
  10524. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  10525. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10526. $voice_name = trim(getProp($item, 'voice_name'));
  10527. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  10528. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  10529. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  10530. }else {
  10531. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  10532. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10533. }
  10534. $content .= "\n";
  10535. }
  10536. return trim($content);
  10537. }
  10538. private function getEpisodeChatContent($animeId, $sequence, $content) {
  10539. if ((int)$sequence <= 0) {
  10540. return [];
  10541. }
  10542. $origin_content = '';
  10543. if ($content) {
  10544. $origin_content = '本集剧情内容:'.$content;
  10545. }else {
  10546. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  10547. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  10548. }
  10549. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  10550. // 获取分集信息
  10551. $episode = DB::table('mp_anime_episodes')
  10552. ->where('anime_id', $animeId)
  10553. ->where('episode_number', $sequence)
  10554. ->where('is_default', 1)
  10555. ->first();
  10556. if (!$episode) {
  10557. return [];
  10558. }
  10559. $episode_id = getProp($episode, 'id');
  10560. $episode_number = getProp($episode, 'episode_number');
  10561. $title = getProp($episode, 'title');
  10562. $intro = getProp($episode, 'intro');
  10563. $art_style = getProp($episode, 'art_style');
  10564. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10565. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10566. // 组装纯文本内容
  10567. $content = '';
  10568. // 添加分集标题和梗概
  10569. $content .= "###第{$episode_number}集:{$title}\n\n";
  10570. $content .= "###故事梗概\n";
  10571. $content .= trim($intro) . "\n\n";
  10572. // 添加美术风格
  10573. $content .= "###美术风格\n";
  10574. $content .= trim($art_style) . "\n\n";
  10575. // 添加主体列表
  10576. $content .= "###主体列表\n";
  10577. $pangbai_voice_prompt = "";
  10578. foreach ($roles as $role) {
  10579. $name = getProp($role, 'role');
  10580. $description = getProp($role, 'description');
  10581. $pic_prompt = getProp($role, 'pic_prompt');
  10582. $voice_prompt = getProp($role, 'voice_prompt');
  10583. $voice_name = getProp($role, 'voice_name');
  10584. $content .= "{$name}: {$description}";
  10585. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10586. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  10587. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  10588. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  10589. $content .= "\n";
  10590. }
  10591. $content .= "\n";
  10592. // 添加场景列表
  10593. $content .= "###场景列表\n";
  10594. foreach ($scenes as $scene) {
  10595. $name = getProp($scene, 'scene');
  10596. $description = getProp($scene, 'description');
  10597. $pic_prompt = getProp($scene, 'pic_prompt');
  10598. $content .= "{$name}: {$description}";
  10599. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10600. $content .= "\n";
  10601. }
  10602. $content .= "\n";
  10603. // 获取分镜信息
  10604. $segments = DB::table('mp_episode_segments')
  10605. ->where('anime_id', $animeId)
  10606. ->where('episode_id', $episode_id)
  10607. ->orderBy('segment_number')
  10608. ->get();
  10609. if ($segments && count($segments) > 0) {
  10610. if ((int)$ace_mode === 1) {
  10611. $content .= "###分段剧本\n";
  10612. // 获取片段数量
  10613. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  10614. $content .= "片段数量:{$act_count}\n";
  10615. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  10616. $content .= "\n";
  10617. }else {
  10618. $content .= "###分镜剧本\n";
  10619. }
  10620. // 按幕分组
  10621. $currentAct = null;
  10622. foreach ($segments as $segment) {
  10623. $act_number = getProp($segment, 'act_number');
  10624. $act_title = getProp($segment, 'act_title');
  10625. $act_duration = getProp($segment, 'act_duration');
  10626. $segment_number = getProp($segment, 'segment_number');
  10627. $segment_content = getProp($segment, 'segment_content');
  10628. $scene_description = getProp($segment, 'scene_description');
  10629. $scene_name = getProp($segment, 'scene_name');
  10630. $composition = getProp($segment, 'composition');
  10631. $camera_movement = getProp($segment, 'camera_movement');
  10632. $voice_type = getProp($segment, 'voice_type');
  10633. $characters = getProp($segment, 'characters');
  10634. $dialogue = getProp($segment, 'dialogue');
  10635. $frame_type = getProp($segment, 'frame_type');
  10636. $tail_frame_description = getProp($segment, 'tail_frame_description');
  10637. // 判断是否是全能模式
  10638. if ((int)$ace_mode === 1) { // 全能模式
  10639. // 如果是新的分段,添加分段标题
  10640. if ($act_number !== $currentAct) {
  10641. $currentAct = $act_number;
  10642. $content .= "##{$act_title}\n";
  10643. $content .= "时长:{$act_duration}s\n";
  10644. }
  10645. }else {
  10646. // 如果是新的幕,添加幕标题
  10647. if ($act_number !== $currentAct) {
  10648. $currentAct = $act_number;
  10649. $content .= "##第{$act_number}幕:{$scene_name}\n";
  10650. }
  10651. }
  10652. // 添加分镜信息
  10653. $content .= "分镜{$segment_number}\n";
  10654. $content .= "分镜内容:\n{$segment_content}\n";
  10655. // $content .= "画面描述:{$scene_description}\n";
  10656. // $content .= "场景:{$scene_name}\n";
  10657. // $content .= "构图设计:{$composition}\n";
  10658. // $content .= "运镜调度:{$camera_movement}\n";
  10659. // if (!empty($voice_type)) {
  10660. // $content .= "配音角色:{$voice_type}\n";
  10661. // }
  10662. // if (!empty($characters)) {
  10663. // $content .= "出镜角色:{$characters}\n";
  10664. // }
  10665. // if (!empty($dialogue)) {
  10666. // $content .= "台词内容:\"{$dialogue}\"\n";
  10667. // }
  10668. // $content .= "画面类型:{$frame_type}\n";
  10669. // $content .= "尾帧描述:{$tail_frame_description}\n";
  10670. $content .= "\n";
  10671. }
  10672. }
  10673. $content = trim($content);
  10674. if($content) $content = "上集剧本内容:\n{$content}";
  10675. return [
  10676. [
  10677. 'role' => 'user',
  10678. 'content' => $origin_content
  10679. ],
  10680. [
  10681. 'role' => 'assistant',
  10682. 'content' => $content
  10683. ]
  10684. ];
  10685. }
  10686. private function getEpisodeChatMessages($animeId, $sequence): array
  10687. {
  10688. if ((int)$sequence <= 0) {
  10689. return [];
  10690. }
  10691. return DB::table('mp_anime_records')
  10692. ->where('anime_id', $animeId)
  10693. ->where('sequence', $sequence)
  10694. ->where('episode_id', '>', 0)
  10695. ->select('role', 'content')
  10696. ->orderBy('created_at')
  10697. ->orderBy('id')
  10698. ->get()
  10699. ->map(function ($value) {
  10700. return (array)$value;
  10701. })
  10702. ->toArray();
  10703. }
  10704. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  10705. {
  10706. $existingMap = [];
  10707. foreach ($existingItems as $item) {
  10708. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10709. if ($itemKey === '') {
  10710. continue;
  10711. }
  10712. $existingMap[$itemKey] = $item;
  10713. }
  10714. if (!$generatedItems) {
  10715. return array_values($existingItems);
  10716. }
  10717. $merged = [];
  10718. foreach ($generatedItems as $item) {
  10719. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10720. if ($itemKey === '') {
  10721. continue;
  10722. }
  10723. if (isset($existingMap[$itemKey])) {
  10724. if (trim((string)getProp($item, 'description')) === '') {
  10725. $merged[] = $existingMap[$itemKey];
  10726. continue;
  10727. }
  10728. // 检查内容是否发生变化
  10729. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  10730. if (!$isChanged) {
  10731. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  10732. $mergedItem = [
  10733. $nameKey => trim((string)getProp($item, $nameKey)),
  10734. 'description' => trim((string)getProp($item, 'description')),
  10735. ];
  10736. // 如果有 pic_prompt,添加到合并项中
  10737. $picPrompt = getProp($item, 'pic_prompt');
  10738. if (!empty($picPrompt)) {
  10739. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  10740. }
  10741. // 继承现有项的 URL
  10742. $existingUrl = getProp($existingMap[$itemKey], 'url');
  10743. if (!empty($existingUrl)) {
  10744. $mergedItem['url'] = $existingUrl;
  10745. }
  10746. // 继承现有项的 task_id
  10747. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  10748. if (!empty($existingTaskId)) {
  10749. $mergedItem['task_id'] = $existingTaskId;
  10750. }
  10751. // 继承现有项的 task_status
  10752. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  10753. if (!empty($existingTaskStatus)) {
  10754. $mergedItem['task_status'] = $existingTaskStatus;
  10755. }
  10756. // 保留生成项的音色字段
  10757. $voiceName = getProp($item, 'voice_name');
  10758. if (!empty($voiceName)) {
  10759. $mergedItem['voice_name'] = $voiceName;
  10760. }
  10761. $voiceType = getProp($item, 'voice_type');
  10762. if (!empty($voiceType)) {
  10763. $mergedItem['voice_type'] = $voiceType;
  10764. }
  10765. $audioUrl = getProp($item, 'voice_audio_url');
  10766. if (!empty($audioUrl)) {
  10767. $mergedItem['voice_audio_url'] = $audioUrl;
  10768. }
  10769. $merged[] = $mergedItem;
  10770. } else {
  10771. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  10772. $mergedItem = [
  10773. $nameKey => trim((string)getProp($item, $nameKey)),
  10774. 'description' => trim((string)getProp($item, 'description')),
  10775. ];
  10776. // 如果有 pic_prompt,添加到合并项中
  10777. $picPrompt = getProp($item, 'pic_prompt');
  10778. if (!empty($picPrompt)) {
  10779. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  10780. }
  10781. // 保留生成项的音色字段
  10782. $voiceName = getProp($item, 'voice_name');
  10783. if (!empty($voiceName)) {
  10784. $mergedItem['voice_name'] = $voiceName;
  10785. }
  10786. $voiceType = getProp($item, 'voice_type');
  10787. if (!empty($voiceType)) {
  10788. $mergedItem['voice_type'] = $voiceType;
  10789. }
  10790. $audioUrl = getProp($item, 'voice_audio_url');
  10791. if (!empty($audioUrl)) {
  10792. $mergedItem['voice_audio_url'] = $audioUrl;
  10793. }
  10794. // 不继承 URL、task_id 和 task_status(重置状态)
  10795. $merged[] = $mergedItem;
  10796. }
  10797. } else {
  10798. // 新增项,保留生成项的所有字段
  10799. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  10800. }
  10801. }
  10802. return $merged ?: array_values($existingItems);
  10803. }
  10804. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  10805. {
  10806. $resetItem = [
  10807. $nameKey => trim((string)getProp($item, $nameKey)),
  10808. 'description' => trim((string)getProp($item, 'description')),
  10809. ];
  10810. // 保留指定的字段
  10811. foreach ($preserveFields as $field) {
  10812. $value = getProp($item, $field);
  10813. if (!empty($value)) {
  10814. $resetItem[$field] = $value;
  10815. }
  10816. }
  10817. return $resetItem;
  10818. }
  10819. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  10820. {
  10821. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  10822. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  10823. if ($existingKey !== $generatedKey) {
  10824. return true;
  10825. }
  10826. // 比较 description 是否变化
  10827. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  10828. return true;
  10829. }
  10830. // 比较 pic_prompt 是否变化
  10831. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  10832. }
  10833. private function normalizeEpisodeResourceKey($value): string
  10834. {
  10835. $value = trim((string)$value);
  10836. if ($value === '') {
  10837. return '';
  10838. }
  10839. return strtolower((string)preg_replace('/\s+/u', '', $value));
  10840. }
  10841. // 生成全局角色图片
  10842. private function batchSetGlobalRoleImg($data, $is_force=false) {
  10843. $anime_id = getProp($data, 'anime_id');
  10844. if (!$anime_id) Utils::throwError('1002:请选择对话');
  10845. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10846. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10847. $art_style = getProp($anime, 'art_style');
  10848. $update_flag = false;
  10849. foreach ($roles as &$role) {
  10850. $role_name = getProp($role, 'role');
  10851. if ($role_name == '旁白') continue;
  10852. // 优先使用 pic_prompt,如果没有则使用 description
  10853. $pic_prompt = getProp($role, 'pic_prompt');
  10854. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  10855. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  10856. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  10857. // 参考图地址
  10858. $ref_img_url = getProp($role, 'url');
  10859. if (!$is_force && $ref_img_url) continue;
  10860. $update_flag = true;
  10861. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  10862. try {
  10863. $params = [
  10864. 'prompt' => $description,
  10865. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  10866. 'ref_img_urls' => []
  10867. ];
  10868. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10869. $task_id = $task->id;
  10870. if (!$task_id) {
  10871. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  10872. }
  10873. $role['task_id'] = $task_id;
  10874. $role['task_status'] = 'processing';
  10875. } catch (\Exception $e) {
  10876. Utils::throwError("20003:" . $e->getMessage());
  10877. }
  10878. }
  10879. if (!$update_flag) return true;
  10880. // 保存角色信息
  10881. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  10882. 'roles' => json_encode($roles, 256),
  10883. 'generate_status' => '执行中',
  10884. 'generate_at' => date('Y-m-d H:i:s'),
  10885. 'updated_at' => date('Y-m-d H:i:s')
  10886. ]);
  10887. if (!$boolen) {
  10888. Utils::throwError('20003:保存角色信息失败');
  10889. }
  10890. return $boolen;
  10891. }
  10892. // 生成全局场景图片
  10893. private function batchSetGlobalSceneImg($data, $is_force=false) {
  10894. $anime_id = getProp($data, 'anime_id');
  10895. if (!$anime_id) Utils::throwError('1002:请选择对话');
  10896. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10897. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10898. $art_style = getProp($anime, 'art_style');
  10899. $update_flag = false;
  10900. foreach ($scenes as &$scene) {
  10901. $scene_name = getProp($scene, 'scene');
  10902. // 优先使用 pic_prompt,如果没有则使用 description
  10903. $pic_prompt = getProp($scene, 'pic_prompt');
  10904. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  10905. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  10906. // 参考图地址
  10907. $ref_img_url = getProp($scene, 'url');
  10908. if (!$is_force && $ref_img_url) continue;
  10909. $update_flag = true;
  10910. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  10911. try {
  10912. $params = [
  10913. 'prompt' => $description,
  10914. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  10915. 'ref_img_urls' => []
  10916. ];
  10917. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10918. $task_id = $task->id;
  10919. if (!$task_id) {
  10920. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  10921. }
  10922. $scene['task_id'] = $task_id;
  10923. $scene['task_status'] = 'processing';
  10924. } catch (\Exception $e) {
  10925. Utils::throwError("20003:" . $e->getMessage());
  10926. }
  10927. }
  10928. if (!$update_flag) return true;
  10929. // 保存角色信息
  10930. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  10931. 'scenes' => json_encode($scenes, 256),
  10932. 'generate_status' => '执行中',
  10933. 'generate_at' => date('Y-m-d H:i:s'),
  10934. 'updated_at' => date('Y-m-d H:i:s')
  10935. ]);
  10936. if (!$boolen) {
  10937. Utils::throwError('20003:保存角色信息失败');
  10938. }
  10939. return $boolen;
  10940. }
  10941. // 生成分镜主体、场景和道具图片
  10942. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  10943. $character_prefix = '';
  10944. $scene_prefix = '';
  10945. $prop_prefix = '';
  10946. if ($art_style_type) {
  10947. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  10948. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  10949. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  10950. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  10951. }
  10952. $update_flag = false;
  10953. // 获取上一集的roles、scenes和props数据
  10954. $prev_roles = [];
  10955. $prev_scenes = [];
  10956. $prev_props = [];
  10957. if ($episode_number > 1) {
  10958. $prev_episode = DB::table('mp_anime_episodes')
  10959. ->where('anime_id', $anime_id)
  10960. ->where('episode_number', $episode_number - 1)
  10961. ->where('is_default', 1)
  10962. ->first();
  10963. if ($prev_episode) {
  10964. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  10965. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  10966. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  10967. dLog('deepseek')->info("获取上一集数据成功", [
  10968. 'anime_id' => $anime_id,
  10969. 'prev_episode_number' => $episode_number - 1,
  10970. 'prev_roles_count' => count($prev_roles),
  10971. 'prev_scenes_count' => count($prev_scenes),
  10972. 'prev_props_count' => count($prev_props)
  10973. ]);
  10974. }
  10975. }
  10976. // 处理角色图片生成
  10977. foreach ($roles as &$role) {
  10978. $role_name = getProp($role, 'role');
  10979. if ($role_name == '旁白') continue;
  10980. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  10981. if (isset($ref_products[$role_name])) {
  10982. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  10983. if ($role['url']) continue;
  10984. }
  10985. $role_description = getProp($role, 'description');
  10986. $role_pic_prompt = getProp($role, 'pic_prompt');
  10987. $role_url = getProp($role, 'url');
  10988. // 检查是否可以从上一集继承
  10989. $inherited = false;
  10990. if (!$is_force && !empty($prev_roles)) {
  10991. foreach ($prev_roles as $prev_role) {
  10992. $prev_role_name = getProp($prev_role, 'role');
  10993. $prev_description = getProp($prev_role, 'description');
  10994. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  10995. $prev_url = getProp($prev_role, 'url');
  10996. $prev_task_id = getProp($prev_role, 'task_id');
  10997. $prev_task_status = getProp($prev_role, 'task_status');
  10998. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  10999. if ($role_name == $prev_role_name
  11000. && $role_description == $prev_description
  11001. && $role_pic_prompt == $prev_pic_prompt
  11002. && !empty($prev_url)) {
  11003. $role['task_id'] = $prev_task_id;
  11004. $role['task_status'] = $prev_task_status;
  11005. $role['url'] = $prev_url;
  11006. $inherited = true;
  11007. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  11008. 'anime_id' => $anime_id,
  11009. 'episode_number' => $episode_number,
  11010. 'task_id' => $prev_task_id,
  11011. 'url' => $prev_url
  11012. ]);
  11013. break;
  11014. }
  11015. }
  11016. }
  11017. // 如果已继承或已有url,跳过生成
  11018. if ($inherited || (!$is_force && $role_url)) {
  11019. continue;
  11020. }
  11021. // 优先使用 pic_prompt,如果没有则使用 description
  11022. $pic_prompt = getProp($role, 'pic_prompt');
  11023. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  11024. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11025. $update_flag = true;
  11026. // 调用AIImageGenerationService的生成图片任务接口
  11027. try {
  11028. $params = [
  11029. 'prompt' => $description,
  11030. 'ref_img_urls' => []
  11031. ];
  11032. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11033. $task_id = $task->id;
  11034. if (!$task_id) {
  11035. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  11036. continue; // 不中断,继续处理其他角色
  11037. }
  11038. $role['task_id'] = $task_id;
  11039. $role['task_status'] = 'processing';
  11040. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  11041. 'anime_id' => $anime_id,
  11042. 'episode_number' => $episode_number,
  11043. 'task_id' => $task_id
  11044. ]);
  11045. } catch (\Exception $e) {
  11046. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  11047. // 不抛出异常,继续处理其他角色
  11048. }
  11049. }
  11050. // 处理场景图片生成
  11051. foreach ($scenes as &$scene) {
  11052. $scene_name = getProp($scene, 'scene');
  11053. $scene_description = getProp($scene, 'description');
  11054. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  11055. $scene_url = getProp($scene, 'url');
  11056. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  11057. if (isset($ref_products[$scene_name])) {
  11058. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  11059. if ($scene['url']) continue;
  11060. }
  11061. // 检查是否可以从上一集继承
  11062. $inherited = false;
  11063. if (!$is_force && !empty($prev_scenes)) {
  11064. foreach ($prev_scenes as $prev_scene) {
  11065. $prev_scene_name = getProp($prev_scene, 'scene');
  11066. $prev_description = getProp($prev_scene, 'description');
  11067. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  11068. $prev_url = getProp($prev_scene, 'url');
  11069. $prev_task_id = getProp($prev_scene, 'task_id');
  11070. $prev_task_status = getProp($prev_scene, 'task_status');
  11071. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  11072. if ($scene_name == $prev_scene_name
  11073. && $scene_description == $prev_description
  11074. && $scene_pic_prompt == $prev_pic_prompt
  11075. && !empty($prev_url)) {
  11076. $scene['task_id'] = $prev_task_id;
  11077. $scene['task_status'] = $prev_task_status;
  11078. $scene['url'] = $prev_url;
  11079. $inherited = true;
  11080. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  11081. 'anime_id' => $anime_id,
  11082. 'episode_number' => $episode_number,
  11083. 'task_id' => $prev_task_id,
  11084. 'url' => $prev_url
  11085. ]);
  11086. break;
  11087. }
  11088. }
  11089. }
  11090. // 如果已继承或已有url,跳过生成
  11091. if ($inherited || (!$is_force && $scene_url)) {
  11092. continue;
  11093. }
  11094. // 优先使用 pic_prompt,如果没有则使用 description
  11095. $pic_prompt = getProp($scene, 'pic_prompt');
  11096. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  11097. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11098. $update_flag = true;
  11099. // 调用AIImageGenerationService的生成图片任务接口
  11100. try {
  11101. $params = [
  11102. 'prompt' => $description,
  11103. 'ref_img_urls' => []
  11104. ];
  11105. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11106. $task_id = $task->id;
  11107. if (!$task_id) {
  11108. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  11109. continue; // 不中断,继续处理其他场景
  11110. }
  11111. $scene['task_id'] = $task_id;
  11112. $scene['task_status'] = 'processing';
  11113. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  11114. 'anime_id' => $anime_id,
  11115. 'episode_number' => $episode_number,
  11116. 'task_id' => $task_id
  11117. ]);
  11118. } catch (\Exception $e) {
  11119. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  11120. // 不抛出异常,继续处理其他场景
  11121. }
  11122. }
  11123. // 处理道具图片生成(逻辑与场景一致)
  11124. foreach ($props as &$prop) {
  11125. $prop_name = getProp($prop, 'prop');
  11126. $prop_description = getProp($prop, 'description');
  11127. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  11128. $prop_url = getProp($prop, 'url');
  11129. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  11130. if (isset($ref_products[$prop_name])) {
  11131. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  11132. if ($prop['url']) continue;
  11133. }
  11134. // 检查是否可以从上一集继承
  11135. $inherited = false;
  11136. if (!$is_force && !empty($prev_props)) {
  11137. foreach ($prev_props as $prev_prop) {
  11138. $prev_prop_name = getProp($prev_prop, 'prop');
  11139. $prev_description = getProp($prev_prop, 'description');
  11140. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  11141. $prev_url = getProp($prev_prop, 'url');
  11142. $prev_task_id = getProp($prev_prop, 'task_id');
  11143. $prev_task_status = getProp($prev_prop, 'task_status');
  11144. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  11145. if ($prop_name == $prev_prop_name
  11146. && $prop_description == $prev_description
  11147. && $prop_pic_prompt == $prev_pic_prompt
  11148. && !empty($prev_url)) {
  11149. $prop['task_id'] = $prev_task_id;
  11150. $prop['task_status'] = $prev_task_status;
  11151. $prop['url'] = $prev_url;
  11152. $inherited = true;
  11153. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  11154. 'anime_id' => $anime_id,
  11155. 'episode_number' => $episode_number,
  11156. 'task_id' => $prev_task_id,
  11157. 'url' => $prev_url
  11158. ]);
  11159. break;
  11160. }
  11161. }
  11162. }
  11163. // 如果已继承或已有url,跳过生成
  11164. if ($inherited || (!$is_force && $prop_url)) {
  11165. continue;
  11166. }
  11167. // 优先使用 pic_prompt,如果没有则使用 description
  11168. $pic_prompt = getProp($prop, 'pic_prompt');
  11169. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  11170. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11171. $update_flag = true;
  11172. // 调用AIImageGenerationService的生成图片任务接口
  11173. try {
  11174. $params = [
  11175. 'prompt' => $description,
  11176. 'ref_img_urls' => []
  11177. ];
  11178. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11179. $task_id = $task->id;
  11180. if (!$task_id) {
  11181. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  11182. continue; // 不中断,继续处理其他道具
  11183. }
  11184. $prop['task_id'] = $task_id;
  11185. $prop['task_status'] = 'processing';
  11186. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  11187. 'anime_id' => $anime_id,
  11188. 'episode_number' => $episode_number,
  11189. 'task_id' => $task_id
  11190. ]);
  11191. } catch (\Exception $e) {
  11192. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  11193. // 不抛出异常,继续处理其他道具
  11194. }
  11195. }
  11196. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11197. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  11198. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  11199. // // 保存剧集的角色和场景信息
  11200. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  11201. // 'roles' => json_encode($roles, 256),
  11202. // 'scenes' => json_encode($scenes, 256),
  11203. // 'generate_status' => '执行中',
  11204. // 'generate_at' => date('Y-m-d H:i:s'),
  11205. // 'updated_at' => date('Y-m-d H:i:s')
  11206. // ]);
  11207. // if (!$boolen) {
  11208. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  11209. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  11210. // }
  11211. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  11212. // 'episode_id' => $episode_id,
  11213. 'roles_count' => count($roles),
  11214. 'scenes_count' => count($scenes),
  11215. 'props_count' => count($props)
  11216. ]);
  11217. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11218. }
  11219. /**
  11220. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  11221. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  11222. *
  11223. * @param int $anime_id 动漫对话ID
  11224. * @param array $episode_roles 剧集角色数据
  11225. * @param array $episode_scenes 剧集场景数据
  11226. * @param array $episode_props 剧集道具数据
  11227. * @return bool
  11228. */
  11229. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  11230. // 获取全局数据
  11231. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11232. if (!$anime) {
  11233. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  11234. return false;
  11235. }
  11236. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11237. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11238. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  11239. $roles_added = false;
  11240. $roles_updated = false;
  11241. $scenes_added = false;
  11242. $props_added = false;
  11243. // 处理角色同步
  11244. foreach ($episode_roles as $episode_role) {
  11245. $episode_role_name = getProp($episode_role, 'role');
  11246. $episode_description = getProp($episode_role, 'description');
  11247. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  11248. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  11249. // 跳过旁白
  11250. if ($episode_role_name == '旁白') {
  11251. continue;
  11252. }
  11253. // 检查全局中是否已存在相同的角色
  11254. $exists = false;
  11255. $global_role_index = -1;
  11256. foreach ($global_roles as $index => $global_role) {
  11257. $global_role_name = getProp($global_role, 'role');
  11258. $global_description = getProp($global_role, 'description');
  11259. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  11260. // 如果role、description、pic_prompt三项都一致,则认为已存在
  11261. if ($episode_role_name == $global_role_name
  11262. && $episode_description == $global_description
  11263. && $episode_pic_prompt == $global_pic_prompt) {
  11264. $exists = true;
  11265. $global_role_index = $index;
  11266. break;
  11267. }
  11268. }
  11269. // 如果不存在,则添加到全局
  11270. if (!$exists) {
  11271. $global_roles[] = $episode_role;
  11272. $roles_added = true;
  11273. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  11274. 'anime_id' => $anime_id,
  11275. 'role' => $episode_role_name
  11276. ]);
  11277. } else {
  11278. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  11279. if (!empty($episode_voice_prompt)) {
  11280. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  11281. // 如果全局没有voice_prompt或与剧集不一致,则更新
  11282. if ($global_voice_prompt !== $episode_voice_prompt) {
  11283. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  11284. $roles_updated = true;
  11285. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  11286. 'anime_id' => $anime_id,
  11287. 'role' => $episode_role_name,
  11288. 'voice_prompt' => $episode_voice_prompt
  11289. ]);
  11290. }
  11291. }
  11292. }
  11293. }
  11294. // 处理场景同步
  11295. foreach ($episode_scenes as $episode_scene) {
  11296. $episode_scene_name = getProp($episode_scene, 'scene');
  11297. $episode_description = getProp($episode_scene, 'description');
  11298. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  11299. // 检查全局中是否已存在相同的场景
  11300. $exists = false;
  11301. foreach ($global_scenes as $global_scene) {
  11302. $global_scene_name = getProp($global_scene, 'scene');
  11303. $global_description = getProp($global_scene, 'description');
  11304. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  11305. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  11306. if ($episode_scene_name == $global_scene_name
  11307. && $episode_description == $global_description
  11308. && $episode_pic_prompt == $global_pic_prompt) {
  11309. $exists = true;
  11310. break;
  11311. }
  11312. }
  11313. // 如果不存在,则添加到全局
  11314. if (!$exists) {
  11315. $global_scenes[] = $episode_scene;
  11316. $scenes_added = true;
  11317. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  11318. 'anime_id' => $anime_id,
  11319. 'scene' => $episode_scene_name
  11320. ]);
  11321. }
  11322. }
  11323. // 处理道具同步(逻辑与场景一致)
  11324. foreach ($episode_props as $episode_prop) {
  11325. $episode_prop_name = getProp($episode_prop, 'prop');
  11326. $episode_description = getProp($episode_prop, 'description');
  11327. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  11328. // 检查全局中是否已存在相同的道具
  11329. $exists = false;
  11330. foreach ($global_props as $global_prop) {
  11331. $global_prop_name = getProp($global_prop, 'prop');
  11332. $global_description = getProp($global_prop, 'description');
  11333. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  11334. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  11335. if ($episode_prop_name == $global_prop_name
  11336. && $episode_description == $global_description
  11337. && $episode_pic_prompt == $global_pic_prompt) {
  11338. $exists = true;
  11339. break;
  11340. }
  11341. }
  11342. // 如果不存在,则添加到全局
  11343. if (!$exists) {
  11344. $global_props[] = $episode_prop;
  11345. $props_added = true;
  11346. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  11347. 'anime_id' => $anime_id,
  11348. 'prop' => $episode_prop_name
  11349. ]);
  11350. }
  11351. }
  11352. // 如果有新增或更新,则更新全局数据
  11353. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  11354. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  11355. if ($roles_added || $roles_updated) {
  11356. $update_data['roles'] = json_encode($global_roles, 256);
  11357. }
  11358. if ($scenes_added) {
  11359. $update_data['scenes'] = json_encode($global_scenes, 256);
  11360. }
  11361. if ($props_added) {
  11362. $update_data['props'] = json_encode($global_props, 256);
  11363. }
  11364. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11365. dLog('deepseek')->info('剧集数据同步到全局完成', [
  11366. 'anime_id' => $anime_id,
  11367. 'roles_added' => $roles_added,
  11368. 'roles_updated' => $roles_updated,
  11369. 'scenes_added' => $scenes_added,
  11370. 'props_added' => $props_added,
  11371. 'global_roles_count' => count($global_roles),
  11372. 'global_scenes_count' => count($global_scenes),
  11373. 'global_props_count' => count($global_props)
  11374. ]);
  11375. }
  11376. return true;
  11377. }
  11378. /**
  11379. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  11380. *
  11381. * @param int $anime_id 动漫对话ID
  11382. * @param int $episode_id 分集ID
  11383. * @return bool
  11384. */
  11385. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  11386. // 获取全局角色和场景数据
  11387. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11388. if (!$anime) {
  11389. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  11390. return false;
  11391. }
  11392. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11393. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11394. // 获取指定的分集
  11395. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  11396. if (!$episode) {
  11397. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  11398. return false;
  11399. }
  11400. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  11401. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  11402. $roles_updated = false;
  11403. $scenes_updated = false;
  11404. // 继承角色的task_id、task_status和url
  11405. foreach ($episode_roles as &$episode_role) {
  11406. $episode_role_name = getProp($episode_role, 'role');
  11407. $episode_description = getProp($episode_role, 'description');
  11408. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  11409. $episode_url = getProp($episode_role, 'url');
  11410. // 跳过旁白角色
  11411. if ($episode_role_name == '旁白') {
  11412. continue;
  11413. }
  11414. // 如果剧集中已有URL,跳过
  11415. if (!empty($episode_url)) {
  11416. continue;
  11417. }
  11418. // 遍历全局角色数据,查找匹配的角色
  11419. foreach ($global_roles as $global_role) {
  11420. $global_role_name = getProp($global_role, 'role');
  11421. $global_description = getProp($global_role, 'description');
  11422. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  11423. $global_url = getProp($global_role, 'url');
  11424. $global_task_id = getProp($global_role, 'task_id');
  11425. $global_task_status = getProp($global_role, 'task_status');
  11426. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  11427. if ($episode_role_name == $global_role_name
  11428. && $episode_description == $global_description
  11429. && $episode_pic_prompt == $global_pic_prompt) {
  11430. // 继承 task_id、task_status 和 url
  11431. if (!empty($global_task_id)) {
  11432. $episode_role['task_id'] = $global_task_id;
  11433. $episode_role['task_status'] = $global_task_status;
  11434. $roles_updated = true;
  11435. dLog('deepseek')->info('剧集角色继承全局task_id', [
  11436. 'episode_id' => $episode_id,
  11437. 'role' => $episode_role_name,
  11438. 'task_id' => $global_task_id,
  11439. 'task_status' => $global_task_status
  11440. ]);
  11441. }
  11442. if (!empty($global_url)) {
  11443. $episode_role['url'] = $global_url;
  11444. $roles_updated = true;
  11445. dLog('deepseek')->info('剧集角色继承全局url', [
  11446. 'episode_id' => $episode_id,
  11447. 'role' => $episode_role_name,
  11448. 'url' => $global_url
  11449. ]);
  11450. }
  11451. break;
  11452. }
  11453. }
  11454. }
  11455. // 继承场景的task_id、task_status和url
  11456. foreach ($episode_scenes as &$episode_scene) {
  11457. $episode_scene_name = getProp($episode_scene, 'scene');
  11458. $episode_description = getProp($episode_scene, 'description');
  11459. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  11460. $episode_url = getProp($episode_scene, 'url');
  11461. // 如果剧集中已有URL,跳过
  11462. if (!empty($episode_url)) {
  11463. continue;
  11464. }
  11465. // 遍历全局场景数据,查找匹配的场景
  11466. foreach ($global_scenes as $global_scene) {
  11467. $global_scene_name = getProp($global_scene, 'scene');
  11468. $global_description = getProp($global_scene, 'description');
  11469. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  11470. $global_url = getProp($global_scene, 'url');
  11471. $global_task_id = getProp($global_scene, 'task_id');
  11472. $global_task_status = getProp($global_scene, 'task_status');
  11473. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  11474. if ($episode_scene_name == $global_scene_name
  11475. && $episode_description == $global_description
  11476. && $episode_pic_prompt == $global_pic_prompt) {
  11477. // 继承 task_id、task_status 和 url
  11478. if (!empty($global_task_id)) {
  11479. $episode_scene['task_id'] = $global_task_id;
  11480. $episode_scene['task_status'] = $global_task_status;
  11481. $scenes_updated = true;
  11482. dLog('deepseek')->info('剧集场景继承全局task_id', [
  11483. 'episode_id' => $episode_id,
  11484. 'scene' => $episode_scene_name,
  11485. 'task_id' => $global_task_id,
  11486. 'task_status' => $global_task_status
  11487. ]);
  11488. }
  11489. if (!empty($global_url)) {
  11490. $episode_scene['url'] = $global_url;
  11491. $scenes_updated = true;
  11492. dLog('deepseek')->info('剧集场景继承全局url', [
  11493. 'episode_id' => $episode_id,
  11494. 'scene' => $episode_scene_name,
  11495. 'url' => $global_url
  11496. ]);
  11497. }
  11498. break;
  11499. }
  11500. }
  11501. }
  11502. // 如果有更新,则保存到数据库
  11503. if ($roles_updated || $scenes_updated) {
  11504. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  11505. if ($roles_updated) {
  11506. $update_data['roles'] = json_encode($episode_roles, 256);
  11507. }
  11508. if ($scenes_updated) {
  11509. $update_data['scenes'] = json_encode($episode_scenes, 256);
  11510. }
  11511. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  11512. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  11513. 'episode_id' => $episode_id,
  11514. 'roles_updated' => $roles_updated,
  11515. 'scenes_updated' => $scenes_updated
  11516. ]);
  11517. }
  11518. return true;
  11519. }
  11520. public function chatChangeImg($data) {
  11521. $segment = getProp($data, 'segment');
  11522. $segment_content = getProp($segment, 'segment_content');
  11523. $prompt = getProp($data, 'prompt');
  11524. $ref_img = getProp($data, 'ref_img');
  11525. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  11526. // 处理文本模型
  11527. $model = getProp($data, 'model');
  11528. if (!$model) {
  11529. // 用户没有输入,从anime表获取
  11530. $segment_id = getProp($segment, 'segment_id');
  11531. if ($segment_id) {
  11532. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  11533. if ($episode_id) {
  11534. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  11535. if ($anime_id) {
  11536. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  11537. }
  11538. }
  11539. }
  11540. if (!$model) {
  11541. // anime表也没有,使用默认值
  11542. $model = 'doubao-seed-2-0-mini-260215';
  11543. }
  11544. }
  11545. // 验证模型是否在可用模型表中
  11546. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  11547. $model = 'doubao-seed-2-0-mini-260215';
  11548. }
  11549. $messages[] =
  11550. [
  11551. 'role' => 'user',
  11552. 'content' => $question
  11553. ];
  11554. $post_data = [
  11555. 'model' => $model,
  11556. 'messages' => $messages,
  11557. // 'max_tokens' => 8192,
  11558. 'temperature' => 0.7,
  11559. 'frequency_penalty' => 0,
  11560. 'presence_penalty' => 0,
  11561. 'response_format' => ['type' => 'text'],
  11562. 'stream' => false // 是否启用流式输出
  11563. ];
  11564. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11565. // DeepSeek 官方模型使用 DeepSeek API
  11566. $chatResult = $this->chatOnly($post_data);
  11567. } else if (in_array($model, $this->gpt_text_models)) {
  11568. // GPT-5.4 模型使用 TokenRouter API
  11569. $chatResult = $this->gpt54ChatOnly($post_data);
  11570. } else {
  11571. // 其他模型使用火山引擎API
  11572. $chatResult = $this->volcEngineChatCompletion($post_data);
  11573. }
  11574. if (is_array($chatResult)) {
  11575. extract($chatResult);
  11576. }else {
  11577. Utils::throwError('20003: 接口调用失败!');
  11578. }
  11579. return [
  11580. 'type' => 'done',
  11581. // 'episode' => $episode,
  11582. 'answer' => $fullContent,
  11583. 'reasoning' => $fullReasoningContent,
  11584. 'usage' => $usage
  11585. ];
  11586. }
  11587. // 仅调用deepseek对话接口
  11588. private function chatOnly($post_data) {
  11589. $post_data['max_tokens'] = 300000;
  11590. $client = new Client(['timeout' => 1800, 'verify' => false]);
  11591. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  11592. $response = $result->getBody()->getContents();
  11593. $response_arr = json_decode($response, true);
  11594. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  11595. $fullContent = '';
  11596. $fullReasoningContent = [];
  11597. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  11598. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  11599. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  11600. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  11601. }
  11602. return [
  11603. 'fullContent' => $fullContent,
  11604. 'fullReasoningContent' => $fullReasoningContent,
  11605. 'usage' => $usage
  11606. ];
  11607. }
  11608. // 仅调用 GPT-5.4 对话接口(非流式)
  11609. private function gpt54ChatOnly($post_data) {
  11610. $apiKey = env('GPT_54_API_KEY');
  11611. if (empty($apiKey)) {
  11612. Utils::throwError('20003:GPT-5.4 API Key未配置');
  11613. }
  11614. // 先探活,服务不可用时自动重试
  11615. $this->ensureGptServiceAvailable();
  11616. $client = new Client(['timeout' => 1800, 'verify' => false]);
  11617. $headers = [
  11618. 'Authorization' => 'Bearer ' . $apiKey,
  11619. 'Content-Type' => 'application/json'
  11620. ];
  11621. // 移除 thinking 参数,GPT-5.4 不支持
  11622. if (isset($post_data['thinking'])) {
  11623. unset($post_data['thinking']);
  11624. }
  11625. if (isset($post_data['reasoning_effort'])) {
  11626. unset($post_data['reasoning_effort']);
  11627. }
  11628. $post_data['max_completion_tokens'] = 100000;
  11629. // 确保 stream 为 false
  11630. $post_data['stream'] = false;
  11631. $maxRetries = $this->gptRetryTimes();
  11632. $interval = $this->gptRetryInterval();
  11633. $attempt = 0;
  11634. while (true) {
  11635. try {
  11636. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  11637. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  11638. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  11639. 'json' => $post_data,
  11640. 'headers' => $headers
  11641. ]);
  11642. $response = $result->getBody()->getContents();
  11643. $response_arr = json_decode($response, true);
  11644. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  11645. $fullContent = '';
  11646. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  11647. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  11648. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  11649. }
  11650. return [
  11651. 'fullContent' => $fullContent,
  11652. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  11653. 'usage' => $usage
  11654. ];
  11655. } catch (\Exception $e) {
  11656. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  11657. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  11658. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  11659. throw $e;
  11660. }
  11661. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  11662. 'retry' => $attempt + 1,
  11663. 'max_retries' => $maxRetries,
  11664. 'error' => $e->getMessage()
  11665. ]);
  11666. sleep($interval);
  11667. $attempt++;
  11668. }
  11669. }
  11670. }
  11671. private function splitContent($content) {
  11672. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  11673. $chapters = [];
  11674. // 匹配章节标题格式:
  11675. // 1. 标题可能独占一行,也可能在正文末尾或中间
  11676. // 2. 格式支持:
  11677. // - **第一集**
  11678. // - 第一集:
  11679. // - ###第1章 重生
  11680. // - ##第2章 相救
  11681. // - 第三章 共处一室
  11682. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  11683. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  11684. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  11685. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  11686. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  11687. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  11688. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  11689. // 先在每个标题前插入换行符(如果前面不是换行的话)
  11690. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  11691. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  11692. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  11693. // 用正则找出所有章节标题的位置
  11694. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  11695. $titleCount = count($matches[0]);
  11696. for ($i = 0; $i < $titleCount; $i++) {
  11697. // 获取当前章节标题
  11698. $titleLine = trim($matches[0][$i][0]);
  11699. // 去除标题开头的特殊符号
  11700. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  11701. // 去除标题结尾的冒号和特殊符号
  11702. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  11703. $cleanTitle = trim($cleanTitle);
  11704. // 获取当前标题的结束位置
  11705. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  11706. // 获取下一个章节标题的开始位置(如果存在)
  11707. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  11708. // 提取章节内容(从标题结束到下一个标题开始)
  11709. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  11710. // 清理内容:去除前后空白和分隔线
  11711. $chapterContent = trim($chapterContent);
  11712. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  11713. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  11714. if (!empty($cleanTitle) && !empty($chapterContent)) {
  11715. $chapters[] = [
  11716. 'title' => $cleanTitle,
  11717. 'content' => $chapterContent
  11718. ];
  11719. }
  11720. }
  11721. } else {
  11722. // 如果没有匹配到章节,返回整个内容
  11723. $chapters[] = [
  11724. 'title' => '',
  11725. 'content' => $content
  11726. ];
  11727. }
  11728. return $chapters;
  11729. }
  11730. public function getContentByBid($bid) {
  11731. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  11732. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  11733. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  11734. $content = '';
  11735. foreach ($chapters as $chapter) {
  11736. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  11737. }
  11738. return $content;
  11739. }
  11740. public function getContentByScriptId($script_id) {
  11741. $content = '';
  11742. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  11743. if ($contents) {
  11744. $content = implode(PHP_EOL, $contents);
  11745. }else {
  11746. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  11747. }
  11748. return $content;
  11749. }
  11750. /**
  11751. * 根据文件类型提取文本内容
  11752. *
  11753. * @param mixed $file 文件对象或文件路径
  11754. * @return string
  11755. */
  11756. public function extractFileContent($file) {
  11757. // 获取文件路径和扩展名
  11758. if (is_string($file)) {
  11759. $filePath = $file;
  11760. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  11761. } else {
  11762. // Laravel UploadedFile 对象
  11763. $filePath = $file->getRealPath();
  11764. $extension = strtolower($file->getClientOriginalExtension());
  11765. }
  11766. $content = '';
  11767. switch ($extension) {
  11768. case 'txt':
  11769. $content = $this->extractTxtContent($filePath);
  11770. break;
  11771. case 'pdf':
  11772. $content = $this->extractPdfContent($filePath);
  11773. break;
  11774. case 'doc':
  11775. case 'docx':
  11776. $content = $this->extractWordContent($filePath);
  11777. break;
  11778. // case 'jpg':
  11779. // case 'jpeg':
  11780. // case 'png':
  11781. // case 'gif':
  11782. // case 'bmp':
  11783. // case 'webp':
  11784. // $content = $this->extractImageContent($filePath);
  11785. // break;
  11786. default:
  11787. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  11788. }
  11789. return $content;
  11790. }
  11791. /**
  11792. * 提取 TXT 文件内容
  11793. */
  11794. private function extractTxtContent($filePath) {
  11795. if (!file_exists($filePath)) {
  11796. Utils::throwError('20003:文件不存在');
  11797. }
  11798. $content = file_get_contents($filePath);
  11799. // 尝试检测并转换编码
  11800. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  11801. if ($encoding && $encoding !== 'UTF-8') {
  11802. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  11803. }
  11804. return trim($content);
  11805. }
  11806. /**
  11807. * 提取 PDF 文件内容
  11808. */
  11809. private function extractPdfContent($filePath) {
  11810. if (!file_exists($filePath)) {
  11811. Utils::throwError('20003:文件不存在');
  11812. }
  11813. try {
  11814. $parser = new PdfParser();
  11815. $pdf = $parser->parseFile($filePath);
  11816. $content = $pdf->getText();
  11817. return trim($content);
  11818. } catch (\Exception $e) {
  11819. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  11820. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  11821. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  11822. }
  11823. }
  11824. /**
  11825. * 提取 Word 文件内容(支持 doc 和 docx)
  11826. */
  11827. private function extractWordContent($filePath) {
  11828. if (!file_exists($filePath)) {
  11829. Utils::throwError('20003:文件不存在');
  11830. }
  11831. try {
  11832. $phpWord = WordIOFactory::load($filePath);
  11833. $content = '';
  11834. foreach ($phpWord->getSections() as $section) {
  11835. foreach ($section->getElements() as $element) {
  11836. $content .= $this->extractWordElementText($element);
  11837. }
  11838. }
  11839. return trim($content);
  11840. } catch (\Exception $e) {
  11841. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  11842. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  11843. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  11844. }
  11845. }
  11846. /**
  11847. * 递归提取 Word 元素中的文本
  11848. */
  11849. private function extractWordElementText($element) {
  11850. $text = '';
  11851. if (method_exists($element, 'getText')) {
  11852. $text .= $element->getText() . "\n";
  11853. } elseif (method_exists($element, 'getElements')) {
  11854. foreach ($element->getElements() as $childElement) {
  11855. $text .= $this->extractWordElementText($childElement);
  11856. }
  11857. }
  11858. return $text;
  11859. }
  11860. /**
  11861. * 提取图片内容(使用火山引擎 OCR)
  11862. */
  11863. private function extractImageContent($filePath) {
  11864. if (!file_exists($filePath)) {
  11865. Utils::throwError('20003:文件不存在');
  11866. }
  11867. try {
  11868. // 读取图片并转换为 base64
  11869. $imageData = file_get_contents($filePath);
  11870. $base64Image = base64_encode($imageData);
  11871. // 调用火山引擎 OCR 服务
  11872. $content = $this->callVolcEngineOCR($base64Image);
  11873. return trim($content);
  11874. } catch (\Exception $e) {
  11875. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  11876. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  11877. Utils::throwError('20003:图片识别失败');
  11878. }
  11879. }
  11880. /**
  11881. * 调用火山引擎 OCR 服务识别图片文字
  11882. *
  11883. * @param string $base64Image base64 编码的图片数据
  11884. * @return string 识别的文字内容
  11885. */
  11886. private function callVolcEngineOCR($base64Image) {
  11887. $method = 'POST';
  11888. $service = 'cv';
  11889. $host = 'visual.volcengineapi.com';
  11890. $region = env('VOLC_REGION', 'cn-north-1');
  11891. $access_key = env('VOLC_AK');
  11892. $secret_key = env('VOLC_SK');
  11893. $action = 'OCRNormal';
  11894. $version = '2020-08-26';
  11895. if (!$access_key || !$secret_key) {
  11896. Utils::throwError('20003:请配置火山引擎 AK/SK');
  11897. }
  11898. // 请求体
  11899. $body = json_encode([
  11900. 'image_base64' => $base64Image
  11901. ]);
  11902. // 生成签名
  11903. $headers = $this->getVolcEngineSignHeaders(
  11904. $method, $service, $host, $region,
  11905. "Action={$action}&Version={$version}",
  11906. $access_key, $secret_key, $body
  11907. );
  11908. $client = new Client(['timeout' => 1800, 'verify' => false]);
  11909. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  11910. 'headers' => $headers,
  11911. 'body' => $body
  11912. ]);
  11913. $response_arr = json_decode($response->getBody()->getContents(), true);
  11914. // 提取识别的文字
  11915. $textLines = [];
  11916. if (isset($response_arr['data']['line_texts'])) {
  11917. $textLines = $response_arr['data']['line_texts'];
  11918. } elseif (isset($response_arr['data']['ocr_infos'])) {
  11919. foreach ($response_arr['data']['ocr_infos'] as $info) {
  11920. if (isset($info['text'])) {
  11921. $textLines[] = $info['text'];
  11922. }
  11923. }
  11924. }
  11925. if (empty($textLines)) {
  11926. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  11927. return '';
  11928. }
  11929. return implode("\n", $textLines);
  11930. }
  11931. /**
  11932. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  11933. */
  11934. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  11935. $contentType = 'application/json';
  11936. $accept = 'application/json';
  11937. // 获取当前UTC时间
  11938. $t = new DateTime('now', new DateTimeZone('UTC'));
  11939. $xDate = $t->format('Ymd\THis\Z');
  11940. $dateStamp = $t->format('Ymd');
  11941. // 计算 body 的 sha256 哈希
  11942. $payloadHash = hash('sha256', $body);
  11943. // 1. 拼接规范请求串
  11944. $canonicalUri = '/';
  11945. $canonicalQueryString = $queryString;
  11946. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  11947. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  11948. $canonicalRequest = implode("\n", [
  11949. $method,
  11950. $canonicalUri,
  11951. $canonicalQueryString,
  11952. $canonicalHeaders,
  11953. $signedHeaders,
  11954. $payloadHash
  11955. ]);
  11956. // 2. 拼接待签名字符串
  11957. $algorithm = 'HMAC-SHA256';
  11958. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  11959. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  11960. $stringToSign = implode("\n", [
  11961. $algorithm,
  11962. $xDate,
  11963. $credentialScope,
  11964. $hashedCanonicalRequest
  11965. ]);
  11966. // 3. 计算签名
  11967. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  11968. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  11969. // 4. 添加签名到请求头
  11970. $authorizationHeader = sprintf(
  11971. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  11972. $algorithm,
  11973. $access_key,
  11974. $credentialScope,
  11975. $signedHeaders,
  11976. $signature
  11977. );
  11978. return [
  11979. 'Accept' => $accept,
  11980. 'Content-Type' => $contentType,
  11981. 'Host' => $host,
  11982. 'X-Date' => $xDate,
  11983. 'X-Content-Sha256'=> $payloadHash,
  11984. 'Authorization' => $authorizationHeader
  11985. ];
  11986. }
  11987. public function generateScriptWords($cid, $model = 'r1') {
  11988. ini_set('max_execution_time', 0);
  11989. if (!$cid) Utils::throwError('20003: 请选择章节!');
  11990. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  11991. // 模型兼容性处理和思考模式设置
  11992. $thinkingMode = 'disabled';
  11993. $reasoningEffort = 'high';
  11994. if ($model == 'r1') {
  11995. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  11996. $thinkingMode = 'enabled';
  11997. } else {
  11998. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  11999. $thinkingMode = 'disabled';
  12000. }
  12001. $messages = [
  12002. [
  12003. 'role' => 'system',
  12004. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  12005. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  12006. 2.非对话部分请全部用旁白角色代替
  12007. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  12008. ],
  12009. [
  12010. 'role' => 'user',
  12011. 'content' => $content
  12012. ]
  12013. ];
  12014. $post_data = [
  12015. 'model' => $model,
  12016. 'messages' => $messages,
  12017. // 'max_tokens' => 8192,
  12018. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  12019. 'frequency_penalty' => 0,
  12020. 'presence_penalty' => 0,
  12021. 'thinking' => ['type' => $thinkingMode],
  12022. 'response_format' => [
  12023. 'type' => 'text'
  12024. ],
  12025. 'stream' => false
  12026. ];
  12027. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  12028. // 根据模型类型选择调用方法
  12029. $fullContent = '';
  12030. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  12031. // DeepSeek 官方模型使用 DeepSeek API
  12032. $chatResult = $this->chatOnly($post_data);
  12033. } else if (in_array($model, $this->gpt_text_models)) {
  12034. // GPT-5.4 模型使用 TokenRouter API
  12035. $chatResult = $this->gpt54ChatOnly($post_data);
  12036. } else {
  12037. // 其他模型使用火山引擎API
  12038. $chatResult = $this->volcEngineChatCompletion($post_data);
  12039. }
  12040. if (is_array($chatResult)) {
  12041. $fullContent = $chatResult['fullContent'];
  12042. }
  12043. return $fullContent;
  12044. }
  12045. /**
  12046. * 智能化解析集数信息
  12047. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  12048. *
  12049. * @param string $prompt 用户输入的提示词
  12050. * @return int|null 解析出的集数,如果没有找到则返回null
  12051. */
  12052. private function extractEpisodeNumber($prompt)
  12053. {
  12054. if (empty($prompt)) {
  12055. return null;
  12056. }
  12057. // 定义各种可能的表达模式
  12058. $patterns = [
  12059. // 基本模式:改成N集、调整成N集、修改成N集
  12060. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  12061. // 扩展模式:分成N集、拆分成N集、分割成N集
  12062. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  12063. // 数量模式:N集、共N集、总共N集
  12064. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  12065. // 制作模式:制作N集、生成N集、创建N集
  12066. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  12067. // 计划模式:计划N集、预计N集、打算N集
  12068. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  12069. // 需要模式:需要N集、要N集
  12070. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  12071. // 中文数字模式:改成三集、调整成五集等
  12072. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  12073. // 英文数字模式
  12074. '/(?: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',
  12075. ];
  12076. // 中文数字转阿拉伯数字的映射
  12077. $chineseNumbers = [
  12078. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  12079. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  12080. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  12081. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  12082. ];
  12083. // 逐个尝试匹配模式
  12084. foreach ($patterns as $pattern) {
  12085. if (preg_match($pattern, $prompt, $matches)) {
  12086. $number = trim($matches[1]);
  12087. // 如果是中文数字,转换为阿拉伯数字
  12088. if (isset($chineseNumbers[$number])) {
  12089. return $chineseNumbers[$number];
  12090. }
  12091. // 如果是阿拉伯数字,直接返回
  12092. if (is_numeric($number)) {
  12093. $episodeNum = intval($number);
  12094. // 合理性检查:集数应该在1-100之间
  12095. if ($episodeNum >= 1 && $episodeNum <= 100) {
  12096. return $episodeNum;
  12097. }
  12098. }
  12099. }
  12100. }
  12101. return null;
  12102. }
  12103. /**
  12104. * 调用火山引擎对话(Chat) API
  12105. *
  12106. * @param array $params 包含以下参数:
  12107. * - model: 模型ID(必填)
  12108. * - messages: 消息列表(必填)
  12109. * - stream: 是否流式输出(可选,默认false)
  12110. * - max_tokens: 最大输出token数(可选)
  12111. * - temperature: 采样温度(可选,默认1)
  12112. * - top_p: 核采样概率(可选,默认0.7)
  12113. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  12114. * - presence_penalty: 存在惩罚系数(可选,默认0)
  12115. * - stop: 停止词(可选)
  12116. * - tools: 工具列表(可选)
  12117. * @return array|Generator 非流式返回数组,流式返回生成器
  12118. */
  12119. public function volcEngineChatCompletion(array $params)
  12120. {
  12121. $apiKey = env('VOLC_AI_API_KEY');
  12122. if (empty($apiKey)) {
  12123. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  12124. }
  12125. // 构建请求参数
  12126. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  12127. $requestData = [
  12128. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  12129. 'messages' => $params['messages'] ?? [],
  12130. ];
  12131. if (!in_array($originalModel, $this->valid_text_models)) {
  12132. Utils::throwError('20003:该模型不支持!');
  12133. }
  12134. // 添加可选参数
  12135. if (isset($params['stream'])) {
  12136. $requestData['stream'] = $params['stream'];
  12137. }
  12138. if (isset($params['stream_options'])) {
  12139. $requestData['stream_options'] = $params['stream_options'];
  12140. }
  12141. if (isset($params['max_tokens'])) {
  12142. $requestData['max_tokens'] = $params['max_tokens'];
  12143. }else if (isset($params['max_completion_tokens'])) {
  12144. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  12145. }else {
  12146. $requestData['max_completion_tokens'] = 100000;
  12147. }
  12148. if (isset($params['temperature'])) {
  12149. $requestData['temperature'] = $params['temperature'];
  12150. }
  12151. if (isset($params['top_p'])) {
  12152. $requestData['top_p'] = $params['top_p'];
  12153. }
  12154. if (isset($params['frequency_penalty'])) {
  12155. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  12156. }
  12157. if (isset($params['presence_penalty'])) {
  12158. $requestData['presence_penalty'] = $params['presence_penalty'];
  12159. }
  12160. if (isset($params['stop'])) {
  12161. $requestData['stop'] = $params['stop'];
  12162. }
  12163. if (isset($params['tools'])) {
  12164. $requestData['tools'] = $params['tools'];
  12165. }
  12166. if (isset($params['tool_choice'])) {
  12167. $requestData['tool_choice'] = $params['tool_choice'];
  12168. }
  12169. if (isset($params['response_format'])) {
  12170. $requestData['response_format'] = $params['response_format'];
  12171. }
  12172. if (isset($params['thinking'])) {
  12173. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  12174. if (is_array($params['thinking'])) {
  12175. $requestData['thinking'] = $params['thinking'];
  12176. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  12177. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  12178. }
  12179. } else {
  12180. $requestData['thinking'] = ['type' => $params['thinking']];
  12181. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  12182. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  12183. }
  12184. }
  12185. } else {
  12186. $requestData['thinking'] = ['type' => 'disabled'];
  12187. }
  12188. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  12189. $client = new Client(['verify' => false, 'timeout' => 1800]);
  12190. try {
  12191. // 判断是否为流式输出
  12192. $isStream = isset($params['stream']) && $params['stream'] === true;
  12193. if ($isStream) {
  12194. // 流式输出
  12195. // 流式请求默认声明返回 usage(未显式传参时)
  12196. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  12197. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  12198. } else {
  12199. // 非流式输出
  12200. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  12201. 'headers' => [
  12202. 'Authorization' => 'Bearer ' . $apiKey,
  12203. 'Content-Type' => 'application/json',
  12204. ],
  12205. 'json' => $requestData
  12206. ]);
  12207. $responseData = json_decode($response->getBody(), true);
  12208. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  12209. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  12210. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  12211. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  12212. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  12213. }
  12214. return [
  12215. 'fullContent' => $fullContent,
  12216. 'fullReasoningContent' => $fullReasoningContent,
  12217. 'usage' => $usage
  12218. ];
  12219. }
  12220. } catch (\Exception $e) {
  12221. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  12222. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  12223. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  12224. }
  12225. }
  12226. /**
  12227. * 火山引擎对话API流式输出
  12228. *
  12229. * @param Client $client HTTP客户端
  12230. * @param string $apiKey API密钥
  12231. * @param array $requestData 请求数据
  12232. * @return Generator
  12233. */
  12234. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  12235. {
  12236. try {
  12237. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  12238. 'headers' => [
  12239. 'Authorization' => 'Bearer ' . $apiKey,
  12240. 'Content-Type' => 'application/json',
  12241. ],
  12242. 'json' => $requestData,
  12243. 'stream' => true
  12244. ]);
  12245. $body = $response->getBody();
  12246. $buffer = '';
  12247. $fullContent = '';
  12248. $fullReasoningContent = '';
  12249. $usage = [];
  12250. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  12251. // 逐行读取流式响应
  12252. while (!$body->eof()) {
  12253. $chunk = $body->read(1024);
  12254. $buffer .= $chunk;
  12255. // 按行分割
  12256. $lines = explode("\n", $buffer);
  12257. $buffer = array_pop($lines);
  12258. foreach ($lines as $line) {
  12259. $line = trim($line);
  12260. if (empty($line)) {
  12261. continue;
  12262. }
  12263. // 检查是否是SSE数据行
  12264. if (strpos($line, 'data: ') !== 0) {
  12265. continue;
  12266. }
  12267. $data = substr($line, 6);
  12268. if ($data === '[DONE]') {
  12269. dLog('deepseek')->info('收到结束标记');
  12270. break 2;
  12271. }
  12272. try {
  12273. $json = json_decode($data, true);
  12274. if (json_last_error() !== JSON_ERROR_NONE) {
  12275. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  12276. continue;
  12277. }
  12278. if (isset($json['choices'][0]['delta'])) {
  12279. $delta = $json['choices'][0]['delta'];
  12280. // 处理思维链内容
  12281. if (isset($delta['reasoning_content'])) {
  12282. $fullReasoningContent .= $delta['reasoning_content'];
  12283. yield [
  12284. 'type' => 'reasoning',
  12285. 'content' => $delta['reasoning_content'],
  12286. 'full_reasoning' => $fullReasoningContent
  12287. ];
  12288. }
  12289. // 处理回答内容
  12290. if (isset($delta['content'])) {
  12291. $fullContent .= $delta['content'];
  12292. yield [
  12293. 'type' => 'content',
  12294. 'content' => $delta['content'],
  12295. ];
  12296. }
  12297. }
  12298. // 获取使用统计信息
  12299. if (isset($json['usage'])) {
  12300. $usage = $json['usage'];
  12301. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  12302. }
  12303. } catch (\Exception $e) {
  12304. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  12305. continue;
  12306. }
  12307. }
  12308. }
  12309. dLog('deepseek')->info('流式读取完成', [
  12310. 'content_length' => strlen($fullContent),
  12311. 'reasoning_length' => strlen($fullReasoningContent)
  12312. ]);
  12313. yield [
  12314. 'type' => 'done',
  12315. 'full_content' => $fullContent,
  12316. 'full_reasoning' => $fullReasoningContent,
  12317. 'usage' => $usage
  12318. ];
  12319. } catch (\Exception $e) {
  12320. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  12321. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  12322. throw $e;
  12323. }
  12324. }
  12325. /**
  12326. * 检查并创建图片生成任务
  12327. *
  12328. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  12329. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  12330. * @param string $nameKey 资源名称字段('role' 或 'scene')
  12331. * @param string $art_style 美术风格
  12332. * @return array 更新后的资源列表
  12333. */
  12334. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  12335. {
  12336. // 确保参数为数组
  12337. $merged_items = is_array($merged_items) ? $merged_items : [];
  12338. $global_items = is_array($global_items) ? $global_items : [];
  12339. // 构建全局资源映射表,用于快速查找
  12340. $global_map = [];
  12341. foreach ($global_items as $item) {
  12342. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  12343. if ($itemKey === '') {
  12344. continue;
  12345. }
  12346. $global_map[$itemKey] = $item;
  12347. }
  12348. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  12349. foreach ($merged_items as &$item) {
  12350. $item_name = getProp($item, $nameKey);
  12351. $item_description = getProp($item, 'description');
  12352. // $item_url = getProp($item, 'url');
  12353. // // 如果已有图片URL,跳过
  12354. // if (!empty($item_url)) {
  12355. // continue;
  12356. // }
  12357. // 如果是旁白角色,跳过
  12358. if ($nameKey === 'role' && $item_name === '旁白') {
  12359. continue;
  12360. }
  12361. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  12362. if ($itemKey === '') {
  12363. continue;
  12364. }
  12365. $need_create_task = false;
  12366. // 条件1:在全局资源中找不到匹配的名称
  12367. if (!isset($global_map[$itemKey])) {
  12368. $need_create_task = true;
  12369. } else {
  12370. // 条件2:名称匹配但描述或 pic_prompt 不一致
  12371. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  12372. $current_description = trim((string)$item_description);
  12373. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  12374. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  12375. // 如果 description 或 pic_prompt 有变化,需要重新生成
  12376. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  12377. $need_create_task = true;
  12378. }
  12379. }
  12380. // 如果需要创建任务,调用图片生成服务
  12381. if ($need_create_task) {
  12382. try {
  12383. // 优先使用 pic_prompt,如果没有则使用 description
  12384. $pic_prompt = getProp($item, 'pic_prompt');
  12385. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  12386. // 添加美术风格前缀
  12387. if ($art_style) {
  12388. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  12389. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  12390. $description = "{$prefix}:{$description}";
  12391. }
  12392. $params = [
  12393. 'prompt' => $description,
  12394. 'ref_img_urls' => []
  12395. ];
  12396. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12397. $task_id = $task->id;
  12398. if ($task_id) {
  12399. $item['task_id'] = $task_id;
  12400. $item['task_status'] = 'processing';
  12401. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  12402. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  12403. }
  12404. } catch (\Exception $e) {
  12405. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  12406. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  12407. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  12408. // 不抛出异常,继续处理其他资源
  12409. }
  12410. }
  12411. }
  12412. return $merged_items;
  12413. }
  12414. /**
  12415. * 同步新出现的主体和场景到全局
  12416. *
  12417. * @param int $anime_id 动漫ID
  12418. * @param array $merged_roles 合并后的角色列表
  12419. * @param array $merged_scenes 合并后的场景列表
  12420. * @param array $global_roles 全局角色列表
  12421. * @param array $global_scenes 全局场景列表
  12422. * @return void
  12423. */
  12424. private function syncNewResourcesToGlobal(
  12425. int $anime_id,
  12426. array $merged_roles,
  12427. array $merged_scenes,
  12428. array $global_roles,
  12429. array $global_scenes
  12430. ): void {
  12431. // 构建全局角色映射表
  12432. $global_role_map = [];
  12433. foreach ($global_roles as $role) {
  12434. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  12435. if ($roleKey !== '') {
  12436. $global_role_map[$roleKey] = $role;
  12437. }
  12438. }
  12439. // 构建全局场景映射表
  12440. $global_scene_map = [];
  12441. foreach ($global_scenes as $scene) {
  12442. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  12443. if ($sceneKey !== '') {
  12444. $global_scene_map[$sceneKey] = $scene;
  12445. }
  12446. }
  12447. $need_update = false;
  12448. $new_global_roles = $global_roles;
  12449. $new_global_scenes = $global_scenes;
  12450. // 检查并添加新角色到全局
  12451. foreach ($merged_roles as $role) {
  12452. $role_name = getProp($role, 'role');
  12453. // 跳过旁白
  12454. if ($role_name === '旁白') {
  12455. continue;
  12456. }
  12457. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  12458. if ($roleKey === '') {
  12459. continue;
  12460. }
  12461. // 如果全局中不存在该角色,添加到全局
  12462. if (!isset($global_role_map[$roleKey])) {
  12463. $new_global_roles[] = [
  12464. 'role' => $role_name,
  12465. 'description' => getProp($role, 'description', ''),
  12466. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  12467. 'voice_name' => getProp($role, 'voice_name', ''),
  12468. 'voice_type' => getProp($role, 'voice_type', ''),
  12469. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  12470. 'url' => getProp($role, 'url', ''),
  12471. 'task_id' => getProp($role, 'task_id', ''),
  12472. 'task_status' => getProp($role, 'task_status', ''),
  12473. ];
  12474. $global_role_map[$roleKey] = true; // 标记已添加
  12475. $need_update = true;
  12476. dLog('deepseek')->info("新角色同步到全局", [
  12477. 'anime_id' => $anime_id,
  12478. 'role' => $role_name,
  12479. 'task_id' => getProp($role, 'task_id', ''),
  12480. ]);
  12481. }
  12482. // else {
  12483. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  12484. // $global_role = $global_role_map[$roleKey];
  12485. // if (is_array($global_role)) {
  12486. // $updated = false;
  12487. // $update_fields = [];
  12488. // // 检查描述是否更新
  12489. // $current_description = trim((string)getProp($role, 'description'));
  12490. // $global_description = trim((string)getProp($global_role, 'description'));
  12491. // if ($current_description !== '' && $current_description !== $global_description) {
  12492. // $updated = true;
  12493. // $update_fields[] = 'description';
  12494. // }
  12495. // // 检查pic_prompt是否更新
  12496. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  12497. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  12498. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  12499. // $updated = true;
  12500. // $update_fields[] = 'pic_prompt';
  12501. // }
  12502. // // 检查图片任务信息是否更新
  12503. // $current_task_id = getProp($role, 'task_id');
  12504. // $global_task_id = getProp($global_role, 'task_id');
  12505. // if ($current_task_id && $current_task_id !== $global_task_id) {
  12506. // $updated = true;
  12507. // $update_fields[] = 'task_id';
  12508. // }
  12509. // // 如果有更新,同步到全局
  12510. // if ($updated) {
  12511. // foreach ($new_global_roles as &$global_role_item) {
  12512. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  12513. // if ($global_role_key === $roleKey) {
  12514. // if (in_array('description', $update_fields)) {
  12515. // $global_role_item['description'] = $current_description;
  12516. // }
  12517. // if (in_array('pic_prompt', $update_fields)) {
  12518. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  12519. // }
  12520. // if (in_array('task_id', $update_fields)) {
  12521. // $global_role_item['task_id'] = $current_task_id;
  12522. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  12523. // $global_role_item['url'] = getProp($role, 'url', '');
  12524. // }
  12525. // break;
  12526. // }
  12527. // }
  12528. // $need_update = true;
  12529. // dLog('deepseek')->info("角色信息更新到全局", [
  12530. // 'anime_id' => $anime_id,
  12531. // 'role' => $role_name,
  12532. // 'update_fields' => implode(',', $update_fields),
  12533. // ]);
  12534. // }
  12535. // }
  12536. // }
  12537. }
  12538. // 检查并添加新场景到全局
  12539. foreach ($merged_scenes as $scene) {
  12540. $scene_name = getProp($scene, 'scene');
  12541. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  12542. if ($sceneKey === '') {
  12543. continue;
  12544. }
  12545. // 如果全局中不存在该场景,添加到全局
  12546. if (!isset($global_scene_map[$sceneKey])) {
  12547. $new_global_scenes[] = [
  12548. 'scene' => $scene_name,
  12549. 'description' => getProp($scene, 'description', ''),
  12550. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  12551. 'url' => getProp($scene, 'url', ''),
  12552. 'task_id' => getProp($scene, 'task_id', ''),
  12553. 'task_status' => getProp($scene, 'task_status', ''),
  12554. ];
  12555. $global_scene_map[$sceneKey] = true; // 标记已添加
  12556. $need_update = true;
  12557. dLog('deepseek')->info("新场景同步到全局", [
  12558. 'anime_id' => $anime_id,
  12559. 'scene' => $scene_name,
  12560. 'task_id' => getProp($scene, 'task_id', ''),
  12561. ]);
  12562. }
  12563. // else {
  12564. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  12565. // $global_scene = $global_scene_map[$sceneKey];
  12566. // if (is_array($global_scene)) {
  12567. // $updated = false;
  12568. // $update_fields = [];
  12569. // // 检查描述是否更新
  12570. // $current_description = trim((string)getProp($scene, 'description'));
  12571. // $global_description = trim((string)getProp($global_scene, 'description'));
  12572. // if ($current_description !== '' && $current_description !== $global_description) {
  12573. // $updated = true;
  12574. // $update_fields[] = 'description';
  12575. // }
  12576. // // 检查pic_prompt是否更新
  12577. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  12578. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  12579. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  12580. // $updated = true;
  12581. // $update_fields[] = 'pic_prompt';
  12582. // }
  12583. // // 检查图片任务信息是否更新
  12584. // $current_task_id = getProp($scene, 'task_id');
  12585. // $global_task_id = getProp($global_scene, 'task_id');
  12586. // if ($current_task_id && $current_task_id !== $global_task_id) {
  12587. // $updated = true;
  12588. // $update_fields[] = 'task_id';
  12589. // }
  12590. // // 如果有更新,同步到全局
  12591. // if ($updated) {
  12592. // foreach ($new_global_scenes as &$global_scene_item) {
  12593. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  12594. // if ($global_scene_key === $sceneKey) {
  12595. // if (in_array('description', $update_fields)) {
  12596. // $global_scene_item['description'] = $current_description;
  12597. // }
  12598. // if (in_array('pic_prompt', $update_fields)) {
  12599. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  12600. // }
  12601. // if (in_array('task_id', $update_fields)) {
  12602. // $global_scene_item['task_id'] = $current_task_id;
  12603. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  12604. // $global_scene_item['url'] = getProp($scene, 'url', '');
  12605. // }
  12606. // break;
  12607. // }
  12608. // }
  12609. // $need_update = true;
  12610. // dLog('deepseek')->info("场景信息更新到全局", [
  12611. // 'anime_id' => $anime_id,
  12612. // 'scene' => $scene_name,
  12613. // 'update_fields' => implode(',', $update_fields),
  12614. // ]);
  12615. // }
  12616. // }
  12617. // }
  12618. }
  12619. // 如果有新增或更新,更新数据库
  12620. if ($need_update) {
  12621. $update_data = [
  12622. 'roles' => json_encode($new_global_roles, 256),
  12623. 'scenes' => json_encode($new_global_scenes, 256),
  12624. 'updated_at' => date('Y-m-d H:i:s'),
  12625. ];
  12626. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  12627. if ($result !== false) {
  12628. dLog('deepseek')->info("全局角色和场景更新成功", [
  12629. 'anime_id' => $anime_id,
  12630. 'roles_count' => count($new_global_roles),
  12631. 'scenes_count' => count($new_global_scenes),
  12632. ]);
  12633. } else {
  12634. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  12635. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  12636. }
  12637. }
  12638. }
  12639. }