DeepSeekService.php 358 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Facade\Site;
  5. use App\Libs\Utils;
  6. use GuzzleHttp\Client;
  7. use DateTime;
  8. use DateTimeZone;
  9. use App\Services\AIGeneration\AIImageGenerationService;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Facades\Log;
  12. use Illuminate\Support\Facades\Redis;
  13. use OSS\Core\OssException;
  14. use OSS\OssClient;
  15. use Smalot\PdfParser\Parser as PdfParser;
  16. use TCPDF;
  17. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  18. use Predis\Command\Traits\Get\Get;
  19. class DeepSeekService
  20. {
  21. private $url;
  22. private $api_key;
  23. private $sys_message;
  24. private $headers;
  25. private $valid_text_models;
  26. protected $aiImageGenerationService;
  27. public function __construct(AIImageGenerationService $aiImageGenerationService) {
  28. $this->aiImageGenerationService = $aiImageGenerationService;
  29. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  30. $this->api_key = env('DEEPSEEK_API_KEY');
  31. $this->headers = [
  32. 'Authorization' => 'Bearer '.$this->api_key,
  33. 'Content-Type' => 'application/json; charset=UTF-8'
  34. ];
  35. // 火山引擎模型列表
  36. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  37. $this->sys_message = [
  38. 'role' => 'system',
  39. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  40. 强制要求:\n
  41. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  42. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  43. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  44. 普通要求:\n
  45. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  46. 2.<分集剧本>的要求如下:
  47.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  48.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  49.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  50.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  51. \n\n
  52. 示例如下:\n
  53. ###剧本名:西昆仑
  54. ###故事梗概
  55. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  56. ###剧本亮点
  57. 亮点1:绝境奇药,生死一线
  58. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  59. 亮点2:结拜兄妹,化解尴尬
  60. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  61. 亮点3:纤发夺命,情愫暗涌
  62. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  63. ###人物关系
  64. 阿雪与梁萧之间存在兄妹之情。
  65. ###核心矛盾
  66. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  67. ###主体列表
  68. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  69. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  70. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  71. 阴阳球:天地异宝,能化生精气,救人于危难。
  72. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  73. ###美术风格
  74. 基础画风风格词:厚涂古风
  75. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  76. ###场景列表
  77. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  78. ###分集剧本
  79. ##分集01
  80. 第1集: 第一集的标题
  81. 场景描述:地点、时间、场景
  82. 运镜:固定近距离
  83. 出场角色:男主、女主
  84. 台词内容:
  85. 女主: 女主对话
  86. 男主:男主对话
  87. 女主: 女主对话
  88. 男主: 男主对话
  89. ##分集02
  90. 第2集: 第二集的标题
  91. 场景描述:地点、时间、场景
  92. 运镜:固定近距离
  93. 出场角色:男主、女主
  94. 台词内容:
  95. 女主: 女主对话
  96. 男主:男主对话
  97. 女主: 女主对话
  98. 男主: 男主对话"
  99. ];
  100. }
  101. /**
  102. * 通用文生文方法 - 支持多模型流式输出和图片输入
  103. *
  104. * @param array $data 请求参数
  105. * @return \Generator 返回生成器,用于流式输出
  106. */
  107. public function generateText($data) {
  108. // 获取请求参数
  109. $model = getProp($data, 'model', 'deepseek-v3-2-251201'); // 默认使用deepseek-v3
  110. $messages = getProp($data, 'messages', []);
  111. $systemPrompt = getProp($data, 'system_prompt', '');
  112. $prompt = getProp($data, 'prompt', '');
  113. $images = getProp($data, 'images', []); // 支持多张图片
  114. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  115. // 如果没有提供messages,则根据system_prompt、content和images构建
  116. if (empty($messages)) {
  117. $messages = [];
  118. // 添加系统提示词
  119. if (!empty($systemPrompt)) {
  120. $messages[] = [
  121. 'role' => 'system',
  122. 'content' => $systemPrompt
  123. ];
  124. }
  125. // 构建用户消息内容(支持文本+图片)
  126. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  127. $userMessage = [
  128. 'role' => 'user',
  129. 'content' => []
  130. ];
  131. // 添加文本内容
  132. if (!empty($prompt)) {
  133. $userMessage['content'][] = [
  134. 'type' => 'text',
  135. 'text' => $prompt
  136. ];
  137. }
  138. // 处理上传的图片文件
  139. if (!empty($images)) {
  140. if (!is_array($images)) {
  141. $images = [$images];
  142. }
  143. foreach ($images as $image) {
  144. $imageBase64 = $this->processImageToBase64($image);
  145. if ($imageBase64) {
  146. $userMessage['content'][] = [
  147. 'type' => 'image_url',
  148. 'image_url' => [
  149. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  150. ]
  151. ];
  152. }
  153. }
  154. }
  155. // 处理图片URL
  156. if (!empty($imageUrls)) {
  157. if (!is_array($imageUrls)) {
  158. $imageUrls = [$imageUrls];
  159. }
  160. foreach ($imageUrls as $url) {
  161. if (!empty($url)) {
  162. $userMessage['content'][] = [
  163. 'type' => 'image_url',
  164. 'image_url' => [
  165. 'url' => $url
  166. ]
  167. ];
  168. }
  169. }
  170. }
  171. // 如果只有文本内容,简化为字符串格式
  172. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  173. $userMessage['content'] = $userMessage['content'][0]['text'];
  174. }
  175. $messages[] = $userMessage;
  176. }
  177. }
  178. // 验证messages不为空
  179. if (empty($messages)) {
  180. Utils::throwError('20003:请提供有效的对话内容');
  181. }
  182. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  183. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  184. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  185. if ($model === 'deepseek-chat') {
  186. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  187. $model = 'deepseek-v4-flash';
  188. $thinkingMode = 'disabled';
  189. } elseif ($model === 'deepseek-reasoner') {
  190. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  191. $model = 'deepseek-v4-flash';
  192. $thinkingMode = 'enabled';
  193. }
  194. // 构建请求参数
  195. $post_data = [
  196. 'model' => $model,
  197. 'messages' => $messages,
  198. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  199. 'temperature' => getProp($data, 'temperature', 1),
  200. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  201. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  202. 'thinking' => ['type' => $thinkingMode],
  203. 'stream' => true // 启用流式输出
  204. ];
  205. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  206. // 添加可选参数
  207. if (isset($data['top_p'])) {
  208. $post_data['top_p'] = $data['top_p'];
  209. }
  210. if (isset($data['response_format'])) {
  211. $post_data['response_format'] = $data['response_format'];
  212. }
  213. dLog('deepseek')->info('通用文生文请求参数', ['model' => $model, 'thinking' => $thinkingMode, 'messages_count' => count($messages)]);
  214. // 根据模型类型选择调用方法
  215. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  216. // DeepSeek 官方模型使用 DeepSeek API
  217. return $this->deepSeekStreamResponse($post_data);
  218. } else if (in_array($model, $this->valid_text_models)) {
  219. // 火山引擎支持的模型使用火山引擎 API
  220. return $this->volcEngineChatCompletion($post_data);
  221. } else {
  222. Utils::throwError('20003:不支持的模型: ' . $model);
  223. }
  224. }
  225. /**
  226. * 处理图片转换为base64
  227. *
  228. * @param mixed $image 图片文件对象或文件路径
  229. * @return string|null base64编码的图片数据
  230. */
  231. private function processImageToBase64($image) {
  232. try {
  233. // 获取文件路径
  234. if (is_string($image)) {
  235. $filePath = $image;
  236. } else {
  237. // Laravel UploadedFile 对象
  238. $filePath = $image->getRealPath();
  239. }
  240. if (!file_exists($filePath)) {
  241. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  242. return null;
  243. }
  244. // 验证是否为图片文件
  245. $imageInfo = @getimagesize($filePath);
  246. if ($imageInfo === false) {
  247. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  248. return null;
  249. }
  250. // 读取图片并转换为base64
  251. $imageData = file_get_contents($filePath);
  252. $base64Image = base64_encode($imageData);
  253. dLog('deepseek')->info('图片转换成功', [
  254. 'size' => strlen($imageData),
  255. 'type' => $imageInfo['mime']
  256. ]);
  257. return $base64Image;
  258. } catch (\Exception $e) {
  259. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  260. return null;
  261. }
  262. }
  263. private function getArtStylePromptMappings(): array
  264. {
  265. return [
  266. '唯美真人风格' => [
  267. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  268. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  269. 2. 色彩色调
  270. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  271. 3. 画质精度
  272. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  273. 4. 画面观感
  274. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  275. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  276. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  277. ],
  278. '真人古风风格' => [
  279. 'aliases' => ['真人古风风格', '真人古风'],
  280. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  281. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  282. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  283. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  284. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  285. ],
  286. '日系动漫风格' => [
  287. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  288. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  289. 正向提示词(中文)
  290. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  291. 必须遵守规则
  292. • 全程保持日系动漫风格,不混入其他画风
  293. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  294. • 画面适配所选画面比例,构图居中,主体突出
  295. • 线条干净、色彩统一,不杂乱、不突兀
  296. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  297. ],
  298. '国漫风格' => [
  299. 'aliases' => ['国漫风格', '国漫'],
  300. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  301. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  302. 必须遵守规则
  303. • 严格保持国漫画风,不串风格、不混画风
  304. • 角色形象统一,不随意改变五官、身材、服饰
  305. • 画面构图稳定,适合漫剧叙事展示
  306. • 色调统一,不出现脏色、杂色
  307. 禁止/避免词汇
  308. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  309. ],
  310. 'Q版卡通风格' => [
  311. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  312. 'prompt' => "风格说明
  313. 头大身小,造型可爱圆润,简约干净
  314. 正向提示词(中文)
  315. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  316. 必须遵守规则
  317. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  318. • 角色造型统一,表情可爱,不诡异
  319. • 画面简洁清爽,无多余复杂元素
  320. • 色彩明亮柔和,不刺眼
  321. 禁止/避免词汇
  322. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  323. ],
  324. '简约扁平风格' => [
  325. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  326. 'prompt' => "风格说明
  327. 色块简洁、无复杂渐变,现代极简风
  328. 正向提示词(中文)
  329. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  330. 必须遵守规则
  331. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  332. • 构图简洁,主体突出,无多余装饰
  333. • 色彩统一、干净,不杂乱
  334. 禁止/避免词汇
  335. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  336. ],
  337. '武侠风格' => [
  338. 'aliases' => ['武侠风格', '武侠'],
  339. 'prompt' => "风格说明
  340. 江湖气息,线条硬朗,动作感强
  341. 正向提示词(中文)
  342. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  343. 必须遵守规则
  344. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  345. • 角色形象、服饰、身材比例统一
  346. • 画面动作自然,不扭曲、不畸形
  347. 禁止/避免词汇
  348. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  349. ],
  350. '古风仙侠风格' => [
  351. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  352. 'prompt' => "风格说明
  353. 飘逸汉服、云雾仙气、唯美空灵
  354. 正向提示词(中文)
  355. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  356. 必须遵守规则
  357. • 保持古风仙侠统一画风,不混入现代、科幻元素
  358. • 角色服饰、发型、形象前后一致
  359. • 场景仙气飘逸,色调清雅统一
  360. • 画面唯美柔和,不阴暗、不诡异
  361. 禁止/避免词汇
  362. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  363. ],
  364. '新中式水墨风格' => [
  365. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  366. 'prompt' => "风格说明
  367. 淡墨渲染,毛笔笔触,留白意境
  368. 正向提示词(中文)
  369. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  370. 必须遵守规则
  371. • 严格保持水墨质感,不混入厚涂、写实、卡通
  372. • 色调淡雅统一,不浓艳杂乱
  373. • 画面干净有意境,不堆砌元素
  374. 禁止/避免词汇
  375. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  376. ],
  377. '写实插画风格' => [
  378. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  379. 'prompt' => "风格说明
  380. 接近真人比例,光影真实,质感细腻
  381. 正向提示词(中文)
  382. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  383. 必须遵守规则
  384. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  385. • 角色五官、身材、服饰高度统一
  386. • 画面清晰、光影自然、不扭曲
  387. 禁止/避免词汇
  388. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  389. ],
  390. '3D卡通风格' => [
  391. 'aliases' => ['3D卡通风格', '3D卡通'],
  392. 'prompt' => "风格说明
  393. 3D建模质感,柔和渲染,圆润可爱
  394. 正向提示词(中文)
  395. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  396. 必须遵守规则
  397. • 保持3D卡通统一质感,不出现2D杂乱线条
  398. • 角色模型、比例、形象前后一致
  399. • 画面干净,不模糊、不穿模
  400. 禁止/避免词汇
  401. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  402. ],
  403. '条漫风格' => [
  404. 'aliases' => ['条漫风格', '条漫'],
  405. 'prompt' => "风格说明
  406. 纵向分镜,上下滑动阅读,轻量化
  407. 正向提示词(中文)
  408. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  409. 必须遵守规则
  410. • 保持条漫纵向阅读逻辑,构图简洁
  411. • 画风统一,不混写实、3D、水墨
  412. • 画面干净,不杂乱
  413. 禁止/避免词汇
  414. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  415. ],
  416. '赛博朋克风格' => [
  417. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  418. 'prompt' => "风格说明
  419. 霓虹灯光、未来都市、暗色调、科技机械
  420. 正向提示词(中文)
  421. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  422. 必须遵守规则
  423. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  424. • 色调以暗调+霓虹为主,色彩统一
  425. • 画面科技感强,不杂乱
  426. 禁止/避免词汇
  427. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  428. ],
  429. '暗黑悬疑风格' => [
  430. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  431. 'prompt' => "风格说明
  432. 低饱和、冷色调、阴影重、神秘压抑
  433. 正向提示词(中文)
  434. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  435. 必须遵守规则
  436. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  437. • 画面氛围压抑神秘,但不低俗、不血腥
  438. • 角色形象统一,不崩坏
  439. 禁止/避免词汇
  440. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  441. ],
  442. '治愈清新风格' => [
  443. 'aliases' => ['治愈清新风格', '治愈清新'],
  444. 'prompt' => "风格说明
  445. 马卡龙色系、柔光、温暖干净
  446. 正向提示词(中文)
  447. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  448. 必须遵守规则
  449. • 保持治愈清新统一色调,不阴暗、不诡异
  450. • 画面柔和干净,无杂乱元素
  451. • 角色形象柔和可爱,不狰狞
  452. 禁止/避免词汇
  453. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  454. ],
  455. ];
  456. }
  457. public function getArtStylePromptByInput($inputArtStyle): string
  458. {
  459. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  460. if ($normalizedInput === '') {
  461. return '';
  462. }
  463. foreach ($this->getArtStylePromptMappings() as $mapping) {
  464. foreach ($mapping['aliases'] as $alias) {
  465. $normalizedAlias = $this->normalizeArtStyleInput($alias);
  466. if ($normalizedAlias === '') {
  467. continue;
  468. }
  469. if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  470. return $mapping['prompt'];
  471. }
  472. }
  473. }
  474. return '';
  475. }
  476. private function normalizeArtStyleInput($value): string
  477. {
  478. $value = trim((string)$value);
  479. if ($value === '') {
  480. return '';
  481. }
  482. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  483. return mb_strtolower($value, 'UTF-8');
  484. }
  485. private function replaceArtStyleSection(string $content, string $artStyle): string
  486. {
  487. if ($content === '' || $artStyle === '') {
  488. return $content;
  489. }
  490. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  491. if (!preg_match($pattern, $content)) {
  492. return $content;
  493. }
  494. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  495. }
  496. /**
  497. * DeepSeek流式输出处理方法
  498. *
  499. * @param array $post_data DeepSeek API请求参数
  500. * @return \Generator 返回生成器,用于流式输出
  501. */
  502. private function deepSeekStreamResponse($post_data) {
  503. $client = new Client(['timeout' => 1200, 'verify' => false]);
  504. $response = $client->post($this->url, [
  505. 'json' => $post_data,
  506. 'headers' => $this->headers,
  507. 'stream' => true // 启用流式响应
  508. ]);
  509. $body = $response->getBody();
  510. $fullContent = '';
  511. $fullReasoningContent = '';
  512. $usage = [];
  513. $buffer = '';
  514. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  515. // 逐行读取流式响应
  516. while (!$body->eof()) {
  517. $chunk = $body->read(1024); // 每次读取 1KB
  518. $buffer .= $chunk;
  519. // 按行分割
  520. $lines = explode("\n", $buffer);
  521. // 保留最后一个不完整的行
  522. $buffer = array_pop($lines);
  523. foreach ($lines as $line) {
  524. $line = trim($line);
  525. // 跳过空行
  526. if (empty($line)) {
  527. continue;
  528. }
  529. // 检查是否是 SSE 数据行
  530. if (strpos($line, 'data: ') !== 0) {
  531. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  532. continue;
  533. }
  534. $data = substr($line, 6); // 移除 "data: " 前缀
  535. if ($data === '[DONE]') {
  536. dLog('deepseek')->info('收到结束标记');
  537. break 2; // 跳出两层循环
  538. }
  539. try {
  540. $json = json_decode($data, true);
  541. if (json_last_error() !== JSON_ERROR_NONE) {
  542. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  543. continue;
  544. }
  545. if (isset($json['choices'][0]['delta'])) {
  546. $delta = $json['choices'][0]['delta'];
  547. // 处理思维链内容(仅 deepseek-reasoner 模型)
  548. if (isset($delta['reasoning_content'])) {
  549. $fullReasoningContent .= $delta['reasoning_content'];
  550. yield [
  551. 'type' => 'reasoning',
  552. 'content' => $delta['reasoning_content'],
  553. 'full_reasoning' => $fullReasoningContent
  554. ];
  555. }
  556. // 处理最终回答内容
  557. if (isset($delta['content'])) {
  558. $fullContent .= $delta['content'];
  559. yield [
  560. 'type' => 'content',
  561. 'content' => $delta['content'],
  562. ];
  563. }
  564. }
  565. // 获取使用统计信息
  566. if (isset($json['usage'])) {
  567. $usage = $json['usage'];
  568. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  569. }
  570. } catch (\Exception $e) {
  571. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  572. continue;
  573. }
  574. }
  575. }
  576. dLog('deepseek')->info('流式读取完成', [
  577. 'content_length' => strlen($fullContent),
  578. 'reasoning_length' => strlen($fullReasoningContent)
  579. ]);
  580. yield [
  581. 'type' => 'done',
  582. 'full_content' => $fullContent,
  583. 'full_reasoning' => $fullReasoningContent,
  584. 'usage' => $usage
  585. ];
  586. }
  587. // 与推理模型对话
  588. public function chatWithReasoner($data) {
  589. $content = getProp($data, 'content');
  590. $model = getProp($data, 'model', 'r1');
  591. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  592. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  593. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  594. if ($model == 'r1') {
  595. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  596. $thinkingMode = 'disabled';
  597. } else {
  598. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  599. $thinkingMode = 'disabled';
  600. }
  601. // 获取可选情感(根据音色可支持情感选)
  602. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  603. $emotion_list = [];
  604. foreach ($timbre_emotion as $emotion) {
  605. $tmp = explode(',', $emotion);
  606. $emotion_list = array_merge($emotion_list, $tmp);
  607. }
  608. $emotion_list = array_unique($emotion_list);
  609. $emotion_str = implode('、', $emotion_list);
  610. // // 获取可选情感
  611. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  612. // $emotion_str = implode('、', $emotion_list);
  613. // 是否启用情感
  614. $enable_emotion = getProp($data, 'enable_emotion', 0);
  615. if ($enable_emotion) {
  616. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  617. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  618. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  619. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  620. }else {
  621. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  622. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  623. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  624. }
  625. $messages = [
  626. [
  627. 'role' => 'system',
  628. 'content' => $sys_content
  629. ],
  630. [
  631. 'role' => 'user',
  632. 'content' => $content
  633. ]
  634. ];
  635. $post_data = [
  636. 'model' => $model,
  637. 'messages' => $messages,
  638. // 'max_tokens' => 8192,
  639. 'temperature' => 1,
  640. 'frequency_penalty' => 0,
  641. 'presence_penalty' => 0,
  642. 'thinking' => ['type' => $thinkingMode],
  643. 'response_format' => [
  644. 'type' => 'text'
  645. ],
  646. 'stream' => false
  647. ];
  648. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  649. // 根据模型类型选择调用方法
  650. $fullContent = '';
  651. $usage = [];
  652. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  653. // DeepSeek 官方模型使用 DeepSeek API
  654. $chatResult = $this->chatOnly($post_data);
  655. } else {
  656. // 其他模型使用火山引擎API
  657. $chatResult = $this->volcEngineChatCompletion($post_data);
  658. }
  659. if (is_array($chatResult)) {
  660. $fullContent = $chatResult['fullContent'];
  661. $usage = $chatResult['usage'];
  662. }
  663. // 处理获取到的剧本数据
  664. $script_content = handleScriptWords($fullContent, $enable_emotion);
  665. $result = [
  666. 'origin_content' => $fullContent,
  667. 'roles' => getProp($script_content, 'roles'),
  668. 'words' => getProp($script_content, 'words'),
  669. ];
  670. return $result;
  671. }
  672. public function resetParagraphAudio($data) {
  673. $bid = getProp($data, 'bid');
  674. $cid = getProp($data, 'cid');
  675. $version_id = getProp($data, 'version_id');
  676. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  677. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  678. 'generate_status' => '待制作',
  679. 'updated_at' => date('Y-m-d H:i:s')
  680. ]);
  681. }
  682. public function saveParagraphAudio($data) {
  683. $bid = getProp($data, 'bid');
  684. $cid = getProp($data, 'cid');
  685. $version_id = getProp($data, 'version_id');
  686. $sequence = getProp($data, 'sequence');
  687. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  688. // 获取所有情感
  689. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  690. $emotion_list = array_flip($emotion_list);
  691. // 获取音色支持情感
  692. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  693. $timbre_emotion = explode(',', $timbre_emotion);
  694. $emotion = getProp($data, 'emotion');
  695. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  696. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  697. $list = [
  698. 'bid' => $bid,
  699. 'cid' => $cid,
  700. 'version_id' => $version_id,
  701. 'sequence' => $sequence,
  702. 'role' => getProp($data, 'role'),
  703. 'gender' => getProp($data, 'gender'),
  704. 'text' => trim(getProp($data, 'text')),
  705. 'emotion' => $emotion,
  706. 'emotion_type' => $emotion_type,
  707. 'voice_type' => getProp($data, 'voice_type'),
  708. 'voice_name' => getProp($data, 'voice_name'),
  709. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  710. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  711. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  712. 'pitch' => getProp($data, 'pitch', 0),
  713. // 'paragraph_audio_url' => '',
  714. 'generate_status' => '制作中',
  715. 'error_msg' => '',
  716. 'updated_at' => date('Y-m-d H:i:s')
  717. ];
  718. $continue = false;
  719. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  720. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  721. $list['generate_status'] = '制作成功';
  722. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  723. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  724. $continue = true;
  725. }
  726. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  727. if ($id) {
  728. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  729. }else {
  730. $list['created_at'] = date('Y-m-d H:i:s');
  731. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  732. $boolen = $id ? true : false;
  733. }
  734. // 如果更新成功则加入查询队列
  735. if ($boolen) {
  736. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  737. Redis::sadd($redis_key, $id);
  738. }
  739. if ($boolen && !$continue) {
  740. $boolen = false;
  741. $client = new Client(['timeout' => 300, 'verify' => false]);
  742. // 根据ID通过API通知合成音频
  743. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  744. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  745. $response = $result->getBody()->getContents();
  746. $response_arr = json_decode($response, true);
  747. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  748. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  749. Log::info('通知火山生成段落音频失败: '.$error_msg);
  750. Utils::throwError('20003:通知火山生成段落音频失败');
  751. }
  752. $boolen = true;
  753. }
  754. return $boolen;
  755. }
  756. public function insertAudioEffect($data) {
  757. $audio_id = getProp($data, 'audio_id');
  758. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  759. $bid = getProp($chapter_audio, 'bid');
  760. $version_id = getProp($chapter_audio, 'version_id');
  761. $cid = getProp($chapter_audio, 'cid');
  762. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  763. $audio_effect_json = getProp($data, 'audio_effect_json');
  764. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  765. try {
  766. DB::beginTransaction();
  767. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  768. if (!$count) {
  769. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  770. }else {
  771. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  772. }
  773. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  774. 'audio_effect_status' => '添加中',
  775. 'audio_effect_json' => $audio_effect_json,
  776. 'updated_at' => date('Y-m-d H:i:s')
  777. ]);
  778. if (!$boolen1) {
  779. DB::rollBack();
  780. Utils::throwError('20003:更新生成数据失败');
  781. }
  782. $id = DB::table('mp_audio_tasks')->insertGetId([
  783. 'audio_id' => $audio_id,
  784. 'generate_status' => '执行中',
  785. 'generate_json' => json_encode([], 256),
  786. 'bid' => $bid,
  787. 'book_name' => getProp($chapter_audio, 'book_name'),
  788. 'version_id' => $version_id,
  789. 'version_name' => getProp($chapter_audio, 'version_name'),
  790. 'cid' => $cid,
  791. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  792. 'task_name' => $task_name,
  793. 'created_at' => date('Y-m-d H:i:s'),
  794. 'updated_at' => date('Y-m-d H:i:s')
  795. ]);
  796. if (!$id) {
  797. DB::rollBack();
  798. Utils::throwError('20003:创建任务失败');
  799. }
  800. }catch (\Exception $e) {
  801. DB::rollBack();
  802. Utils::throwError('20003:'.$e->getMessage());
  803. }
  804. DB::commit();
  805. $client = new Client(['timeout' => 300, 'verify' => false]);
  806. // 根据ID通过API通知合成音频
  807. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  808. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  809. $response = $result->getBody()->getContents();
  810. $response_arr = json_decode($response, true);
  811. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  812. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  813. Log::info('通知火山插入音效失败: '.$error_msg);
  814. Utils::throwError('20003:通知火山插入音效失败');
  815. }
  816. return true;
  817. }
  818. public function insertBgm($data) {
  819. $audio_id = getProp($data, 'audio_id');
  820. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  821. $bid = getProp($chapter_audio, 'bid');
  822. $version_id = getProp($chapter_audio, 'version_id');
  823. $cid = getProp($chapter_audio, 'cid');
  824. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  825. $bgm_json = getProp($data, 'bgm_json');
  826. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  827. if (!$bgm_json) {
  828. $bgm_json = getProp($data, 'audio_effect_json');
  829. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  830. }
  831. try {
  832. DB::beginTransaction();
  833. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  834. if (!$count) {
  835. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  836. }else {
  837. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  838. }
  839. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  840. 'bgm_status' => '添加中',
  841. 'bgm_json' => $bgm_json,
  842. 'updated_at' => date('Y-m-d H:i:s')
  843. ]);
  844. if (!$boolen1) {
  845. DB::rollBack();
  846. Utils::throwError('20003:更新生成数据失败');
  847. }
  848. $id = DB::table('mp_audio_tasks')->insertGetId([
  849. 'audio_id' => $audio_id,
  850. 'generate_status' => '执行中',
  851. 'generate_json' => json_encode([], 256),
  852. 'bid' => $bid,
  853. 'book_name' => getProp($chapter_audio, 'book_name'),
  854. 'version_id' => $version_id,
  855. 'version_name' => getProp($chapter_audio, 'version_name'),
  856. 'cid' => $cid,
  857. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  858. 'task_name' => $task_name,
  859. 'created_at' => date('Y-m-d H:i:s'),
  860. 'updated_at' => date('Y-m-d H:i:s')
  861. ]);
  862. if (!$id) {
  863. DB::rollBack();
  864. Utils::throwError('20003:创建任务失败');
  865. }
  866. }catch (\Exception $e) {
  867. DB::rollBack();
  868. Utils::throwError('20003:'.$e->getMessage());
  869. }
  870. DB::commit();
  871. $client = new Client(['timeout' => 300, 'verify' => false]);
  872. // 根据ID通过API通知合成音频
  873. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  874. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  875. $response = $result->getBody()->getContents();
  876. $response_arr = json_decode($response, true);
  877. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  878. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  879. Log::info('通知火山插入bgm失败: '.$error_msg);
  880. Utils::throwError('20003:通知火山插入bgm失败');
  881. }
  882. return true;
  883. }
  884. public function getParagraphAudios($data) {
  885. $bid = getProp($data, 'bid');
  886. $cid = getProp($data, 'cid');
  887. $version_id = getProp($data, 'version_id');
  888. $sequence = getProp($data, 'sequence');
  889. // 获取已生成的音频
  890. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  891. if ($sequence) $query->where('sequence', $sequence);
  892. $paragraph_audios = $query->orderBy('sequence')->get();
  893. $result = [];
  894. foreach($paragraph_audios as $item) {
  895. $result[] = [
  896. 'sequence' => getProp($item, 'sequence'),
  897. 'role' => getProp($item, 'role'),
  898. 'gender' => getProp($item, 'gender'),
  899. 'text' => trim(getProp($item, 'text')),
  900. 'emotion' => getProp($item, 'emotion'),
  901. 'emotion_type' => getProp($item, 'emotion_type'),
  902. 'voice_type' => getProp($item, 'voice_type'),
  903. 'voice_name' => getProp($item, 'voice_name'),
  904. 'speed_ratio' => getProp($item, 'speed_ratio'),
  905. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  906. 'emotion_scale' => getProp($item, 'emotion_scale'),
  907. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  908. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  909. ];
  910. }
  911. return $result;
  912. }
  913. // 新增合成任务
  914. public function addGenerateTask($data) {
  915. $bid = getProp($data, 'bid');
  916. $cid = getProp($data, 'cid');
  917. $version_id = getProp($data, 'version_id');
  918. $generate_json = getProp($data, 'generate_json');
  919. // 获取已生成的音频
  920. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  921. $paragraph_list = [];
  922. foreach($paragraph_audios as $item) {
  923. $paragraph_list[getProp($item, 'sequence')] = [
  924. 'role' => getProp($item, 'role'),
  925. 'gender' => getProp($item, 'gender'),
  926. 'text' => trim(getProp($item, 'text')),
  927. 'emotion' => getProp($item, 'emotion'),
  928. 'emotion_type' => getProp($item, 'emotion_type'),
  929. 'voice_type' => getProp($item, 'voice_type'),
  930. 'voice_name' => getProp($item, 'voice_name'),
  931. 'speed_ratio' => getProp($item, 'speed_ratio'),
  932. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  933. 'emotion_scale' => getProp($item, 'emotion_scale'),
  934. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  935. ];
  936. }
  937. // 更新角色-音色信息
  938. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  939. $existed_role_info = json_decode($existed_role_info, true);
  940. if (!$existed_role_info) $existed_role_info = [];
  941. // 获取情感信息
  942. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  943. $emotion_list = array_flip($emotion_list);
  944. // 获取音色对应情感组
  945. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  946. $timbre_emotion_list = [];
  947. foreach($timbre_emotions as $item) {
  948. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  949. }
  950. // 构造生成音频的json
  951. $words = json_decode($generate_json, true);
  952. // 最终合成前的参数组
  953. $mp_chapter_paragraph_audios = [];
  954. $sequence = 1;
  955. $complete_paragraph_sequences = [];
  956. foreach($words as &$word) {
  957. 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:参数格式有误');
  958. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  959. $role = getProp($word, 'role');
  960. $word['gender'] = (int)$word['gender'];
  961. // 判断音色对应情感是否支持,不支持则调整为中性
  962. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  963. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  964. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  965. if (isset($emotion_list[getProp($word, 'emotion')])) {
  966. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  967. }else {
  968. $word['emotion'] = '中性';
  969. $word['emotion_type'] = 'neutral';
  970. }
  971. $existed_role_info[$role] = [
  972. 'timbre_type' => $word['voice_type'],
  973. 'timbre_name' => $word['voice_name'],
  974. 'emotion' => $word['emotion'],
  975. 'emotion_type' => $word['emotion_type'],
  976. 'speed_ratio' => $word['speed_ratio'],
  977. 'loudness_ratio'=> $word['loudness_ratio'],
  978. 'emotion_scale' => $word['emotion_scale'],
  979. 'pitch' => $word['pitch']
  980. ];
  981. $word['paragraph_audio_url'] = '';
  982. // 判断生成参数是否相同,相同则直接使用已生成的音频
  983. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  984. // 如果音频存在并且参数都未改变则使用已生成的音频
  985. if (getProp($paragraph, 'paragraph_audio_url')) {
  986. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  987. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  988. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  989. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  990. // {
  991. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  992. // }
  993. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  994. }
  995. $tmp = $word;
  996. // 组装章节分句音频数据
  997. // $tmp['sequence'] = getProp($word, 'sequence');
  998. // $tmp['text'] = getProp($word, 'text');
  999. // $tmp['emotion'] = getProp($word, 'emotion');
  1000. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  1001. // $tmp['voice_name'] = getProp($word, 'voice_name');
  1002. // $tmp['voice_type'] = getProp($word, 'voice_type');
  1003. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  1004. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  1005. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  1006. $tmp['bid'] = $bid;
  1007. $tmp['version_id'] = $version_id;
  1008. $tmp['cid'] = $cid;
  1009. $tmp['sequence'] = $sequence;
  1010. $tmp['created_at'] = date('Y-m-d H:i:s');
  1011. $tmp['updated_at'] = date('Y-m-d H:i:s');
  1012. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  1013. $mp_chapter_paragraph_audios[] = $tmp;
  1014. $complete_paragraph_sequences[] = $sequence;
  1015. $sequence++;
  1016. }
  1017. $generate_json = json_encode($words, 256);
  1018. // 判断是否有未生成字幕的段落
  1019. $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();
  1020. if ($no_subtitle_sequences) {
  1021. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  1022. }
  1023. try {
  1024. DB::beginTransaction();
  1025. $role_info = json_encode($existed_role_info, 256);
  1026. $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')]);
  1027. if (!$boolen) {
  1028. DB::rollBack();
  1029. Utils::throwError('20003:更新角色信息失败');
  1030. }
  1031. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  1032. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  1033. if (!$count) {
  1034. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1035. }else {
  1036. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1037. }
  1038. $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')]);
  1039. if (!$boolen1) {
  1040. DB::rollBack();
  1041. Utils::throwError('20003:更新生成数据失败');
  1042. }
  1043. $id = DB::table('mp_audio_tasks')->insertGetId([
  1044. 'audio_id' => getProp($chapter_audio, 'id'),
  1045. 'generate_status' => '执行中',
  1046. 'generate_json' => $generate_json,
  1047. 'bid' => $bid,
  1048. 'book_name' => getProp($chapter_audio, 'book_name'),
  1049. 'version_id' => $version_id,
  1050. 'version_name' => getProp($chapter_audio, 'version_name'),
  1051. 'cid' => $cid,
  1052. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1053. 'task_name' => $task_name,
  1054. 'created_at' => date('Y-m-d H:i:s'),
  1055. 'updated_at' => date('Y-m-d H:i:s')
  1056. ]);
  1057. if (!$id) {
  1058. DB::rollBack();
  1059. Utils::throwError('20003:创建任务失败');
  1060. }
  1061. // 删除不在段落序号范围内的其他数据
  1062. if ($complete_paragraph_sequences) {
  1063. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  1064. }
  1065. // // 删除章节分句音频数据并重新插入
  1066. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  1067. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  1068. // if (!$boolen3) {
  1069. // DB::rollBack();
  1070. // Utils::throwError('20003:更新章节分句音频失败');
  1071. // }
  1072. } catch (\Exception $e) {
  1073. DB::rollBack();
  1074. Utils::throwError('20003:'.$e->getMessage());
  1075. }
  1076. DB::commit();
  1077. // 通知火山生成音频
  1078. $client = new Client(['timeout' => 300, 'verify' => false]);
  1079. // 根据ID通过API通知合成音频
  1080. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  1081. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  1082. $response = $result->getBody()->getContents();
  1083. $response_arr = json_decode($response, true);
  1084. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1085. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1086. Log::info('通知火山生成音频失败: '.$error_msg);
  1087. Utils::throwError('20003:通知火山生成音频失败');
  1088. }
  1089. return true;
  1090. }
  1091. public function timbreList($data) {
  1092. $gender = getProp($data, 'gender');
  1093. $timbre_name = getProp($data, 'voice_name');
  1094. $category_id = getProp($data, 'category_id');
  1095. $age_stage = getProp($data, 'age_stage');
  1096. $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');
  1097. if ($gender) {
  1098. $query->where('gender', $gender);
  1099. }
  1100. if ($timbre_name) {
  1101. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  1102. }
  1103. if ($category_id) {
  1104. $query->where(function ($query) use ($category_id) {
  1105. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  1106. });
  1107. }
  1108. if ($age_stage) {
  1109. $query->where('age_stage', $age_stage);
  1110. }
  1111. $list = $query->get()->map(function ($value) {
  1112. $value = (array)$value;
  1113. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  1114. return $value;
  1115. })->toArray();
  1116. return $list;
  1117. }
  1118. // 生成火山临时token
  1119. public function setStsToken() {
  1120. // ************* 配置参数 *************
  1121. $method = 'GET';
  1122. $service = 'sts';
  1123. $host = 'open.volcengineapi.com';
  1124. $region = env('VOLC_REGION');
  1125. $endpoint = 'https://open.volcengineapi.com';
  1126. // $endpoint = 'https://tos-cn-beijing.volces.com';
  1127. $access_key = env('VOLC_AK');
  1128. $secret_key = env('VOLC_SK');
  1129. // 获取缓存中的token,如果没有则请求接口
  1130. $token = Redis::get('volc_sts_token');
  1131. if (!$token) {
  1132. // 查询参数
  1133. $query_parameters = [
  1134. 'Action' => 'AssumeRole',
  1135. 'RoleSessionName' => 'user@zw',
  1136. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  1137. 'Version' => '2018-01-01'
  1138. ];
  1139. // 生成URL编码的查询字符串
  1140. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  1141. // 获取签名头信息
  1142. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  1143. // 构建完整URL
  1144. $request_url = $endpoint . '?' . $request_parameters;
  1145. $client = new Client(['verify' => false]);
  1146. $response = $client->get($request_url, ['headers' => $headers]);
  1147. $response_arr = json_decode($response->getBody()->getContents(), true);
  1148. $result = [
  1149. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  1150. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  1151. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  1152. 'Region' => env('VOLC_REGION'),
  1153. 'Endpoint' => env('VOLC_END_POINT'),
  1154. 'Bucket' => env('VOLC_BUCKET'),
  1155. ];
  1156. // 缓存token
  1157. Redis::setex('volc_sts_token', 3000, json_encode($result));
  1158. return $result;
  1159. } else {
  1160. return json_decode($token, true);
  1161. }
  1162. // $response = $response['Response'];
  1163. // $access_key = $response['Credentials']['AccessKeyId'];
  1164. // $secret_key = $response['Credentials']['AccessKeySecret'];
  1165. // $security_token = $response['Credentials']['SecurityToken'];
  1166. // $expiration = $response['Credentials']['Expiration'];
  1167. // dd($response_arr);
  1168. }
  1169. public function emotionGroups($data) {
  1170. $id = getProp($data, 'group_id');
  1171. $group_name = getProp($data, 'group_name');
  1172. $voice_type = getProp($data, 'voice_type');
  1173. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  1174. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  1175. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  1176. if ($group_name) {
  1177. $query->where('group_name', 'like', "%{$group_name}%");
  1178. }
  1179. if ($id) {
  1180. $query->where('id', $id);
  1181. }
  1182. if ($voice_type) {
  1183. $query->where('voice_type', $voice_type);
  1184. }
  1185. return $query->orderBy('id')->get()->map(function ($value) {
  1186. return (array)$value;
  1187. })->toArray();
  1188. }
  1189. private function sign($key, $msg) {
  1190. return hash_hmac('sha256', $msg, $key, true);
  1191. }
  1192. // 生成签名密钥
  1193. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  1194. $kDate = $this->sign($key, $dateStamp);
  1195. $kRegion = $this->sign($kDate, $regionName);
  1196. $kService = $this->sign($kRegion, $serviceName);
  1197. $kSigning = $this->sign($kService, 'request');
  1198. return $kSigning;
  1199. }
  1200. // 获取签名头信息
  1201. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  1202. $contenttype = 'application/x-www-form-urlencoded';
  1203. $accept = 'application/json';
  1204. // 获取当前UTC时间
  1205. $t = new DateTime('now', new DateTimeZone('UTC'));
  1206. $xdate = $t->format('Ymd\THis\Z');
  1207. $datestamp = $t->format('Ymd');
  1208. // 1. 拼接规范请求串
  1209. $canonical_uri = '/';
  1210. $canonical_querystring = $request_parameters;
  1211. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  1212. $signed_headers = 'content-type;host;x-date';
  1213. // 空请求体的SHA256哈希
  1214. $payload_hash = hash('sha256', '');
  1215. $canonical_request = implode("\n", [
  1216. $method,
  1217. $canonical_uri,
  1218. $canonical_querystring,
  1219. $canonical_headers,
  1220. $signed_headers,
  1221. $payload_hash
  1222. ]);
  1223. // 2. 拼接待签名字符串
  1224. $algorithm = 'HMAC-SHA256';
  1225. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  1226. $hashed_canonical_request = hash('sha256', $canonical_request);
  1227. $string_to_sign = implode("\n", [
  1228. $algorithm,
  1229. $xdate,
  1230. $credential_scope,
  1231. $hashed_canonical_request
  1232. ]);
  1233. // 3. 计算签名
  1234. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  1235. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  1236. // 4. 添加签名到请求头
  1237. $authorization_header = sprintf(
  1238. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  1239. $algorithm,
  1240. $access_key,
  1241. $credential_scope,
  1242. $signed_headers,
  1243. $signature
  1244. );
  1245. return [
  1246. 'Accept' => $accept,
  1247. 'Content-Type' => $contenttype,
  1248. 'X-Date' => $xdate,
  1249. 'Authorization' => $authorization_header
  1250. ];
  1251. }
  1252. // 文字合成语音(火山引擎)
  1253. public function tts($data) {
  1254. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  1255. $headers = [
  1256. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  1257. 'Content-Type' => 'application/json; charset=UTF-8'
  1258. ];
  1259. $post_data = [
  1260. 'app' => [
  1261. 'appid' => env('VOLC_APPID'),
  1262. 'token' => env('VOLC_TOKEN'),
  1263. 'cluster' => 'volcano_tts'
  1264. ],
  1265. 'user' => [
  1266. 'uid' => 'mp_audio'
  1267. ],
  1268. // 'audio' => [
  1269. // 'voice_type' =>
  1270. // ],
  1271. ];
  1272. }
  1273. public function scriptList($data) {
  1274. $script_id = getProp($data, 'script_id');
  1275. $script_name = getProp($data, 'script_name');
  1276. $query = DB::table('mp_scripts')->where('is_deleted', 0)->select('*');
  1277. if ($script_id) {
  1278. $query->where('id', $script_id);
  1279. }
  1280. if ($script_name) {
  1281. $query->where('script_name', 'like', "%{$script_name}%");
  1282. }
  1283. return $query->orderBy('created_at', 'desc')->paginate(12);
  1284. }
  1285. public function scripts($data) {
  1286. $script_id = getProp($data, 'script_id');
  1287. $script_name = getProp($data, 'script_name');
  1288. $query = DB::table('mp_scripts')->where('is_deleted', 0)->select('id as script_id', 'script_name');
  1289. if ($script_id) {
  1290. $query->where('id', $script_id);
  1291. }
  1292. if ($script_name) {
  1293. $query->where('script_name', 'like', "%{$script_name}%");
  1294. }
  1295. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  1296. return (array)$value;
  1297. })->toArray();
  1298. }
  1299. public function scriptInfo($data) {
  1300. $script_id = getProp($data, 'script_id');
  1301. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  1302. // ->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();
  1303. ->selectRaw('id as script_id, script_name')->first();
  1304. if (!$script) Utils::throwError('20003:该剧本不存在!');
  1305. $script = (array)$script;
  1306. // 获取分集组信息
  1307. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  1308. ->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')
  1309. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  1310. $value = (array)$value;
  1311. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  1312. return (array)$value;
  1313. })->toArray();
  1314. $script['group'] = $groups;
  1315. return $script;
  1316. }
  1317. public function createScript($data) {
  1318. $script_name = getProp($data, 'script_name');
  1319. $uid = Site::getUid(); // 获取当前用户ID
  1320. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  1321. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  1322. $script_name .= '_'.date('YmdHis');
  1323. }
  1324. return DB::table('mp_scripts')->insertGetId([
  1325. 'script_name' => $script_name,
  1326. 'user_id' => $uid,
  1327. 'created_at' => date('Y-m-d H:i:s'),
  1328. 'updated_at' => date('Y-m-d H:i:s')
  1329. ]);
  1330. }
  1331. public function editScript($data) {
  1332. $script_id = getProp($data, 'script_id');
  1333. $script_name = getProp($data, 'script_name');
  1334. $uid = Site::getUid(); // 获取当前用户ID
  1335. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  1336. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  1337. if ($id && (int)$id !== (int)$script_id) {
  1338. $script_name .= '_'.date('YmdHis');
  1339. }
  1340. return DB::table('mp_scripts')->where('id', $script_id)->update([
  1341. 'script_name' => $script_name,
  1342. 'updated_at' => date('Y-m-d H:i:s')
  1343. ]);
  1344. }
  1345. public function delScript($data) {
  1346. $script_id = getProp($data, 'script_id');
  1347. $uid = Site::getUid(); // 获取当前用户ID
  1348. if (!$script_id) Utils::throwError('20003:请选择剧本');
  1349. return DB::table('mp_scripts')->where('id', $script_id)->update([
  1350. 'is_deleted' => 1,
  1351. 'updated_at' => date('Y-m-d H:i:s')
  1352. ]);
  1353. }
  1354. public function createEpisode($data) {
  1355. $script_id = getProp($data, 'script_id');
  1356. $group_name = getProp($data, 'group_name');
  1357. $remark = getProp($data, 'remark');
  1358. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  1359. $uid = Site::getUid(); // 获取当前用户ID
  1360. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  1361. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  1362. $group_name .= '_'.date('YmdHis');
  1363. }
  1364. return DB::table('mp_script_episode_group')->insertGetId([
  1365. 'script_id' => $script_id,
  1366. 'group_name' => $group_name,
  1367. 'user_id' => $uid,
  1368. 'remark' => $remark,
  1369. 'created_at' => date('Y-m-d H:i:s'),
  1370. 'updated_at' => date('Y-m-d H:i:s')
  1371. ]);
  1372. }
  1373. public function editEpisode($data) {
  1374. $group_id = getProp($data, 'group_id');
  1375. $start_episode_number = getProp($data, 'start_episode_number');
  1376. $end_episode_number = getProp($data, 'end_episode_number');
  1377. $group_name = getProp($data, 'group_name');
  1378. $uid = Site::getUid(); // 获取当前用户ID
  1379. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  1380. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  1381. if ($id && (int)$id !== (int)$group_id) {
  1382. $group_name .= '_'.date('YmdHis');
  1383. }
  1384. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1385. 'group_name' => $group_name,
  1386. 'start_episode_number' => $start_episode_number,
  1387. 'end_episode_number' => $end_episode_number,
  1388. 'updated_at' => date('Y-m-d H:i:s')
  1389. ]);
  1390. }
  1391. public function delEpisode($data) {
  1392. $group_id = getProp($data, 'group_id');
  1393. $uid = Site::getUid(); // 获取当前用户ID
  1394. if (!$group_id) Utils::throwError('20003:请选择分集');
  1395. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1396. 'is_deleted' => 1,
  1397. 'updated_at' => date('Y-m-d H:i:s')
  1398. ]);
  1399. }
  1400. /**
  1401. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  1402. *
  1403. * @param array $data 包含以下参数:
  1404. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1405. * - question: 用户问题(可选)
  1406. * - model: 使用的模型(r1 或 v3,默认 v3)
  1407. * @return \Generator 返回生成器,用于流式输出
  1408. */
  1409. public function generateEpisodes($data) {
  1410. $script_id = getProp($data, 'script_id');
  1411. $group_id = getProp($data, 'group_id');
  1412. // $file = getProp($data, 'file');
  1413. $file = '';
  1414. $content = getProp($data, 'content', '');
  1415. // $bid = getProp($data, 'bid', 0);
  1416. $bid = 0;
  1417. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  1418. if (!$group) {
  1419. Utils::throwError('20003:剧本分集不存在');
  1420. }
  1421. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  1422. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  1423. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  1424. $prompt = getProp($data, 'prompt');
  1425. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  1426. $model = getProp($data, 'model');
  1427. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  1428. Utils::throwError('20003:该模型不存在!');
  1429. }
  1430. // 检查是否存在重叠的剧集序号范围
  1431. $exists_groups = DB::table('mp_script_episode_group')
  1432. ->where('script_id', $script_id)
  1433. ->where('id', '<>', $group_id) // 排除当前组
  1434. ->where('is_deleted', 0)
  1435. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  1436. // 检查新范围是否与现有范围重叠
  1437. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1438. // 新范围的开始在现有范围内
  1439. $q->where('start_episode_number', '<=', $start_episode_sequence)
  1440. ->where('end_episode_number', '>=', $start_episode_sequence);
  1441. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1442. // 新范围的结束在现有范围内
  1443. $q->where('start_episode_number', '<=', $end_episode_sequence)
  1444. ->where('end_episode_number', '>=', $end_episode_sequence);
  1445. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1446. // 新范围完全包含现有范围
  1447. $q->where('start_episode_number', '>=', $start_episode_sequence)
  1448. ->where('end_episode_number', '<=', $end_episode_sequence);
  1449. });
  1450. })
  1451. ->select('start_episode_number', 'end_episode_number')
  1452. ->get();
  1453. if ($exists_groups->isNotEmpty()) {
  1454. $conflict_ranges = [];
  1455. foreach ($exists_groups as $group) {
  1456. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  1457. }
  1458. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  1459. }
  1460. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1461. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1462. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1463. if ($model === 'deepseek-chat') {
  1464. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1465. $model = 'deepseek-v4-flash';
  1466. $thinkingMode = 'disabled';
  1467. } elseif ($model === 'deepseek-reasoner') {
  1468. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1469. $model = 'deepseek-v4-flash';
  1470. $thinkingMode = 'enabled';
  1471. }
  1472. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1473. if (!$script) {
  1474. Utils::throwError('20003:剧本不存在');
  1475. }
  1476. $content = getProp($group, 'content');
  1477. if (!$file && !$content && !$bid) {
  1478. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1479. }
  1480. // 提取文件内容
  1481. if ($file) {
  1482. $content = $this->extractFileContent($file);
  1483. if (!$content) {
  1484. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1485. }
  1486. } elseif ($bid) {
  1487. $content = $this->getContentByBid($bid);
  1488. if (!$content) {
  1489. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1490. }
  1491. } elseif ($content) {
  1492. $content = filterContent($content);
  1493. } elseif ($prompt) {
  1494. $content = filterContent($prompt);
  1495. } else {
  1496. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1497. }
  1498. // 构建消息
  1499. $messages = [
  1500. $this->sys_message,
  1501. [
  1502. 'role' => 'user',
  1503. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1504. ]
  1505. ];
  1506. $post_data = [
  1507. 'model' => $model,
  1508. 'messages' => $messages,
  1509. // 'max_tokens' => 8192,
  1510. 'temperature' => 0.7,
  1511. 'frequency_penalty' => 0,
  1512. 'presence_penalty' => 0,
  1513. 'thinking' => ['type' => $thinkingMode],
  1514. 'response_format' => ['type' => 'text'],
  1515. 'stream' => true
  1516. ];
  1517. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1518. // 根据模型类型选择调用方法
  1519. $fullContent = '';
  1520. $fullReasoningContent = '';
  1521. $usage = [];
  1522. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1523. // DeepSeek 官方模型使用 DeepSeek API
  1524. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  1525. } else {
  1526. // 其他模型使用火山引擎API
  1527. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  1528. }
  1529. // 处理流式输出
  1530. foreach ($streamGenerator as $chunk) {
  1531. if (isset($chunk['type'])) {
  1532. if ($chunk['type'] === 'done') {
  1533. // 最终结果
  1534. $fullContent = $chunk['full_content'];
  1535. $fullReasoningContent = $chunk['full_reasoning'];
  1536. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  1537. } else {
  1538. // 逐块yield数据
  1539. yield $chunk;
  1540. }
  1541. }
  1542. }
  1543. dLog('deepseek')->info('完整内容: '.$fullContent);
  1544. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  1545. // 处理完整内容并返回最终结果
  1546. $script_arr = [];
  1547. if ($fullContent) {
  1548. $script_arr = extractScriptContent($fullContent);
  1549. }
  1550. logDB('deepseek', 'info', '解析内容', $script_arr);
  1551. if (!$script_arr['episodes']) {
  1552. Utils::throwError('20003:未生成剧本相关信息');
  1553. // yield [
  1554. // 'type' => 'done',
  1555. // 'script' => $script_arr,
  1556. // 'msg' => '未生成剧本相关信息',
  1557. // 'answer' => $fullContent,
  1558. // 'reasoning' => $fullReasoningContent,
  1559. // 'usage' => $usage
  1560. // ];
  1561. // return ;
  1562. }
  1563. try {
  1564. DB::beginTransaction();
  1565. // // 返回前保存剧本内容
  1566. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  1567. // 'content' => $content,
  1568. // 'updated_at' => date('Y-m-d H:i:s')
  1569. // ]);
  1570. // if (!$boolen) {
  1571. // Utils::throwError('20003:保存剧本内容失败');
  1572. // }
  1573. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1574. // 'start_episode_number' => $start_episode_sequence,
  1575. // 'end_episode_number' => $end_episode_sequence,
  1576. // 'updated_at' => date('Y-m-d H:i:s')
  1577. // ]);
  1578. // if (!$boolen1) {
  1579. // Utils::throwError('20003:保存分集失败');
  1580. // }
  1581. $episode_content = '';
  1582. $episodes = [];
  1583. foreach ($script_arr['episodes'] as $item) {
  1584. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  1585. // $episodes[] = [
  1586. // 'script_id' => $script_id,
  1587. // 'episode_number' => $item['episode_number'],
  1588. // 'episode_name' => $item['episode_name'],
  1589. // 'episode_content' => $item['episode_content'],
  1590. // 'created_at' => date('Y-m-d H:i:s'),
  1591. // 'updated_at' => date('Y-m-d H:i:s'),
  1592. // ];
  1593. }
  1594. if ($episode_content) {
  1595. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1596. 'episode_content' => $episode_content,
  1597. 'updated_at' => date('Y-m-d H:i:s')
  1598. ]);
  1599. if (!$boolen2) {
  1600. Utils::throwError('20003:保存分集内容失败');
  1601. }
  1602. }else {
  1603. Utils::throwError('20003:分集剧本解析失败');
  1604. }
  1605. }catch (\Exception $e) {
  1606. DB::rollBack();
  1607. Utils::throwError('20003:'.$e->getMessage());
  1608. }
  1609. DB::commit();
  1610. yield [
  1611. 'type' => 'done',
  1612. 'script' => $script_arr,
  1613. 'episode_content' => $episode_content,
  1614. 'answer' => $fullContent,
  1615. 'reasoning' => $fullReasoningContent,
  1616. 'usage' => $usage
  1617. ];
  1618. }
  1619. public function chatWithFileStream($data) {
  1620. $script_id = getProp($data, 'script_id');
  1621. $group_id = getProp($data, 'group_id');
  1622. $file = getProp($data, 'file');
  1623. $content = getProp($data, 'content', '');
  1624. $bid = getProp($data, 'bid', 0);
  1625. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1626. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1627. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  1628. $prompt = getProp($data, 'prompt');
  1629. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n本次修改要求如下: {$prompt}\n");
  1630. $model = getProp($data, 'model');
  1631. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  1632. Utils::throwError('20003:该模型不存在!');
  1633. }
  1634. // 检查是否存在重叠的剧集序号范围
  1635. $exists_groups = DB::table('mp_script_episode_group')
  1636. ->where('script_id', $script_id)
  1637. ->where('id', '<>', $group_id)
  1638. ->where('is_deleted', 0)
  1639. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  1640. // 检查新范围是否与现有范围重叠
  1641. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1642. // 新范围的开始在现有范围内
  1643. $q->where('start_episode_number', '<=', $start_episode_sequence)
  1644. ->where('end_episode_number', '>=', $start_episode_sequence);
  1645. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1646. // 新范围的结束在现有范围内
  1647. $q->where('start_episode_number', '<=', $end_episode_sequence)
  1648. ->where('end_episode_number', '>=', $end_episode_sequence);
  1649. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1650. // 新范围完全包含现有范围
  1651. $q->where('start_episode_number', '>=', $start_episode_sequence)
  1652. ->where('end_episode_number', '<=', $end_episode_sequence);
  1653. });
  1654. })
  1655. ->select('start_episode_number', 'end_episode_number')
  1656. ->get();
  1657. if ($exists_groups->isNotEmpty()) {
  1658. $conflict_ranges = [];
  1659. foreach ($exists_groups as $group) {
  1660. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  1661. }
  1662. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  1663. }
  1664. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1665. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1666. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1667. if ($model === 'deepseek-chat') {
  1668. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1669. $model = 'deepseek-v4-flash';
  1670. $thinkingMode = 'disabled';
  1671. } elseif ($model === 'deepseek-reasoner') {
  1672. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1673. $model = 'deepseek-v4-flash';
  1674. $thinkingMode = 'enabled';
  1675. }
  1676. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1677. if (!$script) {
  1678. Utils::throwError('20003:剧本不存在');
  1679. }
  1680. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  1681. if (!$group) {
  1682. Utils::throwError('20003:剧本分集不存在');
  1683. }
  1684. if (!$file && !$content && !$bid) {
  1685. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1686. }
  1687. // 提取文件内容
  1688. if ($file) {
  1689. $content = $this->extractFileContent($file);
  1690. if (!$content) {
  1691. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1692. }
  1693. } elseif ($bid) {
  1694. $content = $this->getContentByBid($bid);
  1695. if (!$content) {
  1696. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1697. }
  1698. } elseif ($content) {
  1699. $content = filterContent($content);
  1700. } elseif ($prompt) {
  1701. $content = filterContent($prompt);
  1702. } else {
  1703. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1704. }
  1705. // 构建消息
  1706. $messages = [
  1707. [
  1708. 'role' => 'system',
  1709. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  1710. 强制要求:\n
  1711. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  1712. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  1713. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  1714. 普通要求:\n
  1715. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  1716. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  1717. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  1718. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  1719. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  1720. 示例如下:\n
  1721. ###剧本名:西昆仑
  1722. ###故事梗概
  1723. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1724. ###剧本亮点
  1725. 亮点1:绝境奇药,生死一线
  1726. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  1727. 亮点2:结拜兄妹,化解尴尬
  1728. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  1729. 亮点3:纤发夺命,情愫暗涌
  1730. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  1731. ###人物关系
  1732. 阿雪与梁萧之间存在兄妹之情。
  1733. ###核心矛盾
  1734. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1735. ###主体列表
  1736. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  1737. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  1738. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  1739. 阴阳球:天地异宝,能化生精气,救人于危难。
  1740. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  1741. ###美术风格
  1742. 基础画风风格词:厚涂古风
  1743. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  1744. ###场景列表
  1745. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  1746. [
  1747. 'role' => 'user',
  1748. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1749. ]
  1750. ];
  1751. $post_data = [
  1752. 'model' => $model,
  1753. 'messages' => $messages,
  1754. // 'max_tokens' => 8192,
  1755. 'temperature' => 0.7,
  1756. 'frequency_penalty' => 0,
  1757. 'presence_penalty' => 0,
  1758. 'thinking' => ['type' => $thinkingMode],
  1759. 'response_format' => ['type' => 'text'],
  1760. 'stream' => true
  1761. ];
  1762. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1763. // 根据模型类型选择调用方法
  1764. $fullContent = '';
  1765. $fullReasoningContent = '';
  1766. $usage = [];
  1767. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1768. // DeepSeek 官方模型使用 DeepSeek API
  1769. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  1770. } else {
  1771. // 其他模型使用火山引擎API
  1772. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  1773. }
  1774. // 处理流式输出
  1775. foreach ($streamGenerator as $chunk) {
  1776. if (isset($chunk['type'])) {
  1777. if ($chunk['type'] === 'done') {
  1778. // 最终结果
  1779. $fullContent = $chunk['full_content'];
  1780. $fullReasoningContent = $chunk['full_reasoning'];
  1781. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  1782. } else {
  1783. // 逐块yield数据
  1784. yield $chunk;
  1785. }
  1786. }
  1787. }
  1788. dLog('deepseek')->info('完整内容: '.$fullContent);
  1789. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  1790. // 处理完整内容并返回最终结果
  1791. $script_arr = [];
  1792. if ($fullContent) {
  1793. $script_arr = extractScriptContent($fullContent);
  1794. }
  1795. logDB('deepseek', 'info', '解析内容', $script_arr);
  1796. if (!$script_arr['roles']) {
  1797. Utils::throwError('20003:未生成剧本相关信息');
  1798. // yield [
  1799. // 'type' => 'done',
  1800. // 'script' => $script_arr,
  1801. // 'msg' => '未生成剧本相关信息',
  1802. // 'answer' => $fullContent,
  1803. // 'reasoning' => $fullReasoningContent,
  1804. // 'usage' => $usage
  1805. // ];
  1806. }
  1807. try {
  1808. DB::beginTransaction();
  1809. // // 返回前保存剧本内容
  1810. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  1811. // 'content' => $content,
  1812. // 'status' => '解析完成',
  1813. // 'updated_at' => date('Y-m-d H:i:s')
  1814. // ]);
  1815. // if (!$boolen) {
  1816. // Utils::throwError('20003:保存剧本内容失败');
  1817. // }
  1818. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1819. 'start_episode_number' => $start_episode_sequence,
  1820. 'end_episode_number' => $end_episode_sequence,
  1821. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1822. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1823. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1824. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1825. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1826. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1827. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1828. 'status' => '解析完成',
  1829. 'content' => $content,
  1830. 'updated_at' => date('Y-m-d H:i:s')
  1831. ]);
  1832. if (!$boolen1) {
  1833. Utils::throwError('20003:保存分集失败');
  1834. }
  1835. // $episodes = [];
  1836. // foreach ($script_arr['episodes'] as $item) {
  1837. // $episodes[] = [
  1838. // 'script_id' => $script_id,
  1839. // 'episode_number' => $item['episode_number'],
  1840. // 'episode_name' => $item['episode_name'],
  1841. // 'episode_content' => $item['episode_content'],
  1842. // 'created_at' => date('Y-m-d H:i:s'),
  1843. // 'updated_at' => date('Y-m-d H:i:s'),
  1844. // ];
  1845. // }
  1846. // if ($episodes) {
  1847. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  1848. // if (!$boolen2) {
  1849. // Utils::throwError('20003:保存分集内容失败');
  1850. // }
  1851. // }else {
  1852. // Utils::throwError('20003:分集剧本解析失败');
  1853. // }
  1854. }catch (\Exception $e) {
  1855. DB::rollBack();
  1856. Utils::throwError('20003:'.$e->getMessage());
  1857. }
  1858. DB::commit();
  1859. yield [
  1860. 'type' => 'done',
  1861. 'script' => $script_arr,
  1862. 'answer' => $fullContent,
  1863. 'reasoning' => $fullReasoningContent,
  1864. 'usage' => $usage
  1865. ];
  1866. }
  1867. /**
  1868. * 上传文件识别文字内容并与 DeepSeek 进行对话
  1869. *
  1870. * @param array $data 包含以下参数:
  1871. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1872. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  1873. * - model: 使用的模型(r1 或 v3,默认 v3)
  1874. * @return array
  1875. */
  1876. public function chatWithFile($data) {
  1877. $script_id = getProp($data, 'script_id');
  1878. $file = getProp($data, 'file');
  1879. $content = getProp($data, 'content', '');
  1880. $bid = getProp($data, 'bid', 0);
  1881. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1882. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1883. $prompt = getProp($data, 'prompt');
  1884. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n本次修改要求如下: {$prompt}\n");
  1885. // 处理文本模型
  1886. $model = getProp($data, 'model');
  1887. if (!$model) {
  1888. // 用户没有输入,使用默认值
  1889. $model = 'doubao-seed-2-0-mini-260215';
  1890. }
  1891. // 验证模型是否在可用模型表中
  1892. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1893. $model = 'doubao-seed-2-0-mini-260215';
  1894. }
  1895. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1896. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1897. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1898. if ($model === 'deepseek-chat') {
  1899. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1900. $model = 'deepseek-v4-flash';
  1901. $thinkingMode = 'disabled';
  1902. } elseif ($model === 'deepseek-reasoner') {
  1903. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1904. $model = 'deepseek-v4-flash';
  1905. $thinkingMode = 'enabled';
  1906. }
  1907. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1908. if (!$script) {
  1909. Utils::throwError('20003:剧本不存在');
  1910. }
  1911. if (!$file && !$content && !$bid) {
  1912. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1913. }
  1914. // 提取文件内容
  1915. if ($file) {
  1916. $content = $this->extractFileContent($file);
  1917. if (!$content) {
  1918. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1919. }
  1920. } elseif ($bid) {
  1921. $content = $this->getContentByBid($bid);
  1922. if (!$content) {
  1923. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1924. }
  1925. } elseif ($content) {
  1926. $content = filterContent($content);
  1927. } elseif ($prompt) {
  1928. $content = filterContent($prompt);
  1929. } else {
  1930. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1931. }
  1932. // 构建消息
  1933. $messages = [
  1934. $this->sys_message,
  1935. [
  1936. 'role' => 'user',
  1937. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1938. ]
  1939. ];
  1940. $post_data = [
  1941. 'model' => $model,
  1942. 'messages' => $messages,
  1943. // 'max_tokens' => 8192,
  1944. 'temperature' => 0.7,
  1945. 'frequency_penalty' => 0,
  1946. 'presence_penalty' => 0,
  1947. 'thinking' => ['type' => $thinkingMode],
  1948. 'response_format' => ['type' => 'text'],
  1949. 'stream' => false
  1950. ];
  1951. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1952. // 根据模型类型选择调用方法
  1953. $fullContent = '';
  1954. $usage = [];
  1955. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1956. // DeepSeek 官方模型使用 DeepSeek API
  1957. $chatResult = $this->chatOnly($post_data);
  1958. } else {
  1959. // 其他模型使用火山引擎API
  1960. $chatResult = $this->volcEngineChatCompletion($post_data);
  1961. }
  1962. if (is_array($chatResult)) {
  1963. $fullContent = $chatResult['fullContent'];
  1964. $usage = $chatResult['usage'];
  1965. }
  1966. $script_arr = [];
  1967. // 处理结果
  1968. if ($fullContent) {
  1969. $script_arr = extractScriptContent($fullContent);
  1970. }
  1971. // 返回前保存剧本内容
  1972. DB::table('mp_scripts')->where('id', $script_id)->update([
  1973. 'content' => $content,
  1974. 'updated_at' => date('Y-m-d H:i:s')
  1975. ]);
  1976. return [
  1977. 'script' => $script_arr,
  1978. 'answer' => $fullContent,
  1979. 'usage' => $usage
  1980. ];
  1981. }
  1982. public function getEpisodeContent($data) {
  1983. $group_id = getProp($data, 'group_id');
  1984. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  1985. }
  1986. public function saveEpisodeContent($data) {
  1987. $script_id = getProp($data, 'script_id');
  1988. $group_id = getProp($data, 'group_id');
  1989. $start_episode_sequence = getProp($data, 'start_episode_number');
  1990. $end_episode_sequence = getProp($data, 'end_episode_number');
  1991. // 检查是否存在重叠的剧集序号范围
  1992. $exists_groups = DB::table('mp_script_episode_group')
  1993. ->where('script_id', $script_id)
  1994. ->where('id', '<>', $group_id) // 排除当前组
  1995. ->where('is_deleted', 0)
  1996. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  1997. // 检查新范围是否与现有范围重叠
  1998. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1999. // 新范围的开始在现有范围内
  2000. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2001. ->where('end_episode_number', '>=', $start_episode_sequence);
  2002. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2003. // 新范围的结束在现有范围内
  2004. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2005. ->where('end_episode_number', '>=', $end_episode_sequence);
  2006. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2007. // 新范围完全包含现有范围
  2008. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2009. ->where('end_episode_number', '<=', $end_episode_sequence);
  2010. });
  2011. })
  2012. ->select('start_episode_number', 'end_episode_number')
  2013. ->get();
  2014. if ($exists_groups->isNotEmpty()) {
  2015. $conflict_ranges = [];
  2016. foreach ($exists_groups as $group) {
  2017. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2018. }
  2019. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2020. }
  2021. $episode_content = getProp($data, 'episode_content');
  2022. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  2023. 'content' => $episode_content,
  2024. 'start_episode_number' => $start_episode_sequence,
  2025. 'end_episode_number' => $end_episode_sequence,
  2026. 'updated_at' => date('Y-m-d H:i:s')
  2027. ]);
  2028. $script_arr =getProp($data, 'script', []);
  2029. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  2030. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2031. $script_id = getProp($data, 'script_id');
  2032. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  2033. try {
  2034. DB::beginTransaction();
  2035. $update_data = [
  2036. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2037. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2038. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2039. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2040. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  2041. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2042. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  2043. 'status' => 3,
  2044. 'start_episode_sequence' => $start_episode_sequence,
  2045. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  2046. 'episode_num' => count($script_arr['episodes']),
  2047. 'updated_at' => date('Y-m-d H:i:s')
  2048. ];
  2049. // 保存剧本内容
  2050. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  2051. if (!$boolen) {
  2052. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  2053. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  2054. Utils::throwError('20003:剧本内容保存失败');
  2055. }
  2056. // 保存分集内容
  2057. // 删除历史分集内容
  2058. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  2059. $episodes = [];
  2060. $sequence = 1;
  2061. foreach ($script_arr['episodes'] as $episode) {
  2062. $segment_number = 1;
  2063. foreach($episode['segments'] as $segment) {
  2064. $episodes[] = [
  2065. 'script_id' => $script_id,
  2066. 'episode_number' => $episode['episode_number'],
  2067. 'title' => $episode['title'],
  2068. // 'content' => $episode['content'],
  2069. 'content' => '',
  2070. 'segment_number' => $segment_number,
  2071. 'segment_content' => $segment['segment_content'],
  2072. 'sequence' => $sequence,
  2073. 'created_at' => date('Y-m-d H:i:s'),
  2074. 'updated_at' => date('Y-m-d H:i:s')
  2075. ];
  2076. $sequence++;
  2077. $segment_number++;
  2078. }
  2079. }
  2080. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2081. if (!$boolen2) {
  2082. dLog('deepseek')->info('分集内容保存失败', $episodes);
  2083. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  2084. Utils::throwError('20003:分集内容保存失败');
  2085. }
  2086. } catch (\Exception $e) {
  2087. DB::rollBack();
  2088. Utils::throwError('20003:'.$e->getMessage());
  2089. }
  2090. DB::commit();
  2091. return true;
  2092. }
  2093. public function getBookContent($data) {
  2094. $bid = getProp($data, 'bid');
  2095. $start_sequence = getProp($data, 'start_sequence');
  2096. $end_sequence = getProp($data, 'end_sequence');
  2097. $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])
  2098. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  2099. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  2100. return $return_content;
  2101. }
  2102. public function exportScript($data) {
  2103. $filename = getProp($data, 'filename');
  2104. $script_id = getProp($data, 'script_id');
  2105. $group_id = getProp($data, 'group_id');
  2106. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  2107. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  2108. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2109. $script = (array)$script;
  2110. // 获取分集组信息
  2111. if ($group_id) {
  2112. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2113. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2114. ->get()->map(function($value) {
  2115. return (array)$value;
  2116. })->toArray();
  2117. }else {
  2118. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2119. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2120. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  2121. return (array)$value;
  2122. })->toArray();
  2123. }
  2124. if (!$groups) Utils::throwError('20003:分集不存在');
  2125. $script['group'] = $groups;
  2126. $export_type = getProp($data, 'export_type', 'txt');
  2127. // 生成文件名
  2128. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  2129. // 根据导出类型生成不同格式的文件
  2130. switch ($export_type) {
  2131. case 'txt':
  2132. return $this->exportScriptAsTxt($script, $filename);
  2133. case 'pdf':
  2134. return $this->exportScriptAsPdf($script, $filename);
  2135. default:
  2136. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  2137. }
  2138. }
  2139. /**
  2140. * 导出剧本为TXT格式
  2141. */
  2142. private function exportScriptAsTxt($script, $filename) {
  2143. // 构建TXT内容
  2144. $content = $this->buildScriptContent($script);
  2145. // 设置响应头,直接下载
  2146. header('Content-Type: text/plain; charset=utf-8');
  2147. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  2148. header('Content-Length: ' . strlen($content));
  2149. // 输出内容并结束
  2150. echo $content;
  2151. exit();
  2152. }
  2153. /**
  2154. * 导出剧本为PDF格式
  2155. */
  2156. private function exportScriptAsPdf($script, $filename) {
  2157. // 使用HTML转PDF的方式来更好地支持中文
  2158. $htmlContent = $this->buildScriptHtmlForPdf($script);
  2159. // 创建PDF实例
  2160. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  2161. // 设置文档信息
  2162. $pdf->SetCreator('剧本导出系统');
  2163. $pdf->SetAuthor('系统');
  2164. $pdf->SetTitle($script['script_name']);
  2165. $pdf->SetSubject('剧本导出');
  2166. // 设置边距
  2167. $pdf->SetMargins(15, 15, 15);
  2168. $pdf->SetAutoPageBreak(TRUE, 15);
  2169. // 添加页面
  2170. $pdf->AddPage();
  2171. // 注册并使用 simsun.ttf 字体
  2172. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  2173. // 使用HTML内容生成PDF
  2174. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  2175. // 直接输出PDF文件供下载
  2176. header('Content-Type: application/pdf');
  2177. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  2178. // 直接输出PDF内容
  2179. $pdf->Output($filename . '.pdf', 'D');
  2180. exit();
  2181. }
  2182. /**
  2183. * 构建用于PDF的HTML内容
  2184. */
  2185. private function buildScriptHtmlForPdf($script) {
  2186. $html = '<style>
  2187. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  2188. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  2189. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  2190. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  2191. .info { margin-bottom: 8px; }
  2192. .group { margin-bottom: 30px; page-break-inside: avoid; }
  2193. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  2194. .segment { margin-bottom: 10px; margin-left: 20px; }
  2195. .episode-content { white-space: pre-wrap; }
  2196. </style>';
  2197. // 标题
  2198. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  2199. // 处理分组数据
  2200. if (!empty($script['group']) && is_array($script['group'])) {
  2201. $groups = (array)$script['group'];
  2202. foreach ($groups as $group) {
  2203. $html .= '<div class="group">';
  2204. // 分组标题
  2205. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  2206. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  2207. // 故事梗概
  2208. if (!empty($group['intro'])) {
  2209. $html .= '<h3>故事梗概</h3>';
  2210. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  2211. }
  2212. // 剧本亮点
  2213. if (!empty($group['highlights'])) {
  2214. $html .= '<h3>剧本亮点</h3>';
  2215. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  2216. }
  2217. // 人物关系
  2218. if (!empty($group['role_relationship'])) {
  2219. $html .= '<h3>人物关系</h3>';
  2220. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  2221. }
  2222. // 核心矛盾
  2223. if (!empty($group['core_contradiction'])) {
  2224. $html .= '<h3>核心矛盾</h3>';
  2225. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  2226. }
  2227. // 主体列表
  2228. if (!empty($group['roles']) && is_array($group['roles'])) {
  2229. $html .= '<h3>主体列表</h3>';
  2230. $html .= '<ul>';
  2231. foreach ($group['roles'] as $role) {
  2232. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  2233. }
  2234. $html .= '</ul>';
  2235. }
  2236. // 美术风格
  2237. if (!empty($group['art_style'])) {
  2238. $html .= '<h3>美术风格</h3>';
  2239. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  2240. }
  2241. // 场景列表
  2242. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  2243. $html .= '<h3>场景列表</h3>';
  2244. $html .= '<ul>';
  2245. foreach ($group['scenes'] as $scene) {
  2246. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  2247. }
  2248. $html .= '</ul>';
  2249. }
  2250. // 分集剧本
  2251. if (!empty($group['episode_content'])) {
  2252. $html .= '<h3>分集剧本</h3>';
  2253. // 去除零宽字符和其他不可见字符
  2254. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  2255. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  2256. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  2257. }
  2258. $html .= '</div>';
  2259. }
  2260. }
  2261. return $html;
  2262. }
  2263. /**
  2264. * 构建PDF内容
  2265. */
  2266. private function buildPdfContent($pdf, $script) {
  2267. // 标题
  2268. $pdf->SetFont('dejavusans', 'B', 18);
  2269. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  2270. $pdf->Ln(5);
  2271. // 基本信息
  2272. $pdf->SetFont('dejavusans', '', 12);
  2273. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  2274. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  2275. $pdf->Ln(5);
  2276. // 剧本简介
  2277. if (!empty($script['intro'])) {
  2278. $pdf->SetFont('dejavusans', 'B', 14);
  2279. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  2280. $pdf->SetFont('dejavusans', '', 12);
  2281. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  2282. $pdf->Ln(3);
  2283. }
  2284. // 亮点
  2285. if (!empty($script['highlights'])) {
  2286. $pdf->SetFont('dejavusans', 'B', 14);
  2287. $pdf->Cell(0, 10, '亮点', 0, 1);
  2288. $pdf->SetFont('dejavusans', '', 12);
  2289. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  2290. $pdf->Ln(3);
  2291. }
  2292. // 核心矛盾
  2293. if (!empty($script['core_contradiction'])) {
  2294. $pdf->SetFont('dejavusans', 'B', 14);
  2295. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  2296. $pdf->SetFont('dejavusans', '', 12);
  2297. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  2298. $pdf->Ln(3);
  2299. }
  2300. // 艺术风格
  2301. if (!empty($script['art_style'])) {
  2302. $pdf->SetFont('dejavusans', 'B', 14);
  2303. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  2304. $pdf->SetFont('dejavusans', '', 12);
  2305. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  2306. $pdf->Ln(3);
  2307. }
  2308. // 备注
  2309. if (!empty($script['remark'])) {
  2310. $pdf->SetFont('dejavusans', 'B', 14);
  2311. $pdf->Cell(0, 10, '备注', 0, 1);
  2312. $pdf->SetFont('dejavusans', '', 12);
  2313. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  2314. $pdf->Ln(3);
  2315. }
  2316. // 角色列表
  2317. if (!empty($script['roles']) && is_array($script['roles'])) {
  2318. $pdf->SetFont('dejavusans', 'B', 14);
  2319. $pdf->Cell(0, 10, '角色列表', 0, 1);
  2320. $pdf->SetFont('dejavusans', '', 12);
  2321. foreach ($script['roles'] as $index => $role) {
  2322. if (is_array($role) || is_object($role)) {
  2323. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  2324. } else {
  2325. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  2326. }
  2327. }
  2328. $pdf->Ln(3);
  2329. }
  2330. // 角色关系
  2331. if (!empty($script['role_relationship'])) {
  2332. $pdf->SetFont('dejavusans', 'B', 14);
  2333. $pdf->Cell(0, 10, '角色关系', 0, 1);
  2334. $pdf->SetFont('dejavusans', '', 12);
  2335. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  2336. $pdf->Ln(3);
  2337. }
  2338. // 场景列表
  2339. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  2340. $pdf->SetFont('dejavusans', 'B', 14);
  2341. $pdf->Cell(0, 10, '场景列表', 0, 1);
  2342. $pdf->SetFont('dejavusans', '', 12);
  2343. foreach ($script['scenes'] as $index => $scene) {
  2344. if (is_array($scene) || is_object($scene)) {
  2345. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  2346. } else {
  2347. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  2348. }
  2349. }
  2350. $pdf->Ln(5);
  2351. }
  2352. // 分集内容
  2353. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  2354. $pdf->SetFont('dejavusans', 'B', 16);
  2355. $pdf->Cell(0, 12, '分集内容', 0, 1);
  2356. $pdf->Ln(3);
  2357. foreach ($script['episodes'] as $episode) {
  2358. // 检查是否需要新页面
  2359. if ($pdf->GetY() > 250) {
  2360. $pdf->AddPage();
  2361. }
  2362. $pdf->SetFont('dejavusans', 'B', 14);
  2363. $episodeTitle = '第' . $episode['episode_number'] . '集';
  2364. if (!empty($episode['title'])) {
  2365. $episodeTitle .= ':' . $episode['title'];
  2366. }
  2367. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  2368. // 处理分段内容
  2369. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  2370. $pdf->SetFont('dejavusans', '', 12);
  2371. foreach ($episode['segments'] as $segment) {
  2372. if (!empty($segment['segment_content'])) {
  2373. // 如果有分段编号,显示分段标题
  2374. if (!empty($segment['segment_number'])) {
  2375. $pdf->SetFont('dejavusans', 'B', 12);
  2376. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  2377. $pdf->SetFont('dejavusans', '', 12);
  2378. }
  2379. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  2380. $pdf->Ln(2);
  2381. }
  2382. }
  2383. }
  2384. $pdf->Ln(5);
  2385. }
  2386. }
  2387. }
  2388. /**
  2389. * 构建剧本文本内容
  2390. */
  2391. private function buildScriptContent($script) {
  2392. $content = '';
  2393. $groups = $script['group'];
  2394. $groups = (array)$groups;
  2395. foreach ($groups as $group) {
  2396. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  2397. // 剧本基本信息
  2398. if (!empty($group['intro'])) {
  2399. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  2400. }
  2401. if (!empty($group['highlights'])) {
  2402. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  2403. }
  2404. if (!empty($group['role_relationship'])) {
  2405. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  2406. }
  2407. if (!empty($group['core_contradiction'])) {
  2408. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  2409. }
  2410. if (!empty($group['roles']) && is_array($group['roles'])) {
  2411. $content .= "###主体列表\n";
  2412. foreach ($group['roles'] as $role) {
  2413. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  2414. }
  2415. $content .= "\n\n";
  2416. }
  2417. if (!empty($group['art_style'])) {
  2418. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  2419. }
  2420. // 场景信息
  2421. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  2422. $content .= "###场景列表\n";
  2423. foreach ($group['scenes'] as $scene) {
  2424. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  2425. }
  2426. $content .= "\n\n";
  2427. }
  2428. // 分集内容
  2429. if (!empty($group['episode_content'])) {
  2430. $content .= "###分集剧本\n";
  2431. $content .= $group['episode_content'];
  2432. // foreach ($script['episodes'] as $episode) {
  2433. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  2434. // // if (!empty($episode['episode_name'])) {
  2435. // // $content .= ":" . $episode['episode_name'];
  2436. // // }
  2437. // // $content .= "\n";
  2438. // $content .= $episode['episode_content'] . "\n\n";
  2439. // }
  2440. }
  2441. }
  2442. return $content;
  2443. }
  2444. /**
  2445. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2446. *
  2447. * @param array $data 包含以下参数:
  2448. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2449. * - question: 用户问题(可选)
  2450. * - model: 使用的模型(r1 或 v3,默认 v3)
  2451. * @return \Generator 返回生成器,用于流式输出
  2452. */
  2453. public function addChat($data) {
  2454. $uid = Site::getUid();
  2455. $anime_id = getProp($data, 'anime_id');
  2456. if (!$anime_id) Utils::throwError('20003:请选择对话');
  2457. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  2458. if (!$anime) Utils::throwError('20003:对话不存在');
  2459. $file = getProp($data, 'file');
  2460. $content = getProp($data, 'content', '');
  2461. $bid = getProp($data, 'bid', 0);
  2462. $script_id = getProp($data, 'script_id', 0);
  2463. $prompt = getProp($data, 'prompt');
  2464. $user_anime_name = getProp($anime, 'anime_name');
  2465. // 处理文本模型
  2466. $model = getProp($data, 'model');
  2467. if (!$model) {
  2468. // 用户没有输入,从anime表获取
  2469. $model = getProp($anime, 'model');
  2470. if (!$model) {
  2471. // anime表也没有,使用默认值
  2472. $model = 'doubao-seed-2-0-mini-260215';
  2473. }
  2474. }
  2475. // 验证模型是否在可用模型表中
  2476. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2477. $model = 'doubao-seed-2-0-mini-260215';
  2478. }
  2479. $is_multi = getProp($anime, 'is_multi');
  2480. $is_single = (int)$is_multi !== 1;
  2481. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n本次修改要求如下:\n{$prompt}" : "请根据实例格式完成剧本大纲\n本次修改要求如下:\n{$prompt}");
  2482. // if (!$file && !$content && !$bid) {
  2483. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2484. // }
  2485. // 提取文件内容
  2486. if ($file) {
  2487. $content = $this->extractFileContent($file);
  2488. if (!$content) {
  2489. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2490. }
  2491. } elseif ($script_id) {
  2492. $content = $this->getContentByScriptId($script_id);
  2493. if (!$content) {
  2494. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  2495. }
  2496. } elseif ($bid) {
  2497. $content = $this->getContentByBid($bid);
  2498. if (!$content) {
  2499. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2500. }
  2501. } elseif ($content) {
  2502. $content = filterContent($content);
  2503. } else {
  2504. $content = getProp($anime, 'content');
  2505. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  2506. $need_generate_content = true;
  2507. }
  2508. }
  2509. // 美术风格
  2510. $input_art_style = getProp($data, 'art_style');
  2511. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  2512. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  2513. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  2514. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  2515. 中年女:邻居阿姨
  2516. 老年男:幽默大爷
  2517. 老年女:婆婆
  2518. 萌娃:奶气萌娃";
  2519. // 判断是否需要生成原文内容
  2520. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  2521. // 如果需要生成原文内容,添加额外的要求
  2522. $content_generation_requirement = $need_generate_content
  2523. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  2524. : "";
  2525. // 美术风格
  2526. if (!$mappedArtStyle) {
  2527. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  2528. }else {
  2529. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$input_art_style}\n{$mappedArtStyle}>\n";
  2530. }
  2531. $systemPrompt = $is_single
  2532. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  2533. 强制要求:
  2534. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2535. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2536. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2537. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2538. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2539. 普通要求:
  2540. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  2541. 2.{$mappedArtStyle_prompt}
  2542. 2.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如角色-少年、角色-青年、角色-中年、角色-老年这种情况,不得出现角色-愤怒、角色-隐忍、角色-求生等情绪和状态变化的同一角色
  2543. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  2544. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  2545. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、清晰的面部五官结构描写、身体体型特征(身高比例、体态、肌肉或瘦弱程度)、整体视觉风格,以及详细的穿着风格和服装细节。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数150-200字左右)在主体描述后用{}框起来。
  2546. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  2547. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  2548. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  2549. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  2550. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  2551. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  2552. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  2553. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  2554. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  2555. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  2556. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  2557. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)。
  2558. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  2559. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  2560. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  2561. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  2562. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  2563. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  2564. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  2565. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  2566. 示例如下:\n
  2567. ###剧本名:西昆仑
  2568. ###故事梗概
  2569. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2570. ###剧本亮点
  2571. 亮点1:绝境奇药,生死一线
  2572. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2573. 亮点2:结拜兄妹,化解尴尬
  2574. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2575. 亮点3:纤发夺命,情愫暗涌
  2576. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2577. ###人物关系
  2578. 阿雪与梁萧之间存在兄妹之情。
  2579. ###核心矛盾
  2580. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2581. ###主体列表
  2582. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{写实。全景,正面拍摄,青年女性,亚洲人。
  2583. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  2584. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  2585. 姿态:站立。}{{甜心小美}}
  2586. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。{写实。
  2587. 全景,正面拍摄,青年男性,亚洲人。
  2588. 黑色短碎发,五官清秀。
  2589. 服饰穿搭:70年代白色棉质汗衫,深蓝色土布长裤,质地粗糙。
  2590. 姿态:站立。}{{爽快思思}}
  2591. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  2592. 全景,正面拍摄,青年女性,亚洲人。
  2593. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  2594. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  2595. 姿态:站立。}{{阳光青年}}
  2596. ###美术风格
  2597. 基础画风风格词:厚涂古风
  2598. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2599. ###场景列表
  2600. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{写实。影视质感。广角。
  2601. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  2602. 无人物。}
  2603. ###分镜剧本
  2604. ##第1幕:徐家老旧厨房 白天 室内
  2605. 分镜1
  2606. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  2607. 场景:徐家老旧厨房
  2608. 构图设计:全景,低角度仰视
  2609. 运镜调度:手持拍摄
  2610. 配音角色:旁白
  2611. 出镜角色:许芸-校服装、徐母
  2612. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  2613. 画面类型:普通画面
  2614. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  2615. 分镜2
  2616. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  2617. 场景:徐家老旧厨房
  2618. 构图设计:近景,徐母面部特写
  2619. 运镜调度:固定镜头
  2620. 配音角色:徐母
  2621. 出镜角色:徐母
  2622. 台词内容:问我夜不归宿死哪儿去了。
  2623. 画面类型:对口型
  2624. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  2625. ##第2幕:徐家简陋客厅 黄昏 室内
  2626. 分镜3
  2627. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  2628. 场景:徐家简陋客厅
  2629. 构图设计:全景,景深虚化
  2630. 运镜调度:固定镜头
  2631. 配音角色:旁白
  2632. 出镜角色:无
  2633. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  2634. 画面类型:普通画面
  2635. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  2636. 分镜4
  2637. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  2638. 场景:徐家简陋客厅
  2639. 构图设计:特写,火车票
  2640. 运镜调度:固定镜头
  2641. 配音角色:旁白
  2642. 出镜角色:无
  2643. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  2644. 画面类型:普通画面
  2645. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  2646. "
  2647. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  2648. 强制要求:\n
  2649. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2650. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2651. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2652. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2653. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2654. 普通要求:\n
  2655. 1.剧本名(必须生成)必须与文档内容高度相关
  2656. 2.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如角色-少年、角色-青年、角色-中年、角色-老年这种情况,不得出现角色-愤怒、角色-隐忍、角色-求生等情绪和状态变化的同一角色
  2657. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  2658. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  2659. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、清晰的面部五官结构描写、身体体型特征(身高比例、体态、肌肉或瘦弱程度)、整体视觉风格,以及详细的穿着风格和服装细节。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数150-200字左右)在主体描述后用{}框起来。
  2660. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  2661. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  2662. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  2663. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  2664. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  2665. 3.{$mappedArtStyle_prompt}\n\n
  2666. 示例如下:\n
  2667. ###剧本名:西昆仑
  2668. ###故事梗概
  2669. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2670. ###剧本亮点
  2671. 亮点1:绝境奇药,生死一线
  2672. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2673. 亮点2:结拜兄妹,化解尴尬
  2674. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2675. 亮点3:纤发夺命,情愫暗涌
  2676. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2677. ###人物关系
  2678. 阿雪与梁萧之间存在兄妹之情。
  2679. ###核心矛盾
  2680. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2681. ###主体列表
  2682. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  2683. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  2684. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}}
  2685. ###美术风格
  2686. 基础画风风格词:厚涂古风
  2687. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2688. ###场景列表
  2689. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{写实。影视质感。广角。
  2690. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  2691. 无人物。}";
  2692. // 构建消息
  2693. $messages = [
  2694. [
  2695. 'role' => 'system',
  2696. 'content' => $systemPrompt
  2697. ],
  2698. [
  2699. 'role' => 'user',
  2700. 'content' => "以下是文档内容:
  2701. {$content}
  2702. 用户问题:
  2703. {$question}"
  2704. ]
  2705. ];
  2706. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2707. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2708. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2709. if ($model === 'deepseek-chat') {
  2710. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2711. $model = 'deepseek-v4-flash';
  2712. $thinkingMode = 'disabled';
  2713. } elseif ($model === 'deepseek-reasoner') {
  2714. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2715. $model = 'deepseek-v4-flash';
  2716. $thinkingMode = 'enabled';
  2717. }
  2718. $post_data = [
  2719. 'model' => $model,
  2720. 'messages' => $messages,
  2721. // 'max_tokens' => 8192,
  2722. 'temperature' => 0.7,
  2723. 'frequency_penalty' => 0,
  2724. 'presence_penalty' => 0,
  2725. 'response_format' => ['type' => 'text'],
  2726. 'thinking' => ['type'=>$thinkingMode],
  2727. 'stream' => true // 启用流式输出
  2728. ];
  2729. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2730. // 根据模型类型选择调用方法
  2731. $fullContent = '';
  2732. $fullReasoningContent = '';
  2733. $usage = [];
  2734. try {
  2735. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2736. // DeepSeek 官方模型使用 DeepSeek API
  2737. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2738. } else {
  2739. // 其他模型使用火山引擎API
  2740. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2741. }
  2742. // 验证返回值类型
  2743. if (!is_iterable($streamGenerator)) {
  2744. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  2745. dLog('deepseek')->error('addChat流式生成器无效', [
  2746. 'generator_type' => $errorType,
  2747. 'model' => $model,
  2748. 'anime_id' => $anime_id
  2749. ]);
  2750. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  2751. 'type' => $errorType,
  2752. 'model' => $model
  2753. ]);
  2754. yield [
  2755. 'type' => 'error',
  2756. 'script' => [],
  2757. 'episode' => [],
  2758. 'answer' => '',
  2759. 'reasoning' => '',
  2760. 'usage' => [],
  2761. 'error' => '接口返回数据异常,请重新请求'
  2762. ];
  2763. return;
  2764. }
  2765. // 处理流式输出
  2766. foreach ($streamGenerator as $chunk) {
  2767. if (isset($chunk['type'])) {
  2768. if ($chunk['type'] === 'done') {
  2769. // 最终结果
  2770. $fullContent = $chunk['full_content'];
  2771. $fullReasoningContent = $chunk['full_reasoning'];
  2772. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2773. } else {
  2774. // 逐块yield数据
  2775. yield $chunk;
  2776. }
  2777. }
  2778. }
  2779. } catch (\Exception $e) {
  2780. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  2781. 'model' => $model,
  2782. 'anime_id' => $anime_id,
  2783. 'trace' => $e->getTraceAsString()
  2784. ]);
  2785. logDB('deepseek', 'error', 'addChat流式处理失败', [
  2786. 'error' => $e->getMessage(),
  2787. 'model' => $model
  2788. ]);
  2789. yield [
  2790. 'type' => 'error',
  2791. 'script' => [],
  2792. 'episode' => [],
  2793. 'answer' => '',
  2794. 'reasoning' => '',
  2795. 'usage' => [],
  2796. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  2797. ];
  2798. return;
  2799. }
  2800. dLog('deepseek')->info('完整内容: '.$fullContent);
  2801. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  2802. // 处理完整内容并返回最终结果
  2803. $script_arr = [];
  2804. if ($fullContent) {
  2805. $script_arr = handleScriptContent($fullContent);
  2806. dLog('deepseek')->info('解析内容', $script_arr);
  2807. logDB('deepseek', 'info', '解析内容', $script_arr);
  2808. }
  2809. if (empty($script_arr['roles'])) {
  2810. // 未生成剧本相关内容,保存对话记录并返回提示
  2811. dLog('deepseek')->info('未生成剧本相关的内容');
  2812. try {
  2813. DB::beginTransaction();
  2814. $now = date('Y-m-d H:i:s');
  2815. // 保存对话记录
  2816. $records = [
  2817. [
  2818. 'uid' => $uid,
  2819. 'anime_id' => $anime_id,
  2820. 'sequence' => 0,
  2821. 'role' => 'user',
  2822. 'content' => $prompt,
  2823. 'created_at' => $now,
  2824. 'updated_at' => $now
  2825. ],
  2826. [
  2827. 'uid' => $uid,
  2828. 'anime_id' => $anime_id,
  2829. 'sequence' => 0,
  2830. 'role' => 'assistant',
  2831. // 'content' => $fullContent,
  2832. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  2833. 'created_at' => $now,
  2834. 'updated_at' => $now
  2835. ]
  2836. ];
  2837. DB::table('mp_anime_records')->insert($records);
  2838. DB::commit();
  2839. } catch (\Exception $e) {
  2840. DB::rollBack();
  2841. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  2842. }
  2843. yield [
  2844. 'type' => 'done',
  2845. 'script' => [],
  2846. 'episode' => [],
  2847. 'answer' => $fullContent,
  2848. 'reasoning' => $fullReasoningContent,
  2849. 'usage' => $usage,
  2850. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  2851. ];
  2852. return;
  2853. }
  2854. // 如果需要生成原文内容,从script_arr中提取
  2855. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  2856. $content = $script_arr['content'];
  2857. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  2858. if (!$content) {
  2859. yield [
  2860. 'type' => 'done',
  2861. 'script' => [],
  2862. 'episode' => [],
  2863. 'answer' => $fullContent,
  2864. 'reasoning' => $fullReasoningContent,
  2865. 'usage' => $usage,
  2866. 'error' => '未生成剧本内容,请调整提示词再试'
  2867. ];
  2868. return;
  2869. }
  2870. }
  2871. // 替换美术风格
  2872. if ($mappedArtStyle !== '') {
  2873. $script_arr['art_style'] = $mappedArtStyle;
  2874. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  2875. }
  2876. // 新建动漫
  2877. if ($user_anime_name == '新剧本策划') {
  2878. $anime_name = getProp($script_arr, 'script_name');
  2879. // if (!$anime_name) {
  2880. // // 未识别到剧本名,保存对话记录并返回提示
  2881. // dLog('deepseek')->info('未能识别到剧本名称');
  2882. // try {
  2883. // DB::beginTransaction();
  2884. // $now = date('Y-m-d H:i:s');
  2885. // // 保存对话记录
  2886. // $records = [
  2887. // [
  2888. // 'uid' => $uid,
  2889. // 'anime_id' => $anime_id,
  2890. // 'sequence' => 0,
  2891. // 'role' => 'user',
  2892. // 'content' => $prompt,
  2893. // 'created_at' => $now,
  2894. // 'updated_at' => $now
  2895. // ],
  2896. // [
  2897. // 'uid' => $uid,
  2898. // 'anime_id' => $anime_id,
  2899. // 'sequence' => 0,
  2900. // 'role' => 'assistant',
  2901. // 'content' => '未能生成剧本名称,请重试',
  2902. // 'created_at' => $now,
  2903. // 'updated_at' => $now
  2904. // ]
  2905. // ];
  2906. // DB::table('mp_anime_records')->insert($records);
  2907. // DB::commit();
  2908. // } catch (\Exception $e) {
  2909. // DB::rollBack();
  2910. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  2911. // }
  2912. // yield [
  2913. // 'type' => 'done',
  2914. // 'script' => [],
  2915. // 'episode' => [],
  2916. // 'answer' => $fullContent,
  2917. // 'reasoning' => $fullReasoningContent,
  2918. // 'usage' => $usage,
  2919. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  2920. // ];
  2921. // return;
  2922. // }
  2923. // 确认对话名称唯一性
  2924. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  2925. $anime_name = $anime_name . '_' . date('YmdHis');
  2926. }
  2927. }else {
  2928. $anime_name = $user_anime_name;
  2929. }
  2930. $table_data = [
  2931. 'user_id' => $uid,
  2932. 'anime_name' => $anime_name,
  2933. 'model' => $model,
  2934. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2935. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2936. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2937. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2938. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  2939. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2940. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  2941. 'status' => '解析完成',
  2942. 'content' => $content,
  2943. 'is_multi' => $is_multi,
  2944. 'generate_status' => '待执行',
  2945. 'updated_at' => date('Y-m-d H:i:s')
  2946. ];
  2947. $single_episode = [];
  2948. try {
  2949. DB::beginTransaction();
  2950. $now = date('Y-m-d H:i:s');
  2951. // 更新动漫大纲
  2952. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  2953. if (!$boolen) {
  2954. dLog('deepseek')->info('动漫保存失败', $table_data);
  2955. Utils::throwError('20003:动漫保存失败');
  2956. }
  2957. // 保存对话记录
  2958. $records = [
  2959. [
  2960. 'uid' => $uid,
  2961. 'anime_id' => $anime_id,
  2962. 'sequence' => 0,
  2963. 'role' => 'user',
  2964. 'content' => $prompt,
  2965. 'created_at' => date('Y-m-d H:i:s'),
  2966. 'updated_at' => date('Y-m-d H:i:s')
  2967. ],
  2968. [
  2969. 'uid' => $uid,
  2970. 'anime_id' => $anime_id,
  2971. 'sequence' => 0,
  2972. 'role' => 'assistant',
  2973. 'content' => $fullContent,
  2974. 'created_at' => date('Y-m-d H:i:s'),
  2975. 'updated_at' => date('Y-m-d H:i:s')
  2976. ]
  2977. ];
  2978. // 保存对话记录
  2979. $boolen3 = DB::table('mp_anime_records')->insert($records);
  2980. if (!$boolen3) {
  2981. Utils::throwError('20003:对话记录保存失败');
  2982. }
  2983. if ($is_single) {
  2984. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  2985. if (empty($episode_arr['acts'])) {
  2986. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  2987. }
  2988. $saveResult = $this->saveEpisodeVersionData(
  2989. $anime_id,
  2990. 1,
  2991. $episode_arr,
  2992. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  2993. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  2994. null,
  2995. null,
  2996. false,
  2997. $content,
  2998. $now
  2999. );
  3000. $single_episode = $saveResult['episode'];
  3001. $episode_id = $saveResult['episode_id'];
  3002. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3003. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3004. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3005. 'updated_at' => $now
  3006. ]);
  3007. if ($boolen5 === false) {
  3008. Utils::throwError('20003:单剧集主表资源同步失败');
  3009. }
  3010. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3011. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3012. $episode_record_content = '确认分镜大纲';
  3013. if ($content !== '') {
  3014. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3015. }
  3016. $episode_records = [
  3017. [
  3018. 'uid' => $uid,
  3019. 'anime_id' => $anime_id,
  3020. 'role' => 'user',
  3021. 'content' => $episode_record_content,
  3022. 'sequence' => 1,
  3023. 'episode_id' => $episode_id,
  3024. 'created_at' => $now,
  3025. 'updated_at' => $now
  3026. ],
  3027. [
  3028. 'uid' => $uid,
  3029. 'anime_id' => $anime_id,
  3030. 'role' => 'assistant',
  3031. 'content' => $fullContent,
  3032. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3033. 'sequence' => 1,
  3034. 'episode_id' => $episode_id,
  3035. 'created_at' => $now,
  3036. 'updated_at' => $now
  3037. ]
  3038. ];
  3039. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3040. if (!$boolen4) {
  3041. Utils::throwError('20003:单剧集分镜记录保存失败');
  3042. }
  3043. }
  3044. }catch (\Exception $e) {
  3045. DB::rollBack();
  3046. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3047. yield [
  3048. 'type' => 'done',
  3049. 'answer' => $fullContent,
  3050. 'reasoning' => $fullReasoningContent,
  3051. 'usage' => $usage,
  3052. 'error' => $e->getMessage(),
  3053. ];
  3054. return;
  3055. }
  3056. DB::commit();
  3057. dLog('deepseek')->info('保存完毕');
  3058. if ($is_single && !empty($single_episode)) {
  3059. // $this->batchSetGlobalRoleImg([
  3060. // 'anime_id' => $anime_id,
  3061. // ]);
  3062. // $this->batchSetGlobalSceneImg([
  3063. // 'anime_id' => $anime_id,
  3064. // ]);
  3065. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  3066. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  3067. }
  3068. $table_data['anime_id'] = $anime_id;
  3069. $table_data['roles'] = json_decode($table_data['roles'], true);
  3070. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3071. // $table_data['episodes'] = $script_arr['episodes'];
  3072. unset($table_data['created_at']);
  3073. unset($table_data['updated_at']);
  3074. unset($table_data['status']);
  3075. dLog('deepseek')->info('开始返回');
  3076. yield [
  3077. 'type' => 'done',
  3078. 'script' => $table_data,
  3079. 'episode' => $single_episode,
  3080. 'answer' => $fullContent,
  3081. 'reasoning' => $fullReasoningContent,
  3082. 'usage' => $usage
  3083. ];
  3084. }
  3085. public function reGenerateAnime($data) {
  3086. $uid = Site::getUid();
  3087. $file = getProp($data, 'file');
  3088. $content = getProp($data, 'content', '');
  3089. $bid = getProp($data, 'bid', 0);
  3090. $script_id = getProp($data, 'script_id', 0);
  3091. $anime_id = getProp($data, 'anime_id');
  3092. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3093. if (!$anime) {
  3094. Utils::throwError('20003:该对话不存在');
  3095. }
  3096. $user_anime_name = getProp($anime, 'anime_name');
  3097. $prompt = getProp($data, 'prompt');
  3098. // 处理文本模型
  3099. $model = getProp($data, 'model');
  3100. if (!$model) {
  3101. // 用户没有输入,从anime表获取
  3102. $model = getProp($anime, 'model');
  3103. if (!$model) {
  3104. // anime表也没有,使用默认值
  3105. $model = 'doubao-seed-2-0-mini-260215';
  3106. }
  3107. }
  3108. // 验证模型是否在可用模型表中
  3109. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3110. $model = 'doubao-seed-2-0-mini-260215';
  3111. }
  3112. $is_multi = getProp($anime, 'is_multi', 1);
  3113. $is_single = (int)$is_multi !== 1;
  3114. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  3115. if ($is_single) {
  3116. $episode_exists = DB::table('mp_anime_episodes')
  3117. ->where('anime_id', $anime_id)
  3118. ->where('sequence', 1)
  3119. ->exists();
  3120. if ($episode_exists) {
  3121. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  3122. }
  3123. }
  3124. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n本次修改要求如下:\n{$prompt}" : "请根据实例格式完成剧本大纲\n本次修改要求如下:\n{$prompt}");
  3125. // 提取文件内容
  3126. if ($file) {
  3127. $content = $this->extractFileContent($file);
  3128. if (!$content) {
  3129. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3130. }
  3131. } elseif ($script_id) {
  3132. $content = $this->getContentByScriptId($script_id);
  3133. if (!$content) {
  3134. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3135. }
  3136. } elseif ($bid) {
  3137. $content = $this->getContentByBid($bid);
  3138. if (!$content) {
  3139. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3140. }
  3141. } elseif ($content) {
  3142. $content = filterContent($content);
  3143. }else {
  3144. $content = filterContent(getProp($anime, 'content'));
  3145. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3146. $need_generate_content = true;
  3147. }
  3148. }
  3149. // 判断是否需要生成原文内容
  3150. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3151. // 如果需要生成原文内容,添加额外的要求
  3152. $content_generation_requirement = $need_generate_content
  3153. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3154. : "";
  3155. // 美术风格
  3156. $input_art_style = getProp($anime, 'art_style');
  3157. if (!$input_art_style) {
  3158. $input_art_style = getProp($data, 'art_style');
  3159. }
  3160. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3161. // 美术风格
  3162. if (!$mappedArtStyle) {
  3163. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3164. }else {
  3165. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$input_art_style}\n{$mappedArtStyle}>\n";
  3166. }
  3167. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3168. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3169. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3170. 中年女:邻居阿姨
  3171. 老年男:幽默大爷
  3172. 老年女:婆婆
  3173. 萌娃:奶气萌娃";
  3174. $system_message = ['role'=>'system', 'content'=>$is_single
  3175. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3176. 强制要求:
  3177. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3178. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3179. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3180. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3181. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3182. 普通要求:
  3183. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3184. 2.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如角色-少年、角色-青年、角色-中年、角色-老年这种情况,不得出现角色-愤怒、角色-隐忍、角色-求生等情绪和状态变化的同一角色
  3185. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3186. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3187. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、清晰的面部五官结构描写、身体体型特征(身高比例、体态、肌肉或瘦弱程度)、整体视觉风格,以及详细的穿着风格和服装细节。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数150-200字左右)在主体描述后用{}框起来。
  3188. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3189. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3190. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3191. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3192. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3193. 3.$mappedArtStyle_prompt\n\n
  3194. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3195. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3196. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3197. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3198. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3199. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3200. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)。
  3201. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3202. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3203. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3204. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3205. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3206. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3207. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3208. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3209. 示例如下:\n
  3210. ###剧本名:西昆仑
  3211. ###故事梗概
  3212. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3213. ###剧本亮点
  3214. 亮点1:绝境奇药,生死一线
  3215. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3216. 亮点2:结拜兄妹,化解尴尬
  3217. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3218. 亮点3:纤发夺命,情愫暗涌
  3219. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3220. ###人物关系
  3221. 阿雪与梁萧之间存在兄妹之情。
  3222. ###核心矛盾
  3223. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3224. ###主体列表
  3225. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  3226. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  3227. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}}
  3228. ###美术风格
  3229. 基础画风风格词:厚涂古风
  3230. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3231. ###场景列表
  3232. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{写实。影视质感。广角。
  3233. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3234. 无人物。}
  3235. ###分镜剧本
  3236. ##第1幕:徐家老旧厨房 白天 室内
  3237. 分镜1
  3238. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3239. 场景:徐家老旧厨房
  3240. 构图设计:全景,低角度仰视
  3241. 运镜调度:手持拍摄
  3242. 配音角色:旁白
  3243. 出镜角色:许芸-校服装、徐母
  3244. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3245. 画面类型:普通画面
  3246. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3247. 分镜2
  3248. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3249. 场景:徐家老旧厨房
  3250. 构图设计:近景,徐母面部特写
  3251. 运镜调度:固定镜头
  3252. 配音角色:徐母
  3253. 出镜角色:徐母
  3254. 台词内容:问我夜不归宿死哪儿去了。
  3255. 画面类型:对口型
  3256. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3257. ##第2幕:徐家简陋客厅 黄昏 室内
  3258. 分镜3
  3259. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3260. 场景:徐家简陋客厅
  3261. 构图设计:全景,景深虚化
  3262. 运镜调度:固定镜头
  3263. 配音角色:旁白
  3264. 出镜角色:无
  3265. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3266. 画面类型:普通画面
  3267. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3268. 分镜4
  3269. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3270. 场景:徐家简陋客厅
  3271. 构图设计:特写,火车票
  3272. 运镜调度:固定镜头
  3273. 配音角色:旁白
  3274. 出镜角色:无
  3275. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3276. 画面类型:普通画面
  3277. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3278. "
  3279. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3280. 强制要求:\n
  3281. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3282. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3283. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3284. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3285. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3286. 普通要求:\n
  3287. 1.剧本名(必须生成)必须与文档内容高度相关
  3288. 2.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如角色-少年、角色-青年、角色-中年、角色-老年这种情况,不得出现角色-愤怒、角色-隐忍、角色-求生等情绪和状态变化的同一角色
  3289. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3290. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3291. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、清晰的面部五官结构描写、身体体型特征(身高比例、体态、肌肉或瘦弱程度)、整体视觉风格,以及详细的穿着风格和服装细节。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数150-200字左右)在主体描述后用{}框起来。
  3292. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3293. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3294. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3295. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3296. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3297. 4.$mappedArtStyle_prompt\n\n
  3298. 示例如下:\n
  3299. ###剧本名:西昆仑
  3300. ###故事梗概
  3301. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3302. ###剧本亮点
  3303. 亮点1:绝境奇药,生死一线
  3304. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3305. 亮点2:结拜兄妹,化解尴尬
  3306. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3307. 亮点3:纤发夺命,情愫暗涌
  3308. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3309. ###人物关系
  3310. 阿雪与梁萧之间存在兄妹之情。
  3311. ###核心矛盾
  3312. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3313. ###主体列表
  3314. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  3315. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  3316. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}}
  3317. ###美术风格
  3318. 基础画风风格词:厚涂古风
  3319. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3320. ###场景列表
  3321. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{写实。影视质感。广角。
  3322. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3323. 无人物。}"];
  3324. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  3325. $episode_count = $this->extractEpisodeNumber($prompt);
  3326. if ((int)getProp($anime, 'is_multi') !== 1) {
  3327. yield [
  3328. 'type' => 'done',
  3329. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  3330. 'reasoning' => '',
  3331. 'usage' => []
  3332. ];
  3333. return;
  3334. }
  3335. if ($episode_count) {
  3336. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  3337. $system_message = [
  3338. 'role' => 'system',
  3339. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3340. 强制要求:\n
  3341. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3342. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3343. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3344. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3345. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3346. 普通要求:\n
  3347. 2.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如角色-少年、角色-青年、角色-中年、角色-老年这种情况,不得出现角色-愤怒、角色-隐忍、角色-求生等情绪和状态变化的同一角色
  3348. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3349. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3350. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、清晰的面部五官结构描写、身体体型特征(身高比例、体态、肌肉或瘦弱程度)、整体视觉风格,以及详细的穿着风格和服装细节。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数150-200字左右)在主体描述后用{}框起来。
  3351. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3352. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3353. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  3354. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3355. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3356. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  3357. 示例如下:\n
  3358. ###剧本名:西昆仑
  3359. ###故事梗概
  3360. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3361. ###剧本亮点
  3362. 亮点1:绝境奇药,生死一线
  3363. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3364. 亮点2:结拜兄妹,化解尴尬
  3365. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3366. 亮点3:纤发夺命,情愫暗涌
  3367. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3368. ###人物关系
  3369. 阿雪与梁萧之间存在兄妹之情。
  3370. ###核心矛盾
  3371. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3372. ###主体列表
  3373. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  3374. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  3375. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}}
  3376. ###美术风格
  3377. 基础画风风格词:厚涂古风
  3378. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3379. ###场景列表
  3380. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{写实。影视质感。广角。
  3381. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3382. 无人物。}
  3383. ###分集详细内容
  3384. ##第1章 重生
  3385. 我重生了。
  3386. 源于一个男人偏执的暗恋。
  3387. ##第2章 相救
  3388. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  3389. 我眼睛扫向站在锅炉后的卞大伟。"
  3390. ];
  3391. // 构建消息
  3392. $messages = [
  3393. $system_message,
  3394. [
  3395. 'role' => 'user',
  3396. 'content' => "以下是文档内容:
  3397. {$content}
  3398. 用户问题:
  3399. {$question}"
  3400. ]
  3401. ];
  3402. }else {
  3403. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  3404. // 构建消息
  3405. $messages = [
  3406. $system_message,
  3407. [
  3408. 'role' => 'user',
  3409. 'content' => "以下是文档内容:
  3410. {$content}
  3411. 用户问题:
  3412. {$question}"
  3413. ]
  3414. ];
  3415. }else {
  3416. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  3417. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  3418. return (array)$value;
  3419. })->toArray();
  3420. array_unshift($messages, $system_message);
  3421. $messages[] = [
  3422. 'role' => 'user',
  3423. 'content' => $prompt
  3424. ];
  3425. }
  3426. }
  3427. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3428. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3429. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3430. if ($model === 'deepseek-chat') {
  3431. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3432. $model = 'deepseek-v4-flash';
  3433. $thinkingMode = 'disabled';
  3434. } elseif ($model === 'deepseek-reasoner') {
  3435. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3436. $model = 'deepseek-v4-flash';
  3437. $thinkingMode = 'enabled';
  3438. }
  3439. $post_data = [
  3440. 'model' => $model,
  3441. 'messages' => $messages,
  3442. // 'max_tokens' => 8192,
  3443. 'temperature' => 0.7,
  3444. 'frequency_penalty' => 0,
  3445. 'presence_penalty' => 0,
  3446. 'response_format' => ['type' => 'text'],
  3447. 'thinking' => ['type' => $thinkingMode],
  3448. 'stream' => true // 启用流式输出
  3449. ];
  3450. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3451. // 根据模型类型选择调用方法
  3452. $fullContent = '';
  3453. $fullReasoningContent = '';
  3454. $usage = [];
  3455. // dd($post_data);
  3456. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  3457. try {
  3458. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3459. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3460. } else {
  3461. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3462. }
  3463. // 验证返回值类型
  3464. if (!is_iterable($streamGenerator)) {
  3465. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3466. dLog('deepseek')->error('方法名流式生成器无效', [
  3467. 'generator_type' => $errorType,
  3468. 'model' => $model,
  3469. // 添加其他上下文信息
  3470. ]);
  3471. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  3472. 'type' => $errorType,
  3473. 'model' => $model
  3474. ]);
  3475. yield [
  3476. 'type' => 'error',
  3477. // 根据方法返回相应的空数据结构
  3478. 'answer' => '',
  3479. 'reasoning' => '',
  3480. 'usage' => [],
  3481. 'error' => '接口返回数据异常,请重新请求'
  3482. ];
  3483. return;
  3484. }
  3485. // 处理流式输出
  3486. foreach ($streamGenerator as $chunk) {
  3487. if (isset($chunk['type'])) {
  3488. if ($chunk['type'] === 'done') {
  3489. $fullContent = $chunk['full_content'];
  3490. $fullReasoningContent = $chunk['full_reasoning'];
  3491. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3492. } else {
  3493. yield $chunk;
  3494. }
  3495. }
  3496. }
  3497. } catch (\Exception $e) {
  3498. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  3499. 'model' => $model,
  3500. 'trace' => $e->getTraceAsString()
  3501. ]);
  3502. logDB('deepseek', 'error', '方法名流式处理失败', [
  3503. 'error' => $e->getMessage(),
  3504. 'model' => $model
  3505. ]);
  3506. yield [
  3507. 'type' => 'error',
  3508. // 根据方法返回相应的空数据结构
  3509. 'answer' => '',
  3510. 'reasoning' => '',
  3511. 'usage' => [],
  3512. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3513. ];
  3514. return;
  3515. }
  3516. dLog('deepseek')->info('完整内容: '.$fullContent);
  3517. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3518. // 处理完整内容并返回最终结果
  3519. $script_arr = [];
  3520. if ($fullContent) {
  3521. $script_arr = handleScriptContent($fullContent);
  3522. dLog('deepseek')->info('解析内容', $script_arr);
  3523. logDB('deepseek', 'info', '解析内容', $script_arr);
  3524. }
  3525. if (empty($script_arr['roles'])) {
  3526. // 未生成剧本相关内容,保存对话记录并返回提示
  3527. dLog('deepseek')->info('未生成剧本相关的内容');
  3528. try {
  3529. $now = date('Y-m-d H:i:s');
  3530. // 保存对话记录
  3531. $records = [
  3532. [
  3533. 'uid' => $uid,
  3534. 'anime_id' => $anime_id,
  3535. 'sequence' => 0,
  3536. 'role' => 'user',
  3537. 'content' => $prompt,
  3538. 'created_at' => $now,
  3539. 'updated_at' => $now
  3540. ],
  3541. [
  3542. 'uid' => $uid,
  3543. 'anime_id' => $anime_id,
  3544. 'sequence' => 0,
  3545. 'role' => 'assistant',
  3546. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  3547. 'created_at' => $now,
  3548. 'updated_at' => $now
  3549. ]
  3550. ];
  3551. DB::table('mp_anime_records')->insert($records);
  3552. } catch (\Exception $e) {
  3553. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3554. }
  3555. yield [
  3556. 'type' => 'done',
  3557. 'script' => [],
  3558. 'episode' => [],
  3559. 'answer' => $fullContent,
  3560. 'reasoning' => $fullReasoningContent,
  3561. 'usage' => $usage,
  3562. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3563. ];
  3564. return;
  3565. }
  3566. // 替换美术风格
  3567. if ($mappedArtStyle !== '') {
  3568. $script_arr['art_style'] = $mappedArtStyle;
  3569. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3570. }
  3571. if ($user_anime_name != '新剧本策划') {
  3572. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  3573. // 确认对话名称唯一性
  3574. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  3575. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  3576. }
  3577. }else {
  3578. $anime_name = $user_anime_name;
  3579. }
  3580. $table_data = [
  3581. 'user_id' => $uid,
  3582. 'model' => $model,
  3583. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3584. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3585. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3586. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3587. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  3588. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3589. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  3590. 'status' => '解析完成',
  3591. 'generate_status' => '待执行',
  3592. 'updated_at' => date('Y-m-d H:i:s')
  3593. ];
  3594. if ($anime_name) $table_data['anime_name'] = $anime_name;
  3595. // 如果是修改集数,则将content内容更新(会改变原文)
  3596. if (isset($episode_count) && $episode_count > 0) {
  3597. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  3598. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  3599. }else {
  3600. // 如果需要生成原文内容,从script_arr中提取
  3601. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3602. $table_data['content'] = $script_arr['content'];
  3603. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  3604. if (!$content) {
  3605. yield [
  3606. 'type' => 'done',
  3607. 'script' => [],
  3608. 'episode' => [],
  3609. 'answer' => $fullContent,
  3610. 'reasoning' => $fullReasoningContent,
  3611. 'usage' => $usage,
  3612. 'error' => '未生成剧本内容,请调整提示词再试'
  3613. ];
  3614. return;
  3615. }
  3616. } else {
  3617. $chapters = $this->splitContent($content);
  3618. $chapter_count = count($chapters);
  3619. if ($chapter_count > 0) {
  3620. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3621. }
  3622. }
  3623. }
  3624. $single_episode = [];
  3625. try {
  3626. DB::beginTransaction();
  3627. $now = date('Y-m-d H:i:s');
  3628. // 更新动漫大纲
  3629. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3630. if (!$boolen) {
  3631. dLog('deepseek')->info('对话修改失败', $table_data);
  3632. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  3633. Utils::throwError('20003:对话修改失败');
  3634. }
  3635. // 保存对话记录
  3636. $records = [
  3637. [
  3638. 'uid' => $uid,
  3639. 'anime_id' => $anime_id,
  3640. 'sequence' => 0,
  3641. 'role' => 'user',
  3642. 'content' => $prompt,
  3643. 'created_at' => $now,
  3644. 'updated_at' => $now
  3645. ],
  3646. [
  3647. 'uid' => $uid,
  3648. 'anime_id' => $anime_id,
  3649. 'sequence' => 0,
  3650. 'role' => 'assistant',
  3651. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3652. 'content' => $fullContent,
  3653. 'created_at' => $now,
  3654. 'updated_at' => $now
  3655. ]
  3656. ];
  3657. // 保存对话记录
  3658. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3659. if (!$boolen3) {
  3660. Utils::throwError('20003:对话记录保存失败');
  3661. }
  3662. // 单剧集模式:生成并保存剧集信息
  3663. if ($is_single) {
  3664. $anime_name = getProp($anime, 'anime_name', '未命名');
  3665. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3666. if (empty($episode_arr['acts'])) {
  3667. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3668. }
  3669. $saveResult = $this->saveEpisodeVersionData(
  3670. $anime_id,
  3671. 1,
  3672. $episode_arr,
  3673. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3674. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3675. null,
  3676. null,
  3677. false,
  3678. $content,
  3679. $now
  3680. );
  3681. $single_episode = $saveResult['episode'];
  3682. $episode_id = $saveResult['episode_id'];
  3683. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3684. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3685. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3686. 'updated_at' => $now
  3687. ]);
  3688. if ($boolen5 === false) {
  3689. Utils::throwError('20003:单剧集主表资源同步失败');
  3690. }
  3691. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3692. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3693. $episode_record_content = '确认分镜大纲';
  3694. if ($content !== '') {
  3695. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3696. }
  3697. $episode_records = [
  3698. [
  3699. 'uid' => $uid,
  3700. 'anime_id' => $anime_id,
  3701. 'role' => 'user',
  3702. 'content' => $episode_record_content,
  3703. 'sequence' => 1,
  3704. 'episode_id' => $episode_id,
  3705. 'created_at' => $now,
  3706. 'updated_at' => $now
  3707. ],
  3708. [
  3709. 'uid' => $uid,
  3710. 'anime_id' => $anime_id,
  3711. 'role' => 'assistant',
  3712. 'content' => $fullContent,
  3713. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3714. 'sequence' => 1,
  3715. 'episode_id' => $episode_id,
  3716. 'created_at' => $now,
  3717. 'updated_at' => $now
  3718. ]
  3719. ];
  3720. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3721. if (!$boolen4) {
  3722. Utils::throwError('20003:单剧集分镜记录保存失败');
  3723. }
  3724. }
  3725. }catch (\Exception $e) {
  3726. DB::rollBack();
  3727. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  3728. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  3729. yield [
  3730. 'type' => 'done',
  3731. 'answer' => $fullContent,
  3732. 'reasoning' => $fullReasoningContent,
  3733. 'usage' => $usage,
  3734. 'error' => $e->getMessage(),
  3735. ];
  3736. return;
  3737. }
  3738. DB::commit();
  3739. dLog('deepseek')->info('保存完毕');
  3740. if ($is_single && !empty($single_episode)) {
  3741. // $this->batchSetGlobalRoleImg([
  3742. // 'anime_id' => $anime_id,
  3743. // ]);
  3744. // $this->batchSetGlobalSceneImg([
  3745. // 'anime_id' => $anime_id,
  3746. // ]);
  3747. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  3748. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  3749. }
  3750. $table_data['anime_id'] = $anime_id;
  3751. $table_data['roles'] = json_decode($table_data['roles'], true);
  3752. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3753. unset($table_data['updated_at']);
  3754. unset($table_data['status']);
  3755. yield [
  3756. 'type' => 'done',
  3757. 'script' => $table_data,
  3758. 'episode' => $single_episode,
  3759. 'answer' => $fullContent,
  3760. 'reasoning' => $fullReasoningContent,
  3761. 'usage' => $usage
  3762. ];
  3763. }
  3764. public function chat($data) {
  3765. $uid = Site::getUid();
  3766. $anime_id = getProp($data, 'anime_id');
  3767. $file = getProp($data, 'file');
  3768. $content = getProp($data, 'content', '');
  3769. $bid = getProp($data, 'bid', 0);
  3770. $script_id = getProp($data, 'script_id', 0);
  3771. $episode_number = getProp($data, 'episode_number', 1);
  3772. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  3773. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3774. if (!$anime) Utils::throwError('20003:该对话不存在!');
  3775. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  3776. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  3777. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  3778. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  3779. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  3780. $roles = is_array($roles) ? $roles : [];
  3781. $scenes = is_array($scenes) ? $scenes : [];
  3782. // 转换主体列表和场景列表的格式
  3783. // 获取参考主体或场景
  3784. if ((int)$episode_number === 1) {
  3785. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  3786. }else {
  3787. $prev_episode_number = $episode_number - 1;
  3788. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  3789. }
  3790. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  3791. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  3792. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  3793. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  3794. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3795. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3796. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3797. 中年女:邻居阿姨
  3798. 老年男:幽默大爷
  3799. 老年女:婆婆
  3800. 萌娃:奶气萌娃";
  3801. // 提取文件内容
  3802. if ($file) {
  3803. $uploaded_content = $this->extractFileContent($file);
  3804. if (!$uploaded_content) {
  3805. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3806. }
  3807. } elseif ($script_id) {
  3808. $uploaded_content = $this->getContentByScriptId($script_id);
  3809. if (!$uploaded_content) {
  3810. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3811. }
  3812. } elseif ($bid) {
  3813. $uploaded_content = $this->getContentByBid($bid);
  3814. if (!$uploaded_content) {
  3815. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3816. }
  3817. } elseif ($content) {
  3818. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  3819. }
  3820. // elseif ($prompt) {
  3821. // $uploaded_content = filterContent($prompt);
  3822. // }
  3823. else {
  3824. $uploaded_content = '';
  3825. }
  3826. $input_art_style = getProp($anime, 'art_style');
  3827. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3828. // 美术风格
  3829. if (!$mappedArtStyle) {
  3830. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3831. }else {
  3832. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$input_art_style}\n{$mappedArtStyle}>\n";
  3833. }
  3834. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  3835. $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3836. 强制要求:
  3837. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3838. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3839. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3840. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  3841. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3842. 普通要求:
  3843. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  3844. 2.<主体列表>可在以下主体中{$roles_content}\n选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  3845. 2.1如果分集内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了变化比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  3846. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3847. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3848. → 新主体的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、清晰的面部五官结构描写、身体体型特征(身高比例、体态、肌肉或瘦弱程度)、整体视觉风格,以及详细的穿着风格和服装细节。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数150-200字左右)在主体描述后用{}框起来。
  3849. → 新主体的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3850. 3.<场景列表>可在以下场景中{$scenes_content}\n选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(需带上冒号后的具体描述以及{}中的内容,原样输出)。
  3851. 3.1如果分集内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  3852. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3853. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3854. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3855. 3.$mappedArtStyle_prompt\n\n
  3856. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3857. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3858. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3859. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3860. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3861. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3862. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)。
  3863. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3864. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3865. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3866. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3867. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3868. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3869. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3870. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3871. 示例格式:\n
  3872. 第1集:隐形的守护者
  3873. ###故事梗概
  3874. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  3875. ###美术风格
  3876. 基础画风风格词:韩漫二次元
  3877. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  3878. ###主体列表
  3879. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  3880. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  3881. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  3882. ###场景列表
  3883. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{写实。影视质感。广角。
  3884. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3885. 无人物。}
  3886. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{写实。影视质感。冷青色调,浓雾弥漫。
  3887. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  3888. 无人物。}
  3889. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{写实。
  3890. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  3891. 无人物。}
  3892. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{写实。
  3893. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  3894. 无人物。}
  3895. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{写实。
  3896. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  3897. 无人物。}
  3898. ###分镜剧本
  3899. ##第1幕:徐家老旧厨房 白天 室内
  3900. 分镜1
  3901. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3902. 场景:徐家老旧厨房
  3903. 构图设计:全景,低角度仰视
  3904. 运镜调度:手持拍摄
  3905. 配音角色:旁白
  3906. 出镜角色:许芸-校服装、徐母
  3907. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3908. 画面类型:普通画面
  3909. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3910. 分镜2
  3911. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3912. 场景:徐家老旧厨房
  3913. 构图设计:近景,徐母面部特写
  3914. 运镜调度:固定镜头
  3915. 配音角色:徐母
  3916. 出镜角色:徐母
  3917. 台词内容:问我夜不归宿死哪儿去了。
  3918. 画面类型:对口型
  3919. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3920. ##第2幕:徐家简陋客厅 黄昏 室内
  3921. 分镜3
  3922. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3923. 场景:徐家简陋客厅
  3924. 构图设计:全景,景深虚化
  3925. 运镜调度:固定镜头
  3926. 配音角色:旁白
  3927. 出镜角色:无
  3928. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3929. 画面类型:普通画面
  3930. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3931. 分镜4
  3932. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3933. 场景:徐家简陋客厅
  3934. 构图设计:特写,火车票
  3935. 运镜调度:固定镜头
  3936. 配音角色:旁白
  3937. 出镜角色:无
  3938. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3939. 画面类型:普通画面
  3940. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  3941. \n\n";
  3942. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  3943. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  3944. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  3945. $prompt = $origin_prompt;
  3946. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  3947. // 获取章节内容
  3948. $full_content = getProp($anime, 'content');
  3949. // 根据章节内容拆分章节
  3950. $chapters = $this->splitContent($full_content);
  3951. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  3952. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  3953. $messages = [];
  3954. if ($prompt == '确认分镜大纲') {
  3955. // 暂时保留
  3956. $content = $uploaded_content ?: $chapter_content;
  3957. if ($is_single) $content = $full_content; // 单剧集使用全文
  3958. if (!$content) {
  3959. Utils::throwError('20003:章节内容无法获取,请确认');
  3960. }
  3961. $question = $is_single
  3962. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  3963. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本章剧情内容如下: \n\n$content";
  3964. // 构建消息
  3965. $messages[] =
  3966. [
  3967. 'role' => 'user',
  3968. 'content' => $question
  3969. ];
  3970. }else if ($prompt == '继续策划下一集') {
  3971. if ($is_single) {
  3972. Utils::throwError('20003:单剧集不支持继续策划下一集');
  3973. }
  3974. $content = $uploaded_content ?: $chapter_content;
  3975. if (!$content) {
  3976. Utils::throwError('20003:章节内容无法获取,请确认');
  3977. }
  3978. $question = $demo."请根据以上要求分析本章剧情,完成本章分镜剧本(需衔接上一章内容)";
  3979. // 获取上一集最后记录
  3980. $prev_sequence = $episode_number - 1;
  3981. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  3982. // 构建消息
  3983. $messages[] =
  3984. [
  3985. 'role' => 'user',
  3986. 'content' => $question
  3987. ];
  3988. }else {
  3989. $content = $uploaded_content ?: trim((string)getProp($base_episode, 'content'));
  3990. if (!$content) {
  3991. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  3992. }
  3993. if (!$content) {
  3994. Utils::throwError('20003:章节内容无法获取,请确认');
  3995. }
  3996. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  3997. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  3998. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。"
  3999. . "\n\n本次修改要求如下:\n{$origin_prompt}";
  4000. $messages[] =
  4001. [
  4002. 'role' => 'user',
  4003. 'content' => $question
  4004. ];
  4005. }
  4006. // 处理文本模型
  4007. $model = getProp($data, 'model');
  4008. if (!$model) {
  4009. // 用户没有输入,从anime表获取
  4010. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4011. $model = getProp($anime, 'model');
  4012. if (!$model) {
  4013. // anime表也没有,使用默认值
  4014. $model = 'doubao-seed-2-0-mini-260215';
  4015. }
  4016. }
  4017. // 验证模型是否在可用模型表中
  4018. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4019. $model = 'doubao-seed-2-0-mini-260215';
  4020. }
  4021. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4022. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4023. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4024. if ($model === 'deepseek-chat') {
  4025. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4026. $model = 'deepseek-v4-flash';
  4027. $thinkingMode = 'disabled';
  4028. } elseif ($model === 'deepseek-reasoner') {
  4029. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4030. $model = 'deepseek-v4-flash';
  4031. $thinkingMode = 'enabled';
  4032. }
  4033. $post_data = [
  4034. 'model' => $model,
  4035. 'messages' => $messages,
  4036. // 'max_tokens' => 8192,
  4037. 'temperature' => 0.7,
  4038. 'frequency_penalty' => 0,
  4039. 'presence_penalty' => 0,
  4040. 'response_format' => ['type' => 'text'],
  4041. 'thinking' => ['type' => $thinkingMode],
  4042. 'stream' => true // 启用流式输出
  4043. ];
  4044. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4045. // 根据模型类型选择调用方法
  4046. $fullContent = '';
  4047. $fullReasoningContent = '';
  4048. $usage = [];
  4049. try {
  4050. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4051. // DeepSeek 官方模型使用 DeepSeek API
  4052. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4053. } else {
  4054. // 其他模型使用火山引擎API
  4055. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4056. }
  4057. // 验证返回值类型
  4058. if (!is_iterable($streamGenerator)) {
  4059. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4060. dLog('deepseek')->error('chat流式生成器无效', [
  4061. 'generator_type' => $errorType,
  4062. 'model' => $model,
  4063. 'anime_id' => $anime_id,
  4064. 'episode_number' => $episode_number
  4065. ]);
  4066. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  4067. 'type' => $errorType,
  4068. 'model' => $model
  4069. ]);
  4070. yield [
  4071. 'type' => 'error',
  4072. 'episode' => [],
  4073. 'answer' => '',
  4074. 'reasoning' => '',
  4075. 'usage' => [],
  4076. 'error' => '接口返回数据异常,请重新请求'
  4077. ];
  4078. return;
  4079. }
  4080. // 处理流式输出
  4081. foreach ($streamGenerator as $chunk) {
  4082. if (isset($chunk['type'])) {
  4083. if ($chunk['type'] === 'done') {
  4084. // 最终结果
  4085. $fullContent = $chunk['full_content'];
  4086. $fullReasoningContent = $chunk['full_reasoning'];
  4087. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4088. } else {
  4089. // 逐块yield数据
  4090. yield $chunk;
  4091. }
  4092. }
  4093. }
  4094. } catch (\Exception $e) {
  4095. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  4096. 'model' => $model,
  4097. 'anime_id' => $anime_id,
  4098. 'episode_number' => $episode_number,
  4099. 'trace' => $e->getTraceAsString()
  4100. ]);
  4101. logDB('deepseek', 'error', 'chat流式处理失败', [
  4102. 'error' => $e->getMessage(),
  4103. 'model' => $model
  4104. ]);
  4105. yield [
  4106. 'type' => 'error',
  4107. 'episode' => [],
  4108. 'answer' => '',
  4109. 'reasoning' => '',
  4110. 'usage' => [],
  4111. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4112. ];
  4113. return;
  4114. }
  4115. dLog('deepseek')->info('完整内容: '.$fullContent);
  4116. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4117. // 处理完整内容并返回最终结果
  4118. $episode_arr = handleEpisodeContent($fullContent);
  4119. logDB('deepseek', 'info', '解析内容', $episode_arr);
  4120. if (empty($episode_arr['acts'])) {
  4121. // 未生成剧本相关内容,保存对话记录并返回提示
  4122. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  4123. try {
  4124. $now = date('Y-m-d H:i:s');
  4125. // 保存对话记录
  4126. $records = [
  4127. [
  4128. 'uid' => $uid,
  4129. 'anime_id' => $anime_id,
  4130. 'sequence' => $episode_number,
  4131. 'role' => 'user',
  4132. 'content' => $prompt,
  4133. 'created_at' => $now,
  4134. 'updated_at' => $now
  4135. ],
  4136. [
  4137. 'uid' => $uid,
  4138. 'anime_id' => $anime_id,
  4139. 'sequence' => $episode_number,
  4140. 'role' => 'assistant',
  4141. 'content' => $fullContent,
  4142. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4143. 'created_at' => $now,
  4144. 'updated_at' => $now
  4145. ]
  4146. ];
  4147. DB::table('mp_anime_records')->insert($records);
  4148. } catch (\Exception $e) {
  4149. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4150. }
  4151. yield [
  4152. 'type' => 'done',
  4153. 'episode' => [],
  4154. 'answer' => $fullContent,
  4155. 'reasoning' => $fullReasoningContent,
  4156. 'usage' => $usage,
  4157. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  4158. ];
  4159. return;
  4160. }
  4161. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  4162. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  4163. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  4164. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  4165. $now = date('Y-m-d H:i:s');
  4166. try {
  4167. DB::beginTransaction();
  4168. $saveResult = $this->saveEpisodeVersionData(
  4169. $anime_id,
  4170. $episode_number,
  4171. $episode_arr,
  4172. $existing_roles,
  4173. $existing_scenes,
  4174. $current_episode,
  4175. $base_episode,
  4176. $is_regenerate_version,
  4177. $content,
  4178. $now
  4179. );
  4180. $episode = $saveResult['episode'];
  4181. $episode_id = $saveResult['episode_id'];
  4182. $merged_roles = $saveResult['merged_roles'];
  4183. $merged_scenes = $saveResult['merged_scenes'];
  4184. $record_content = $origin_prompt;
  4185. if ($uploaded_content !== '') {
  4186. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  4187. }
  4188. $records = [
  4189. [
  4190. 'uid' => $uid,
  4191. 'anime_id' => $anime_id,
  4192. 'role' => 'user',
  4193. 'content' => $record_content,
  4194. 'sequence' => $episode_number,
  4195. 'episode_id' => $episode_id,
  4196. 'created_at' => $now,
  4197. 'updated_at' => $now
  4198. ],
  4199. [
  4200. 'uid' => $uid,
  4201. 'anime_id' => $anime_id,
  4202. 'role' => 'assistant',
  4203. 'content' => $fullContent,
  4204. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4205. 'sequence' => $episode_number,
  4206. 'episode_id' => $episode_id,
  4207. 'created_at' => $now,
  4208. 'updated_at' => $now
  4209. ]
  4210. ];
  4211. $boolen4 = DB::table('mp_anime_records')->insert($records);
  4212. if (!$boolen4) {
  4213. Utils::throwError('20003:对话记录保存失败');
  4214. }
  4215. // 保存模型到anime表
  4216. DB::table('mp_animes')->where('id', $anime_id)->update([
  4217. 'model' => $model,
  4218. 'updated_at' => $now
  4219. ]);
  4220. }catch (\Exception $e) {
  4221. DB::rollBack();
  4222. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  4223. yield [
  4224. 'type' => 'done',
  4225. 'answer' => $fullContent,
  4226. 'reasoning' => $fullReasoningContent,
  4227. 'usage' => $usage,
  4228. 'error' => $e->getMessage(),
  4229. ];
  4230. return;
  4231. }
  4232. DB::commit();
  4233. if ($is_global_generate_pics) {
  4234. // // 批量生成全局角色图片
  4235. // $this->batchSetGlobalRoleImg([
  4236. // 'anime_id' => $anime_id,
  4237. // ], true);
  4238. // // 批量生成全局场景图片
  4239. // $this->batchSetGlobalSceneImg([
  4240. // 'anime_id' => $anime_id,
  4241. // ], true);
  4242. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4243. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4244. }
  4245. $episode['episode_id'] = $episode_id;
  4246. $episode['roles'] = $merged_roles;
  4247. $episode['scenes'] = $merged_scenes;
  4248. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  4249. yield [
  4250. 'type' => 'done',
  4251. 'episode' => $episode,
  4252. 'answer' => $fullContent,
  4253. 'reasoning' => $fullReasoningContent,
  4254. 'usage' => $usage
  4255. ];
  4256. }
  4257. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  4258. {
  4259. $episode_arr = [
  4260. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  4261. 'intro' => getProp($script_arr, 'intro'),
  4262. 'art_style' => getProp($script_arr, 'art_style'),
  4263. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4264. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4265. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  4266. ];
  4267. if (empty($episode_arr['acts'])) {
  4268. $fallback_episode_arr = handleEpisodeContent($fullContent);
  4269. if (!empty($fallback_episode_arr['acts'])) {
  4270. $episode_arr = array_merge($fallback_episode_arr, [
  4271. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  4272. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  4273. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  4274. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  4275. ]);
  4276. }
  4277. }
  4278. // if (!getProp($episode_arr, 'episode_title')) {
  4279. // $episode_title = '';
  4280. // $episodes = getProp($script_arr, 'episodes', []);
  4281. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  4282. // $episode_title = '第1集:' . $episodes[0]['title'];
  4283. // }
  4284. // if (!$episode_title) {
  4285. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  4286. // }
  4287. // $episode_arr['episode_title'] = $episode_title;
  4288. // }
  4289. return $episode_arr;
  4290. }
  4291. private function saveEpisodeVersionData(
  4292. int $anime_id,
  4293. int $episode_number,
  4294. array $episode_arr,
  4295. array $existing_roles,
  4296. array $existing_scenes,
  4297. $current_episode,
  4298. $base_episode,
  4299. bool $is_regenerate_version,
  4300. string $content,
  4301. string $now
  4302. ): array {
  4303. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  4304. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  4305. $merged_roles = $generated_roles;
  4306. $merged_scenes = $generated_scenes;
  4307. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  4308. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  4309. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  4310. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4311. $global_roles = json_decode(getProp($anime, 'roles'), true);
  4312. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  4313. $global_roles = is_array($global_roles) ? $global_roles : [];
  4314. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  4315. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  4316. // 检查并创建 roles 的图片生成任务
  4317. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  4318. // 检查并创建 scenes 的图片生成任务
  4319. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  4320. $arr = $this->batchSetEpisodeRolesAndScenesImg($merged_roles, $merged_scenes);
  4321. if ($arr && is_array($arr)) {
  4322. $merged_roles = $arr['roles'];
  4323. $merged_scenes = $arr['scenes'];
  4324. }
  4325. // 同步新出现的主体和场景到全局
  4326. $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  4327. $role_arr = [];
  4328. foreach ($merged_roles as $item) {
  4329. $role_arr[$item['role']] = $item;
  4330. }
  4331. $version_count = DB::table('mp_anime_episodes')
  4332. ->where('anime_id', $anime_id)
  4333. ->where('episode_number', $episode_number)
  4334. ->count('id');
  4335. $episode = [
  4336. 'anime_id' => $anime_id,
  4337. 'episode_number' => $episode_number,
  4338. 'title' => getProp($episode_arr, 'episode_title'),
  4339. 'content' => $content,
  4340. 'intro' => getProp($episode_arr, 'intro'),
  4341. 'art_style' => getProp($episode_arr, 'art_style'),
  4342. 'roles' => json_encode($merged_roles, 256),
  4343. 'scenes' => json_encode($merged_scenes, 256),
  4344. 'generate_status' => '待执行',
  4345. 'generate_at' => $now,
  4346. 'is_default' => 1,
  4347. 'updated_at' => $now,
  4348. ];
  4349. $del_flag = false;
  4350. if ($is_regenerate_version) {
  4351. DB::table('mp_anime_episodes')
  4352. ->where('anime_id', $anime_id)
  4353. ->where('episode_number', $episode_number)
  4354. ->update(['is_default' => 0, 'updated_at' => $now]);
  4355. $episode['sequence'] = $version_count + 1;
  4356. $episode['created_at'] = $now;
  4357. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  4358. if (!$episode_id) {
  4359. Utils::throwError('20003:创建剧集版本失败');
  4360. }
  4361. } else {
  4362. $target_episode = $current_episode ?: $base_episode;
  4363. if ($target_episode) {
  4364. $episode_id = getProp($target_episode, 'id');
  4365. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  4366. DB::table('mp_anime_episodes')
  4367. ->where('anime_id', $anime_id)
  4368. ->where('episode_number', $episode_number)
  4369. ->where('id', '<>', $episode_id)
  4370. ->update(['is_default' => 0, 'updated_at' => $now]);
  4371. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  4372. if ($boolen === false) {
  4373. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  4374. Utils::throwError('20003:分集内容保存失败');
  4375. }
  4376. $del_flag = true;
  4377. } else {
  4378. DB::table('mp_anime_episodes')
  4379. ->where('anime_id', $anime_id)
  4380. ->where('episode_number', $episode_number)
  4381. ->update(['is_default' => 0, 'updated_at' => $now]);
  4382. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  4383. $episode['created_at'] = $now;
  4384. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  4385. if (!$episode_id) {
  4386. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  4387. Utils::throwError('20003:分集内容保存失败');
  4388. }
  4389. }
  4390. }
  4391. $segments = [];
  4392. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  4393. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  4394. $emotion_list = array_flip($emotion_list);
  4395. foreach ($acts as $act) {
  4396. $act_segments = getProp($act, 'segments', []);
  4397. if (!is_array($act_segments)) {
  4398. continue;
  4399. }
  4400. foreach ($act_segments as $segment) {
  4401. $voice_actor = getProp($segment, 'voice_actor');
  4402. $timbre_info = isset($role_arr[$voice_actor]) ? $role_arr[$voice_actor] : [];
  4403. $voice_type = getProp($timbre_info, 'voice_type');
  4404. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  4405. if ($timbre_emotion) {
  4406. $timbre_emotion = explode(',', $timbre_emotion);
  4407. } else {
  4408. $timbre_emotion = [];
  4409. }
  4410. $emotion = getProp($segment, 'emotion', '中性');
  4411. if (!in_array($emotion, $timbre_emotion)) {
  4412. $emotion = '中性';
  4413. }
  4414. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  4415. $segments[] = [
  4416. 'anime_id' => $anime_id,
  4417. 'episode_id' => $episode_id,
  4418. 'episode_number' => $episode_number,
  4419. 'act_number' => getProp($act, 'act_number'),
  4420. 'act_title' => getProp($act, 'act_title'),
  4421. 'segment_id' => getProp($segment, 'segment_id'),
  4422. 'segment_number' => getProp($segment, 'segment_number'),
  4423. 'segment_content' => getProp($segment, 'segment_content'),
  4424. 'description' => getProp($segment, 'description'),
  4425. 'composition' => getProp($segment, 'composition'),
  4426. 'camera_movement' => getProp($segment, 'camera_movement'),
  4427. 'voice_actor' => $voice_actor,
  4428. 'dialogue' => getProp($segment, 'dialogue'),
  4429. 'frame_type' => getProp($segment, 'frame_type'),
  4430. 'scene' => getProp($segment, 'scene'),
  4431. 'characters' => getProp($segment, 'characters'),
  4432. 'tail_frame' => getProp($segment, 'tail_frame'),
  4433. 'voice_name' => getProp($timbre_info, 'voice_name'),
  4434. 'voice_type' => $voice_type,
  4435. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  4436. 'emotion' => $emotion,
  4437. 'emotion_type' => $emotion_type,
  4438. 'gender' => getProp($segment, 'gender', '0'),
  4439. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  4440. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  4441. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  4442. 'pitch' => getProp($segment, 'pitch', 0),
  4443. 'created_at' => $now,
  4444. 'updated_at' => $now
  4445. ];
  4446. }
  4447. }
  4448. if ($segments) {
  4449. if ($del_flag) {
  4450. DB::table('mp_episode_segments')
  4451. ->where('anime_id', $anime_id)
  4452. ->where('episode_id', $episode_id)
  4453. ->delete();
  4454. }
  4455. $boolen = DB::table('mp_episode_segments')->insert($segments);
  4456. if (!$boolen) {
  4457. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  4458. Utils::throwError('20003:分镜内容保存失败');
  4459. }
  4460. }
  4461. $episode['episode_id'] = $episode_id;
  4462. $episode['roles'] = $merged_roles;
  4463. $episode['scenes'] = $merged_scenes;
  4464. $episode['acts'] = $acts;
  4465. return [
  4466. 'episode' => $episode,
  4467. 'episode_id' => $episode_id,
  4468. 'merged_roles' => $merged_roles,
  4469. 'merged_scenes' => $merged_scenes,
  4470. ];
  4471. }
  4472. private function buildEpisodeItemContent(array $items, string $nameKey): string
  4473. {
  4474. $content = '';
  4475. foreach ($items as $item) {
  4476. $name = trim((string)getProp($item, $nameKey));
  4477. if ($name === '' || $name === '旁白') {
  4478. continue;
  4479. }
  4480. $description = trim((string)getProp($item, 'description'));
  4481. $content .= $name . ': ' . $description;
  4482. if ($nameKey == 'role') {
  4483. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  4484. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  4485. $voice_name = trim(getProp($item, 'voice_name'));
  4486. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  4487. }else {
  4488. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  4489. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  4490. }
  4491. $content .= "\n";
  4492. }
  4493. return trim($content);
  4494. }
  4495. private function getEpisodeChatContent($animeId, $sequence, $content) {
  4496. if ((int)$sequence <= 0) {
  4497. return [];
  4498. }
  4499. $origin_content = '';
  4500. if ($content) {
  4501. $origin_content = '本集内容:'.$content;
  4502. }else {
  4503. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  4504. if ($origin_content) $origin_content = '原文内容:'.$origin_content;
  4505. }
  4506. // 获取分集信息
  4507. $episode = DB::table('mp_anime_episodes')
  4508. ->where('anime_id', $animeId)
  4509. ->where('sequence', $sequence)
  4510. ->where('is_default', 1)
  4511. ->first();
  4512. if (!$episode) {
  4513. return [];
  4514. }
  4515. $episode_id = getProp($episode, 'id');
  4516. $episode_number = getProp($episode, 'episode_number');
  4517. $title = getProp($episode, 'title');
  4518. $intro = getProp($episode, 'intro');
  4519. $art_style = getProp($episode, 'art_style');
  4520. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  4521. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  4522. // 组装纯文本内容
  4523. $content = '';
  4524. // 添加分集标题和梗概
  4525. $content .= "###第{$episode_number}集:{$title}\n\n";
  4526. $content .= "###故事梗概\n";
  4527. $content .= trim($intro) . "\n\n";
  4528. // 添加美术风格
  4529. $content .= "###美术风格\n";
  4530. $content .= trim($art_style) . "\n\n";
  4531. // 添加主体列表
  4532. $content .= "###主体列表\n";
  4533. foreach ($roles as $role) {
  4534. $name = getProp($role, 'name');
  4535. $description = getProp($role, 'description');
  4536. $pic_prompt = getProp($role, 'pic_prompt');
  4537. $content .= "{$name}: {$description}";
  4538. if ($pic_prompt) $content .= "{{$pic_prompt}}";
  4539. $content .= "\n";
  4540. }
  4541. $content .= "\n";
  4542. // 添加场景列表
  4543. $content .= "###场景列表\n";
  4544. foreach ($scenes as $scene) {
  4545. $name = getProp($scene, 'name');
  4546. $description = getProp($scene, 'description');
  4547. $pic_prompt = getProp($role, 'pic_prompt');
  4548. $content .= "{$name}: {$description}";
  4549. if ($pic_prompt) $content .= "{{$pic_prompt}}";
  4550. $content .= "\n";
  4551. }
  4552. $content .= "\n";
  4553. // 获取分镜信息
  4554. $segments = DB::table('mp_episode_segments')
  4555. ->where('anime_id', $animeId)
  4556. ->where('episode_id', $episode_id)
  4557. ->orderBy('segment_number')
  4558. ->get();
  4559. if ($segments && count($segments) > 0) {
  4560. $content .= "###分镜剧本\n";
  4561. // 按幕分组
  4562. $currentAct = null;
  4563. foreach ($segments as $segment) {
  4564. $act_number = getProp($segment, 'act_number');
  4565. $segment_number = getProp($segment, 'segment_number');
  4566. $segment_content = getProp($segment, 'segment_content');
  4567. $scene_description = getProp($segment, 'scene_description');
  4568. $scene_name = getProp($segment, 'scene_name');
  4569. $composition = getProp($segment, 'composition');
  4570. $camera_movement = getProp($segment, 'camera_movement');
  4571. $voice_type = getProp($segment, 'voice_type');
  4572. $characters = getProp($segment, 'characters');
  4573. $dialogue = getProp($segment, 'dialogue');
  4574. $frame_type = getProp($segment, 'frame_type');
  4575. $tail_frame_description = getProp($segment, 'tail_frame_description');
  4576. // 如果是新的幕,添加幕标题
  4577. if ($act_number !== $currentAct) {
  4578. $currentAct = $act_number;
  4579. $content .= "##第{$act_number}幕:{$scene_name}\n";
  4580. }
  4581. // 添加分镜信息
  4582. $content .= "分镜{$segment_number}\n";
  4583. $content .= "分镜内容:{$segment_content}\n";
  4584. // $content .= "画面描述:{$scene_description}\n";
  4585. // $content .= "场景:{$scene_name}\n";
  4586. // $content .= "构图设计:{$composition}\n";
  4587. // $content .= "运镜调度:{$camera_movement}\n";
  4588. // if (!empty($voice_type)) {
  4589. // $content .= "配音角色:{$voice_type}\n";
  4590. // }
  4591. // if (!empty($characters)) {
  4592. // $content .= "出镜角色:{$characters}\n";
  4593. // }
  4594. // if (!empty($dialogue)) {
  4595. // $content .= "台词内容:\"{$dialogue}\"\n";
  4596. // }
  4597. // $content .= "画面类型:{$frame_type}\n";
  4598. // $content .= "尾帧描述:{$tail_frame_description}\n";
  4599. $content .= "\n";
  4600. }
  4601. }
  4602. $content = trim($content);
  4603. if($content) $content = "上集剧本内容:\n{$content}";
  4604. return [
  4605. [
  4606. 'role' => 'user',
  4607. 'content' => $origin_content
  4608. ],
  4609. [
  4610. 'role' => 'assistant',
  4611. 'content' => $content
  4612. ]
  4613. ];
  4614. }
  4615. private function getEpisodeChatMessages($animeId, $sequence): array
  4616. {
  4617. if ((int)$sequence <= 0) {
  4618. return [];
  4619. }
  4620. return DB::table('mp_anime_records')
  4621. ->where('anime_id', $animeId)
  4622. ->where('sequence', $sequence)
  4623. ->where('episode_id', '>', 0)
  4624. ->select('role', 'content')
  4625. ->orderBy('created_at')
  4626. ->orderBy('id')
  4627. ->get()
  4628. ->map(function ($value) {
  4629. return (array)$value;
  4630. })
  4631. ->toArray();
  4632. }
  4633. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  4634. {
  4635. $existingMap = [];
  4636. foreach ($existingItems as $item) {
  4637. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  4638. if ($itemKey === '') {
  4639. continue;
  4640. }
  4641. $existingMap[$itemKey] = $item;
  4642. }
  4643. if (!$generatedItems) {
  4644. return array_values($existingItems);
  4645. }
  4646. $merged = [];
  4647. foreach ($generatedItems as $item) {
  4648. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  4649. if ($itemKey === '') {
  4650. continue;
  4651. }
  4652. if (isset($existingMap[$itemKey])) {
  4653. if (trim((string)getProp($item, 'description')) === '') {
  4654. $merged[] = $existingMap[$itemKey];
  4655. continue;
  4656. }
  4657. // 检查内容是否发生变化
  4658. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  4659. if (!$isChanged) {
  4660. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  4661. $mergedItem = [
  4662. $nameKey => trim((string)getProp($item, $nameKey)),
  4663. 'description' => trim((string)getProp($item, 'description')),
  4664. ];
  4665. // 如果有 pic_prompt,添加到合并项中
  4666. $picPrompt = getProp($item, 'pic_prompt');
  4667. if (!empty($picPrompt)) {
  4668. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  4669. }
  4670. // 继承现有项的 URL
  4671. $existingUrl = getProp($existingMap[$itemKey], 'url');
  4672. if (!empty($existingUrl)) {
  4673. $mergedItem['url'] = $existingUrl;
  4674. }
  4675. // 继承现有项的 task_id
  4676. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  4677. if (!empty($existingTaskId)) {
  4678. $mergedItem['task_id'] = $existingTaskId;
  4679. }
  4680. // 继承现有项的 task_status
  4681. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  4682. if (!empty($existingTaskStatus)) {
  4683. $mergedItem['task_status'] = $existingTaskStatus;
  4684. }
  4685. // 保留生成项的音色字段
  4686. $voiceName = getProp($item, 'voice_name');
  4687. if (!empty($voiceName)) {
  4688. $mergedItem['voice_name'] = $voiceName;
  4689. }
  4690. $voiceType = getProp($item, 'voice_type');
  4691. if (!empty($voiceType)) {
  4692. $mergedItem['voice_type'] = $voiceType;
  4693. }
  4694. $audioUrl = getProp($item, 'voice_audio_url');
  4695. if (!empty($audioUrl)) {
  4696. $mergedItem['voice_audio_url'] = $audioUrl;
  4697. }
  4698. $merged[] = $mergedItem;
  4699. } else {
  4700. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  4701. $mergedItem = [
  4702. $nameKey => trim((string)getProp($item, $nameKey)),
  4703. 'description' => trim((string)getProp($item, 'description')),
  4704. ];
  4705. // 如果有 pic_prompt,添加到合并项中
  4706. $picPrompt = getProp($item, 'pic_prompt');
  4707. if (!empty($picPrompt)) {
  4708. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  4709. }
  4710. // 保留生成项的音色字段
  4711. $voiceName = getProp($item, 'voice_name');
  4712. if (!empty($voiceName)) {
  4713. $mergedItem['voice_name'] = $voiceName;
  4714. }
  4715. $voiceType = getProp($item, 'voice_type');
  4716. if (!empty($voiceType)) {
  4717. $mergedItem['voice_type'] = $voiceType;
  4718. }
  4719. $audioUrl = getProp($item, 'voice_audio_url');
  4720. if (!empty($audioUrl)) {
  4721. $mergedItem['voice_audio_url'] = $audioUrl;
  4722. }
  4723. // 不继承 URL、task_id 和 task_status(重置状态)
  4724. $merged[] = $mergedItem;
  4725. }
  4726. } else {
  4727. // 新增项,保留生成项的所有字段
  4728. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  4729. }
  4730. }
  4731. return $merged ?: array_values($existingItems);
  4732. }
  4733. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  4734. {
  4735. $resetItem = [
  4736. $nameKey => trim((string)getProp($item, $nameKey)),
  4737. 'description' => trim((string)getProp($item, 'description')),
  4738. ];
  4739. // 保留指定的字段
  4740. foreach ($preserveFields as $field) {
  4741. $value = getProp($item, $field);
  4742. if (!empty($value)) {
  4743. $resetItem[$field] = $value;
  4744. }
  4745. }
  4746. return $resetItem;
  4747. }
  4748. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  4749. {
  4750. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  4751. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  4752. if ($existingKey !== $generatedKey) {
  4753. return true;
  4754. }
  4755. // 比较 description 是否变化
  4756. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  4757. return true;
  4758. }
  4759. // 比较 pic_prompt 是否变化
  4760. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  4761. }
  4762. private function normalizeEpisodeResourceKey($value): string
  4763. {
  4764. $value = trim((string)$value);
  4765. if ($value === '') {
  4766. return '';
  4767. }
  4768. return strtolower((string)preg_replace('/\s+/u', '', $value));
  4769. }
  4770. // 生成全局角色图片
  4771. private function batchSetGlobalRoleImg($data, $is_force=false) {
  4772. $anime_id = getProp($data, 'anime_id');
  4773. if (!$anime_id) Utils::throwError('1002:请选择对话');
  4774. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4775. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  4776. $art_style = getProp($anime, 'art_style');
  4777. $update_flag = false;
  4778. foreach ($roles as &$role) {
  4779. $role_name = getProp($role, 'role');
  4780. if ($role_name == '旁白') continue;
  4781. // 优先使用 pic_prompt,如果没有则使用 description
  4782. $pic_prompt = getProp($role, 'pic_prompt');
  4783. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  4784. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4785. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4786. // 参考图地址
  4787. $ref_img_url = getProp($role, 'url');
  4788. if (!$is_force && $ref_img_url) continue;
  4789. $update_flag = true;
  4790. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  4791. try {
  4792. $params = [
  4793. 'prompt' => $description,
  4794. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  4795. 'ref_img_urls' => []
  4796. ];
  4797. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4798. $task_id = $task->id;
  4799. if (!$task_id) {
  4800. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  4801. }
  4802. $role['task_id'] = $task_id;
  4803. $role['task_status'] = 'processing';
  4804. } catch (\Exception $e) {
  4805. Utils::throwError("20003:" . $e->getMessage());
  4806. }
  4807. }
  4808. if (!$update_flag) return true;
  4809. // 保存角色信息
  4810. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  4811. 'roles' => json_encode($roles, 256),
  4812. 'generate_status' => '执行中',
  4813. 'generate_at' => date('Y-m-d H:i:s'),
  4814. 'updated_at' => date('Y-m-d H:i:s')
  4815. ]);
  4816. if (!$boolen) {
  4817. Utils::throwError('20003:保存角色信息失败');
  4818. }
  4819. return $boolen;
  4820. }
  4821. // 生成全局场景图片
  4822. private function batchSetGlobalSceneImg($data, $is_force=false) {
  4823. $anime_id = getProp($data, 'anime_id');
  4824. if (!$anime_id) Utils::throwError('1002:请选择对话');
  4825. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4826. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  4827. $art_style = getProp($anime, 'art_style');
  4828. $update_flag = false;
  4829. foreach ($scenes as &$scene) {
  4830. $scene_name = getProp($scene, 'scene');
  4831. // 优先使用 pic_prompt,如果没有则使用 description
  4832. $pic_prompt = getProp($scene, 'pic_prompt');
  4833. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  4834. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  4835. // 参考图地址
  4836. $ref_img_url = getProp($scene, 'url');
  4837. if (!$is_force && $ref_img_url) continue;
  4838. $update_flag = true;
  4839. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  4840. try {
  4841. $params = [
  4842. 'prompt' => $description,
  4843. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  4844. 'ref_img_urls' => []
  4845. ];
  4846. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4847. $task_id = $task->id;
  4848. if (!$task_id) {
  4849. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  4850. }
  4851. $scene['task_id'] = $task_id;
  4852. $scene['task_status'] = 'processing';
  4853. } catch (\Exception $e) {
  4854. Utils::throwError("20003:" . $e->getMessage());
  4855. }
  4856. }
  4857. if (!$update_flag) return true;
  4858. // 保存角色信息
  4859. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  4860. 'scenes' => json_encode($scenes, 256),
  4861. 'generate_status' => '执行中',
  4862. 'generate_at' => date('Y-m-d H:i:s'),
  4863. 'updated_at' => date('Y-m-d H:i:s')
  4864. ]);
  4865. if (!$boolen) {
  4866. Utils::throwError('20003:保存角色信息失败');
  4867. }
  4868. return $boolen;
  4869. }
  4870. // 生成分镜主体和场景图片
  4871. private function batchSetEpisodeRolesAndScenesImg($roles, $scenes, $is_force=false) {
  4872. // $episode_id = getProp($data, 'episode_id');
  4873. // if (!$episode_id) Utils::throwError('1002:请选择剧集');
  4874. // $episode = DB::table('mp_anime_episodes')
  4875. // ->where('id', $episode_id)
  4876. // ->where('is_deleted', 0)
  4877. // ->first();
  4878. // if (!$episode) Utils::throwError('20003:该剧集不存在');
  4879. // $anime_id = getProp($episode, 'anime_id');
  4880. // $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  4881. // $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  4882. // $art_style = getProp($episode, 'art_style');
  4883. // // 如果没有美术风格,从动漫全局获取
  4884. // if (!$art_style) {
  4885. // $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4886. // $art_style = getProp($anime, 'art_style');
  4887. // }
  4888. $update_flag = false;
  4889. // 处理角色图片生成
  4890. foreach ($roles as &$role) {
  4891. $role_name = getProp($role, 'role');
  4892. if ($role_name == '旁白') continue;
  4893. // 优先使用 pic_prompt,如果没有则使用 description
  4894. $pic_prompt = getProp($role, 'pic_prompt');
  4895. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  4896. $description = "写实。全景,正面拍摄。主体描述:{$description}\n不要出现场景或背景,只能生成一个人物";
  4897. // 参考图地址
  4898. $ref_img_url = getProp($role, 'url');
  4899. if (!$is_force && $ref_img_url) continue;
  4900. $update_flag = true;
  4901. // 调用AIImageGenerationService的生成图片任务接口
  4902. try {
  4903. $params = [
  4904. 'prompt' => $description,
  4905. 'ref_img_urls' => []
  4906. ];
  4907. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4908. $task_id = $task->id;
  4909. if (!$task_id) {
  4910. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  4911. continue; // 不中断,继续处理其他角色
  4912. }
  4913. $role['task_id'] = $task_id;
  4914. $role['task_status'] = 'processing';
  4915. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  4916. // 'episode_id' => $episode_id,
  4917. 'task_id' => $task_id
  4918. ]);
  4919. } catch (\Exception $e) {
  4920. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  4921. // 不抛出异常,继续处理其他角色
  4922. }
  4923. }
  4924. // 处理场景图片生成
  4925. foreach ($scenes as &$scene) {
  4926. $scene_name = getProp($scene, 'scene');
  4927. // 优先使用 pic_prompt,如果没有则使用 description
  4928. $pic_prompt = getProp($scene, 'pic_prompt');
  4929. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  4930. $description = "写实。\n场景描述:{$description}\n无人物";
  4931. // 参考图地址
  4932. $ref_img_url = getProp($scene, 'url');
  4933. if (!$is_force && $ref_img_url) continue;
  4934. $update_flag = true;
  4935. // 调用AIImageGenerationService的生成图片任务接口
  4936. try {
  4937. $params = [
  4938. 'prompt' => $description,
  4939. 'ref_img_urls' => []
  4940. ];
  4941. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4942. $task_id = $task->id;
  4943. if (!$task_id) {
  4944. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  4945. continue; // 不中断,继续处理其他场景
  4946. }
  4947. $scene['task_id'] = $task_id;
  4948. $scene['task_status'] = 'processing';
  4949. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  4950. // 'episode_id' => $episode_id,
  4951. 'task_id' => $task_id
  4952. ]);
  4953. } catch (\Exception $e) {
  4954. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  4955. // 不抛出异常,继续处理其他场景
  4956. }
  4957. }
  4958. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes];
  4959. // // 保存剧集的角色和场景信息
  4960. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4961. // 'roles' => json_encode($roles, 256),
  4962. // 'scenes' => json_encode($scenes, 256),
  4963. // 'generate_status' => '执行中',
  4964. // 'generate_at' => date('Y-m-d H:i:s'),
  4965. // 'updated_at' => date('Y-m-d H:i:s')
  4966. // ]);
  4967. // if (!$boolen) {
  4968. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  4969. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  4970. // }
  4971. dLog('deepseek')->info('剧集角色和场景图片任务创建完成', [
  4972. // 'episode_id' => $episode_id,
  4973. 'roles_count' => count($roles),
  4974. 'scenes_count' => count($scenes)
  4975. ]);
  4976. return ['roles' => $roles, 'scenes' => $scenes];
  4977. }
  4978. /**
  4979. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  4980. *
  4981. * @param int $anime_id 动漫对话ID
  4982. * @param int $episode_id 分集ID
  4983. * @return bool
  4984. */
  4985. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  4986. // 获取全局角色和场景数据
  4987. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4988. if (!$anime) {
  4989. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  4990. return false;
  4991. }
  4992. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  4993. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  4994. // 获取指定的分集
  4995. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  4996. if (!$episode) {
  4997. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  4998. return false;
  4999. }
  5000. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  5001. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  5002. $roles_updated = false;
  5003. $scenes_updated = false;
  5004. // 继承角色的task_id、task_status和url
  5005. foreach ($episode_roles as &$episode_role) {
  5006. $episode_role_name = getProp($episode_role, 'role');
  5007. $episode_description = getProp($episode_role, 'description');
  5008. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  5009. $episode_url = getProp($episode_role, 'url');
  5010. // 跳过旁白角色
  5011. if ($episode_role_name == '旁白') {
  5012. continue;
  5013. }
  5014. // 如果剧集中已有URL,跳过
  5015. if (!empty($episode_url)) {
  5016. continue;
  5017. }
  5018. // 遍历全局角色数据,查找匹配的角色
  5019. foreach ($global_roles as $global_role) {
  5020. $global_role_name = getProp($global_role, 'role');
  5021. $global_description = getProp($global_role, 'description');
  5022. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  5023. $global_url = getProp($global_role, 'url');
  5024. $global_task_id = getProp($global_role, 'task_id');
  5025. $global_task_status = getProp($global_role, 'task_status');
  5026. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  5027. if ($episode_role_name == $global_role_name
  5028. && $episode_description == $global_description
  5029. && $episode_pic_prompt == $global_pic_prompt) {
  5030. // 继承 task_id、task_status 和 url
  5031. if (!empty($global_task_id)) {
  5032. $episode_role['task_id'] = $global_task_id;
  5033. $episode_role['task_status'] = $global_task_status;
  5034. $roles_updated = true;
  5035. dLog('deepseek')->info('剧集角色继承全局task_id', [
  5036. 'episode_id' => $episode_id,
  5037. 'role' => $episode_role_name,
  5038. 'task_id' => $global_task_id,
  5039. 'task_status' => $global_task_status
  5040. ]);
  5041. }
  5042. if (!empty($global_url)) {
  5043. $episode_role['url'] = $global_url;
  5044. $roles_updated = true;
  5045. dLog('deepseek')->info('剧集角色继承全局url', [
  5046. 'episode_id' => $episode_id,
  5047. 'role' => $episode_role_name,
  5048. 'url' => $global_url
  5049. ]);
  5050. }
  5051. break;
  5052. }
  5053. }
  5054. }
  5055. // 继承场景的task_id、task_status和url
  5056. foreach ($episode_scenes as &$episode_scene) {
  5057. $episode_scene_name = getProp($episode_scene, 'scene');
  5058. $episode_description = getProp($episode_scene, 'description');
  5059. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  5060. $episode_url = getProp($episode_scene, 'url');
  5061. // 如果剧集中已有URL,跳过
  5062. if (!empty($episode_url)) {
  5063. continue;
  5064. }
  5065. // 遍历全局场景数据,查找匹配的场景
  5066. foreach ($global_scenes as $global_scene) {
  5067. $global_scene_name = getProp($global_scene, 'scene');
  5068. $global_description = getProp($global_scene, 'description');
  5069. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  5070. $global_url = getProp($global_scene, 'url');
  5071. $global_task_id = getProp($global_scene, 'task_id');
  5072. $global_task_status = getProp($global_scene, 'task_status');
  5073. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  5074. if ($episode_scene_name == $global_scene_name
  5075. && $episode_description == $global_description
  5076. && $episode_pic_prompt == $global_pic_prompt) {
  5077. // 继承 task_id、task_status 和 url
  5078. if (!empty($global_task_id)) {
  5079. $episode_scene['task_id'] = $global_task_id;
  5080. $episode_scene['task_status'] = $global_task_status;
  5081. $scenes_updated = true;
  5082. dLog('deepseek')->info('剧集场景继承全局task_id', [
  5083. 'episode_id' => $episode_id,
  5084. 'scene' => $episode_scene_name,
  5085. 'task_id' => $global_task_id,
  5086. 'task_status' => $global_task_status
  5087. ]);
  5088. }
  5089. if (!empty($global_url)) {
  5090. $episode_scene['url'] = $global_url;
  5091. $scenes_updated = true;
  5092. dLog('deepseek')->info('剧集场景继承全局url', [
  5093. 'episode_id' => $episode_id,
  5094. 'scene' => $episode_scene_name,
  5095. 'url' => $global_url
  5096. ]);
  5097. }
  5098. break;
  5099. }
  5100. }
  5101. }
  5102. // 如果有更新,则保存到数据库
  5103. if ($roles_updated || $scenes_updated) {
  5104. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5105. if ($roles_updated) {
  5106. $update_data['roles'] = json_encode($episode_roles, 256);
  5107. }
  5108. if ($scenes_updated) {
  5109. $update_data['scenes'] = json_encode($episode_scenes, 256);
  5110. }
  5111. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5112. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  5113. 'episode_id' => $episode_id,
  5114. 'roles_updated' => $roles_updated,
  5115. 'scenes_updated' => $scenes_updated
  5116. ]);
  5117. }
  5118. return true;
  5119. }
  5120. public function chatChangeImg($data) {
  5121. $segment = getProp($data, 'segment');
  5122. $segment_content = getProp($segment, 'segment_content');
  5123. $prompt = getProp($data, 'prompt');
  5124. $ref_img = getProp($data, 'ref_img');
  5125. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  5126. // 处理文本模型
  5127. $model = getProp($data, 'model');
  5128. if (!$model) {
  5129. // 用户没有输入,从anime表获取
  5130. $segment_id = getProp($segment, 'segment_id');
  5131. if ($segment_id) {
  5132. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  5133. if ($episode_id) {
  5134. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  5135. if ($anime_id) {
  5136. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  5137. }
  5138. }
  5139. }
  5140. if (!$model) {
  5141. // anime表也没有,使用默认值
  5142. $model = 'doubao-seed-2-0-mini-260215';
  5143. }
  5144. }
  5145. // 验证模型是否在可用模型表中
  5146. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5147. $model = 'doubao-seed-2-0-mini-260215';
  5148. }
  5149. $messages[] =
  5150. [
  5151. 'role' => 'user',
  5152. 'content' => $question
  5153. ];
  5154. $post_data = [
  5155. 'model' => $model,
  5156. 'messages' => $messages,
  5157. // 'max_tokens' => 8192,
  5158. 'temperature' => 0.7,
  5159. 'frequency_penalty' => 0,
  5160. 'presence_penalty' => 0,
  5161. 'response_format' => ['type' => 'text'],
  5162. 'stream' => false // 是否启用流式输出
  5163. ];
  5164. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5165. // DeepSeek 官方模型使用 DeepSeek API
  5166. $chatResult = $this->chatOnly($post_data);
  5167. } else {
  5168. // 其他模型使用火山引擎API
  5169. $chatResult = $this->volcEngineChatCompletion($post_data);
  5170. }
  5171. if (is_array($chatResult)) {
  5172. extract($chatResult);
  5173. }else {
  5174. Utils::throwError('20003: 接口调用失败!');
  5175. }
  5176. return [
  5177. 'type' => 'done',
  5178. // 'episode' => $episode,
  5179. 'answer' => $fullContent,
  5180. 'reasoning' => $fullReasoningContent,
  5181. 'usage' => $usage
  5182. ];
  5183. }
  5184. // 仅调用deepseek对话接口
  5185. private function chatOnly($post_data) {
  5186. $client = new Client(['timeout' => 1200, 'verify' => false]);
  5187. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  5188. $response = $result->getBody()->getContents();
  5189. $response_arr = json_decode($response, true);
  5190. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  5191. $fullContent = '';
  5192. $fullReasoningContent = [];
  5193. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  5194. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  5195. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  5196. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  5197. }
  5198. return [
  5199. 'fullContent' => $fullContent,
  5200. 'fullReasoningContent' => $fullReasoningContent,
  5201. 'usage' => $usage
  5202. ];
  5203. }
  5204. private function splitContent($content) {
  5205. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  5206. $chapters = [];
  5207. // 匹配不同格式的章节标题:###第X章、##第X章、第X章、###第X集、##第X集、第X集
  5208. $pattern = '/^(#{0,3}\s*第[^章集]*[章集][^\n]*)\n(.*?)(?=\n#{0,3}\s*第[^章集]*[章集]|\z)/ms';
  5209. if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
  5210. foreach ($matches as $match) {
  5211. $title = trim($match[1], "# \t\n\r\0\x0B"); // 去除标题前的#号和空白字符
  5212. $chapterContent = trim($match[2]); // 去除内容前后的空白字符
  5213. if (!empty($title) && !empty($chapterContent)) {
  5214. $chapters[] = [
  5215. 'title' => $title,
  5216. 'content' => $chapterContent
  5217. ];
  5218. }
  5219. }
  5220. }else {
  5221. $chapters[] = [
  5222. 'title' => '',
  5223. 'content' => $content
  5224. ];
  5225. }
  5226. return $chapters;
  5227. }
  5228. public function getContentByBid($bid) {
  5229. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  5230. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  5231. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  5232. $content = '';
  5233. foreach ($chapters as $chapter) {
  5234. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  5235. }
  5236. return $content;
  5237. }
  5238. public function getContentByScriptId($script_id) {
  5239. $content = '';
  5240. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  5241. if ($contents) $content = implode(PHP_EOL, $contents);
  5242. return $content;
  5243. }
  5244. /**
  5245. * 根据文件类型提取文本内容
  5246. *
  5247. * @param mixed $file 文件对象或文件路径
  5248. * @return string
  5249. */
  5250. public function extractFileContent($file) {
  5251. // 获取文件路径和扩展名
  5252. if (is_string($file)) {
  5253. $filePath = $file;
  5254. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  5255. } else {
  5256. // Laravel UploadedFile 对象
  5257. $filePath = $file->getRealPath();
  5258. $extension = strtolower($file->getClientOriginalExtension());
  5259. }
  5260. $content = '';
  5261. switch ($extension) {
  5262. case 'txt':
  5263. $content = $this->extractTxtContent($filePath);
  5264. break;
  5265. case 'pdf':
  5266. $content = $this->extractPdfContent($filePath);
  5267. break;
  5268. case 'doc':
  5269. case 'docx':
  5270. $content = $this->extractWordContent($filePath);
  5271. break;
  5272. // case 'jpg':
  5273. // case 'jpeg':
  5274. // case 'png':
  5275. // case 'gif':
  5276. // case 'bmp':
  5277. // case 'webp':
  5278. // $content = $this->extractImageContent($filePath);
  5279. // break;
  5280. default:
  5281. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  5282. }
  5283. return $content;
  5284. }
  5285. /**
  5286. * 提取 TXT 文件内容
  5287. */
  5288. private function extractTxtContent($filePath) {
  5289. if (!file_exists($filePath)) {
  5290. Utils::throwError('20003:文件不存在');
  5291. }
  5292. $content = file_get_contents($filePath);
  5293. // 尝试检测并转换编码
  5294. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  5295. if ($encoding && $encoding !== 'UTF-8') {
  5296. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  5297. }
  5298. return trim($content);
  5299. }
  5300. /**
  5301. * 提取 PDF 文件内容
  5302. */
  5303. private function extractPdfContent($filePath) {
  5304. if (!file_exists($filePath)) {
  5305. Utils::throwError('20003:文件不存在');
  5306. }
  5307. try {
  5308. $parser = new PdfParser();
  5309. $pdf = $parser->parseFile($filePath);
  5310. $content = $pdf->getText();
  5311. return trim($content);
  5312. } catch (\Exception $e) {
  5313. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  5314. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  5315. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  5316. }
  5317. }
  5318. /**
  5319. * 提取 Word 文件内容(支持 doc 和 docx)
  5320. */
  5321. private function extractWordContent($filePath) {
  5322. if (!file_exists($filePath)) {
  5323. Utils::throwError('20003:文件不存在');
  5324. }
  5325. try {
  5326. $phpWord = WordIOFactory::load($filePath);
  5327. $content = '';
  5328. foreach ($phpWord->getSections() as $section) {
  5329. foreach ($section->getElements() as $element) {
  5330. $content .= $this->extractWordElementText($element);
  5331. }
  5332. }
  5333. return trim($content);
  5334. } catch (\Exception $e) {
  5335. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  5336. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  5337. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  5338. }
  5339. }
  5340. /**
  5341. * 递归提取 Word 元素中的文本
  5342. */
  5343. private function extractWordElementText($element) {
  5344. $text = '';
  5345. if (method_exists($element, 'getText')) {
  5346. $text .= $element->getText() . "\n";
  5347. } elseif (method_exists($element, 'getElements')) {
  5348. foreach ($element->getElements() as $childElement) {
  5349. $text .= $this->extractWordElementText($childElement);
  5350. }
  5351. }
  5352. return $text;
  5353. }
  5354. /**
  5355. * 提取图片内容(使用火山引擎 OCR)
  5356. */
  5357. private function extractImageContent($filePath) {
  5358. if (!file_exists($filePath)) {
  5359. Utils::throwError('20003:文件不存在');
  5360. }
  5361. try {
  5362. // 读取图片并转换为 base64
  5363. $imageData = file_get_contents($filePath);
  5364. $base64Image = base64_encode($imageData);
  5365. // 调用火山引擎 OCR 服务
  5366. $content = $this->callVolcEngineOCR($base64Image);
  5367. return trim($content);
  5368. } catch (\Exception $e) {
  5369. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  5370. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  5371. Utils::throwError('20003:图片识别失败');
  5372. }
  5373. }
  5374. /**
  5375. * 调用火山引擎 OCR 服务识别图片文字
  5376. *
  5377. * @param string $base64Image base64 编码的图片数据
  5378. * @return string 识别的文字内容
  5379. */
  5380. private function callVolcEngineOCR($base64Image) {
  5381. $method = 'POST';
  5382. $service = 'cv';
  5383. $host = 'visual.volcengineapi.com';
  5384. $region = env('VOLC_REGION', 'cn-north-1');
  5385. $access_key = env('VOLC_AK');
  5386. $secret_key = env('VOLC_SK');
  5387. $action = 'OCRNormal';
  5388. $version = '2020-08-26';
  5389. if (!$access_key || !$secret_key) {
  5390. Utils::throwError('20003:请配置火山引擎 AK/SK');
  5391. }
  5392. // 请求体
  5393. $body = json_encode([
  5394. 'image_base64' => $base64Image
  5395. ]);
  5396. // 生成签名
  5397. $headers = $this->getVolcEngineSignHeaders(
  5398. $method, $service, $host, $region,
  5399. "Action={$action}&Version={$version}",
  5400. $access_key, $secret_key, $body
  5401. );
  5402. $client = new Client(['timeout' => 60, 'verify' => false]);
  5403. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  5404. 'headers' => $headers,
  5405. 'body' => $body
  5406. ]);
  5407. $response_arr = json_decode($response->getBody()->getContents(), true);
  5408. // 提取识别的文字
  5409. $textLines = [];
  5410. if (isset($response_arr['data']['line_texts'])) {
  5411. $textLines = $response_arr['data']['line_texts'];
  5412. } elseif (isset($response_arr['data']['ocr_infos'])) {
  5413. foreach ($response_arr['data']['ocr_infos'] as $info) {
  5414. if (isset($info['text'])) {
  5415. $textLines[] = $info['text'];
  5416. }
  5417. }
  5418. }
  5419. if (empty($textLines)) {
  5420. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  5421. return '';
  5422. }
  5423. return implode("\n", $textLines);
  5424. }
  5425. /**
  5426. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  5427. */
  5428. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  5429. $contentType = 'application/json';
  5430. $accept = 'application/json';
  5431. // 获取当前UTC时间
  5432. $t = new DateTime('now', new DateTimeZone('UTC'));
  5433. $xDate = $t->format('Ymd\THis\Z');
  5434. $dateStamp = $t->format('Ymd');
  5435. // 计算 body 的 sha256 哈希
  5436. $payloadHash = hash('sha256', $body);
  5437. // 1. 拼接规范请求串
  5438. $canonicalUri = '/';
  5439. $canonicalQueryString = $queryString;
  5440. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  5441. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  5442. $canonicalRequest = implode("\n", [
  5443. $method,
  5444. $canonicalUri,
  5445. $canonicalQueryString,
  5446. $canonicalHeaders,
  5447. $signedHeaders,
  5448. $payloadHash
  5449. ]);
  5450. // 2. 拼接待签名字符串
  5451. $algorithm = 'HMAC-SHA256';
  5452. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  5453. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  5454. $stringToSign = implode("\n", [
  5455. $algorithm,
  5456. $xDate,
  5457. $credentialScope,
  5458. $hashedCanonicalRequest
  5459. ]);
  5460. // 3. 计算签名
  5461. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  5462. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  5463. // 4. 添加签名到请求头
  5464. $authorizationHeader = sprintf(
  5465. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  5466. $algorithm,
  5467. $access_key,
  5468. $credentialScope,
  5469. $signedHeaders,
  5470. $signature
  5471. );
  5472. return [
  5473. 'Accept' => $accept,
  5474. 'Content-Type' => $contentType,
  5475. 'Host' => $host,
  5476. 'X-Date' => $xDate,
  5477. 'X-Content-Sha256'=> $payloadHash,
  5478. 'Authorization' => $authorizationHeader
  5479. ];
  5480. }
  5481. public function generateScriptWords($cid, $model = 'r1') {
  5482. ini_set('max_execution_time', 0);
  5483. if (!$cid) Utils::throwError('20003: 请选择章节!');
  5484. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  5485. // 模型兼容性处理和思考模式设置
  5486. $thinkingMode = 'disabled';
  5487. $reasoningEffort = 'high';
  5488. if ($model == 'r1') {
  5489. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  5490. $thinkingMode = 'enabled';
  5491. } else {
  5492. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  5493. $thinkingMode = 'disabled';
  5494. }
  5495. $messages = [
  5496. [
  5497. 'role' => 'system',
  5498. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  5499. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  5500. 2.非对话部分请全部用旁白角色代替
  5501. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  5502. ],
  5503. [
  5504. 'role' => 'user',
  5505. 'content' => $content
  5506. ]
  5507. ];
  5508. $post_data = [
  5509. 'model' => $model,
  5510. 'messages' => $messages,
  5511. // 'max_tokens' => 8192,
  5512. 'temperature' => 1,
  5513. 'frequency_penalty' => 0,
  5514. 'presence_penalty' => 0,
  5515. 'thinking' => ['type' => $thinkingMode],
  5516. 'response_format' => [
  5517. 'type' => 'text'
  5518. ],
  5519. 'stream' => false
  5520. ];
  5521. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5522. // 根据模型类型选择调用方法
  5523. $fullContent = '';
  5524. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5525. // DeepSeek 官方模型使用 DeepSeek API
  5526. $chatResult = $this->chatOnly($post_data);
  5527. } else {
  5528. // 其他模型使用火山引擎API
  5529. $chatResult = $this->volcEngineChatCompletion($post_data);
  5530. }
  5531. if (is_array($chatResult)) {
  5532. $fullContent = $chatResult['fullContent'];
  5533. }
  5534. return $fullContent;
  5535. }
  5536. /**
  5537. * 智能化解析集数信息
  5538. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  5539. *
  5540. * @param string $prompt 用户输入的提示词
  5541. * @return int|null 解析出的集数,如果没有找到则返回null
  5542. */
  5543. private function extractEpisodeNumber($prompt)
  5544. {
  5545. if (empty($prompt)) {
  5546. return null;
  5547. }
  5548. // 定义各种可能的表达模式
  5549. $patterns = [
  5550. // 基本模式:改成N集、调整成N集、修改成N集
  5551. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  5552. // 扩展模式:分成N集、拆分成N集、分割成N集
  5553. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  5554. // 数量模式:N集、共N集、总共N集
  5555. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  5556. // 制作模式:制作N集、生成N集、创建N集
  5557. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  5558. // 计划模式:计划N集、预计N集、打算N集
  5559. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  5560. // 需要模式:需要N集、要N集
  5561. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  5562. // 中文数字模式:改成三集、调整成五集等
  5563. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  5564. // 英文数字模式
  5565. '/(?: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',
  5566. ];
  5567. // 中文数字转阿拉伯数字的映射
  5568. $chineseNumbers = [
  5569. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  5570. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  5571. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  5572. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  5573. ];
  5574. // 逐个尝试匹配模式
  5575. foreach ($patterns as $pattern) {
  5576. if (preg_match($pattern, $prompt, $matches)) {
  5577. $number = trim($matches[1]);
  5578. // 如果是中文数字,转换为阿拉伯数字
  5579. if (isset($chineseNumbers[$number])) {
  5580. return $chineseNumbers[$number];
  5581. }
  5582. // 如果是阿拉伯数字,直接返回
  5583. if (is_numeric($number)) {
  5584. $episodeNum = intval($number);
  5585. // 合理性检查:集数应该在1-100之间
  5586. if ($episodeNum >= 1 && $episodeNum <= 100) {
  5587. return $episodeNum;
  5588. }
  5589. }
  5590. }
  5591. }
  5592. return null;
  5593. }
  5594. /**
  5595. * 调用火山引擎对话(Chat) API
  5596. *
  5597. * @param array $params 包含以下参数:
  5598. * - model: 模型ID(必填)
  5599. * - messages: 消息列表(必填)
  5600. * - stream: 是否流式输出(可选,默认false)
  5601. * - max_tokens: 最大输出token数(可选)
  5602. * - temperature: 采样温度(可选,默认1)
  5603. * - top_p: 核采样概率(可选,默认0.7)
  5604. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  5605. * - presence_penalty: 存在惩罚系数(可选,默认0)
  5606. * - stop: 停止词(可选)
  5607. * - tools: 工具列表(可选)
  5608. * @return array|Generator 非流式返回数组,流式返回生成器
  5609. */
  5610. public function volcEngineChatCompletion(array $params)
  5611. {
  5612. $apiKey = env('VOLC_AI_API_KEY');
  5613. if (empty($apiKey)) {
  5614. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  5615. }
  5616. // 构建请求参数
  5617. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  5618. $requestData = [
  5619. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  5620. 'messages' => $params['messages'] ?? [],
  5621. ];
  5622. if (!in_array($originalModel, $this->valid_text_models)) {
  5623. Utils::throwError('20003:该模型不支持!');
  5624. }
  5625. // 添加可选参数
  5626. if (isset($params['stream'])) {
  5627. $requestData['stream'] = $params['stream'];
  5628. }
  5629. if (isset($params['stream_options'])) {
  5630. $requestData['stream_options'] = $params['stream_options'];
  5631. }
  5632. if (isset($params['max_tokens'])) {
  5633. $requestData['max_tokens'] = $params['max_tokens'];
  5634. }
  5635. if (isset($params['max_completion_tokens'])) {
  5636. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  5637. }
  5638. if (isset($params['temperature'])) {
  5639. $requestData['temperature'] = $params['temperature'];
  5640. }
  5641. if (isset($params['top_p'])) {
  5642. $requestData['top_p'] = $params['top_p'];
  5643. }
  5644. if (isset($params['frequency_penalty'])) {
  5645. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  5646. }
  5647. if (isset($params['presence_penalty'])) {
  5648. $requestData['presence_penalty'] = $params['presence_penalty'];
  5649. }
  5650. if (isset($params['stop'])) {
  5651. $requestData['stop'] = $params['stop'];
  5652. }
  5653. if (isset($params['tools'])) {
  5654. $requestData['tools'] = $params['tools'];
  5655. }
  5656. if (isset($params['tool_choice'])) {
  5657. $requestData['tool_choice'] = $params['tool_choice'];
  5658. }
  5659. if (isset($params['response_format'])) {
  5660. $requestData['response_format'] = $params['response_format'];
  5661. }
  5662. if (isset($params['thinking'])) {
  5663. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  5664. if (is_array($params['thinking'])) {
  5665. $requestData['thinking'] = $params['thinking'];
  5666. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  5667. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  5668. }
  5669. } else {
  5670. $requestData['thinking'] = ['type' => $params['thinking']];
  5671. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  5672. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  5673. }
  5674. }
  5675. } else {
  5676. $requestData['thinking'] = ['type' => 'disabled'];
  5677. }
  5678. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  5679. $client = new Client(['verify' => false, 'timeout' => 1200]);
  5680. try {
  5681. // 判断是否为流式输出
  5682. $isStream = isset($params['stream']) && $params['stream'] === true;
  5683. if ($isStream) {
  5684. // 流式输出
  5685. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  5686. } else {
  5687. // 非流式输出
  5688. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  5689. 'headers' => [
  5690. 'Authorization' => 'Bearer ' . $apiKey,
  5691. 'Content-Type' => 'application/json',
  5692. ],
  5693. 'json' => $requestData
  5694. ]);
  5695. $responseData = json_decode($response->getBody(), true);
  5696. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  5697. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  5698. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  5699. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  5700. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  5701. }
  5702. return [
  5703. 'fullContent' => $fullContent,
  5704. 'fullReasoningContent' => $fullReasoningContent,
  5705. 'usage' => $usage
  5706. ];
  5707. }
  5708. } catch (\Exception $e) {
  5709. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  5710. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  5711. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  5712. }
  5713. }
  5714. /**
  5715. * 火山引擎对话API流式输出
  5716. *
  5717. * @param Client $client HTTP客户端
  5718. * @param string $apiKey API密钥
  5719. * @param array $requestData 请求数据
  5720. * @return Generator
  5721. */
  5722. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  5723. {
  5724. try {
  5725. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  5726. 'headers' => [
  5727. 'Authorization' => 'Bearer ' . $apiKey,
  5728. 'Content-Type' => 'application/json',
  5729. ],
  5730. 'json' => $requestData,
  5731. 'stream' => true
  5732. ]);
  5733. $body = $response->getBody();
  5734. $buffer = '';
  5735. $fullContent = '';
  5736. $fullReasoningContent = '';
  5737. $usage = [];
  5738. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  5739. // 逐行读取流式响应
  5740. while (!$body->eof()) {
  5741. $chunk = $body->read(1024);
  5742. $buffer .= $chunk;
  5743. // 按行分割
  5744. $lines = explode("\n", $buffer);
  5745. $buffer = array_pop($lines);
  5746. foreach ($lines as $line) {
  5747. $line = trim($line);
  5748. if (empty($line)) {
  5749. continue;
  5750. }
  5751. // 检查是否是SSE数据行
  5752. if (strpos($line, 'data: ') !== 0) {
  5753. continue;
  5754. }
  5755. $data = substr($line, 6);
  5756. if ($data === '[DONE]') {
  5757. dLog('deepseek')->info('收到结束标记');
  5758. break 2;
  5759. }
  5760. try {
  5761. $json = json_decode($data, true);
  5762. if (json_last_error() !== JSON_ERROR_NONE) {
  5763. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  5764. continue;
  5765. }
  5766. if (isset($json['choices'][0]['delta'])) {
  5767. $delta = $json['choices'][0]['delta'];
  5768. // 处理思维链内容
  5769. if (isset($delta['reasoning_content'])) {
  5770. $fullReasoningContent .= $delta['reasoning_content'];
  5771. yield [
  5772. 'type' => 'reasoning',
  5773. 'content' => $delta['reasoning_content'],
  5774. 'full_reasoning' => $fullReasoningContent
  5775. ];
  5776. }
  5777. // 处理回答内容
  5778. if (isset($delta['content'])) {
  5779. $fullContent .= $delta['content'];
  5780. yield [
  5781. 'type' => 'content',
  5782. 'content' => $delta['content'],
  5783. ];
  5784. }
  5785. }
  5786. // 获取使用统计信息
  5787. if (isset($json['usage'])) {
  5788. $usage = $json['usage'];
  5789. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  5790. }
  5791. } catch (\Exception $e) {
  5792. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  5793. continue;
  5794. }
  5795. }
  5796. }
  5797. dLog('deepseek')->info('流式读取完成', [
  5798. 'content_length' => strlen($fullContent),
  5799. 'reasoning_length' => strlen($fullReasoningContent)
  5800. ]);
  5801. yield [
  5802. 'type' => 'done',
  5803. 'full_content' => $fullContent,
  5804. 'full_reasoning' => $fullReasoningContent,
  5805. 'usage' => $usage
  5806. ];
  5807. } catch (\Exception $e) {
  5808. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  5809. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  5810. throw $e;
  5811. }
  5812. }
  5813. /**
  5814. * 检查并创建图片生成任务
  5815. *
  5816. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  5817. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  5818. * @param string $nameKey 资源名称字段('role' 或 'scene')
  5819. * @param string $art_style 美术风格
  5820. * @return array 更新后的资源列表
  5821. */
  5822. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  5823. {
  5824. // 确保参数为数组
  5825. $merged_items = is_array($merged_items) ? $merged_items : [];
  5826. $global_items = is_array($global_items) ? $global_items : [];
  5827. // 构建全局资源映射表,用于快速查找
  5828. $global_map = [];
  5829. foreach ($global_items as $item) {
  5830. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  5831. if ($itemKey === '') {
  5832. continue;
  5833. }
  5834. $global_map[$itemKey] = $item;
  5835. }
  5836. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  5837. foreach ($merged_items as &$item) {
  5838. $item_name = getProp($item, $nameKey);
  5839. $item_description = getProp($item, 'description');
  5840. // $item_url = getProp($item, 'url');
  5841. // // 如果已有图片URL,跳过
  5842. // if (!empty($item_url)) {
  5843. // continue;
  5844. // }
  5845. // 如果是旁白角色,跳过
  5846. if ($nameKey === 'role' && $item_name === '旁白') {
  5847. continue;
  5848. }
  5849. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  5850. if ($itemKey === '') {
  5851. continue;
  5852. }
  5853. $need_create_task = false;
  5854. // 条件1:在全局资源中找不到匹配的名称
  5855. if (!isset($global_map[$itemKey])) {
  5856. $need_create_task = true;
  5857. } else {
  5858. // 条件2:名称匹配但描述或 pic_prompt 不一致
  5859. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  5860. $current_description = trim((string)$item_description);
  5861. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  5862. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  5863. // 如果 description 或 pic_prompt 有变化,需要重新生成
  5864. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  5865. $need_create_task = true;
  5866. }
  5867. }
  5868. // 如果需要创建任务,调用图片生成服务
  5869. if ($need_create_task) {
  5870. try {
  5871. // 优先使用 pic_prompt,如果没有则使用 description
  5872. $pic_prompt = getProp($item, 'pic_prompt');
  5873. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  5874. // 添加美术风格前缀
  5875. if ($art_style) {
  5876. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  5877. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  5878. $description = "{$prefix}:{$description}";
  5879. }
  5880. $params = [
  5881. 'prompt' => $description,
  5882. 'ref_img_urls' => []
  5883. ];
  5884. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5885. $task_id = $task->id;
  5886. if ($task_id) {
  5887. $item['task_id'] = $task_id;
  5888. $item['task_status'] = 'processing';
  5889. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  5890. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  5891. }
  5892. } catch (\Exception $e) {
  5893. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  5894. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  5895. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  5896. // 不抛出异常,继续处理其他资源
  5897. }
  5898. }
  5899. }
  5900. return $merged_items;
  5901. }
  5902. /**
  5903. * 同步新出现的主体和场景到全局
  5904. *
  5905. * @param int $anime_id 动漫ID
  5906. * @param array $merged_roles 合并后的角色列表
  5907. * @param array $merged_scenes 合并后的场景列表
  5908. * @param array $global_roles 全局角色列表
  5909. * @param array $global_scenes 全局场景列表
  5910. * @return void
  5911. */
  5912. private function syncNewResourcesToGlobal(
  5913. int $anime_id,
  5914. array $merged_roles,
  5915. array $merged_scenes,
  5916. array $global_roles,
  5917. array $global_scenes
  5918. ): void {
  5919. // 构建全局角色映射表
  5920. $global_role_map = [];
  5921. foreach ($global_roles as $role) {
  5922. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  5923. if ($roleKey !== '') {
  5924. $global_role_map[$roleKey] = $role;
  5925. }
  5926. }
  5927. // 构建全局场景映射表
  5928. $global_scene_map = [];
  5929. foreach ($global_scenes as $scene) {
  5930. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  5931. if ($sceneKey !== '') {
  5932. $global_scene_map[$sceneKey] = $scene;
  5933. }
  5934. }
  5935. $need_update = false;
  5936. $new_global_roles = $global_roles;
  5937. $new_global_scenes = $global_scenes;
  5938. // 检查并添加新角色到全局
  5939. foreach ($merged_roles as $role) {
  5940. $role_name = getProp($role, 'role');
  5941. // 跳过旁白
  5942. if ($role_name === '旁白') {
  5943. continue;
  5944. }
  5945. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  5946. if ($roleKey === '') {
  5947. continue;
  5948. }
  5949. // 如果全局中不存在该角色,添加到全局
  5950. if (!isset($global_role_map[$roleKey])) {
  5951. $new_global_roles[] = [
  5952. 'role' => $role_name,
  5953. 'description' => getProp($role, 'description', ''),
  5954. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  5955. 'voice_name' => getProp($role, 'voice_name', ''),
  5956. 'voice_type' => getProp($role, 'voice_type', ''),
  5957. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  5958. 'url' => getProp($role, 'url', ''),
  5959. 'task_id' => getProp($role, 'task_id', ''),
  5960. 'task_status' => getProp($role, 'task_status', ''),
  5961. ];
  5962. $global_role_map[$roleKey] = true; // 标记已添加
  5963. $need_update = true;
  5964. dLog('deepseek')->info("新角色同步到全局", [
  5965. 'anime_id' => $anime_id,
  5966. 'role' => $role_name,
  5967. 'task_id' => getProp($role, 'task_id', ''),
  5968. ]);
  5969. }
  5970. // else {
  5971. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  5972. // $global_role = $global_role_map[$roleKey];
  5973. // if (is_array($global_role)) {
  5974. // $updated = false;
  5975. // $update_fields = [];
  5976. // // 检查描述是否更新
  5977. // $current_description = trim((string)getProp($role, 'description'));
  5978. // $global_description = trim((string)getProp($global_role, 'description'));
  5979. // if ($current_description !== '' && $current_description !== $global_description) {
  5980. // $updated = true;
  5981. // $update_fields[] = 'description';
  5982. // }
  5983. // // 检查pic_prompt是否更新
  5984. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  5985. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  5986. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  5987. // $updated = true;
  5988. // $update_fields[] = 'pic_prompt';
  5989. // }
  5990. // // 检查图片任务信息是否更新
  5991. // $current_task_id = getProp($role, 'task_id');
  5992. // $global_task_id = getProp($global_role, 'task_id');
  5993. // if ($current_task_id && $current_task_id !== $global_task_id) {
  5994. // $updated = true;
  5995. // $update_fields[] = 'task_id';
  5996. // }
  5997. // // 如果有更新,同步到全局
  5998. // if ($updated) {
  5999. // foreach ($new_global_roles as &$global_role_item) {
  6000. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  6001. // if ($global_role_key === $roleKey) {
  6002. // if (in_array('description', $update_fields)) {
  6003. // $global_role_item['description'] = $current_description;
  6004. // }
  6005. // if (in_array('pic_prompt', $update_fields)) {
  6006. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  6007. // }
  6008. // if (in_array('task_id', $update_fields)) {
  6009. // $global_role_item['task_id'] = $current_task_id;
  6010. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  6011. // $global_role_item['url'] = getProp($role, 'url', '');
  6012. // }
  6013. // break;
  6014. // }
  6015. // }
  6016. // $need_update = true;
  6017. // dLog('deepseek')->info("角色信息更新到全局", [
  6018. // 'anime_id' => $anime_id,
  6019. // 'role' => $role_name,
  6020. // 'update_fields' => implode(',', $update_fields),
  6021. // ]);
  6022. // }
  6023. // }
  6024. // }
  6025. }
  6026. // 检查并添加新场景到全局
  6027. foreach ($merged_scenes as $scene) {
  6028. $scene_name = getProp($scene, 'scene');
  6029. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  6030. if ($sceneKey === '') {
  6031. continue;
  6032. }
  6033. // 如果全局中不存在该场景,添加到全局
  6034. if (!isset($global_scene_map[$sceneKey])) {
  6035. $new_global_scenes[] = [
  6036. 'scene' => $scene_name,
  6037. 'description' => getProp($scene, 'description', ''),
  6038. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  6039. 'url' => getProp($scene, 'url', ''),
  6040. 'task_id' => getProp($scene, 'task_id', ''),
  6041. 'task_status' => getProp($scene, 'task_status', ''),
  6042. ];
  6043. $global_scene_map[$sceneKey] = true; // 标记已添加
  6044. $need_update = true;
  6045. dLog('deepseek')->info("新场景同步到全局", [
  6046. 'anime_id' => $anime_id,
  6047. 'scene' => $scene_name,
  6048. 'task_id' => getProp($scene, 'task_id', ''),
  6049. ]);
  6050. }
  6051. // else {
  6052. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  6053. // $global_scene = $global_scene_map[$sceneKey];
  6054. // if (is_array($global_scene)) {
  6055. // $updated = false;
  6056. // $update_fields = [];
  6057. // // 检查描述是否更新
  6058. // $current_description = trim((string)getProp($scene, 'description'));
  6059. // $global_description = trim((string)getProp($global_scene, 'description'));
  6060. // if ($current_description !== '' && $current_description !== $global_description) {
  6061. // $updated = true;
  6062. // $update_fields[] = 'description';
  6063. // }
  6064. // // 检查pic_prompt是否更新
  6065. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  6066. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  6067. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  6068. // $updated = true;
  6069. // $update_fields[] = 'pic_prompt';
  6070. // }
  6071. // // 检查图片任务信息是否更新
  6072. // $current_task_id = getProp($scene, 'task_id');
  6073. // $global_task_id = getProp($global_scene, 'task_id');
  6074. // if ($current_task_id && $current_task_id !== $global_task_id) {
  6075. // $updated = true;
  6076. // $update_fields[] = 'task_id';
  6077. // }
  6078. // // 如果有更新,同步到全局
  6079. // if ($updated) {
  6080. // foreach ($new_global_scenes as &$global_scene_item) {
  6081. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  6082. // if ($global_scene_key === $sceneKey) {
  6083. // if (in_array('description', $update_fields)) {
  6084. // $global_scene_item['description'] = $current_description;
  6085. // }
  6086. // if (in_array('pic_prompt', $update_fields)) {
  6087. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  6088. // }
  6089. // if (in_array('task_id', $update_fields)) {
  6090. // $global_scene_item['task_id'] = $current_task_id;
  6091. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  6092. // $global_scene_item['url'] = getProp($scene, 'url', '');
  6093. // }
  6094. // break;
  6095. // }
  6096. // }
  6097. // $need_update = true;
  6098. // dLog('deepseek')->info("场景信息更新到全局", [
  6099. // 'anime_id' => $anime_id,
  6100. // 'scene' => $scene_name,
  6101. // 'update_fields' => implode(',', $update_fields),
  6102. // ]);
  6103. // }
  6104. // }
  6105. // }
  6106. }
  6107. // 如果有新增或更新,更新数据库
  6108. if ($need_update) {
  6109. $update_data = [
  6110. 'roles' => json_encode($new_global_roles, 256),
  6111. 'scenes' => json_encode($new_global_scenes, 256),
  6112. 'updated_at' => date('Y-m-d H:i:s'),
  6113. ];
  6114. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  6115. if ($result !== false) {
  6116. dLog('deepseek')->info("全局角色和场景更新成功", [
  6117. 'anime_id' => $anime_id,
  6118. 'roles_count' => count($new_global_roles),
  6119. 'scenes_count' => count($new_global_scenes),
  6120. ]);
  6121. } else {
  6122. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  6123. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  6124. }
  6125. }
  6126. }
  6127. /**
  6128. * 解析分镜内容的公开方法
  6129. */
  6130. public function parseSegmentContent($segment_content, $model = null) {
  6131. if (!$model) {
  6132. $model = DB::table('mp_text_models')->where('is_enabled', 1)->orderBy('id')->value('model');
  6133. if (!$model) {
  6134. return $segment_content;
  6135. }
  6136. }
  6137. // 构建系统提示词
  6138. $systemPrompt = "你是一个专业的分镜内容解析助手。请将用户提供的分镜内容解析成标准格式,包含以下字段:
  6139. 画面描述:详细描述画面内容
  6140. 构图设计:镜头构图方式
  6141. 运镜调度:摄影机运动方式
  6142. 配音角色:配音的角色名称
  6143. 台词内容:角色说的话
  6144. 画面类型:普通画面或对口型
  6145. 场景:拍摄场景
  6146. 出镜角色:画面中出现的角色
  6147. 尾帧描述:镜头结束时的画面描述
  6148. 情感:配音情感(开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦)
  6149. 性别:1(男)、2(女)、0(中性)
  6150. 语速:-50到100之间的整数
  6151. 音量:-50到100之间的整数
  6152. 情感强度:1到5之间的整数
  6153. 音调:-12到12之间的整数
  6154. 请严格按照上述格式输出,如果某个字段无法确定,请设置合理的默认值。";
  6155. // 构建消息
  6156. $messages = [
  6157. [
  6158. 'role' => 'system',
  6159. 'content' => $systemPrompt
  6160. ],
  6161. [
  6162. 'role' => 'user',
  6163. 'content' => $segment_content
  6164. ]
  6165. ];
  6166. $post_data = [
  6167. 'model' => $model,
  6168. 'messages' => $messages,
  6169. // 'max_tokens' => 2048,
  6170. 'temperature' => 0.7,
  6171. 'frequency_penalty' => 0,
  6172. 'presence_penalty' => 0,
  6173. 'response_format' => ['type' => 'text'],
  6174. 'stream' => false
  6175. ];
  6176. try {
  6177. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6178. // 使用DeepSeek API
  6179. $chatResult = $this->chatOnly($post_data);
  6180. } else {
  6181. // 使用火山引擎API
  6182. $chatResult = $this->volcEngineChatCompletion($post_data);
  6183. }
  6184. if (is_array($chatResult) && !empty($chatResult['fullContent'])) {
  6185. return $chatResult['fullContent'];
  6186. }
  6187. } catch (\Exception $e) {
  6188. dLog('deepseek')->error('解析分镜内容失败: ' . $e->getMessage());
  6189. logDB('deepseek', 'error', '解析分镜内容失败', ['error' => $e->getMessage()]);
  6190. }
  6191. return $segment_content;
  6192. }
  6193. }