app.ts 310 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740
  1. import { Component, signal, NgZone, ChangeDetectorRef, ViewEncapsulation, inject } from '@angular/core';
  2. import { CommonModule } from '@angular/common';
  3. import { FormsModule } from '@angular/forms';
  4. import { RouterModule } from '@angular/router';
  5. import { TimeFormatPipe } from './pipes/time-format.pipe';
  6. import { NumberFormatPipe } from './pipes/number-format.pipe';
  7. import { FileSizePipe } from './pipes/file-size.pipe';
  8. import { DouyinService } from './services/douyin.service';
  9. import { JimengService } from './services/jimeng.service';
  10. import { LlmService } from './services/llm.service';
  11. import { PortraitPipelineService, PortraitPipelineResult } from './services/portrait-pipeline.service';
  12. import { DigitalHumanService, DigitalHumanRequest, DigitalHumanEvent } from './services/digital-human.service';
  13. import { DigitalHumanFormComponent, TimbreOption, PromptPreset } from './components/digital-human-form/digital-human-form.component';
  14. import { PortraitPrepareComponent, PortraitPrepareOutput } from './components/portrait-prepare/portrait-prepare.component';
  15. import { HttpClient, HttpErrorResponse } from '@angular/common/http';
  16. import { timeout, finalize, switchMap } from 'rxjs/operators';
  17. import { of, Observable, from } from 'rxjs';
  18. import { PIPELINES, PipelineDef, getSidebarPipelines } from './pipelines/pipeline-registry';
  19. import { ImageToVideoComponent } from './pages/pipelines/image-to-video/image-to-video.component';
  20. import { ActionTransferComponent } from './pages/pipelines/action-transfer/action-transfer.component';
  21. import { AssetRemixComponent } from './pages/pipelines/asset-remix/asset-remix.component';
  22. import { TopicToVideoComponent } from './pages/pipelines/topic-to-video/topic-to-video.component';
  23. import { ImageGenerationComponent } from './pages/pipelines/image-generation/image-generation.component';
  24. import { DraftsComponent } from './pages/drafts/drafts.component';
  25. import { LibraryComponent } from './pages/library/library.component';
  26. import { PipelineSessionService } from './services/pipeline-session.service';
  27. import { QiniuUploadService } from './services/qiniu-upload.service';
  28. import { BrowserFfmpegService, BrowserAudioExtractionResult } from './services/browser-ffmpeg.service';
  29. import { PipelineRoute } from './pipelines/pipeline-registry';
  30. import { AppSidebarComponent } from './components/app-sidebar/app-sidebar.component';
  31. import { HomeComponent } from './pages/home/home.component';
  32. import { RecentTaskPillComponent, RecentTaskView } from './components/recent-task-pill/recent-task-pill.component';
  33. import { AppAssistantComponent } from './components/app-assistant/app-assistant.component';
  34. import { AssistantSuggestion } from './services/assistant.service';
  35. import { OFFICIAL_VOICE_LIBRARY, VoicePickerComponent, VoiceSelection } from './components/voice-picker/voice-picker.component';
  36. // 类型定义
  37. interface VideoInfo {
  38. aweme_id: string;
  39. desc: string;
  40. cover_url: string;
  41. cover_candidates?: string[];
  42. duration: number;
  43. create_time?: number;
  44. publishDate?: Date | null;
  45. author: {
  46. nickname: string;
  47. sec_uid: string;
  48. };
  49. statistics: {
  50. play_count: number;
  51. digg_count: number;
  52. comment_count: number;
  53. share_count: number;
  54. };
  55. text_extra?: string[];
  56. // 下载相关
  57. downloadProgress?: number;
  58. isDownloading?: boolean;
  59. downloadUrl?: string;
  60. }
  61. interface Task {
  62. id: string;
  63. keyword: string;
  64. status: 'pending' | 'processing' | 'completed' | 'failed' | 'timeout';
  65. step: 'search' | 'detail' | 'comments' | 'download' | 'transcribe' | 'generate' | 'complete'
  66. | 'vg-upload' | 'vg-analyze' | 'vg-script' | 'vg-image' | 'vg-voice' | 'vg-composite';
  67. progress: number;
  68. cost: number;
  69. created_at: Date;
  70. updated_at: Date;
  71. result_url?: string;
  72. error_message?: string;
  73. original_video_title?: string;
  74. duration?: string;
  75. // 任务类型:remix=AI重塑, video-generation=视频生成
  76. type?: 'remix' | 'video-generation';
  77. // 视频生成专用持久化数据
  78. vgData?: {
  79. videoId: string;
  80. sourceFileName: string;
  81. sourceVideoUrl: string;
  82. step: number;
  83. transcript: string;
  84. analysisText: string;
  85. script: string;
  86. scriptSegments: { id: string; narration: string; imagePrompt: string; imagePromptCn?: string; }[];
  87. imageResults: { id: string; prompt: string; imageUrl: string; status: 'pending' | 'generating' | 'done' | 'failed'; }[];
  88. audioUrls: { segId: string; audioUrl: string; }[];
  89. voiceMode: 'clone' | 'system';
  90. voiceSpeakerId: string;
  91. voiceTimbreId: string;
  92. voiceName?: string;
  93. finalVideoUrl: string;
  94. };
  95. }
  96. interface TaskStats {
  97. pending: number;
  98. processing: number;
  99. completed: number;
  100. failed: number;
  101. }
  102. interface VoiceProfile {
  103. id: string;
  104. name: string;
  105. creation_mode?: string;
  106. speaker_id: string;
  107. timbre_id?: string;
  108. sample_text: string;
  109. text_prompt?: string;
  110. source_audio_text?: string;
  111. source_audio_name?: string;
  112. source_audio_format?: string;
  113. language: number;
  114. status: number | null;
  115. status_label: string;
  116. demo_audio: string;
  117. available_training_times: number | null;
  118. image_prompt_name?: string;
  119. x_api_resource_id?: string;
  120. model_version?: string;
  121. icl_speaker_id?: string;
  122. occupied?: boolean;
  123. synthesized_audio_url?: string;
  124. synthesized_work_id?: string;
  125. last_synthesis_text?: string;
  126. last_synthesis_ssml?: string;
  127. last_synthesis_x_api_resource_id?: string;
  128. last_synthesis_model?: string;
  129. last_synthesis_format?: string;
  130. last_synthesis_sample_rate?: number;
  131. last_synthesis_speech_rate?: number;
  132. last_synthesis_loudness_rate?: number;
  133. last_synthesis_emotion?: string;
  134. last_synthesis_emotion_scale?: number;
  135. last_synthesis_enable_subtitle?: boolean;
  136. last_synthesis_silence_duration?: number;
  137. last_synthesis_enable_language_detector?: boolean;
  138. last_synthesis_disable_markdown_filter?: boolean;
  139. last_synthesis_disable_emoji_filter?: boolean;
  140. last_synthesis_explicit_language?: string;
  141. latest_audio_url?: string;
  142. draft_synthesis_text?: string;
  143. draft_synthesis_ssml?: string;
  144. draft_synthesis_x_api_resource_id?: string;
  145. draft_synthesis_model?: string;
  146. draft_synthesis_format?: string;
  147. draft_synthesis_sample_rate?: number;
  148. draft_synthesis_speech_rate?: number;
  149. draft_synthesis_loudness_rate?: number;
  150. draft_synthesis_emotion?: string;
  151. draft_synthesis_emotion_scale?: number;
  152. draft_synthesis_enable_subtitle?: boolean;
  153. draft_synthesis_silence_duration?: number;
  154. draft_synthesis_enable_language_detector?: boolean;
  155. draft_synthesis_disable_markdown_filter?: boolean;
  156. draft_synthesis_disable_emoji_filter?: boolean;
  157. draft_synthesis_explicit_language?: string;
  158. is_synthesizing?: boolean;
  159. message?: string;
  160. request_id?: string;
  161. created_at: Date;
  162. updated_at?: Date;
  163. }
  164. interface GeneratedResult {
  165. id: string;
  166. type: 'video' | 'image';
  167. url: string;
  168. title: string;
  169. created_at: Date;
  170. quality: string;
  171. duration: string;
  172. cost: number;
  173. remixId?: string;
  174. videoId?: string;
  175. voiceProfileId?: string;
  176. voiceProfileName?: string;
  177. audioSourceLabel?: string;
  178. segments?: { id: string; videoUrl: string; prompt: string; status: string }[];
  179. /** P0+: 所属生成模式(来自 pipeline-registry,如 'digital_human' / 'image_to_video' 等) */
  180. pipelineId?: string;
  181. }
  182. interface HistoryRecord {
  183. id: string;
  184. original_video_title?: string;
  185. keyword: string;
  186. status: 'completed' | 'failed';
  187. cost: number;
  188. created_at: Date;
  189. duration?: string;
  190. remixId?: string;
  191. videoId?: string;
  192. styleName?: string;
  193. segmentCount?: number;
  194. successCount?: number;
  195. resultUrl?: string;
  196. quality?: string;
  197. voiceProfileId?: string;
  198. voiceProfileName?: string;
  199. audioSourceLabel?: string;
  200. /** P0+: 所属生成模式 id(与 pipeline-registry.PIPELINES[*].id 对应) */
  201. pipelineId?: string;
  202. }
  203. interface ManagedVideo {
  204. id: string;
  205. title: string;
  206. filename: string;
  207. filepath: string;
  208. size: number;
  209. duration: number;
  210. created_at: Date;
  211. modified_at: Date;
  212. category: string;
  213. tags: string[];
  214. description: string;
  215. thumbnail?: string;
  216. source: 'downloaded' | 'generated' | 'uploaded';
  217. metadata: {
  218. resolution: string;
  219. format: string;
  220. bitrate?: number;
  221. };
  222. // Whisper 转录文件路径
  223. whisper?: {
  224. transcript?: string;
  225. srt?: string;
  226. storyboard?: string;
  227. beautified?: string;
  228. };
  229. // AI重塑相关字段
  230. isRemixing?: boolean;
  231. remixProgress?: number;
  232. remixStyle?: string;
  233. originalVideoId?: string;
  234. remixVersions?: RemixVersion[];
  235. }
  236. interface RemixVersion {
  237. id: string;
  238. style: string;
  239. created_at: Date;
  240. file_path: string;
  241. thumbnail: string;
  242. description: string;
  243. parameters: RemixParameters;
  244. }
  245. interface RemixParameters {
  246. style: string;
  247. intensity: number;
  248. preserve_audio: boolean;
  249. quality: 'standard' | 'high' | 'ultra';
  250. effects: string[];
  251. }
  252. interface VideoCategory {
  253. id: string;
  254. name: string;
  255. color: string;
  256. count: number;
  257. }
  258. interface StoryboardSegment {
  259. id: string;
  260. act: string;
  261. narration: string;
  262. prompt: string;
  263. duration: string;
  264. videoUrl?: string;
  265. workId?: string;
  266. status: 'pending' | 'generating' | 'completed' | 'failed';
  267. error?: string;
  268. }
  269. interface RemixFlowStep {
  270. step: number;
  271. label: string;
  272. }
  273. interface MonitorWork {
  274. id: string;
  275. desc: string;
  276. coverUrl: string;
  277. coverCandidates: string[];
  278. duration: number;
  279. createTime?: Date;
  280. type: 'video' | 'image';
  281. statistics: {
  282. play_count: number;
  283. digg_count: number;
  284. comment_count: number;
  285. share_count: number;
  286. };
  287. isDownloading?: boolean;
  288. downloadProgress?: number;
  289. }
  290. interface MonitorAuthor {
  291. id: string;
  292. uid: string;
  293. secUserId: string;
  294. nickname: string;
  295. uniqueId: string;
  296. shortId: string;
  297. signature: string;
  298. ipLocation: string;
  299. verifiedText: string;
  300. avatarUrl: string;
  301. avatarCandidates: string[];
  302. coverUrl: string;
  303. coverCandidates: string[];
  304. followerCount: number;
  305. followingCount: number;
  306. totalFavorited: number;
  307. awemeCount: number;
  308. works: MonitorWork[];
  309. worksCursor: string;
  310. hasMoreWorks: boolean;
  311. loadingWorks: boolean;
  312. }
  313. @Component({
  314. selector: 'app-root',
  315. imports: [
  316. CommonModule,
  317. FormsModule,
  318. RouterModule,
  319. TimeFormatPipe,
  320. NumberFormatPipe,
  321. FileSizePipe,
  322. DigitalHumanFormComponent,
  323. PortraitPrepareComponent,
  324. ImageToVideoComponent,
  325. ActionTransferComponent,
  326. AssetRemixComponent,
  327. TopicToVideoComponent,
  328. ImageGenerationComponent,
  329. DraftsComponent,
  330. LibraryComponent,
  331. AppSidebarComponent,
  332. HomeComponent,
  333. RecentTaskPillComponent,
  334. AppAssistantComponent,
  335. VoicePickerComponent
  336. ],
  337. templateUrl: './app.html',
  338. styleUrl: './app.css',
  339. // 关键:app.css 包含全局 dh-* / pl-* / pipeline-* 等设计系统类,
  340. // 必须设为 None 才能让其作用到 standalone 子组件(图生视频/动作迁移/
  341. // 素材合成/主题生视频)。否则 Angular 默认 Emulated 会给所有选择器
  342. // 添加 [_ngcontent-xxx] 属性后缀,导致子组件 DOM 无法匹配,UI 失样。
  343. encapsulation: ViewEncapsulation.None
  344. })
  345. export class App {
  346. private pipelineSession = inject(PipelineSessionService);
  347. protected readonly title = signal('抖音AI视频生成系统');
  348. // 当前激活的标签页
  349. currentTab: 'home' | 'search' | 'monitor' | 'tasks' | 'history' | 'results' | 'videos' | 'voice-synthesis' | 'pipelines' | 'digital-human' | 'image-generation' | 'video-generation' | 'image-to-video' | 'action-transfer' | 'asset-remix' | 'topic-to-video' | 'drafts' | 'library' = 'home';
  350. /** Pipeline 注册中心数据,模板中通过 *ngFor 动态渲染 */
  351. readonly pipelines = PIPELINES;
  352. readonly sidebarPipelines = getSidebarPipelines();
  353. private readonly TAB_STORAGE_KEY = 'tiktok.currentTab';
  354. // 主题模式(默认浅色)
  355. themeMode: 'day' | 'night' = 'day';
  356. private readonly THEME_STORAGE_KEY = 'tiktok.themeMode';
  357. private readonly TIMBRE_LIST_STORAGE_KEY = 'tiktok.vsClonedTimbreList';
  358. private readonly MONITOR_AUTHORS_STORAGE_KEY = 'tiktok.monitorAuthors';
  359. private readonly MONITOR_SELECTED_AUTHOR_STORAGE_KEY = 'tiktok.monitorSelectedAuthorId';
  360. // 搜索相关属性
  361. searchKeyword: string = '';
  362. sortType: string = '0';
  363. publishTime: string = '0';
  364. filterDuration: string = '0';
  365. isSearching: boolean = false;
  366. searchResults: VideoInfo[] = [];
  367. filteredSearchResults: VideoInfo[] = [];
  368. hasMore: boolean = false;
  369. monitorUniqueIdInput: string = '';
  370. monitorAuthors: MonitorAuthor[] = [];
  371. selectedMonitorAuthorId: string = '';
  372. isAddingMonitorAuthor: boolean = false;
  373. monitorAddError: string = '';
  374. private readonly voiceApiToken: string = 'Bearer r:f0333969e312a40e4703e8fe4ed1c600';
  375. private readonly voiceTtsBaseUrl: string = 'https://server.fmode.cn/api/volcengine/tts';
  376. private readonly localVoiceTtsBaseUrl: string = '/backend/api/volcengine/tts';
  377. voiceProfiles: VoiceProfile[] = [];
  378. isCreatingVoiceProfile: boolean = false;
  379. voiceDesignError: string = '';
  380. voiceCreateMode: 'clone' | 'design' | 'synthesize' = 'clone';
  381. voiceSourceAudioFile: File | null = null;
  382. voiceSourceAudioName: string = '';
  383. voiceDesignImageFile: File | null = null;
  384. voiceDesignImageName: string = '';
  385. preferredVoiceProfileId: string = '';
  386. readonly fallbackVoiceSpeakerIdOptions = ['S_1g3vlU702', 'S_OLZKhZWZ1', 'S_PLZKhZWZ1', 'S_QLZKhZWZ1', 'S_ULZKhZWZ1', 'S_TLZKhZWZ1', 'S_SLZKhZWZ1', 'S_RWDjSzXZ1'];
  387. voiceSpeakerIdOptions: string[] = [...this.fallbackVoiceSpeakerIdOptions];
  388. voiceForm = {
  389. displayName: '',
  390. speakerId: 'S_1g3vlU702',
  391. textPrompt: '',
  392. audioText: '',
  393. sampleText: '',
  394. synthesisText: '',
  395. language: 0
  396. };
  397. voiceSynthesisForm = {
  398. profileId: '',
  399. speakerId: '',
  400. text: '',
  401. ssml: '',
  402. xApiResourceId: '',
  403. model: '',
  404. format: 'mp3',
  405. sampleRate: 24000,
  406. speechRate: 0,
  407. loudnessRate: 0,
  408. emotion: '',
  409. emotionScale: 4,
  410. enableSubtitle: false,
  411. silenceDuration: 0,
  412. enableLanguageDetector: false,
  413. disableMarkdownFilter: false,
  414. disableEmojiFilter: false,
  415. explicitLanguage: ''
  416. };
  417. isDirectVoiceSynthesizing: boolean = false;
  418. directVoiceSynthesisAudioUrl: string = '';
  419. directVoiceSynthesisWorkId: string = '';
  420. directVoiceSynthesisSpeakerId: string = '';
  421. // 语音合成标签页状态
  422. vsTtsMode: 'clone' | 'synthesize' = 'clone';
  423. vsCloneForm = {
  424. name: '',
  425. speakerId: 'S_ULZKhZWZ1',
  426. audioText: '',
  427. language: 0,
  428. demoText: '青山依旧在,几度夕阳红。'
  429. };
  430. vsCloneAudioFile: File | null = null;
  431. vsCloneAudioName: string = '';
  432. vsCloneAudioUrl: string = '';
  433. vsCloneUploading: boolean = false;
  434. vsCloneLoading: boolean = false;
  435. vsCloneError: string = '';
  436. vsCloneResult: any = null;
  437. vsSynthForm = {
  438. timbreId: '',
  439. text: '白发渔樵江渚上,惯看秋月春风。一壶浊酒喜相逢,古今多少事,都付笑谈中。',
  440. isStream: false,
  441. format: 'mp3',
  442. sampleRate: 24000,
  443. speechRate: 0,
  444. loudnessRate: 0,
  445. /** 当前选中音色来源:'cloned' = 用户复刻;'official' = 官方音色库 */
  446. voiceSource: 'cloned' as 'cloned' | 'official',
  447. /** 仅 voiceSource='official' 时使用,对应火山 voice_type */
  448. voiceType: '',
  449. /** 当前选中音色的显示名(UI 用) */
  450. voiceName: ''
  451. };
  452. /** 音色选择弹窗开关 */
  453. voicePickerOpen: boolean = false;
  454. /** 传给弹窗用于回显高亮的当前选择 */
  455. get currentVoiceSelection(): VoiceSelection | null {
  456. const f = this.vsSynthForm;
  457. if (f.voiceSource === 'official' && f.voiceType) {
  458. return { source: 'official', name: f.voiceName, id: f.voiceType, voiceType: f.voiceType };
  459. }
  460. if (f.voiceSource === 'cloned' && f.timbreId) {
  461. return { source: 'cloned', name: f.voiceName || f.timbreId, id: f.timbreId, timbreId: f.timbreId };
  462. }
  463. return null;
  464. }
  465. openVoicePicker(): void {
  466. this.voicePickerOpen = true;
  467. }
  468. closeVoicePicker(): void {
  469. this.voicePickerOpen = false;
  470. }
  471. onVoicePicked(sel: VoiceSelection): void {
  472. this.vsSynthForm.voiceSource = sel.source;
  473. this.vsSynthForm.voiceName = sel.name;
  474. if (sel.source === 'official') {
  475. this.vsSynthForm.voiceType = sel.voiceType || sel.id;
  476. this.vsSynthForm.timbreId = '';
  477. } else {
  478. this.vsSynthForm.timbreId = sel.timbreId || sel.id;
  479. this.vsSynthForm.voiceType = '';
  480. }
  481. this.vsSynthError = '';
  482. this.voicePickerOpen = false;
  483. this.refreshView();
  484. }
  485. private getOfficialVoiceName(voiceType: string): string {
  486. return OFFICIAL_VOICE_LIBRARY.find((item) => item.voiceType === voiceType)?.name || voiceType;
  487. }
  488. get vgCurrentVoiceSelection(): VoiceSelection | null {
  489. if (this.vgVoiceMode === 'clone' && this.vgVoiceTimbreId) {
  490. const matched = this.vsClonedTimbreList.find((item) => item.objectId === this.vgVoiceTimbreId);
  491. return {
  492. source: 'cloned',
  493. name: this.vgVoiceName || matched?.name || this.vgVoiceTimbreId,
  494. id: this.vgVoiceTimbreId,
  495. timbreId: this.vgVoiceTimbreId,
  496. speakerId: matched?.speakerId,
  497. };
  498. }
  499. if (this.vgVoiceMode === 'system' && this.vgVoiceSpeakerId) {
  500. return {
  501. source: 'official',
  502. name: this.vgVoiceName || this.getOfficialVoiceName(this.vgVoiceSpeakerId),
  503. id: this.vgVoiceSpeakerId,
  504. voiceType: this.vgVoiceSpeakerId,
  505. };
  506. }
  507. return null;
  508. }
  509. openVgVoicePicker(): void {
  510. this.vgVoicePickerOpen = true;
  511. }
  512. closeVgVoicePicker(): void {
  513. this.vgVoicePickerOpen = false;
  514. }
  515. onVgVoicePicked(sel: VoiceSelection): void {
  516. this.vgVoiceMode = sel.source === 'official' ? 'system' : 'clone';
  517. this.vgVoiceName = sel.name;
  518. if (sel.source === 'official') {
  519. this.vgVoiceSpeakerId = sel.voiceType || sel.id;
  520. this.vgVoiceTimbreId = '';
  521. } else {
  522. this.vgVoiceTimbreId = sel.timbreId || sel.id;
  523. this.vgVoiceSpeakerId = '';
  524. }
  525. this.vgError = '';
  526. this.vgVoicePickerOpen = false;
  527. this.refreshView();
  528. }
  529. get dhCurrentVoiceSelection(): VoiceSelection | null {
  530. if (this.dhTtsVoiceSource === 'official' && this.dhTtsVoiceType) {
  531. return {
  532. source: 'official',
  533. name: this.dhTtsVoiceName || this.getOfficialVoiceName(this.dhTtsVoiceType),
  534. id: this.dhTtsVoiceType,
  535. voiceType: this.dhTtsVoiceType,
  536. };
  537. }
  538. if (this.dhTtsVoiceSource === 'cloned' && this.dhTtsTimbreId) {
  539. const matched = this.vsClonedTimbreList.find((item) => item.objectId === this.dhTtsTimbreId);
  540. return {
  541. source: 'cloned',
  542. name: this.dhTtsVoiceName || matched?.name || this.dhTtsTimbreId,
  543. id: this.dhTtsTimbreId,
  544. timbreId: this.dhTtsTimbreId,
  545. speakerId: matched?.speakerId,
  546. };
  547. }
  548. return null;
  549. }
  550. openDhVoicePicker(): void {
  551. this.dhVoicePickerOpen = true;
  552. }
  553. closeDhVoicePicker(): void {
  554. this.dhVoicePickerOpen = false;
  555. }
  556. onDhVoicePicked(sel: VoiceSelection): void {
  557. this.dhTtsVoiceSource = sel.source;
  558. this.dhTtsVoiceName = sel.name;
  559. if (sel.source === 'official') {
  560. this.dhTtsVoiceType = sel.voiceType || sel.id;
  561. this.dhTtsTimbreId = '';
  562. } else {
  563. this.dhTtsTimbreId = sel.timbreId || sel.id;
  564. this.dhTtsVoiceType = '';
  565. }
  566. this.dhError = '';
  567. this.dhVoicePickerOpen = false;
  568. this.refreshView();
  569. }
  570. vsSynthLoading: boolean = false;
  571. vsSynthError: string = '';
  572. vsSynthAudioUrl: string = '';
  573. vsSynthWorkId: string = '';
  574. vsClonedTimbreList: { objectId: string; name: string; speakerId: string }[] = [];
  575. // 数字人合成独立页面状态
  576. dhStep: 'form' | 'generating' | 'done' = 'form';
  577. dhImageFile: File | null = null;
  578. dhImageName: string = '';
  579. dhImagePreviewUrl: string = '';
  580. dhImageAssetUrl: string = '';
  581. dhAudioSource: 'tts' | 'upload' = 'tts';
  582. dhTtsTimbreId: string = '';
  583. dhTtsVoiceSource: 'cloned' | 'official' = 'cloned';
  584. dhTtsVoiceType: string = '';
  585. dhTtsVoiceName: string = '';
  586. dhVoicePickerOpen: boolean = false;
  587. dhTtsText: string = '';
  588. dhUploadAudioFile: File | null = null;
  589. dhUploadAudioName: string = '';
  590. dhUploadAudioUrl: string = '';
  591. dhUploadingAudio: boolean = false;
  592. dhPrompt: string = '';
  593. // dh tab:形象准备产物(来自 <app-portrait-prepare>),存在时优先于原图
  594. dhPreparedPortraitUrl: string = '';
  595. dhPreparedFullBodyUrl: string = '';
  596. dhPreparedBenchmarkSummary: string = '';
  597. // 数字人补充提示词预设
  598. dhPromptPresets: { label: string; value: string }[] = [
  599. { label: '专业播报', value: '以新闻主播的语气朗读,吐字清晰、节奏稳定、表情自信端正。' },
  600. { label: '亲切自然', value: '用朋友聊天的语气,亲切自然、面带微笑,语速适中略带轻松感。' },
  601. { label: '科技感', value: '冷静理性的科技感口吻,节奏明快、抑扬有度,强调数据与关键词。' },
  602. { label: '热情带货', value: '充满活力的带货主播风格,语速略快、情绪饱满,重点处加重音强调。' },
  603. { label: '温柔治愈', value: '温柔轻缓的语气,气息柔和、节奏放慢,适合情感与生活类内容。' },
  604. { label: '正式商务', value: '商务正式风格,语调克制、用词严谨,仪态端庄,适合企业宣传场景。' },
  605. ];
  606. dhFastMode: boolean = false;
  607. dhResolution: '720p' | '1080p' = '1080p';
  608. dhError: string = '';
  609. dhLoading: boolean = false;
  610. dhStatusText: string = '';
  611. dhProgress: number = 0;
  612. dhResultVideoUrl: string = '';
  613. dhSynthesizing: boolean = false;
  614. // 数字人合成页:AI 对话助手(用于让用户与 AI 对话调整口播稿风格 / 优化提示词)
  615. dhChatMessages: Array<{
  616. role: 'user' | 'assistant';
  617. content: string; // 给用户看的文本(assistant 端为 explanation;user 端为输入原文)
  618. suggestedTts?: string; // assistant 建议的新口播文本
  619. suggestedPrompt?: string; // assistant 建议的新补充提示词
  620. appliedTts?: boolean;
  621. appliedPrompt?: boolean;
  622. }> = [];
  623. dhChatInput: string = '';
  624. dhChatLoading: boolean = false;
  625. dhChatError: string = '';
  626. // 任务管理相关属性
  627. activeTasks: Task[] = [];
  628. taskStats: TaskStats = {
  629. pending: 0,
  630. processing: 0,
  631. completed: 0,
  632. failed: 0
  633. };
  634. // 历史记录相关属性
  635. historyRecords: HistoryRecord[] = [];
  636. historyFilter = {
  637. status: ''
  638. };
  639. // 生成结果相关属性
  640. generatedResults: GeneratedResult[] = [];
  641. // 视频管理相关属性
  642. managedVideos: ManagedVideo[] = [];
  643. videoCategories: VideoCategory[] = [];
  644. selectedVideos: Set<string> = new Set();
  645. videoFilter = {
  646. category: '',
  647. source: '',
  648. searchTerm: ''
  649. };
  650. isSelectionMode: boolean = false;
  651. // 视频上传
  652. showUploadModal: boolean = false;
  653. uploadTitle: string = '';
  654. uploadDescription: string = '';
  655. uploadTags: string = '';
  656. isUploading: boolean = false;
  657. uploadProgress: number = 0;
  658. uploadError: string = '';
  659. uploadFile: File | null = null;
  660. uploadFileName: string = '';
  661. // 视频预览模态框
  662. showPreviewModal: boolean = false;
  663. previewVideoUrl: string = '';
  664. previewDownloadUrl: string = '';
  665. previewVideoTitle: string = '';
  666. previewVideoInfo: any = null;
  667. previewSourceVideo: VideoInfo | null = null;
  668. // 搜索游标(分页)
  669. searchCursor: number = 0;
  670. private searchId: string = '';
  671. private searchBacktrace: string = '';
  672. // 视频文件基础路径
  673. private readonly VIDEO_BASE_PATH = '/video';
  674. // AI重塑模式选择弹窗(视频管理页 → 选择 标准AI重塑 / 数字人生成)
  675. showRemixModeChooser: boolean = false;
  676. remixModeChooserVideo: ManagedVideo | null = null;
  677. // ===== 数字人合成页:参考视频(与视频生成页 vg* 完全隔离的独立状态) =====
  678. dhRefFile: File | null = null;
  679. dhRefFileName: string = '';
  680. dhRefFileSize: number = 0;
  681. dhRefVideoUrl: string = '';
  682. dhRefVideoId: string = '';
  683. dhRefUploading: boolean = false;
  684. dhRefUploadProgress: number = 0;
  685. dhRefAnalyzing: boolean = false;
  686. dhRefAnalysisText: string = '';
  687. dhRefTranscript: string = '';
  688. dhRefError: string = '';
  689. dhRefRewriting: boolean = false;
  690. dhRefRewriteError: string = '';
  691. // 当通过「AI 重塑 → 数字人生成」入口进入时,标记需要在分析完成后自动重塑
  692. dhRefAutoRewrite: boolean = false;
  693. // AI重塑模态框 — 多步骤流程
  694. showRemixModal: boolean = false;
  695. remixTargetVideo: ManagedVideo | null = null;
  696. remixStep: number = 1; // 1提取文字稿 2AI美化 3分镜脚本 4生成参数 5生成中 6结果
  697. remixTranscript: string = '';
  698. remixBeautifiedTranscript: string = '';
  699. remixStoryboard: StoryboardSegment[] = [];
  700. remixStyle: string = 'anime';
  701. remixQuality: '720p' | '1080p' | 'pro' = '1080p';
  702. remixFrames: number = 121;
  703. remixAspectRatio: '16:9' | '4:3' | '1:1' | '3:4' | '9:16' | '21:9' = '16:9';
  704. remixStatusText: string = '';
  705. isRemixSubmitting: boolean = false;
  706. remixResults: { total: number; success: number; failed: number } = { total: 0, success: 0, failed: 0 };
  707. remixStitchStatus: 'idle' | 'stitching' | 'polling' | 'done' | 'failed' = 'idle';
  708. remixStitchUrl: string = '';
  709. remixStitchError: string = '';
  710. remixFinalVideoUrl: string = '';
  711. remixMode: 'standard' | 'digital-human' = 'standard';
  712. remixDigitalHumanImageFile: File | null = null;
  713. remixDigitalHumanImageName: string = '';
  714. remixDigitalHumanImagePreviewUrl: string = '';
  715. remixDigitalHumanImageAssetUrl: string = '';
  716. remixDigitalHumanPrompt: string = '';
  717. remixDigitalHumanFastMode: boolean = false;
  718. remixDigitalHumanResolution: '720p' | '1080p' = '1080p';
  719. remixDigitalHumanError: string = '';
  720. remixDigitalHumanAudioSource: 'original' | 'tts' = 'tts';
  721. remixDigitalHumanTtsText: string = '';
  722. remixDigitalHumanTtsTimbreId: string = '';
  723. remixDigitalHumanTtsSynthesizing: boolean = false;
  724. // ===== 数字人形象准备(自拍优化 / 对标重塑)=====
  725. // raw=直接使用原图;normalize=AI 提取正面全身图;benchmark=对标账号重塑
  726. remixPortraitPrepareMode: 'raw' | 'normalize' | 'benchmark' = 'raw';
  727. remixBenchmarkImageFile: File | null = null;
  728. remixBenchmarkImageName: string = '';
  729. remixBenchmarkImagePreviewUrl: string = '';
  730. remixPortraitPipelineRunning: boolean = false;
  731. remixPortraitPipelineStatus: string = '';
  732. remixPortraitPipelineProgress: number = 0;
  733. remixPortraitPipelineError: string = '';
  734. // pipeline 输出,若存在则数字人生成会优先使用
  735. remixGeneratedPortraitUrl: string = '';
  736. remixGeneratedFullBodyUrl: string = '';
  737. remixGeneratedBenchmarkSummary: string = '';
  738. // ===== 视频生成工作流 =====
  739. vgStep: number = 1; // 1上传视频 2视频解析 3脚本生成 4配图生成 5配音 6数字人生成
  740. readonly vgStepLabels = ['上传视频', '视频解析', '脚本生成', '配图生成', '语音配音', '视频合成'];
  741. readonly vgStepSubtitles = [
  742. '选择需要拆解分析的视频源文件',
  743. 'AI 自动转录与内容理解',
  744. 'AI 生成分镜旁白与画面提示词',
  745. '为每个分镜生成 AI 配图',
  746. '逐段合成旁白音频',
  747. '汇总素材并合成最终视频'
  748. ];
  749. // 用户手动展开的「已完成」步骤集合(active 步骤始终展开,locked 步骤始终折叠)
  750. vgUserExpandedSteps: Set<number> = new Set<number>();
  751. vgSourceFile: File | null = null;
  752. vgSourceFileName: string = '';
  753. vgSourceVideoUrl: string = '';
  754. vgUploading: boolean = false;
  755. vgUploadProgress: number = 0;
  756. vgVideoId: string = '';
  757. // Step 2: 视频解析
  758. vgAnalyzing: boolean = false;
  759. vgAnalysisText: string = '';
  760. vgTranscript: string = '';
  761. // Step 3: 脚本生成
  762. vgGeneratingScript: boolean = false;
  763. vgScript: string = '';
  764. vgScriptSegments: { id: string; narration: string; imagePrompt: string; imagePromptCn?: string; }[] = [];
  765. // Step 4: 配图生成
  766. vgGeneratingImages: boolean = false;
  767. vgImageResults: { id: string; prompt: string; imageUrl: string; status: 'pending' | 'generating' | 'done' | 'failed'; }[] = [];
  768. vgImageProgress: number = 0;
  769. // Step 5: 语音配音
  770. vgVoiceMode: 'clone' | 'system' = 'system';
  771. vgVoiceTimbreId: string = '';
  772. vgVoiceSpeakerId: string = 'zh_female_shuangkuai-am_16k';
  773. vgVoiceName: string = '';
  774. vgVoicePickerOpen: boolean = false;
  775. vgSynthesizing: boolean = false;
  776. vgAudioUrls: { segId: string; audioUrl: string; }[] = [];
  777. // Step 6: 视频合成
  778. vgCompositing: boolean = false;
  779. vgCompositingProgress: number = 0;
  780. vgFinalVideoUrl: string = '';
  781. vgError: string = '';
  782. vgTaskId: string = ''; // 关联任务管理中的任务ID
  783. // Whisper 文字稿生成
  784. isWhisperRunning: boolean = false;
  785. whisperStatusText: string = '';
  786. showManualTranscriptInput: boolean = false;
  787. // 当前 AI 重塑关联的任务
  788. currentRemixTaskId: string = '';
  789. currentRemixId: string = ''; // 当前重塑会话ID
  790. private taskSaveReady: Promise<void> = Promise.resolve();
  791. // 历史详情模态框
  792. showHistoryDetailModal: boolean = false;
  793. historyDetailRecord: HistoryRecord | null = null;
  794. historyDetailSegments: { id: string; videoUrl: string; prompt: string; status: string; narration?: string }[] = [];
  795. historyDetailPrimaryVideoUrl: string = '';
  796. historyDetailLoading: boolean = false;
  797. // Toast 通知
  798. toastMessage: string = '';
  799. toastType: 'success' | 'info' | 'warn' | 'error' = 'info';
  800. toastVisible: boolean = false;
  801. private toastTimer: any = null;
  802. readonly remixStepLabels = ['提取文字稿', 'AI美化', '分镜脚本', '生成参数', '视频生成', '结果汇总'];
  803. readonly digitalHumanStepLabels = ['模式选择', '生成参数', '视频生成', '结果汇总'];
  804. // 重塑风格选项
  805. readonly remixStyleOptions = [
  806. { id: 'anime', name: '动漫风格', prompt: 'anime style, Japanese animation, vibrant colors, cel shading' },
  807. { id: 'oil-painting', name: '油画风格', prompt: 'oil painting style, thick brushstrokes, rich textures, classical art' },
  808. { id: 'watercolor', name: '水彩风格', prompt: 'watercolor painting style, soft colors, fluid brushwork, artistic' },
  809. { id: 'cyberpunk', name: '赛博朋克', prompt: 'cyberpunk style, neon lights, futuristic city, high tech low life, dark atmosphere' },
  810. { id: 'cinematic', name: '电影质感', prompt: 'cinematic style, dramatic lighting, shallow depth of field, movie grade color grading' },
  811. { id: '3d-render', name: '3D渲染', prompt: '3D rendered style, realistic materials, ray tracing, studio lighting' },
  812. { id: 'ink-wash', name: '水墨风格', prompt: 'Chinese ink wash painting style, minimalist, elegant brushwork, traditional art' },
  813. { id: 'vintage', name: '复古风格', prompt: 'vintage retro style, film grain, warm tones, nostalgic atmosphere, 1970s aesthetic' }
  814. ];
  815. constructor(private douyinService: DouyinService, private jimengService: JimengService, private llmService: LlmService, private portraitPipeline: PortraitPipelineService, private digitalHumanService: DigitalHumanService, private http: HttpClient, private qiniuUpload: QiniuUploadService, private browserFfmpeg: BrowserFfmpegService, private ngZone: NgZone, private cdr: ChangeDetectorRef) {
  816. void this.pipelineSession.bootstrap();
  817. this.initializeDefaults();
  818. this.restoreTheme();
  819. this.restoreCurrentTab();
  820. this.restoreClonedTimbreList();
  821. this.restorePersistedMonitorState();
  822. this.refreshIncompleteMonitorAuthors();
  823. this.loadVideoManifest();
  824. this.loadPersistedData();
  825. }
  826. // 初始化默认值(非持久化数据)
  827. private initializeDefaults(): void {
  828. this.searchResults = [];
  829. this.filteredSearchResults = [];
  830. this.monitorUniqueIdInput = '';
  831. this.monitorAuthors = [];
  832. this.selectedMonitorAuthorId = '';
  833. this.monitorAddError = '';
  834. this.voiceProfiles = [];
  835. this.voiceDesignError = '';
  836. this.voiceCreateMode = 'clone';
  837. this.voiceSourceAudioFile = null;
  838. this.voiceSourceAudioName = '';
  839. this.voiceDesignImageFile = null;
  840. this.voiceDesignImageName = '';
  841. this.voiceSpeakerIdOptions = [...this.fallbackVoiceSpeakerIdOptions];
  842. this.voiceForm = this.buildDefaultVoiceForm();
  843. this.voiceSynthesisForm = this.buildDefaultVoiceSynthesisForm();
  844. this.taskStats = { pending: 0, processing: 0, completed: 0, failed: 0 };
  845. // 视频分类
  846. this.videoCategories = [
  847. { id: 'downloaded', name: '已下载', color: '#2196F3', count: 0 },
  848. { id: 'generated', name: 'AI生成', color: '#4CAF50', count: 0 },
  849. { id: 'uploaded', name: '已上传', color: '#FF9800', count: 0 }
  850. ];
  851. this.managedVideos = [];
  852. }
  853. private buildDefaultVoiceForm(): typeof this.voiceForm {
  854. return {
  855. displayName: '',
  856. speakerId: this.voiceSpeakerIdOptions[0] || this.fallbackVoiceSpeakerIdOptions[0] || '',
  857. textPrompt: '',
  858. audioText: '',
  859. sampleText: '',
  860. synthesisText: '',
  861. language: 0
  862. };
  863. }
  864. private buildDefaultVoiceSynthesisForm(profileId = ''): typeof this.voiceSynthesisForm {
  865. return {
  866. profileId,
  867. speakerId: '',
  868. text: '',
  869. ssml: '',
  870. xApiResourceId: '',
  871. model: '',
  872. format: 'mp3',
  873. sampleRate: 24000,
  874. speechRate: 0,
  875. loudnessRate: 0,
  876. emotion: '',
  877. emotionScale: 4,
  878. enableSubtitle: false,
  879. silenceDuration: 0,
  880. enableLanguageDetector: false,
  881. disableMarkdownFilter: false,
  882. disableEmojiFilter: false,
  883. explicitLanguage: ''
  884. };
  885. }
  886. private buildVoiceSynthesisFormFromProfile(profile: VoiceProfile | null | undefined): typeof this.voiceSynthesisForm {
  887. if (!profile) {
  888. return this.buildDefaultVoiceSynthesisForm();
  889. }
  890. return {
  891. profileId: profile.id,
  892. speakerId: String(profile.icl_speaker_id || profile.speaker_id || ''),
  893. text: String(profile.draft_synthesis_text || profile.last_synthesis_text || ''),
  894. ssml: String(profile.draft_synthesis_ssml || ''),
  895. xApiResourceId: String(profile.draft_synthesis_x_api_resource_id || profile.x_api_resource_id || ''),
  896. model: String(profile.draft_synthesis_model || ''),
  897. format: this.normalizeVoiceSynthesisFormat(profile.draft_synthesis_format),
  898. sampleRate: this.normalizeVoiceSynthesisSampleRate(profile.draft_synthesis_sample_rate),
  899. speechRate: this.clampVoiceSynthesisRate(profile.draft_synthesis_speech_rate, 0),
  900. loudnessRate: this.clampVoiceSynthesisRate(profile.draft_synthesis_loudness_rate, 0),
  901. emotion: String(profile.draft_synthesis_emotion || ''),
  902. emotionScale: this.clampVoiceSynthesisEmotionScale(profile.draft_synthesis_emotion_scale, 4),
  903. enableSubtitle: !!profile.draft_synthesis_enable_subtitle,
  904. silenceDuration: this.clampVoiceSynthesisSilenceDuration(profile.draft_synthesis_silence_duration, 0),
  905. enableLanguageDetector: !!profile.draft_synthesis_enable_language_detector,
  906. disableMarkdownFilter: !!profile.draft_synthesis_disable_markdown_filter,
  907. disableEmojiFilter: !!profile.draft_synthesis_disable_emoji_filter,
  908. explicitLanguage: String(profile.draft_synthesis_explicit_language || '')
  909. };
  910. }
  911. private syncVoiceSynthesisFormSelection(): void {
  912. const availableProfiles = this.getSynthesisVoiceProfiles();
  913. const selectedProfile = availableProfiles.find((profile) => profile.id === this.voiceSynthesisForm.profileId) || null;
  914. if (selectedProfile) {
  915. this.voiceSynthesisForm = this.buildVoiceSynthesisFormFromProfile(selectedProfile);
  916. return;
  917. }
  918. if (String(this.voiceSynthesisForm.speakerId || '').trim()) {
  919. this.voiceSynthesisForm = {
  920. ...this.voiceSynthesisForm,
  921. profileId: ''
  922. };
  923. return;
  924. }
  925. this.voiceSynthesisForm = this.buildVoiceSynthesisFormFromProfile(availableProfiles[0] || null);
  926. }
  927. private normalizeVoiceSynthesisFormat(value: any): string {
  928. const format = String(value || '').trim().toLowerCase();
  929. return ['mp3', 'ogg_opus', 'pcm'].includes(format) ? format : 'mp3';
  930. }
  931. private normalizeVoiceSynthesisSampleRate(value: any): number {
  932. const sampleRate = Number(value);
  933. return [8000, 16000, 22050, 24000, 32000, 44100, 48000].includes(sampleRate) ? sampleRate : 24000;
  934. }
  935. private clampVoiceSynthesisRate(value: any, fallback = 0): number {
  936. const numericValue = Number(value);
  937. if (!Number.isFinite(numericValue)) {
  938. return fallback;
  939. }
  940. return Math.min(100, Math.max(-50, numericValue));
  941. }
  942. private clampVoiceSynthesisEmotionScale(value: any, fallback = 4): number {
  943. const numericValue = Number(value);
  944. if (!Number.isFinite(numericValue)) {
  945. return fallback;
  946. }
  947. return Math.min(5, Math.max(1, Math.round(numericValue)));
  948. }
  949. private clampVoiceSynthesisSilenceDuration(value: any, fallback = 0): number {
  950. const numericValue = Number(value);
  951. if (!Number.isFinite(numericValue)) {
  952. return fallback;
  953. }
  954. return Math.min(30000, Math.max(0, Math.round(numericValue)));
  955. }
  956. private inferVoiceSourceAudioFormat(file: File): string {
  957. const mimeType = String(file?.type || '').toLowerCase();
  958. const fileName = String(file?.name || '').toLowerCase();
  959. if (mimeType.includes('wav') || fileName.endsWith('.wav')) {
  960. return 'wav';
  961. }
  962. if (mimeType.includes('m4a') || mimeType.includes('mp4') || fileName.endsWith('.m4a')) {
  963. return 'm4a';
  964. }
  965. if (mimeType.includes('aac') || fileName.endsWith('.aac')) {
  966. return 'aac';
  967. }
  968. if (mimeType.includes('flac') || fileName.endsWith('.flac')) {
  969. return 'flac';
  970. }
  971. if (mimeType.includes('opus') || fileName.endsWith('.opus')) {
  972. return 'opus';
  973. }
  974. if (mimeType.includes('ogg') || fileName.endsWith('.ogg')) {
  975. return 'ogg';
  976. }
  977. if (mimeType.includes('pcm') || fileName.endsWith('.pcm')) {
  978. return 'pcm';
  979. }
  980. return 'mp3';
  981. }
  982. private readFileAsBase64(file: File): Promise<string> {
  983. return new Promise((resolve, reject) => {
  984. const reader = new FileReader();
  985. reader.onload = () => {
  986. const result = String(reader.result || '');
  987. const base64 = result.includes(',') ? result.split(',').pop() || '' : result;
  988. if (!base64) {
  989. reject(new Error('音频文件读取失败'));
  990. return;
  991. }
  992. resolve(base64);
  993. };
  994. reader.onerror = () => reject(reader.error || new Error('音频文件读取失败'));
  995. reader.readAsDataURL(file);
  996. });
  997. }
  998. private buildVoiceSynthesisDraft(profile: any): Partial<VoiceProfile> {
  999. return {
  1000. draft_synthesis_text: String(profile?.last_synthesis_text || ''),
  1001. draft_synthesis_ssml: String(profile?.last_synthesis_ssml || ''),
  1002. draft_synthesis_x_api_resource_id: String(profile?.last_synthesis_x_api_resource_id || profile?.x_api_resource_id || ''),
  1003. draft_synthesis_model: String(profile?.last_synthesis_model || ''),
  1004. draft_synthesis_format: this.normalizeVoiceSynthesisFormat(profile?.last_synthesis_format),
  1005. draft_synthesis_sample_rate: this.normalizeVoiceSynthesisSampleRate(profile?.last_synthesis_sample_rate),
  1006. draft_synthesis_speech_rate: this.clampVoiceSynthesisRate(profile?.last_synthesis_speech_rate, 0),
  1007. draft_synthesis_loudness_rate: this.clampVoiceSynthesisRate(profile?.last_synthesis_loudness_rate, 0),
  1008. draft_synthesis_emotion: String(profile?.last_synthesis_emotion || ''),
  1009. draft_synthesis_emotion_scale: this.clampVoiceSynthesisEmotionScale(profile?.last_synthesis_emotion_scale, 4),
  1010. draft_synthesis_enable_subtitle: !!profile?.last_synthesis_enable_subtitle,
  1011. draft_synthesis_silence_duration: this.clampVoiceSynthesisSilenceDuration(profile?.last_synthesis_silence_duration, 0),
  1012. draft_synthesis_enable_language_detector: !!profile?.last_synthesis_enable_language_detector,
  1013. draft_synthesis_disable_markdown_filter: !!profile?.last_synthesis_disable_markdown_filter,
  1014. draft_synthesis_disable_emoji_filter: !!profile?.last_synthesis_disable_emoji_filter,
  1015. draft_synthesis_explicit_language: String(profile?.last_synthesis_explicit_language || '')
  1016. };
  1017. }
  1018. private restoreCurrentTab(): void {
  1019. try {
  1020. const savedTab = localStorage.getItem(this.TAB_STORAGE_KEY);
  1021. const allowed = ['home','search','monitor','tasks','history','results','videos','voice-synthesis','pipelines','digital-human','image-generation','video-generation','image-to-video','action-transfer','asset-remix','topic-to-video','drafts','library'];
  1022. // 旧 tab → 新页面的迁移映射(M4/M5/M6 重组后)
  1023. // 'history' 完整功能被「我的创作」覆盖;'results' 被「素材库」替代。
  1024. const aliases: Record<string, string> = {
  1025. history: 'drafts',
  1026. results: 'library',
  1027. };
  1028. let target = savedTab;
  1029. if (target && aliases[target]) target = aliases[target];
  1030. if (target && allowed.includes(target)) {
  1031. this.currentTab = target as any;
  1032. }
  1033. } catch {}
  1034. }
  1035. private restoreTheme(): void {
  1036. try {
  1037. const saved = localStorage.getItem(this.THEME_STORAGE_KEY);
  1038. if (saved === 'day' || saved === 'night') {
  1039. this.themeMode = saved;
  1040. }
  1041. } catch {}
  1042. }
  1043. toggleTheme(): void {
  1044. this.themeMode = this.themeMode === 'day' ? 'night' : 'day';
  1045. try {
  1046. localStorage.setItem(this.THEME_STORAGE_KEY, this.themeMode);
  1047. } catch {}
  1048. }
  1049. private restoreClonedTimbreList(): void {
  1050. try {
  1051. const saved = localStorage.getItem(this.TIMBRE_LIST_STORAGE_KEY);
  1052. if (saved) {
  1053. const parsed = JSON.parse(saved);
  1054. if (Array.isArray(parsed)) {
  1055. this.vsClonedTimbreList = parsed.filter(
  1056. (t: any) => t && typeof t.objectId === 'string' && t.objectId
  1057. );
  1058. }
  1059. }
  1060. } catch {}
  1061. }
  1062. private saveClonedTimbreList(): void {
  1063. try {
  1064. localStorage.setItem(this.TIMBRE_LIST_STORAGE_KEY, JSON.stringify(this.vsClonedTimbreList));
  1065. } catch {}
  1066. }
  1067. setCurrentTab(tab: 'home' | 'search' | 'monitor' | 'tasks' | 'history' | 'results' | 'videos' | 'voice-synthesis' | 'pipelines' | 'digital-human' | 'image-generation' | 'video-generation' | 'image-to-video' | 'action-transfer' | 'asset-remix' | 'topic-to-video' | 'drafts' | 'library'): void {
  1068. this.currentTab = tab;
  1069. try {
  1070. localStorage.setItem(this.TAB_STORAGE_KEY, tab);
  1071. } catch {}
  1072. }
  1073. /** 右下浮动 mini-pill:当前正在跑的任务(取 activeTasks 中第一个 processing/pending) */
  1074. get currentRunningTask(): RecentTaskView | null {
  1075. const running = (this.activeTasks || []).find(
  1076. (t) => t && (t.status === 'processing' || t.status === 'pending'),
  1077. );
  1078. if (!running) return null;
  1079. return {
  1080. id: running.id,
  1081. keyword: running.keyword,
  1082. status: running.status,
  1083. step: running.step,
  1084. progress: Math.max(0, Math.min(100, running.progress ?? 0)),
  1085. type: running.type,
  1086. };
  1087. }
  1088. /** assistant 浮窗是否展开(由组件回传);展开时 pill 让位到面板上方 */
  1089. assistantExpanded = false;
  1090. /** 首屏内联对话页激活(由 app-home 通过 inlineChatChange 输出):pill / FAB 都隐藏 */
  1091. homeChatActive = false;
  1092. /**
  1093. * pill 隐藏条件:
  1094. * 1. 已经在 tasks 页 —— 重复
  1095. * 2. 浮窗展开 —— 被遮挡
  1096. * 3. 首屏全宽对话页激活 —— 主区已是对话
  1097. */
  1098. get pillHidden(): boolean {
  1099. return this.currentTab === 'tasks' || this.assistantExpanded || this.homeChatActive;
  1100. }
  1101. /** 助手内回复中的「直达 X 模式」按钮被点击 */
  1102. onAssistantSuggestion(s: AssistantSuggestion): void {
  1103. if (!s?.tab) return;
  1104. // 复用首屏跳转通道:含 payload 时同样走 sessionStorage 预填
  1105. this.onHomeNavigate({ tab: s.tab, payload: s.payload });
  1106. }
  1107. /**
  1108. * 「我的创作」页里点「继续编辑」/「再做一版」时调用。
  1109. * 此时 PipelineSessionService.active 已是目标 draft,
  1110. * 切到对应 Pipeline tab 后,组件 ngOnInit 会读取 active 并 fromSnapshot。
  1111. */
  1112. onDraftsNavigate(route: PipelineRoute): void {
  1113. this.setCurrentTab(route);
  1114. }
  1115. /**
  1116. * 「素材库」页点某个卡片 → 打开其所属 draft(到「我的创作」详情)。
  1117. * 跳转后 session 仍保持 active = 该 draft,DraftsComponent 会从 list 中选中。
  1118. */
  1119. async onLibraryNavigate(ev: { draftId: string; pipelineId: PipelineRoute }): Promise<void> {
  1120. await this.pipelineSession.open(ev.draftId);
  1121. this.setCurrentTab('drafts');
  1122. }
  1123. /** 首屏组件输出:可能带 payload(如预填的主题) */
  1124. onHomeNavigate(ev: { tab: string; payload?: any }): void {
  1125. this.setCurrentTab(ev.tab as any);
  1126. // 主题预填:暂存到 sessionStorage,topic-to-video 组件初始化时自取
  1127. if (ev.payload?.topic && ev.tab === 'topic-to-video') {
  1128. try {
  1129. sessionStorage.setItem('t2v.prefillTopic', ev.payload.topic);
  1130. } catch {}
  1131. }
  1132. }
  1133. private restorePersistedMonitorState(): void {
  1134. try {
  1135. const savedAuthors = localStorage.getItem(this.MONITOR_AUTHORS_STORAGE_KEY);
  1136. const savedSelectedAuthorStorageKey = localStorage.getItem(this.MONITOR_SELECTED_AUTHOR_STORAGE_KEY) || '';
  1137. if (savedAuthors) {
  1138. const parsedAuthors = JSON.parse(savedAuthors);
  1139. if (Array.isArray(parsedAuthors)) {
  1140. this.monitorAuthors = parsedAuthors.map((author: any) => this.deserializeMonitorAuthor(author));
  1141. }
  1142. }
  1143. this.selectedMonitorAuthorId = this.monitorAuthors.some(author => author.id === savedSelectedAuthorStorageKey)
  1144. ? savedSelectedAuthorStorageKey
  1145. : '';
  1146. } catch {
  1147. this.monitorAuthors = [];
  1148. this.selectedMonitorAuthorId = '';
  1149. }
  1150. }
  1151. private persistMonitorState(): void {
  1152. try {
  1153. localStorage.setItem(this.MONITOR_AUTHORS_STORAGE_KEY, JSON.stringify(this.monitorAuthors.map(author => this.serializeMonitorAuthor(author))));
  1154. localStorage.setItem(this.MONITOR_SELECTED_AUTHOR_STORAGE_KEY, this.selectedMonitorAuthorId || '');
  1155. } catch {}
  1156. }
  1157. // 从后端加载持久化数据(任务、历史、结果)
  1158. private loadPersistedData(): void {
  1159. // 加载任务
  1160. this.http.get<any[]>('/backend/api/tasks').subscribe({
  1161. next: (tasks) => {
  1162. this.activeTasks = tasks.map(t => ({ ...t, created_at: new Date(t.created_at), updated_at: new Date(t.updated_at) }));
  1163. this.updateTaskStats();
  1164. console.log(`📋 已加载 ${tasks.length} 个任务`);
  1165. // 同步:将 processing 但实际已完成的任务修正
  1166. this.syncTaskStatesFromRemixes();
  1167. this.refreshView();
  1168. },
  1169. error: () => {
  1170. console.warn('⚠️ 无法从后端加载任务,使用空列表');
  1171. this.activeTasks = [];
  1172. this.refreshView();
  1173. }
  1174. });
  1175. // 加载历史
  1176. this.http.get<any[]>('/backend/api/history').subscribe({
  1177. next: (records) => {
  1178. this.historyRecords = records.map(r => ({ ...r, created_at: new Date(r.created_at) }));
  1179. console.log(`📜 已加载 ${records.length} 条历史记录`);
  1180. this.refreshView();
  1181. },
  1182. error: () => {
  1183. console.warn('⚠️ 无法从后端加载历史,使用空列表');
  1184. this.historyRecords = [];
  1185. this.refreshView();
  1186. }
  1187. });
  1188. // 加载结果
  1189. this.http.get<any[]>('/backend/api/results').subscribe({
  1190. next: (results) => {
  1191. this.generatedResults = results.map(r => ({ ...r, created_at: new Date(r.created_at) }));
  1192. console.log(`🎬 已加载 ${results.length} 个生成结果`);
  1193. this.refreshView();
  1194. },
  1195. error: () => {
  1196. console.warn('⚠️ 无法从后端加载结果,使用空列表');
  1197. this.generatedResults = [];
  1198. this.refreshView();
  1199. }
  1200. });
  1201. }
  1202. // 从 remix 数据同步修正任务状态(处理页面刷新后任务状态不一致)
  1203. private syncTaskStatesFromRemixes(): void {
  1204. this.http.get<Record<string, any[]>>('/backend/api/remixes').subscribe({
  1205. next: (allRemixes) => {
  1206. const remixByTaskId = new Map<string, any>();
  1207. for (const remixes of Object.values(allRemixes)) {
  1208. for (const r of remixes) {
  1209. if (r.taskId) remixByTaskId.set(r.taskId, r);
  1210. }
  1211. }
  1212. let changed = false;
  1213. for (const task of this.activeTasks) {
  1214. if (task.status === 'processing') {
  1215. const remix = remixByTaskId.get(task.id);
  1216. if (remix) {
  1217. if (remix.status === 'completed' || remix.status === 'failed') {
  1218. task.status = remix.status;
  1219. task.step = remix.status === 'completed' ? 'complete' : 'generate';
  1220. task.progress = 100;
  1221. const successCount = remix.segments?.filter((s: any) => s.status === 'completed').length || 0;
  1222. const totalCount = remix.segments?.length || 0;
  1223. task.error_message = remix.status === 'failed' ? `${successCount}/${totalCount} 片段成功` : undefined;
  1224. task.result_url = remix.segments?.find((s: any) => s.videoUrl)?.videoUrl;
  1225. task.updated_at = new Date(remix.updated_at || remix.created_at);
  1226. this.updateTask(task);
  1227. changed = true;
  1228. } else if (remix.status === 'generating') {
  1229. const successCount = remix.segments?.filter((s: any) => s.status === 'completed').length || 0;
  1230. const failedCount = remix.segments?.filter((s: any) => s.status === 'failed').length || 0;
  1231. const totalCount = remix.segments?.length || 0;
  1232. const doneCount = successCount + failedCount;
  1233. task.progress = Math.round((doneCount / totalCount) * 80);
  1234. task.updated_at = new Date(remix.updated_at || remix.created_at);
  1235. this.updateTask(task);
  1236. changed = true;
  1237. }
  1238. }
  1239. }
  1240. }
  1241. // 超过1小时仍为 processing 且无匹配 remix 的任务标记为超时
  1242. const oneHourAgo = Date.now() - 60 * 60 * 1000;
  1243. for (const task of this.activeTasks) {
  1244. if (task.status === 'processing' && !remixByTaskId.has(task.id)) {
  1245. if (new Date(task.updated_at).getTime() < oneHourAgo) {
  1246. task.status = 'timeout';
  1247. task.error_message = '任务超时(无匹配生成记录)';
  1248. task.updated_at = new Date();
  1249. this.updateTask(task);
  1250. changed = true;
  1251. }
  1252. }
  1253. }
  1254. if (changed) this.updateTaskStats();
  1255. this.refreshView();
  1256. },
  1257. error: () => {
  1258. this.refreshView();
  1259. }
  1260. });
  1261. }
  1262. // 任务筛选(点击顶部统计卡可缩小到对应状态)
  1263. tasksFilter: '' | 'pending' | 'processing' | 'completed' | 'failed' = '';
  1264. getFilteredTasks(): Task[] {
  1265. if (!this.tasksFilter) return this.activeTasks;
  1266. return this.activeTasks.filter(t => t.status === this.tasksFilter);
  1267. }
  1268. toggleTasksFilter(status: '' | 'pending' | 'processing' | 'completed' | 'failed'): void {
  1269. this.tasksFilter = this.tasksFilter === status ? '' : status;
  1270. this.refreshView();
  1271. }
  1272. // 计算任务统计
  1273. private updateTaskStats(): void {
  1274. this.taskStats = {
  1275. pending: this.activeTasks.filter(t => t.status === 'pending').length,
  1276. processing: this.activeTasks.filter(t => t.status === 'processing').length,
  1277. completed: this.activeTasks.filter(t => t.status === 'completed').length,
  1278. failed: this.activeTasks.filter(t => t.status === 'failed' || t.status === 'timeout').length
  1279. };
  1280. }
  1281. // ==================== 持久化保存方法 ====================
  1282. // 保存任务到后端(返回 Promise,确保 POST 完成后再允许 PUT)
  1283. saveTask(task: Task): void {
  1284. this.taskSaveReady = new Promise<void>((resolve) => {
  1285. this.http.post<any>('/backend/api/tasks', task).subscribe({
  1286. next: (res) => {
  1287. if (res?.task?.id) task.id = res.task.id;
  1288. this.updateTaskStats();
  1289. console.log('💾 任务已保存:', task.id);
  1290. resolve();
  1291. },
  1292. error: (err) => {
  1293. console.warn('⚠️ 任务保存失败:', err);
  1294. resolve(); // 即使失败也 resolve,避免阻塞后续更新
  1295. }
  1296. });
  1297. });
  1298. }
  1299. // 更新任务到后端(等待 POST 完成后再 PUT)
  1300. updateTask(task: Task): void {
  1301. this.taskSaveReady.then(() => {
  1302. this.http.put<any>(`/backend/api/tasks/${task.id}`, task).subscribe({
  1303. next: () => {
  1304. this.updateTaskStats();
  1305. },
  1306. error: (err) => console.warn('⚠️ 任务更新失败:', err)
  1307. });
  1308. });
  1309. }
  1310. // 删除任务(先做本地乐观更新,再持久化;持久化失败也保留本地删除并提示)
  1311. removeTask(taskId: string): void {
  1312. if (!confirm('确定要删除该任务吗?此操作不可恢复。')) return;
  1313. if (!taskId) {
  1314. // ID 为空的脏数据,直接从本地移除
  1315. this.activeTasks = this.activeTasks.filter(t => !!t.id);
  1316. this.updateTaskStats();
  1317. this.refreshView();
  1318. this.showToast('🗑️ 已清除无效任务', 'info');
  1319. return;
  1320. }
  1321. // 乐观删除:立即从本地列表移除,UI 立刻更新
  1322. this.activeTasks = this.activeTasks.filter(t => t.id !== taskId);
  1323. this.canceledTaskIds.add(taskId);
  1324. this.updateTaskStats();
  1325. this.refreshView();
  1326. this.http.delete<any>(`/backend/api/tasks/${taskId}`).subscribe({
  1327. next: () => {
  1328. console.log('🗑️ 任务已删除:', taskId);
  1329. this.showToast('🗑️ 任务已删除', 'success');
  1330. },
  1331. error: (err) => {
  1332. console.warn('⚠️ 任务删除失败:', err);
  1333. this.showToast('⚠️ 后端删除失败,已从列表中移除', 'warn');
  1334. }
  1335. });
  1336. }
  1337. // 保存历史记录到后端
  1338. saveHistoryRecord(record: Partial<HistoryRecord>): void {
  1339. this.http.post<any>('/backend/api/history', record).subscribe({
  1340. next: (res) => {
  1341. if (res?.record) {
  1342. this.historyRecords.unshift({ ...res.record, created_at: new Date(res.record.created_at) });
  1343. }
  1344. console.log('💾 历史记录已保存');
  1345. },
  1346. error: (err) => console.warn('⚠️ 历史保存失败:', err)
  1347. });
  1348. }
  1349. // 删除历史记录
  1350. removeHistoryRecord(recordId: string): void {
  1351. this.http.delete<any>(`/backend/api/history/${recordId}`).subscribe({
  1352. next: () => {
  1353. this.historyRecords = this.historyRecords.filter(r => r.id !== recordId);
  1354. console.log('🗑️ 历史记录已删除:', recordId);
  1355. },
  1356. error: (err) => console.warn('⚠️ 历史删除失败:', err)
  1357. });
  1358. }
  1359. getFilteredHistoryRecords(): HistoryRecord[] {
  1360. return this.historyRecords.filter(record => {
  1361. return !this.historyFilter.status || record.status === this.historyFilter.status;
  1362. });
  1363. }
  1364. // 把标题中嵌入的 #标签 解析出来,主标题与标签分开渲染
  1365. parseHistoryRecordTitle(record: HistoryRecord): { title: string; tags: string[] } {
  1366. const raw = (record.original_video_title || record.keyword || '').trim();
  1367. if (!raw) return { title: '未命名记录', tags: [] };
  1368. const tags: string[] = [];
  1369. const cleaned = raw.replace(/#([^\s#]+)/g, (_, tag) => { tags.push(tag); return ''; }).replace(/\s+/g, ' ').trim();
  1370. return { title: cleaned || raw, tags };
  1371. }
  1372. getHistoryStatusCount(status: string): number {
  1373. if (!status) return this.historyRecords.length;
  1374. return this.historyRecords.filter(r => r.status === status).length;
  1375. }
  1376. // 保存生成结果到后端
  1377. saveResult(result: Partial<GeneratedResult>): void {
  1378. this.http.post<any>('/backend/api/results', result).subscribe({
  1379. next: (res) => {
  1380. if (res?.result) {
  1381. this.generatedResults.unshift({ ...res.result, created_at: new Date(res.result.created_at) });
  1382. }
  1383. console.log('💾 结果已保存');
  1384. },
  1385. error: (err) => console.warn('⚠️ 结果保存失败:', err)
  1386. });
  1387. }
  1388. // 删除生成结果
  1389. removeResult(resultId: string): void {
  1390. this.http.delete<any>(`/backend/api/results/${resultId}`).subscribe({
  1391. next: () => {
  1392. this.generatedResults = this.generatedResults.filter(r => r.id !== resultId);
  1393. console.log('🗑️ 结果已删除:', resultId);
  1394. },
  1395. error: (err) => console.warn('⚠️ 结果删除失败:', err)
  1396. });
  1397. }
  1398. // Toast 通知
  1399. showToast(message: string, type: 'success' | 'info' | 'warn' | 'error' = 'info', duration: number = 4000): void {
  1400. if (this.toastTimer) clearTimeout(this.toastTimer);
  1401. this.toastMessage = message;
  1402. this.toastType = type;
  1403. this.toastVisible = true;
  1404. this.toastTimer = setTimeout(() => {
  1405. this.toastVisible = false;
  1406. }, duration);
  1407. }
  1408. private refreshView(): void {
  1409. this.cdr.detectChanges();
  1410. }
  1411. // 查找并更新任务
  1412. private findRemixTask(): Task | undefined {
  1413. return this.activeTasks.find(t => t.id === this.currentRemixTaskId);
  1414. }
  1415. private updateRemixTaskProgress(step: Task['step'], progress: number, statusText?: string): void {
  1416. const task = this.findRemixTask();
  1417. if (!task) return;
  1418. task.step = step;
  1419. task.progress = Math.round(progress);
  1420. task.updated_at = new Date();
  1421. if (statusText) task.error_message = undefined;
  1422. this.updateTask(task);
  1423. }
  1424. private completeRemixTask(status: 'completed' | 'failed', resultUrl?: string, errorMsg?: string): void {
  1425. const task = this.findRemixTask();
  1426. if (!task) return;
  1427. task.status = status;
  1428. task.step = status === 'completed' ? 'complete' : task.step;
  1429. task.progress = 100;
  1430. task.result_url = resultUrl;
  1431. task.error_message = errorMsg;
  1432. task.updated_at = new Date();
  1433. this.updateTask(task);
  1434. this.updateTaskStats();
  1435. }
  1436. // ==================== Remix 会话持久化 ====================
  1437. // 保存当前重塑会话到后端(每次片段完成时调用)
  1438. private saveRemixSession(status: 'generating' | 'stitching' | 'completed' | 'failed'): void {
  1439. const video = this.remixTargetVideo;
  1440. if (!video || !this.currentRemixId) return;
  1441. const styleName = this.remixMode === 'digital-human'
  1442. ? '数字人生成'
  1443. : (this.remixStyleOptions.find(s => s.id === this.remixStyle)?.name || this.remixStyle);
  1444. const sessionData = {
  1445. remixId: this.currentRemixId,
  1446. videoId: video.id,
  1447. videoTitle: video.title,
  1448. mode: this.remixMode,
  1449. style: this.remixStyle,
  1450. styleName: styleName,
  1451. quality: this.remixMode === 'digital-human' ? this.remixDigitalHumanResolution : this.remixQuality,
  1452. frames: this.remixFrames,
  1453. aspectRatio: this.remixAspectRatio,
  1454. status: status,
  1455. taskId: this.currentRemixTaskId,
  1456. stitchUrl: this.remixStitchUrl || '',
  1457. digitalHumanAudioSource: this.remixMode === 'digital-human' ? this.remixDigitalHumanAudioSource : '',
  1458. digitalHumanVoiceProfileId: '',
  1459. digitalHumanVoiceProfileName: '',
  1460. results: { ...this.remixResults },
  1461. segments: this.remixStoryboard.map(s => ({
  1462. id: s.id,
  1463. act: s.act,
  1464. narration: s.narration,
  1465. prompt: s.prompt,
  1466. duration: s.duration,
  1467. status: s.status,
  1468. videoUrl: s.videoUrl || '',
  1469. workId: s.workId || '',
  1470. error: s.error || ''
  1471. }))
  1472. };
  1473. this.http.post<any>(`/backend/api/remixes/${video.id}`, sessionData).subscribe({
  1474. next: () => console.log(`💾 Remix 会话已保存: ${this.currentRemixId} [${status}]`),
  1475. error: (err) => console.warn('⚠️ Remix 保存失败:', err)
  1476. });
  1477. }
  1478. // 加载某视频的所有重塑记录
  1479. loadVideoRemixes(videoId: string): void {
  1480. this.http.get<any[]>(`/backend/api/remixes/${videoId}`).subscribe({
  1481. next: (remixes) => {
  1482. const video = this.managedVideos.find(v => v.id === videoId);
  1483. if (video && remixes.length > 0) {
  1484. video.remixVersions = remixes.map(r => ({
  1485. id: r.remixId,
  1486. style: r.styleName || r.style,
  1487. created_at: new Date(r.created_at),
  1488. file_path: r.stitchUrl || r.segments?.find((s: any) => s.videoUrl)?.videoUrl || '',
  1489. thumbnail: 'assets/default-remix-thumb.jpg',
  1490. description: `${r.styleName} · ${r.segments?.length || 0}段 · ${r.status === 'completed' ? '已完成' : r.status === 'generating' ? '生成中' : '失败'}`,
  1491. parameters: {
  1492. style: r.style,
  1493. intensity: 0.8,
  1494. preserve_audio: true,
  1495. quality: r.quality === 'pro' ? 'ultra' : 'high',
  1496. effects: [r.style]
  1497. }
  1498. }));
  1499. console.log(`📂 已加载 ${video.title} 的 ${remixes.length} 条重塑记录`);
  1500. }
  1501. },
  1502. error: () => {}
  1503. });
  1504. }
  1505. // 批量加载所有视频的重塑记录
  1506. private loadAllRemixes(): void {
  1507. this.http.get<Record<string, any[]>>('/backend/api/remixes').subscribe({
  1508. next: (allRemixes) => {
  1509. let total = 0;
  1510. for (const [videoId, remixes] of Object.entries(allRemixes)) {
  1511. const video = this.managedVideos.find(v => v.id === videoId);
  1512. if (video && remixes.length > 0) {
  1513. video.remixVersions = remixes.map(r => ({
  1514. id: r.remixId,
  1515. style: r.styleName || r.style,
  1516. created_at: new Date(r.created_at),
  1517. file_path: r.stitchUrl || r.segments?.find((s: any) => s.videoUrl)?.videoUrl || '',
  1518. thumbnail: 'assets/default-remix-thumb.jpg',
  1519. description: `${r.styleName} · ${r.segments?.length || 0}段 · ${r.status === 'completed' ? '已完成' : r.status === 'generating' ? '生成中' : '失败'}`,
  1520. parameters: {
  1521. style: r.style,
  1522. intensity: 0.8,
  1523. preserve_audio: true,
  1524. quality: r.quality === 'pro' ? 'ultra' : 'high',
  1525. effects: [r.style]
  1526. }
  1527. }));
  1528. total += remixes.length;
  1529. }
  1530. }
  1531. if (total > 0) console.log(`📂 已加载 ${total} 条重塑记录`);
  1532. this.refreshView();
  1533. },
  1534. error: () => {
  1535. this.refreshView();
  1536. }
  1537. });
  1538. }
  1539. // 从 src/video/manifest.json 加载视频清单
  1540. private loadVideoManifest(): void {
  1541. this.http.get<any[]>(`/backend/api/manifest`).subscribe({
  1542. next: (manifest) => {
  1543. this.managedVideos = manifest.map((item: any) => ({
  1544. id: item.id,
  1545. title: item.title || item.filename,
  1546. filename: item.filename,
  1547. filepath: (item.filepath && /^https?:\/\//.test(item.filepath)) ? item.filepath : `/backend/api/video/${item.filename}`,
  1548. size: item.size || 0,
  1549. duration: item.duration || 0,
  1550. created_at: item.created_at ? new Date(item.created_at) : new Date(),
  1551. modified_at: item.modified_at ? new Date(item.modified_at) : new Date(),
  1552. category: item.category || 'downloaded',
  1553. tags: item.tags || [],
  1554. description: item.description || '',
  1555. thumbnail: item.thumbnail || '',
  1556. source: item.source || 'downloaded',
  1557. metadata: item.metadata || { resolution: '', format: 'mp4' },
  1558. whisper: item.whisper || undefined
  1559. }));
  1560. this.updateCategoryCounts();
  1561. console.log(`📁 已加载 ${this.managedVideos.length} 个视频`);
  1562. // 加载每个视频的重塑记录
  1563. this.loadAllRemixes();
  1564. this.refreshView();
  1565. },
  1566. error: (err) => {
  1567. console.warn('⚠️ 无法加载视频清单,使用空列表:', err);
  1568. this.managedVideos = [];
  1569. this.refreshView();
  1570. }
  1571. });
  1572. }
  1573. // 将下载的视频添加到管理列表
  1574. private addToManagedVideos(video: VideoInfo, filename: string): void {
  1575. const newVideo: ManagedVideo = {
  1576. id: `VID-${Date.now()}`,
  1577. title: video.desc || filename,
  1578. filename: filename,
  1579. filepath: `${this.VIDEO_BASE_PATH}/${filename}`,
  1580. size: 0,
  1581. duration: video.duration || 0,
  1582. created_at: new Date(),
  1583. modified_at: new Date(),
  1584. category: 'downloaded',
  1585. tags: video.text_extra || [],
  1586. description: video.desc || '',
  1587. thumbnail: video.cover_url || '',
  1588. source: 'downloaded',
  1589. metadata: {
  1590. resolution: '1920x1080',
  1591. format: 'mp4'
  1592. }
  1593. };
  1594. this.managedVideos.unshift(newVideo);
  1595. this.updateCategoryCounts();
  1596. console.log(`✅ 视频已添加到管理列表: ${filename}`);
  1597. }
  1598. addMonitorAuthor(): void {
  1599. const uniqueId = this.monitorUniqueIdInput.trim();
  1600. if (!uniqueId || this.isAddingMonitorAuthor) return;
  1601. const existingAuthor = this.monitorAuthors.find(author => author.uid === uniqueId || author.id === uniqueId || author.uniqueId === uniqueId || author.shortId === uniqueId);
  1602. if (existingAuthor) {
  1603. this.selectedMonitorAuthorId = existingAuthor.id;
  1604. this.persistMonitorState();
  1605. if (existingAuthor.followerCount === 0) {
  1606. this.refreshMonitorAuthorProfile(existingAuthor, false);
  1607. }
  1608. this.showToast(`⚠️ 博主「${existingAuthor.nickname}」已在监测列表中`, 'warn');
  1609. this.refreshView();
  1610. return;
  1611. }
  1612. this.isAddingMonitorAuthor = true;
  1613. this.monitorAddError = '';
  1614. this.buildCompleteMonitorAuthor(uniqueId, (author, usedFallback) => {
  1615. this.monitorAuthors = [author, ...this.monitorAuthors.filter(item => item.id !== author.id && item.uid !== author.uid)];
  1616. this.monitorUniqueIdInput = '';
  1617. this.isAddingMonitorAuthor = false;
  1618. this.persistMonitorState();
  1619. this.showToast(
  1620. usedFallback
  1621. ? `⚠️ 已添加博主「${author.nickname}」,但完整粉丝数据暂未取到`
  1622. : `✅ 已添加博主「${author.nickname}」`,
  1623. usedFallback ? 'warn' : 'success'
  1624. );
  1625. this.fetchMonitorAuthorWorks(author, false);
  1626. this.refreshView();
  1627. }, (message) => {
  1628. this.isAddingMonitorAuthor = false;
  1629. this.monitorAddError = message;
  1630. this.showToast(`❌ ${this.monitorAddError}`, 'error');
  1631. this.refreshView();
  1632. });
  1633. }
  1634. private buildCompleteMonitorAuthor(
  1635. uniqueId: string,
  1636. onSuccess: (author: MonitorAuthor, usedFallback: boolean) => void,
  1637. onError: (message: string) => void
  1638. ): void {
  1639. this.douyinService.getUserProfileByUniqueId(uniqueId).subscribe({
  1640. next: (res: any) => {
  1641. const basicProfile = this.douyinService.extractUserProfileData(res) || {};
  1642. const basicAuthor = this.mapMonitorAuthor(basicProfile, uniqueId);
  1643. if (!basicAuthor.secUserId) {
  1644. onError('未能从抖音号解析出 sec_user_id,暂时无法加载主页作品');
  1645. return;
  1646. }
  1647. this.douyinService.getUserProfileBySecUserId(basicAuthor.secUserId).subscribe({
  1648. next: (detailRes: any) => {
  1649. const detailProfile = this.douyinService.extractUserProfileData(detailRes) || {};
  1650. const author = this.mapMonitorAuthor({
  1651. ...basicProfile,
  1652. ...detailProfile,
  1653. sec_uid: detailProfile?.sec_uid || detailProfile?.sec_user_id || basicProfile?.sec_uid || basicProfile?.sec_user_id || basicAuthor.secUserId,
  1654. sec_user_id: detailProfile?.sec_user_id || detailProfile?.sec_uid || basicProfile?.sec_user_id || basicProfile?.sec_uid || basicAuthor.secUserId,
  1655. unique_id: detailProfile?.unique_id || basicProfile?.unique_id || uniqueId,
  1656. short_id: detailProfile?.short_id || basicProfile?.short_id || '',
  1657. douyin_id: detailProfile?.douyin_id || basicProfile?.douyin_id || ''
  1658. }, uniqueId);
  1659. onSuccess(author, false);
  1660. },
  1661. error: () => {
  1662. onSuccess(basicAuthor, true);
  1663. }
  1664. });
  1665. },
  1666. error: (error: any) => {
  1667. onError(this.getErrorText(error, '获取博主信息失败,请稍后重试'));
  1668. }
  1669. });
  1670. }
  1671. private refreshIncompleteMonitorAuthors(): void {
  1672. this.monitorAuthors
  1673. .filter(author => author.followerCount === 0)
  1674. .forEach(author => this.refreshMonitorAuthorProfile(author, true));
  1675. }
  1676. private refreshMonitorAuthorProfile(author: MonitorAuthor, silent: boolean): void {
  1677. const lookupId = (author.uniqueId || author.shortId || author.uid || '').trim();
  1678. if (!lookupId) {
  1679. return;
  1680. }
  1681. this.buildCompleteMonitorAuthor(lookupId, (nextAuthor, usedFallback) => {
  1682. const mergedAuthor: MonitorAuthor = {
  1683. ...author,
  1684. ...nextAuthor,
  1685. works: author.works,
  1686. worksCursor: author.worksCursor,
  1687. hasMoreWorks: author.hasMoreWorks,
  1688. loadingWorks: author.loadingWorks,
  1689. coverUrl: author.coverUrl || nextAuthor.coverUrl
  1690. };
  1691. this.monitorAuthors = this.monitorAuthors.map(item => (
  1692. item.id === author.id
  1693. || item.uid === author.uid
  1694. || (!!author.secUserId && item.secUserId === author.secUserId)
  1695. || (!!lookupId && (item.uniqueId === lookupId || item.shortId === lookupId || item.uid === lookupId))
  1696. ? mergedAuthor
  1697. : item
  1698. ));
  1699. if (this.selectedMonitorAuthorId === author.id) {
  1700. this.selectedMonitorAuthorId = mergedAuthor.id;
  1701. }
  1702. this.persistMonitorState();
  1703. if (!silent) {
  1704. this.showToast(
  1705. usedFallback
  1706. ? `⚠️ 博主「${mergedAuthor.nickname}」资料已刷新,但完整粉丝数据暂未取到`
  1707. : `✅ 博主「${mergedAuthor.nickname}」资料已刷新`,
  1708. usedFallback ? 'warn' : 'success'
  1709. );
  1710. }
  1711. this.refreshView();
  1712. }, (message) => {
  1713. if (!silent) {
  1714. this.showToast(`❌ ${message}`, 'error');
  1715. }
  1716. });
  1717. }
  1718. openMonitorAuthor(author: MonitorAuthor): void {
  1719. this.selectedMonitorAuthorId = author.id;
  1720. this.persistMonitorState();
  1721. if (author.followerCount === 0) {
  1722. this.refreshMonitorAuthorProfile(author, true);
  1723. }
  1724. if (!author.loadingWorks && author.works.length === 0) {
  1725. this.fetchMonitorAuthorWorks(author, false);
  1726. }
  1727. this.refreshView();
  1728. }
  1729. backToMonitorList(): void {
  1730. this.selectedMonitorAuthorId = '';
  1731. this.persistMonitorState();
  1732. this.refreshView();
  1733. }
  1734. removeMonitorAuthor(author: MonitorAuthor): void {
  1735. if (!confirm(`确定要删除博主「${author.nickname}」吗?`)) {
  1736. return;
  1737. }
  1738. this.monitorAuthors = this.monitorAuthors.filter(item => item.id !== author.id);
  1739. if (this.selectedMonitorAuthorId === author.id) {
  1740. this.selectedMonitorAuthorId = '';
  1741. }
  1742. this.persistMonitorState();
  1743. this.showToast(`🗑️ 已移除博主「${author.nickname}」`, 'success');
  1744. this.refreshView();
  1745. }
  1746. getSelectedMonitorAuthor(): MonitorAuthor | null {
  1747. return this.monitorAuthors.find(author => author.id === this.selectedMonitorAuthorId) || null;
  1748. }
  1749. getTotalMonitorWorksCount(): number {
  1750. return this.monitorAuthors.reduce((total, author) => total + author.works.length, 0);
  1751. }
  1752. reloadMonitorAuthorWorks(author: MonitorAuthor): void {
  1753. this.fetchMonitorAuthorWorks(author, false);
  1754. }
  1755. loadMoreMonitorWorks(author: MonitorAuthor): void {
  1756. if (!author.hasMoreWorks || author.loadingWorks) {
  1757. return;
  1758. }
  1759. this.fetchMonitorAuthorWorks(author, true);
  1760. }
  1761. handleMonitorAuthorAvatarError(author: MonitorAuthor): void {
  1762. const currentIndex = author.avatarCandidates.indexOf(author.avatarUrl);
  1763. const nextIndex = currentIndex >= 0 ? currentIndex + 1 : 0;
  1764. author.avatarUrl = author.avatarCandidates[nextIndex] || this.getMonitorAvatarFallback(author.nickname);
  1765. this.refreshView();
  1766. }
  1767. handleMonitorWorkCoverError(work: MonitorWork): void {
  1768. const currentIndex = work.coverCandidates.indexOf(work.coverUrl);
  1769. const nextIndex = currentIndex >= 0 ? currentIndex + 1 : 0;
  1770. work.coverUrl = work.coverCandidates[nextIndex] || this.getVideoCoverFallback();
  1771. this.refreshView();
  1772. }
  1773. previewMonitorWork(author: MonitorAuthor, work: MonitorWork): void {
  1774. if (work.type !== 'video') {
  1775. window.open(work.coverUrl, '_blank');
  1776. return;
  1777. }
  1778. this.viewVideoDetail(this.buildMonitorVideoInfo(author, work));
  1779. }
  1780. downloadMonitorWork(author: MonitorAuthor, work: MonitorWork): void {
  1781. if (work.type !== 'video' || work.isDownloading) return;
  1782. work.isDownloading = true;
  1783. work.downloadProgress = 0;
  1784. const video = this.buildMonitorVideoInfo(author, work);
  1785. this.douyinService.getVideoDetail(work.id).subscribe({
  1786. next: (res: any) => {
  1787. const detailData = this.douyinService.extractVideoDetailData(res) || {};
  1788. const downloadUrls = this.douyinService.extractVideoDownloadUrls(res);
  1789. const downloadUrl = downloadUrls[0] || '';
  1790. if (!downloadUrl) {
  1791. work.isDownloading = false;
  1792. work.downloadProgress = 0;
  1793. this.showToast('❌ 无法获取下载地址,请稍后重试', 'error');
  1794. this.refreshView();
  1795. return;
  1796. }
  1797. const filename = this.buildVideoFilename(video);
  1798. this.douyinService.startManagedDownload({
  1799. url: downloadUrl,
  1800. urls: downloadUrls,
  1801. filename,
  1802. title: work.desc || work.id,
  1803. description: detailData?.desc || work.desc || '',
  1804. tags: [],
  1805. thumbnail: work.coverUrl || '',
  1806. duration: work.duration || 0,
  1807. resolution: detailData?.video?.ratio || '',
  1808. awemeId: work.id,
  1809. authorName: author.nickname || ''
  1810. }).subscribe({
  1811. next: (taskRes: any) => {
  1812. if (!taskRes?.taskId) {
  1813. work.isDownloading = false;
  1814. work.downloadProgress = 0;
  1815. this.showToast('❌ 下载任务创建失败,请稍后重试', 'error');
  1816. return;
  1817. }
  1818. this.showToast(`📥 正在下载「${work.desc || work.id}」到视频库`, 'info');
  1819. this.pollMonitorWorkDownload(work, taskRes.taskId);
  1820. },
  1821. error: (error: any) => {
  1822. work.isDownloading = false;
  1823. work.downloadProgress = 0;
  1824. this.showToast(`❌ 创建下载任务失败:${error?.error?.error || error?.message || '请稍后重试'}`, 'error');
  1825. this.refreshView();
  1826. }
  1827. });
  1828. },
  1829. error: (error: any) => {
  1830. work.isDownloading = false;
  1831. work.downloadProgress = 0;
  1832. this.showToast(`❌ 获取视频信息失败:${error?.error?.error || error?.message || '请稍后重试'}`, 'error');
  1833. this.refreshView();
  1834. }
  1835. });
  1836. }
  1837. getMonitorHeroBackground(author: MonitorAuthor): string {
  1838. return author.coverUrl
  1839. ? `linear-gradient(90deg, rgba(11, 15, 25, 0.92), rgba(11, 15, 25, 0.55)), url(${author.coverUrl})`
  1840. : 'linear-gradient(135deg, #161a27, #232a3d)';
  1841. }
  1842. // 搜索视频
  1843. searchVideos(): void {
  1844. if (!this.searchKeyword.trim()) return;
  1845. this.isSearching = true;
  1846. this.searchCursor = 0;
  1847. this.searchId = '';
  1848. this.searchBacktrace = '';
  1849. this.searchResults = [];
  1850. this.filteredSearchResults = [];
  1851. this.douyinService.searchVideos(this.searchKeyword, '0', 0, '0', '0', '1')
  1852. .subscribe({
  1853. next: (res: any) => {
  1854. this.isSearching = false;
  1855. const parsed = this.parseSearchResponse(res);
  1856. this.searchResults = parsed.items
  1857. .map((item: any) => this.mapVideoItem(item))
  1858. .filter((item: VideoInfo) => !!item.aweme_id || !!item.desc || !!item.cover_url);
  1859. this.applySearchFilters();
  1860. this.hasMore = parsed.hasMore;
  1861. this.searchCursor = parsed.cursor;
  1862. this.searchId = parsed.searchId;
  1863. this.searchBacktrace = parsed.backtrace;
  1864. console.log('🔍 搜索结果解析:', { raw: res, parsed, mapped: this.searchResults });
  1865. this.refreshView();
  1866. if (this.filteredSearchResults.length === 0) {
  1867. alert('未找到相关视频,请尝试其他关键词');
  1868. }
  1869. },
  1870. error: (error: any) => {
  1871. console.error('搜索失败:', error);
  1872. this.isSearching = false;
  1873. let errorMessage = '搜索失败,请稍后重试';
  1874. if (error.status === 401) {
  1875. errorMessage = '认证失败,Token可能已失效';
  1876. } else if (error.status === 429) {
  1877. errorMessage = '请求过于频繁,请稍后重试';
  1878. } else if (error.status === 0) {
  1879. errorMessage = '网络连接失败,请检查网络设置';
  1880. }
  1881. alert(errorMessage);
  1882. }
  1883. });
  1884. }
  1885. // 映射API返回的视频数据
  1886. private mapVideoItem(item: any): VideoInfo {
  1887. const info = item?.aweme_info || item?.data?.aweme_info || item?.data?.challenge_info || item;
  1888. const coverCandidates = this.buildCoverCandidates(info);
  1889. const coverUrl = coverCandidates[0] || this.getVideoCoverFallback();
  1890. const duration = Math.floor((info.video?.duration || info.duration || 0) / ((info.video?.duration || info.duration || 0) > 1000 ? 1000 : 1));
  1891. const tags = Array.isArray(info.text_extra)
  1892. ? info.text_extra
  1893. .map((tag: any) => tag?.hashtag_name || tag?.cha_name || tag?.tag_name || tag?.hash_tag_name || tag)
  1894. .filter((tag: any) => typeof tag === 'string' && tag.trim())
  1895. : Array.isArray(info.cha_list)
  1896. ? info.cha_list
  1897. .map((tag: any) => tag?.cha_name || tag?.hashtag_name || tag?.tag_name || tag)
  1898. .filter((tag: any) => typeof tag === 'string' && tag.trim())
  1899. : (info.desc ? [info.desc] : []);
  1900. return {
  1901. aweme_id: info.aweme_id || info.group_id || info.cid || item.data_id || '',
  1902. desc: info.desc || info.cha_name || info.title || info.content || '',
  1903. cover_url: coverUrl,
  1904. cover_candidates: coverCandidates,
  1905. duration: duration,
  1906. create_time: info.create_time || item.create_time || 0,
  1907. publishDate: (info.create_time || item.create_time) ? new Date((info.create_time || item.create_time) * 1000) : null,
  1908. author: {
  1909. nickname: info.author?.nickname || info.nickname || '未知作者',
  1910. sec_uid: info.author?.sec_uid || info.author?.uid || ''
  1911. },
  1912. statistics: {
  1913. play_count: info.statistics?.play_count || info.view_count || 0,
  1914. digg_count: info.statistics?.digg_count || info.user_count || 0,
  1915. comment_count: info.statistics?.comment_count || 0,
  1916. share_count: info.statistics?.share_count || 0
  1917. },
  1918. text_extra: tags
  1919. };
  1920. }
  1921. private buildCoverCandidates(info: any): string[] {
  1922. const candidates = [
  1923. info.video?.origin_cover?.url_list?.[0],
  1924. info.video?.cover?.url_list?.[0],
  1925. info.video?.dynamic_cover?.url_list?.[0],
  1926. info.video?.animated_cover?.url_list?.[0],
  1927. info.author?.avatar_larger?.url_list?.[0],
  1928. info.author?.avatar_medium?.url_list?.[0],
  1929. info.author?.avatar_thumb?.url_list?.[0],
  1930. info.hashtag_profile,
  1931. info.cover_url
  1932. ];
  1933. return candidates.filter((url, index, list) => typeof url === 'string' && url.trim() && list.indexOf(url) === index);
  1934. }
  1935. handleVideoCoverError(video: VideoInfo): void {
  1936. const candidates = video.cover_candidates || [];
  1937. const currentIndex = candidates.indexOf(video.cover_url);
  1938. const nextIndex = currentIndex >= 0 ? currentIndex + 1 : 0;
  1939. const nextCover = candidates[nextIndex];
  1940. if (nextCover) {
  1941. video.cover_url = nextCover;
  1942. } else {
  1943. video.cover_url = this.getVideoCoverFallback();
  1944. }
  1945. this.refreshView();
  1946. }
  1947. private getVideoCoverFallback(): string {
  1948. return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="480" height="270" viewBox="0 0 480 270"><rect width="480" height="270" fill="#f3f4f6"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="#9ca3af" font-size="20">封面加载失败</text></svg>');
  1949. }
  1950. private parseSearchResponse(res: any): { items: any[]; hasMore: boolean; cursor: number; searchId: string; backtrace: string } {
  1951. const normalizedResponse = this.parseJsonPayload(res);
  1952. const normalizedData = this.parseJsonPayload(normalizedResponse?.data);
  1953. const nestedData = this.parseJsonPayload(normalizedData?.data);
  1954. const businessConfig = this.parseJsonPayload(normalizedData?.business_config) || {};
  1955. const nextPage = this.parseJsonPayload(businessConfig?.next_page) || {};
  1956. const directData = Array.isArray(normalizedData) ? normalizedData : [];
  1957. const nestedArray = Array.isArray(nestedData) ? nestedData : [];
  1958. const businessData = Array.isArray(normalizedData?.business_data) ? normalizedData.business_data : [];
  1959. const items = directData.length > 0 ? directData : (nestedArray.length > 0 ? nestedArray : businessData);
  1960. const hasMore =
  1961. normalizedResponse?.has_more === 1 ||
  1962. normalizedData?.has_more === 1 ||
  1963. businessConfig?.has_more === 1 ||
  1964. false;
  1965. const cursor =
  1966. normalizedResponse?.cursor ??
  1967. normalizedData?.cursor ??
  1968. nextPage?.cursor ??
  1969. items.length;
  1970. const searchId =
  1971. normalizedResponse?.search_id ||
  1972. normalizedData?.search_id ||
  1973. nextPage?.search_id ||
  1974. nextPage?.search_request_id ||
  1975. '';
  1976. const backtrace =
  1977. normalizedResponse?.backtrace ||
  1978. normalizedData?.backtrace ||
  1979. nextPage?.backtrace ||
  1980. '';
  1981. return {
  1982. items,
  1983. hasMore,
  1984. cursor: typeof cursor === 'number' ? cursor : Number(cursor || items.length),
  1985. searchId,
  1986. backtrace
  1987. };
  1988. }
  1989. private parseJsonPayload(value: any): any {
  1990. let current = value;
  1991. while (typeof current === 'string') {
  1992. const trimmed = current.trim();
  1993. if (!trimmed || (!trimmed.startsWith('{') && !trimmed.startsWith('['))) {
  1994. break;
  1995. }
  1996. try {
  1997. current = JSON.parse(trimmed);
  1998. } catch {
  1999. break;
  2000. }
  2001. }
  2002. return current;
  2003. }
  2004. private normalizeMonitorLabelText(value: any): string {
  2005. const normalized = this.parseJsonPayload(value);
  2006. if (typeof normalized === 'string') {
  2007. const trimmed = normalized.trim();
  2008. if (!trimmed) {
  2009. return '';
  2010. }
  2011. const labelTextMatch = trimmed.match(/"label_text"\s*:\s*"([^"]+)"/);
  2012. if (labelTextMatch?.[1]) {
  2013. return labelTextMatch[1].trim();
  2014. }
  2015. return trimmed;
  2016. }
  2017. if (Array.isArray(normalized)) {
  2018. return normalized
  2019. .map(item => this.normalizeMonitorLabelText(item))
  2020. .find(item => !!item) || '';
  2021. }
  2022. if (normalized && typeof normalized === 'object') {
  2023. const candidateKeys = ['label_text', 'text', 'name', 'title', 'desc'];
  2024. for (const key of candidateKeys) {
  2025. const text = this.normalizeMonitorLabelText(normalized[key]);
  2026. if (text) {
  2027. return text;
  2028. }
  2029. }
  2030. }
  2031. return '';
  2032. }
  2033. getMonitorIpLocationText(author: MonitorAuthor | null | undefined): string {
  2034. const location = this.normalizeMonitorIpLocation(author?.ipLocation);
  2035. return location ? `IP 属地:${location}` : 'IP 属地未抓取';
  2036. }
  2037. private normalizeMonitorIpLocation(value: any): string {
  2038. const normalized = this.normalizeMonitorLabelText(value);
  2039. if (!normalized) {
  2040. return '';
  2041. }
  2042. return normalized.replace(/^IP\s*属地\s*[::]?\s*/i, '').trim();
  2043. }
  2044. private pickMonitorCountValue(values: any[]): number {
  2045. for (const value of values) {
  2046. const parsed = this.parseMonitorCountValue(value);
  2047. if (parsed !== null) {
  2048. return parsed;
  2049. }
  2050. }
  2051. return 0;
  2052. }
  2053. private parseMonitorCountValue(value: any): number | null {
  2054. const normalized = this.parseJsonPayload(value);
  2055. if (typeof normalized === 'number') {
  2056. return Number.isFinite(normalized) ? normalized : null;
  2057. }
  2058. if (typeof normalized === 'string') {
  2059. const trimmed = normalized.trim();
  2060. if (!trimmed) {
  2061. return null;
  2062. }
  2063. const compact = trimmed.replace(/,/g, '').replace(/\s+/g, '');
  2064. const unitMatch = compact.match(/^([\d.]+)(亿|万|[kKmMwW])$/);
  2065. if (unitMatch) {
  2066. const base = Number(unitMatch[1]);
  2067. if (!Number.isFinite(base)) {
  2068. return null;
  2069. }
  2070. const unit = unitMatch[2].toLowerCase();
  2071. const multiplier = unit === '亿'
  2072. ? 100000000
  2073. : (unit === '万' || unit === 'w')
  2074. ? 10000
  2075. : unit === 'm'
  2076. ? 1000000
  2077. : 1000;
  2078. return Math.round(base * multiplier);
  2079. }
  2080. const directNumber = Number(compact);
  2081. return Number.isFinite(directNumber) ? directNumber : null;
  2082. }
  2083. if (normalized && typeof normalized === 'object') {
  2084. const candidateKeys = ['count', 'value', 'total', 'num'];
  2085. for (const key of candidateKeys) {
  2086. const parsed = this.parseMonitorCountValue(normalized[key]);
  2087. if (parsed !== null) {
  2088. return parsed;
  2089. }
  2090. }
  2091. }
  2092. return null;
  2093. }
  2094. onSearchFilterChange(): void {
  2095. this.applySearchFilters();
  2096. this.refreshView();
  2097. }
  2098. private applySearchFilters(): void {
  2099. let items = [...this.searchResults];
  2100. if (this.publishTime !== '0') {
  2101. const nowSeconds = Math.floor(Date.now() / 1000);
  2102. const limitSeconds = Number(this.publishTime) * 24 * 60 * 60;
  2103. items = items.filter((video) => !video.create_time || (nowSeconds - video.create_time) <= limitSeconds);
  2104. }
  2105. if (this.filterDuration !== '0') {
  2106. const [minMinutes, maxMinutes] = this.filterDuration.split('-').map(value => Number(value || 0));
  2107. items = items.filter((video) => {
  2108. const durationMinutes = (video.duration || 0) / 60;
  2109. return durationMinutes >= minMinutes && durationMinutes <= maxMinutes;
  2110. });
  2111. }
  2112. if (this.sortType === '1') {
  2113. items.sort((a, b) => (b.statistics?.digg_count || 0) - (a.statistics?.digg_count || 0));
  2114. } else if (this.sortType === '2') {
  2115. items.sort((a, b) => (b.create_time || 0) - (a.create_time || 0));
  2116. }
  2117. this.filteredSearchResults = items;
  2118. }
  2119. private fetchMonitorAuthorWorks(author: MonitorAuthor, append: boolean): void {
  2120. if (!author.secUserId || author.loadingWorks) {
  2121. return;
  2122. }
  2123. author.loadingWorks = true;
  2124. const cursor = append ? author.worksCursor : '0';
  2125. this.refreshView();
  2126. this.douyinService.getUserPostVideos(author.secUserId, cursor).subscribe({
  2127. next: (res: any) => {
  2128. const parsed = this.douyinService.extractUserPostVideos(res);
  2129. const mappedWorks = parsed.items
  2130. .map((item: any) => this.mapMonitorWork(item))
  2131. .filter((item: MonitorWork) => !!item.id || !!item.desc || !!item.coverUrl);
  2132. author.works = append
  2133. ? [...author.works, ...mappedWorks.filter(item => !author.works.some(existing => existing.id === item.id))]
  2134. : mappedWorks;
  2135. author.worksCursor = parsed.cursor;
  2136. author.hasMoreWorks = parsed.hasMore;
  2137. author.loadingWorks = false;
  2138. author.coverUrl = author.coverUrl || author.works[0]?.coverUrl || author.avatarUrl;
  2139. this.persistMonitorState();
  2140. this.refreshView();
  2141. },
  2142. error: (error: any) => {
  2143. author.loadingWorks = false;
  2144. this.showToast(`❌ ${this.getErrorText(error, '加载博主作品失败,请稍后重试')}`, 'error');
  2145. this.refreshView();
  2146. }
  2147. });
  2148. }
  2149. private mapMonitorAuthor(profile: any, uid: string): MonitorAuthor {
  2150. const avatarCandidates = this.pickUniqueStringValues([
  2151. profile?.avatar_larger?.url_list,
  2152. profile?.avatar_medium?.url_list,
  2153. profile?.avatar_thumb?.url_list,
  2154. profile?.avatar_168x168?.url_list,
  2155. profile?.avatar_url
  2156. ]);
  2157. const coverCandidates = this.pickUniqueStringValues([
  2158. profile?.cover_url,
  2159. profile?.cover_urls,
  2160. profile?.cover_thumb?.url_list,
  2161. profile?.video_cover?.url_list,
  2162. avatarCandidates
  2163. ]);
  2164. const nickname = profile?.nickname || profile?.display_name || `UID ${uid}`;
  2165. const verifiedText = [
  2166. profile?.custom_verify,
  2167. profile?.enterprise_verify_reason,
  2168. profile?.account_cert_info,
  2169. profile?.verification_info
  2170. ].map((item: any) => this.normalizeMonitorLabelText(item)).find((item: string) => !!item) || '';
  2171. const ipLocation = this.normalizeMonitorIpLocation(
  2172. [
  2173. profile?.ip_location,
  2174. profile?.ip_label,
  2175. profile?.ipLocation,
  2176. profile?.ip_info?.location,
  2177. profile?.ip_info?.ip_location,
  2178. profile?.ip_region,
  2179. profile?.location
  2180. ].find((item: any) => !!this.normalizeMonitorLabelText(item)) || ''
  2181. );
  2182. const followerCount = this.pickMonitorCountValue([
  2183. profile?.follower_count,
  2184. profile?.followerCount,
  2185. profile?.fans_count,
  2186. profile?.fansCount,
  2187. profile?.public_fans_count,
  2188. profile?.statistics?.follower_count,
  2189. profile?.statistics?.fans_count,
  2190. profile?.author_stats?.follower_count,
  2191. profile?.author_stats?.fans_count,
  2192. profile?.user_stats?.follower_count,
  2193. profile?.user_stats?.fans_count,
  2194. profile?.user_statistics?.follower_count,
  2195. profile?.user_statistics?.fans_count,
  2196. profile?.stats?.follower_count,
  2197. profile?.stats?.fans_count
  2198. ]);
  2199. const followingCount = this.pickMonitorCountValue([
  2200. profile?.following_count,
  2201. profile?.followingCount,
  2202. profile?.statistics?.following_count,
  2203. profile?.author_stats?.following_count,
  2204. profile?.user_stats?.following_count,
  2205. profile?.user_statistics?.following_count,
  2206. profile?.stats?.following_count
  2207. ]);
  2208. const totalFavorited = this.pickMonitorCountValue([
  2209. profile?.total_favorited,
  2210. profile?.favoriting_count,
  2211. profile?.totalFavorited,
  2212. profile?.liked_count,
  2213. profile?.statistics?.total_favorited,
  2214. profile?.statistics?.favoriting_count,
  2215. profile?.author_stats?.total_favorited,
  2216. profile?.user_stats?.total_favorited,
  2217. profile?.user_statistics?.total_favorited,
  2218. profile?.stats?.total_favorited
  2219. ]);
  2220. const awemeCount = this.pickMonitorCountValue([
  2221. profile?.aweme_count,
  2222. profile?.video_count,
  2223. profile?.awemeCount,
  2224. profile?.statistics?.aweme_count,
  2225. profile?.statistics?.video_count,
  2226. profile?.author_stats?.aweme_count,
  2227. profile?.user_stats?.aweme_count,
  2228. profile?.user_statistics?.aweme_count,
  2229. profile?.stats?.aweme_count
  2230. ]);
  2231. return {
  2232. id: String(profile?.uid || uid),
  2233. uid: String(uid),
  2234. secUserId: String(profile?.sec_uid || profile?.sec_user_id || profile?.secUid || ''),
  2235. nickname,
  2236. uniqueId: String(profile?.unique_id || profile?.short_id || profile?.douyin_id || ''),
  2237. shortId: String(profile?.short_id || profile?.douyin_id || ''),
  2238. signature: profile?.signature || profile?.bio_description || '',
  2239. ipLocation,
  2240. verifiedText,
  2241. avatarUrl: avatarCandidates[0] || this.getMonitorAvatarFallback(nickname),
  2242. avatarCandidates,
  2243. coverUrl: coverCandidates[0] || '',
  2244. coverCandidates,
  2245. followerCount,
  2246. followingCount,
  2247. totalFavorited,
  2248. awemeCount,
  2249. works: [],
  2250. worksCursor: '0',
  2251. hasMoreWorks: false,
  2252. loadingWorks: false
  2253. };
  2254. }
  2255. private mapMonitorWork(item: any): MonitorWork {
  2256. const coverCandidates = this.pickUniqueStringValues([
  2257. item?.video?.origin_cover?.url_list,
  2258. item?.video?.cover?.url_list,
  2259. item?.video?.dynamic_cover?.url_list,
  2260. item?.cover?.url_list,
  2261. item?.images?.map((image: any) => image?.url_list?.[0] || image?.download_url_list?.[0]),
  2262. item?.image_infos?.map((image: any) => image?.label_large?.url_list?.[0] || image?.label_thumb?.url_list?.[0]),
  2263. item?.cover_url
  2264. ]);
  2265. const rawDuration = Number(item?.video?.duration || item?.duration || 0);
  2266. const createTimestamp = Number(item?.create_time || 0);
  2267. const statistics = item?.statistics || item?.statis || {};
  2268. const hasImageGroup = (Array.isArray(item?.images) && item.images.length > 0) || (Array.isArray(item?.image_infos) && item.image_infos.length > 0);
  2269. return {
  2270. id: String(item?.aweme_id || item?.group_id || item?.item_id || `${Date.now()}-${Math.random()}`),
  2271. desc: item?.desc || item?.title || '未命名作品',
  2272. coverUrl: coverCandidates[0] || this.getVideoCoverFallback(),
  2273. coverCandidates,
  2274. duration: Math.floor(rawDuration / (rawDuration > 1000 ? 1000 : 1)),
  2275. createTime: createTimestamp ? new Date(createTimestamp > 1000000000000 ? createTimestamp : createTimestamp * 1000) : undefined,
  2276. type: hasImageGroup ? 'image' : 'video',
  2277. statistics: {
  2278. play_count: Number(statistics?.play_count || statistics?.playCount || 0),
  2279. digg_count: Number(statistics?.digg_count || 0),
  2280. comment_count: Number(statistics?.comment_count || 0),
  2281. share_count: Number(statistics?.share_count || 0)
  2282. }
  2283. };
  2284. }
  2285. private pickUniqueStringValues(values: any[]): string[] {
  2286. const uniqueValues: string[] = [];
  2287. const collect = (value: any) => {
  2288. if (Array.isArray(value)) {
  2289. value.forEach(collect);
  2290. return;
  2291. }
  2292. if (typeof value === 'string' && value.trim() && !uniqueValues.includes(value)) {
  2293. uniqueValues.push(value);
  2294. }
  2295. };
  2296. values.forEach(collect);
  2297. return uniqueValues;
  2298. }
  2299. private getMonitorAvatarFallback(name: string): string {
  2300. const label = (name || '博主').trim().slice(0, 2) || '博主';
  2301. return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="160" height="160" viewBox="0 0 160 160"><rect width="160" height="160" rx="80" fill="#ff0050"/><text x="50%" y="54%" text-anchor="middle" dominant-baseline="middle" fill="#ffffff" font-size="48" font-family="Arial, sans-serif">${label}</text></svg>`);
  2302. }
  2303. private getErrorText(error: any, fallback: string): string {
  2304. const candidates = [
  2305. error?.error?.error,
  2306. error?.error?.message,
  2307. error?.error?.msg,
  2308. error?.error,
  2309. error?.message,
  2310. error,
  2311. ];
  2312. for (const candidate of candidates) {
  2313. const text = this.normalizeErrorText(candidate);
  2314. if (text) return text;
  2315. }
  2316. return fallback;
  2317. }
  2318. private normalizeErrorText(value: any, seen = new Set<any>()): string {
  2319. if (value == null) return '';
  2320. if (typeof value === 'string') return value.trim();
  2321. if (typeof value === 'number' || typeof value === 'boolean') return String(value);
  2322. if (value instanceof Blob) return '';
  2323. if (typeof value !== 'object') return '';
  2324. if (seen.has(value)) return '';
  2325. seen.add(value);
  2326. const nestedKeys = ['message', 'msg', 'error', 'detail', 'reason'];
  2327. for (const key of nestedKeys) {
  2328. const nested = this.normalizeErrorText(value?.[key], seen);
  2329. if (nested) return nested;
  2330. }
  2331. try {
  2332. const serialized = JSON.stringify(value);
  2333. return serialized && serialized !== '{}' ? serialized : '';
  2334. } catch {
  2335. return '';
  2336. }
  2337. }
  2338. private getOfficialTtsResourceId(voiceId: string): string {
  2339. return voiceId.includes('_uranus_bigtts') ? 'seed-tts-2.0' : 'seed-tts-1.0';
  2340. }
  2341. private applyVoiceSelectionToTtsPayload(
  2342. payload: any,
  2343. mode: 'system' | 'clone',
  2344. systemVoiceId: string,
  2345. timbreId: string,
  2346. ): void {
  2347. if (mode === 'clone' && timbreId.trim()) {
  2348. payload.timbreId = timbreId.trim();
  2349. return;
  2350. }
  2351. const voiceId = systemVoiceId.trim() || 'zh_female_shuangkuai-am_16k';
  2352. payload.volcengine_voice_type = voiceId;
  2353. payload.x_api_resource_id = this.getOfficialTtsResourceId(voiceId);
  2354. }
  2355. private async extractHttpBlobErrorMessage(error: any, fallback: string): Promise<string> {
  2356. if (error instanceof HttpErrorResponse && error.error instanceof Blob) {
  2357. try {
  2358. const text = await error.error.text();
  2359. if (text) {
  2360. const parsed = JSON.parse(text);
  2361. return parsed?.error || parsed?.message || fallback;
  2362. }
  2363. } catch {
  2364. return fallback;
  2365. }
  2366. }
  2367. return error?.error?.error || error?.error?.message || error?.message || fallback;
  2368. }
  2369. private serializeMonitorAuthor(author: MonitorAuthor): any {
  2370. return {
  2371. ...author,
  2372. loadingWorks: false,
  2373. works: author.works.map(work => ({
  2374. ...work,
  2375. createTime: work.createTime ? work.createTime.toISOString() : null,
  2376. isDownloading: false,
  2377. downloadProgress: 0
  2378. }))
  2379. };
  2380. }
  2381. private deserializeMonitorAuthor(author: any): MonitorAuthor {
  2382. return {
  2383. id: String(author?.id || ''),
  2384. uid: String(author?.uid || ''),
  2385. secUserId: String(author?.secUserId || ''),
  2386. nickname: String(author?.nickname || ''),
  2387. uniqueId: String(author?.uniqueId || ''),
  2388. shortId: String(author?.shortId || ''),
  2389. signature: String(author?.signature || ''),
  2390. ipLocation: String(author?.ipLocation || ''),
  2391. verifiedText: this.normalizeMonitorLabelText(author?.verifiedText),
  2392. avatarUrl: String(author?.avatarUrl || this.getMonitorAvatarFallback(author?.nickname || '博主')),
  2393. avatarCandidates: Array.isArray(author?.avatarCandidates) ? author.avatarCandidates : [],
  2394. coverUrl: String(author?.coverUrl || ''),
  2395. coverCandidates: Array.isArray(author?.coverCandidates) ? author.coverCandidates : [],
  2396. followerCount: Number(author?.followerCount || 0),
  2397. followingCount: Number(author?.followingCount || 0),
  2398. totalFavorited: Number(author?.totalFavorited || 0),
  2399. awemeCount: Number(author?.awemeCount || 0),
  2400. works: Array.isArray(author?.works)
  2401. ? author.works.map((work: any) => ({
  2402. id: String(work?.id || ''),
  2403. desc: String(work?.desc || ''),
  2404. coverUrl: String(work?.coverUrl || this.getVideoCoverFallback()),
  2405. coverCandidates: Array.isArray(work?.coverCandidates) ? work.coverCandidates : [],
  2406. duration: Number(work?.duration || 0),
  2407. createTime: work?.createTime ? new Date(work.createTime) : undefined,
  2408. type: work?.type === 'image' ? 'image' : 'video',
  2409. statistics: {
  2410. play_count: Number(work?.statistics?.play_count || 0),
  2411. digg_count: Number(work?.statistics?.digg_count || 0),
  2412. comment_count: Number(work?.statistics?.comment_count || 0),
  2413. share_count: Number(work?.statistics?.share_count || 0)
  2414. },
  2415. isDownloading: false,
  2416. downloadProgress: 0
  2417. }))
  2418. : [],
  2419. worksCursor: String(author?.worksCursor || '0'),
  2420. hasMoreWorks: !!author?.hasMoreWorks,
  2421. loadingWorks: false
  2422. };
  2423. }
  2424. // 加载更多搜索结果
  2425. loadMore(): void {
  2426. if (!this.hasMore || this.isSearching) return;
  2427. this.isSearching = true;
  2428. this.douyinService.searchVideos(
  2429. this.searchKeyword, '0', this.searchCursor, '0',
  2430. '0', '1', this.searchId, this.searchBacktrace
  2431. ).subscribe({
  2432. next: (res: any) => {
  2433. this.isSearching = false;
  2434. const parsed = this.parseSearchResponse(res);
  2435. const newItems = parsed.items
  2436. .map((item: any) => this.mapVideoItem(item))
  2437. .filter((item: VideoInfo) => !!item.aweme_id || !!item.desc || !!item.cover_url);
  2438. this.searchResults.push(...newItems);
  2439. this.applySearchFilters();
  2440. this.hasMore = parsed.hasMore;
  2441. this.searchCursor = parsed.cursor;
  2442. this.searchId = parsed.searchId || this.searchId;
  2443. this.searchBacktrace = parsed.backtrace || this.searchBacktrace;
  2444. this.refreshView();
  2445. },
  2446. error: (error: any) => {
  2447. console.error('加载更多失败:', error);
  2448. this.isSearching = false;
  2449. let errorMessage = '加载更多失败,请稍后重试';
  2450. if (error.status === 401) {
  2451. errorMessage = '认证失败,Token可能已失效';
  2452. } else if (error.status === 429) {
  2453. errorMessage = '请求过于频繁,请稍后重试';
  2454. } else if (error.status === 0) {
  2455. errorMessage = '网络连接失败,请检查网络设置';
  2456. }
  2457. alert(errorMessage);
  2458. }
  2459. });
  2460. }
  2461. // 查看视频详情
  2462. viewVideoDetail(video: VideoInfo): void {
  2463. this.openSearchVideoPreview(video, null, '', true);
  2464. this.douyinService.getVideoDetail(video.aweme_id).subscribe({
  2465. next: (res: any) => {
  2466. const detailData = this.douyinService.extractVideoDetailData(res) || {};
  2467. this.openSearchVideoPreview(video, detailData, this.douyinService.extractVideoPreviewUrl(res) || '', false);
  2468. },
  2469. error: (error: any) => {
  2470. console.error('获取视频详情失败:', error);
  2471. this.openSearchVideoPreview(video, null, '', false);
  2472. this.showToast('⚠️ 获取实时详情失败,已展示基础信息', 'warn');
  2473. }
  2474. });
  2475. }
  2476. private openSearchVideoPreview(video: VideoInfo, detailData: any, previewUrl: string, loading: boolean = false): void {
  2477. const info = detailData || {};
  2478. const tags = this.extractVideoTags(info, video.text_extra || []);
  2479. const rawDuration = info.video?.duration || info.duration || video.duration || 0;
  2480. const duration = Math.floor(rawDuration / (rawDuration > 1000 ? 1000 : 1));
  2481. const coverCandidates = detailData ? this.buildCoverCandidates(info) : [];
  2482. const poster = coverCandidates[0] || video.cover_url || this.getVideoCoverFallback();
  2483. const createTime = info.create_time ? new Date(info.create_time * 1000) : undefined;
  2484. const filename = this.buildVideoFilename(video);
  2485. this.previewVideoUrl = previewUrl ? this.buildVideoProxyUrl(previewUrl, filename) : '';
  2486. this.previewDownloadUrl = '';
  2487. this.previewVideoTitle = info.desc || video.desc || video.aweme_id;
  2488. this.previewSourceVideo = video;
  2489. this.previewVideoInfo = {
  2490. duration: duration || video.duration || 0,
  2491. resolution: info.video?.ratio || '',
  2492. format: 'mp4',
  2493. source: 'douyin',
  2494. description: info.desc || video.desc || '',
  2495. tags,
  2496. created_at: createTime,
  2497. poster,
  2498. authorName: info.author?.nickname || video.author.nickname || '',
  2499. playCount: info.statistics?.play_count ?? video.statistics.play_count,
  2500. diggCount: info.statistics?.digg_count ?? video.statistics.digg_count,
  2501. commentCount: info.statistics?.comment_count ?? video.statistics.comment_count,
  2502. shareCount: info.statistics?.share_count ?? video.statistics.share_count,
  2503. loading
  2504. };
  2505. this.showPreviewModal = true;
  2506. this.refreshView();
  2507. }
  2508. private extractVideoTags(info: any, fallbackTags: string[] = []): string[] {
  2509. const textExtraTags = Array.isArray(info?.text_extra)
  2510. ? info.text_extra
  2511. .map((tag: any) => tag?.hashtag_name || tag?.cha_name || tag?.tag_name || tag?.hash_tag_name || tag)
  2512. .filter((tag: any) => typeof tag === 'string' && tag.trim())
  2513. : [];
  2514. const chaListTags = Array.isArray(info?.cha_list)
  2515. ? info.cha_list
  2516. .map((tag: any) => tag?.cha_name || tag?.hashtag_name || tag?.tag_name || tag)
  2517. .filter((tag: any) => typeof tag === 'string' && tag.trim())
  2518. : [];
  2519. return [...textExtraTags, ...chaListTags, ...fallbackTags].filter((tag, index, list) => !!tag && list.indexOf(tag) === index);
  2520. }
  2521. private buildVideoFilename(video: VideoInfo): string {
  2522. return `${video.author.nickname}_${video.desc || video.aweme_id}`
  2523. .replace(/[<>:"/\\|?*]/g, '_')
  2524. .substring(0, 60) + '.mp4';
  2525. }
  2526. private buildVideoProxyUrl(videoUrl: string, filename: string, download: boolean = false): string {
  2527. const params = new URLSearchParams({
  2528. url: videoUrl,
  2529. filename,
  2530. download: download ? '1' : '0'
  2531. });
  2532. return `/backend/api/video-proxy?${params.toString()}`;
  2533. }
  2534. // 下载抖音视频到本地
  2535. downloadVideo(video: VideoInfo): void {
  2536. if (video.isDownloading) return;
  2537. video.isDownloading = true;
  2538. video.downloadProgress = 0;
  2539. // 先获取视频详情拿到下载地址
  2540. this.douyinService.getVideoDetail(video.aweme_id).subscribe({
  2541. next: (res: any) => {
  2542. const detailData = this.douyinService.extractVideoDetailData(res) || {};
  2543. const downloadUrls = this.douyinService.extractVideoDownloadUrls(res);
  2544. const downloadUrl = downloadUrls[0] || '';
  2545. if (!downloadUrl) {
  2546. console.warn('未找到可用下载地址:', detailData);
  2547. video.isDownloading = false;
  2548. this.showToast('❌ 无法获取下载地址,请稍后重试', 'error');
  2549. return;
  2550. }
  2551. const filename = this.buildVideoFilename(video);
  2552. this.douyinService.startManagedDownload({
  2553. url: downloadUrl,
  2554. urls: downloadUrls,
  2555. filename,
  2556. title: video.desc || video.aweme_id,
  2557. description: detailData?.desc || video.desc || '',
  2558. tags: video.text_extra || [],
  2559. thumbnail: video.cover_url || '',
  2560. duration: video.duration || 0,
  2561. resolution: detailData?.video?.ratio || '',
  2562. awemeId: video.aweme_id,
  2563. authorName: video.author.nickname || ''
  2564. }).subscribe({
  2565. next: (taskRes: any) => {
  2566. if (!taskRes?.taskId) {
  2567. video.isDownloading = false;
  2568. video.downloadProgress = 0;
  2569. this.showToast('❌ 下载任务创建失败,请稍后重试', 'error');
  2570. return;
  2571. }
  2572. this.showToast(`📥 正在下载「${video.desc || video.aweme_id}」到视频库`, 'info');
  2573. this.pollManagedDownload(video, taskRes.taskId);
  2574. },
  2575. error: (error: any) => {
  2576. console.error('创建下载任务失败:', error);
  2577. video.isDownloading = false;
  2578. video.downloadProgress = 0;
  2579. this.showToast(`❌ 创建下载任务失败:${error?.error?.error || error?.message || '请稍后重试'}`, 'error');
  2580. }
  2581. });
  2582. },
  2583. error: (error: any) => {
  2584. console.error('获取视频信息失败:', error);
  2585. video.isDownloading = false;
  2586. this.showToast(`❌ 获取视频信息失败:${error?.error?.error || error?.message || '请稍后重试'}`, 'error');
  2587. }
  2588. });
  2589. }
  2590. downloadPreviewVideo(): void {
  2591. if (!this.previewSourceVideo) {
  2592. return;
  2593. }
  2594. this.downloadVideo(this.previewSourceVideo);
  2595. }
  2596. private pollManagedDownload(video: VideoInfo, taskId: string, retryCount: number = 0): void {
  2597. this.douyinService.getManagedDownloadTask(taskId).subscribe({
  2598. next: (task: any) => {
  2599. video.downloadProgress = task?.progress || 0;
  2600. if (task?.status === 'completed') {
  2601. video.isDownloading = false;
  2602. video.downloadProgress = 100;
  2603. this.loadVideoManifest();
  2604. this.showToast(`✅ 视频「${video.desc || video.aweme_id}」已下载到本地视频库`, 'success');
  2605. this.refreshView();
  2606. return;
  2607. }
  2608. if (task?.status === 'failed') {
  2609. video.isDownloading = false;
  2610. video.downloadProgress = 0;
  2611. this.showToast(`❌ 下载失败:${task?.error || '请稍后重试'}`, 'error');
  2612. this.refreshView();
  2613. return;
  2614. }
  2615. this.refreshView();
  2616. setTimeout(() => this.pollManagedDownload(video, taskId), 1000);
  2617. },
  2618. error: (error: any) => {
  2619. console.error('查询下载任务失败:', error);
  2620. if (retryCount < 3) {
  2621. setTimeout(() => this.pollManagedDownload(video, taskId, retryCount + 1), 1500);
  2622. return;
  2623. }
  2624. video.isDownloading = false;
  2625. video.downloadProgress = 0;
  2626. this.showToast('❌ 下载状态查询失败,请稍后重试', 'error');
  2627. this.refreshView();
  2628. }
  2629. });
  2630. }
  2631. private pollMonitorWorkDownload(work: MonitorWork, taskId: string, retryCount: number = 0): void {
  2632. this.douyinService.getManagedDownloadTask(taskId).subscribe({
  2633. next: (task: any) => {
  2634. work.downloadProgress = task?.progress || 0;
  2635. if (task?.status === 'completed') {
  2636. work.isDownloading = false;
  2637. work.downloadProgress = 100;
  2638. this.loadVideoManifest();
  2639. this.showToast(`✅ 视频「${work.desc || work.id}」已下载到本地视频库`, 'success');
  2640. this.refreshView();
  2641. return;
  2642. }
  2643. if (task?.status === 'failed') {
  2644. work.isDownloading = false;
  2645. work.downloadProgress = 0;
  2646. this.showToast(`❌ 下载失败:${task?.error || '请稍后重试'}`, 'error');
  2647. this.refreshView();
  2648. return;
  2649. }
  2650. this.refreshView();
  2651. setTimeout(() => this.pollMonitorWorkDownload(work, taskId), 1000);
  2652. },
  2653. error: () => {
  2654. if (retryCount < 3) {
  2655. setTimeout(() => this.pollMonitorWorkDownload(work, taskId, retryCount + 1), 1500);
  2656. return;
  2657. }
  2658. work.isDownloading = false;
  2659. work.downloadProgress = 0;
  2660. this.showToast('❌ 下载状态查询失败,请稍后重试', 'error');
  2661. this.refreshView();
  2662. }
  2663. });
  2664. }
  2665. private buildMonitorVideoInfo(author: MonitorAuthor, work: MonitorWork): VideoInfo {
  2666. return {
  2667. aweme_id: work.id,
  2668. desc: work.desc,
  2669. cover_url: work.coverUrl,
  2670. cover_candidates: work.coverCandidates,
  2671. duration: work.duration,
  2672. create_time: work.createTime ? Math.floor(work.createTime.getTime() / 1000) : 0,
  2673. author: {
  2674. nickname: author.nickname,
  2675. sec_uid: author.secUserId
  2676. },
  2677. statistics: {
  2678. play_count: 0,
  2679. digg_count: work.statistics.digg_count,
  2680. comment_count: work.statistics.comment_count,
  2681. share_count: work.statistics.share_count
  2682. },
  2683. text_extra: [],
  2684. downloadProgress: work.downloadProgress,
  2685. isDownloading: work.isDownloading
  2686. };
  2687. }
  2688. // 开始AI生成
  2689. startAIGeneration(video: VideoInfo): void {
  2690. console.log('开始AI生成:', video);
  2691. // 创建新任务
  2692. const newTask: Task = {
  2693. id: `TASK-${Date.now()}`,
  2694. keyword: this.searchKeyword,
  2695. status: 'pending',
  2696. step: 'search',
  2697. progress: 0,
  2698. cost: 0,
  2699. created_at: new Date(),
  2700. updated_at: new Date(),
  2701. original_video_title: video.desc
  2702. };
  2703. this.activeTasks.unshift(newTask);
  2704. this.setCurrentTab('tasks');
  2705. // 模拟任务进度更新
  2706. this.simulateTaskProgress(newTask.id);
  2707. }
  2708. // 模拟任务进度
  2709. private simulateTaskProgress(taskId: string): void {
  2710. const task = this.activeTasks.find(t => t.id === taskId);
  2711. if (!task) return;
  2712. const steps: Task['step'][] = ['search', 'detail', 'download', 'transcribe', 'generate'];
  2713. let currentStepIndex = 0;
  2714. const interval = setInterval(() => {
  2715. if (currentStepIndex < steps.length) {
  2716. task.step = steps[currentStepIndex];
  2717. task.progress = Math.min((currentStepIndex + 1) * 20, 100);
  2718. task.status = currentStepIndex === steps.length - 1 ? 'completed' : 'processing';
  2719. task.updated_at = new Date();
  2720. currentStepIndex++;
  2721. } else {
  2722. task.status = 'completed';
  2723. task.progress = 100;
  2724. clearInterval(interval);
  2725. // 添加到生成结果
  2726. this.generatedResults.unshift({
  2727. id: `RESULT-${Date.now()}`,
  2728. type: 'video',
  2729. url: 'https://example.com/generated-video.mp4',
  2730. title: `AI重塑 - ${task.keyword}`,
  2731. created_at: new Date(),
  2732. quality: '1080P',
  2733. duration: '2分钟',
  2734. cost: 2.5
  2735. });
  2736. }
  2737. }, 2000);
  2738. }
  2739. // 获取任务状态颜色
  2740. getTaskStatusColor(status: string): string {
  2741. switch (status) {
  2742. case 'pending': return 'warn';
  2743. case 'processing': return 'accent';
  2744. case 'completed': return 'primary';
  2745. case 'failed': return 'warn';
  2746. default: return '';
  2747. }
  2748. }
  2749. // 获取任务状态文本
  2750. getTaskStatusText(status: string): string {
  2751. switch (status) {
  2752. case 'pending': return '等待中';
  2753. case 'processing': return '处理中';
  2754. case 'completed': return '已完成';
  2755. case 'failed': return '失败';
  2756. case 'timeout': return '超时';
  2757. default: return status;
  2758. }
  2759. }
  2760. // 获取任务步骤文本
  2761. getTaskStepText(step: string): string {
  2762. switch (step) {
  2763. case 'search': return '视频搜索';
  2764. case 'detail': return '详情获取';
  2765. case 'download': return '视频下载';
  2766. case 'transcribe': return '语音转文字';
  2767. case 'generate': return 'AI生成';
  2768. case 'complete': return '完成';
  2769. case 'vg-upload': return '上传视频';
  2770. case 'vg-analyze': return '视频解析';
  2771. case 'vg-script': return '脚本生成';
  2772. case 'vg-image': return '配图生成';
  2773. case 'vg-voice': return '语音配音';
  2774. case 'vg-composite': return '视频合成';
  2775. default: return step;
  2776. }
  2777. }
  2778. // 判断步骤是否完成
  2779. isStepCompleted(currentStep: string, targetStep: string): boolean {
  2780. const steps = ['search', 'detail', 'download', 'transcribe', 'generate'];
  2781. const currentIndex = steps.indexOf(currentStep);
  2782. const targetIndex = steps.indexOf(targetStep);
  2783. return currentIndex > targetIndex;
  2784. }
  2785. // 查看任务详情
  2786. viewTaskDetail(task: Task): void {
  2787. console.log('查看任务详情:', task);
  2788. }
  2789. // 已被用户取消的任务 ID 集合:用于中止后续 vg 流程更新进度时覆盖回 processing 状态
  2790. private canceledTaskIds: Set<string> = new Set<string>();
  2791. // 取消任务(实际生效:标记为 failed 并阻止后续 vg 进度回写;UI 立即刷新)
  2792. cancelTask(task: Task): void {
  2793. if (!task) return;
  2794. task.status = 'failed';
  2795. task.error_message = '用户已取消';
  2796. task.updated_at = new Date();
  2797. if (task.id) this.canceledTaskIds.add(task.id);
  2798. // 若取消的是当前进行中的视频生成任务,清空 vg 运行状态,防止继续触发新请求
  2799. if (task.type === 'video-generation' && this.vgTaskId === task.id) {
  2800. this.vgUploading = false;
  2801. this.vgAnalyzing = false;
  2802. this.vgGeneratingScript = false;
  2803. this.vgGeneratingImages = false;
  2804. this.vgSynthesizing = false;
  2805. this.vgCompositing = false;
  2806. this.vgError = '已取消';
  2807. }
  2808. this.updateTask(task);
  2809. this.updateTaskStats();
  2810. this.refreshView();
  2811. this.showToast('🛑 任务已取消', 'info');
  2812. }
  2813. // 获取状态颜色
  2814. getStatusColor(status: string): string {
  2815. switch (status) {
  2816. case 'completed': return 'primary';
  2817. case 'failed': return 'warn';
  2818. default: return '';
  2819. }
  2820. }
  2821. // 获取状态文本
  2822. getStatusText(status: string): string {
  2823. switch (status) {
  2824. case 'completed': return '已完成';
  2825. case 'failed': return '失败';
  2826. default: return status;
  2827. }
  2828. }
  2829. // 查看历史记录详情
  2830. viewHistoryDetail(record: HistoryRecord): void {
  2831. this.historyDetailRecord = record;
  2832. this.historyDetailSegments = [];
  2833. this.historyDetailPrimaryVideoUrl = this.findHistoryPrimaryVideoUrl(record);
  2834. this.historyDetailLoading = !!record.remixId;
  2835. this.showHistoryDetailModal = true;
  2836. this.refreshView();
  2837. const finalizeHistoryDetail = (remix: any = null) => {
  2838. this.historyDetailSegments = this.buildHistoryDetailSegments(record, remix);
  2839. this.historyDetailPrimaryVideoUrl = this.findHistoryPrimaryVideoUrl(record, remix);
  2840. this.historyDetailLoading = false;
  2841. this.refreshView();
  2842. };
  2843. if (record.remixId && record.videoId) {
  2844. // 从 remix 数据加载片段详情
  2845. this.http.get<any[]>(`/backend/api/remixes/${record.videoId}`).subscribe({
  2846. next: (remixes) => {
  2847. finalizeHistoryDetail(remixes.find(r => r.remixId === record.remixId));
  2848. },
  2849. error: () => {
  2850. finalizeHistoryDetail();
  2851. }
  2852. });
  2853. } else if (record.remixId) {
  2854. // 尝试从所有 remix 数据中查找
  2855. this.http.get<Record<string, any[]>>('/backend/api/remixes').subscribe({
  2856. next: (allRemixes) => {
  2857. let matchedRemix: any = null;
  2858. for (const remixes of Object.values(allRemixes)) {
  2859. const remix = remixes.find(r => r.remixId === record.remixId);
  2860. if (remix) {
  2861. matchedRemix = remix;
  2862. break;
  2863. }
  2864. }
  2865. finalizeHistoryDetail(matchedRemix);
  2866. },
  2867. error: () => {
  2868. finalizeHistoryDetail();
  2869. }
  2870. });
  2871. } else {
  2872. finalizeHistoryDetail();
  2873. }
  2874. }
  2875. closeHistoryDetail(): void {
  2876. this.showHistoryDetailModal = false;
  2877. this.historyDetailRecord = null;
  2878. this.historyDetailSegments = [];
  2879. this.historyDetailPrimaryVideoUrl = '';
  2880. this.historyDetailLoading = false;
  2881. }
  2882. private findGeneratedResultForHistory(record: HistoryRecord): GeneratedResult | undefined {
  2883. return this.generatedResults.find((result) => {
  2884. if (record.remixId && result.remixId === record.remixId) return true;
  2885. if (record.resultUrl && result.url === record.resultUrl) return true;
  2886. if (record.videoId && result.videoId === record.videoId && record.styleName) {
  2887. return result.title?.includes(record.styleName);
  2888. }
  2889. return false;
  2890. });
  2891. }
  2892. private findHistoryPrimaryVideoUrl(record: HistoryRecord, remix?: any): string {
  2893. const result = this.findGeneratedResultForHistory(record);
  2894. return record.resultUrl
  2895. || remix?.stitchUrl
  2896. || result?.url
  2897. || remix?.segments?.find((segment: any) => segment?.videoUrl)?.videoUrl
  2898. || result?.segments?.find((segment: any) => segment?.videoUrl)?.videoUrl
  2899. || '';
  2900. }
  2901. private buildHistoryDetailSegments(record: HistoryRecord, remix?: any): { id: string; videoUrl: string; prompt: string; status: string; narration?: string }[] {
  2902. const remixSegments = Array.isArray(remix?.segments) ? remix.segments : [];
  2903. const resultSegments = Array.isArray(this.findGeneratedResultForHistory(record)?.segments)
  2904. ? this.findGeneratedResultForHistory(record)?.segments || []
  2905. : [];
  2906. const sourceSegments = remixSegments.length > 0 ? remixSegments : resultSegments;
  2907. return sourceSegments.map((segment: any, index: number) => ({
  2908. id: segment?.id || `SEG-${index + 1}`,
  2909. videoUrl: segment?.videoUrl || '',
  2910. prompt: segment?.prompt || '',
  2911. status: segment?.status || 'completed',
  2912. narration: segment?.narration || segment?.prompt || ''
  2913. }));
  2914. }
  2915. // 重新生成任务
  2916. regenerateTask(record: HistoryRecord): void {
  2917. console.log('重新生成任务:', record);
  2918. this.searchKeyword = record.keyword;
  2919. this.setCurrentTab('search');
  2920. }
  2921. // 导出历史记录
  2922. exportHistory(): void {
  2923. const dataStr = JSON.stringify(this.historyRecords, null, 2);
  2924. const dataBlob = new Blob([dataStr], { type: 'application/json' });
  2925. const link = document.createElement('a');
  2926. link.href = URL.createObjectURL(dataBlob);
  2927. link.download = `history-${Date.now()}.json`;
  2928. link.click();
  2929. }
  2930. // 预览结果
  2931. previewResult(result: GeneratedResult): void {
  2932. if (result.type === 'video') {
  2933. this.previewVideoUrl = result.url;
  2934. this.previewDownloadUrl = result.url;
  2935. this.previewVideoTitle = result.title;
  2936. this.previewSourceVideo = null;
  2937. this.previewVideoInfo = {
  2938. quality: result.quality,
  2939. duration: result.duration,
  2940. cost: result.cost,
  2941. created_at: result.created_at
  2942. };
  2943. this.showPreviewModal = true;
  2944. } else {
  2945. window.open(result.url, '_blank');
  2946. }
  2947. }
  2948. // 下载结果
  2949. downloadResult(result: GeneratedResult): void {
  2950. console.log('下载结果:', result);
  2951. const link = document.createElement('a');
  2952. link.href = result.url;
  2953. link.download = `${result.title}.${result.type === 'video' ? 'mp4' : 'jpg'}`;
  2954. link.click();
  2955. }
  2956. // 分享结果
  2957. shareResult(result: GeneratedResult): void {
  2958. if (navigator.share) {
  2959. navigator.share({
  2960. title: result.title,
  2961. text: '查看这个由AI生成的精彩内容!',
  2962. url: result.url
  2963. });
  2964. } else {
  2965. navigator.clipboard.writeText(result.url).then(() => {
  2966. alert('链接已复制到剪贴板');
  2967. });
  2968. }
  2969. }
  2970. // 视频管理相关方法
  2971. // 获取过滤后的视频列表
  2972. getFilteredVideos(): ManagedVideo[] {
  2973. return this.managedVideos.filter(video => {
  2974. const matchesCategory = !this.videoFilter.category || video.category === this.videoFilter.category;
  2975. const matchesSource = !this.videoFilter.source || video.source === this.videoFilter.source;
  2976. const matchesSearch = !this.videoFilter.searchTerm ||
  2977. video.title.toLowerCase().includes(this.videoFilter.searchTerm.toLowerCase()) ||
  2978. video.description.toLowerCase().includes(this.videoFilter.searchTerm.toLowerCase()) ||
  2979. video.tags.some(tag => tag.toLowerCase().includes(this.videoFilter.searchTerm.toLowerCase()));
  2980. return matchesCategory && matchesSource && matchesSearch;
  2981. });
  2982. }
  2983. // 切换视频选择
  2984. toggleVideoSelection(videoId: string): void {
  2985. if (this.selectedVideos.has(videoId)) {
  2986. this.selectedVideos.delete(videoId);
  2987. } else {
  2988. this.selectedVideos.add(videoId);
  2989. }
  2990. }
  2991. // 获取视频可播放 URL(用于封面截帧等)
  2992. getVideoPlayUrl(video: ManagedVideo): string {
  2993. if (!video) return '';
  2994. // 远程 URL(生成的视频)
  2995. if (video.filepath && /^https?:\/\//.test(video.filepath)) return video.filepath;
  2996. // 本地文件
  2997. if (video.filepath) return video.filepath;
  2998. if (video.filename) return `/backend/api/video/${video.filename}`;
  2999. return '';
  3000. }
  3001. private createUploadedVideoEntry(file: File, url: string, title: string, description: string, tags: string[]): any {
  3002. const ext = (file.name.match(/\.([a-z0-9]+)$/i)?.[1] || 'mp4').toLowerCase();
  3003. const now = new Date().toISOString();
  3004. return {
  3005. id: `VID-${Date.now()}`,
  3006. title: title || file.name.replace(/\.[^.]+$/, ''),
  3007. filename: file.name,
  3008. filepath: url,
  3009. size: file.size,
  3010. duration: 0,
  3011. category: 'uploaded',
  3012. tags,
  3013. description: description || '用户上传的视频',
  3014. source: 'uploaded',
  3015. created_at: now,
  3016. modified_at: now,
  3017. metadata: {
  3018. resolution: '未知',
  3019. format: ext,
  3020. },
  3021. };
  3022. }
  3023. private toManagedVideo(entry: any): ManagedVideo {
  3024. return {
  3025. id: entry.id,
  3026. title: entry.title || entry.filename,
  3027. filename: entry.filename,
  3028. filepath: entry.filepath || entry.url || `/backend/api/video/${entry.filename}`,
  3029. size: entry.size || 0,
  3030. duration: entry.duration || 0,
  3031. created_at: entry.created_at ? new Date(entry.created_at) : new Date(),
  3032. modified_at: entry.modified_at ? new Date(entry.modified_at) : new Date(),
  3033. category: entry.category || 'uploaded',
  3034. tags: entry.tags || [],
  3035. description: entry.description || '',
  3036. thumbnail: entry.thumbnail || '',
  3037. source: entry.source || 'uploaded',
  3038. metadata: entry.metadata || { resolution: '未知', format: 'mp4' },
  3039. whisper: entry.whisper || undefined,
  3040. };
  3041. }
  3042. // 获取来源文本
  3043. getSourceText(source: string): string {
  3044. switch (source) {
  3045. case 'downloaded': return '下载';
  3046. case 'generated': return 'AI生成';
  3047. case 'uploaded': return '上传';
  3048. default: return source;
  3049. }
  3050. }
  3051. // 获取分类名称
  3052. getCategoryName(categoryId: string): string {
  3053. const category = this.videoCategories.find(cat => cat.id === categoryId);
  3054. return category ? category.name : '未分类';
  3055. }
  3056. // 获取分类颜色
  3057. getCategoryColor(categoryId: string): string {
  3058. const category = this.videoCategories.find(cat => cat.id === categoryId);
  3059. return category ? category.color : '#757575';
  3060. }
  3061. // 预览视频
  3062. previewVideo(video: ManagedVideo): void {
  3063. this.previewVideoUrl = video.filepath;
  3064. this.previewDownloadUrl = video.filepath;
  3065. this.previewVideoTitle = video.title;
  3066. this.previewSourceVideo = null;
  3067. this.previewVideoInfo = {
  3068. filename: video.filename,
  3069. size: video.size,
  3070. duration: video.duration,
  3071. resolution: video.metadata?.resolution || '',
  3072. format: video.metadata?.format || 'mp4',
  3073. source: video.source,
  3074. description: video.description,
  3075. tags: video.tags,
  3076. created_at: video.created_at
  3077. };
  3078. this.showPreviewModal = true;
  3079. }
  3080. // 关闭预览
  3081. closePreview(): void {
  3082. this.showPreviewModal = false;
  3083. this.previewVideoUrl = '';
  3084. this.previewDownloadUrl = '';
  3085. this.previewVideoTitle = '';
  3086. this.previewVideoInfo = null;
  3087. this.previewSourceVideo = null;
  3088. }
  3089. // 编辑视频
  3090. editVideo(video: ManagedVideo): void {
  3091. console.log('编辑视频:', video);
  3092. // 这里可以打开视频编辑模态框
  3093. const newTitle = prompt('编辑视频标题:', video.title);
  3094. if (newTitle && newTitle !== video.title) {
  3095. video.title = newTitle;
  3096. video.modified_at = new Date();
  3097. console.log('视频标题已更新');
  3098. }
  3099. }
  3100. // 删除单个视频
  3101. deleteVideo(video: ManagedVideo): void {
  3102. if (confirm(`确定要删除视频「${video.title}」吗?`)) {
  3103. this.http.delete<any>(`/backend/api/manifest/${video.id}`).subscribe({
  3104. next: () => {
  3105. this.managedVideos = this.managedVideos.filter(v => v.id !== video.id);
  3106. this.selectedVideos.delete(video.id);
  3107. this.updateCategoryCounts();
  3108. this.showToast(`🗑️ 视频「${video.title}」已删除`, 'success');
  3109. this.refreshView();
  3110. console.log('视频已删除:', video.title);
  3111. },
  3112. error: (err) => {
  3113. const message = err?.error?.error || '删除视频失败';
  3114. this.showToast(`❌ ${message}`, 'error');
  3115. console.warn('⚠️ 删除视频失败:', err);
  3116. this.refreshView();
  3117. }
  3118. });
  3119. }
  3120. }
  3121. // 批量删除视频
  3122. batchDelete(): void {
  3123. if (this.selectedVideos.size === 0) return;
  3124. if (confirm(`确定要删除选中的 ${this.selectedVideos.size} 个视频吗?`)) {
  3125. const selectedIds = Array.from(this.selectedVideos);
  3126. const selectedVideos = this.managedVideos.filter(v => this.selectedVideos.has(v.id));
  3127. let completed = 0;
  3128. let successCount = 0;
  3129. selectedVideos.forEach((video) => {
  3130. this.http.delete<any>(`/backend/api/manifest/${video.id}`).subscribe({
  3131. next: () => {
  3132. successCount += 1;
  3133. this.managedVideos = this.managedVideos.filter(v => v.id !== video.id);
  3134. this.selectedVideos.delete(video.id);
  3135. completed += 1;
  3136. if (completed === selectedIds.length) {
  3137. this.isSelectionMode = false;
  3138. this.selectedVideos.clear();
  3139. this.updateCategoryCounts();
  3140. this.showToast(`🗑️ 已删除 ${successCount} 个视频`, 'success');
  3141. this.refreshView();
  3142. console.log('批量视频已删除');
  3143. }
  3144. },
  3145. error: (err) => {
  3146. completed += 1;
  3147. console.warn(`⚠️ 删除视频失败: ${video.title}`, err);
  3148. if (completed === selectedIds.length) {
  3149. this.isSelectionMode = false;
  3150. this.selectedVideos.clear();
  3151. this.updateCategoryCounts();
  3152. if (successCount > 0) {
  3153. this.showToast(`⚠️ 部分删除成功,已删除 ${successCount}/${selectedIds.length} 个视频`, 'warn');
  3154. } else {
  3155. const message = err?.error?.error || '批量删除失败';
  3156. this.showToast(`❌ ${message}`, 'error');
  3157. }
  3158. this.refreshView();
  3159. }
  3160. }
  3161. });
  3162. });
  3163. }
  3164. }
  3165. // 批量导出视频
  3166. batchExport(): void {
  3167. if (this.selectedVideos.size === 0) return;
  3168. const selectedVideos = this.managedVideos.filter(v => this.selectedVideos.has(v.id));
  3169. console.log('批量导出视频:', selectedVideos.map(v => v.title));
  3170. alert(`正在导出 ${selectedVideos.length} 个视频...`);
  3171. }
  3172. // 批量分类
  3173. batchCategorize(): void {
  3174. if (this.selectedVideos.size === 0) return;
  3175. const categoryId = prompt(`选择分类:\n${this.videoCategories.map((cat, index) =>
  3176. `${index + 1}. ${cat.name}`).join('\n')}`);
  3177. if (categoryId) {
  3178. const categoryIndex = parseInt(categoryId) - 1;
  3179. if (categoryIndex >= 0 && categoryIndex < this.videoCategories.length) {
  3180. const selectedCategory = this.videoCategories[categoryIndex];
  3181. this.managedVideos.forEach(video => {
  3182. if (this.selectedVideos.has(video.id)) {
  3183. video.category = selectedCategory.id;
  3184. video.modified_at = new Date();
  3185. }
  3186. });
  3187. this.updateCategoryCounts();
  3188. this.selectedVideos.clear();
  3189. this.isSelectionMode = false;
  3190. console.log('批量分类完成');
  3191. }
  3192. }
  3193. }
  3194. // 更新分类计数
  3195. private updateCategoryCounts(): void {
  3196. this.videoCategories.forEach(category => {
  3197. category.count = this.managedVideos.filter(video => video.source === category.id || video.category === category.id).length;
  3198. });
  3199. }
  3200. // ==================== 视频上传 ====================
  3201. openUploadModal(): void {
  3202. this.showUploadModal = true;
  3203. this.uploadTitle = '';
  3204. this.uploadDescription = '';
  3205. this.uploadTags = '';
  3206. this.uploadFile = null;
  3207. this.uploadFileName = '';
  3208. this.uploadProgress = 0;
  3209. this.uploadError = '';
  3210. this.isUploading = false;
  3211. }
  3212. closeUploadModal(): void {
  3213. if (this.isUploading) return;
  3214. this.showUploadModal = false;
  3215. this.uploadFile = null;
  3216. this.uploadFileName = '';
  3217. }
  3218. onFileSelected(event: Event): void {
  3219. const input = event.target as HTMLInputElement;
  3220. if (input.files && input.files.length > 0) {
  3221. const file = input.files[0];
  3222. const allowedExts = ['.mp4', '.mov', '.avi', '.webm', '.mkv'];
  3223. const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  3224. if (!allowedExts.includes(ext)) {
  3225. this.uploadError = '不支持的文件格式,仅支持: mp4, mov, avi, webm, mkv';
  3226. input.value = '';
  3227. return;
  3228. }
  3229. if (file.size > 500 * 1024 * 1024) {
  3230. this.uploadError = '文件大小超过限制(最大 500MB)';
  3231. input.value = '';
  3232. return;
  3233. }
  3234. this.uploadFile = file;
  3235. this.uploadFileName = file.name;
  3236. this.uploadError = '';
  3237. // 自动填充标题(去掉扩展名)
  3238. if (!this.uploadTitle) {
  3239. this.uploadTitle = file.name.replace(/\.[^.]+$/, '');
  3240. }
  3241. }
  3242. }
  3243. uploadVideo(): void {
  3244. if (!this.uploadFile || this.isUploading) return;
  3245. this.isUploading = true;
  3246. this.uploadProgress = 0;
  3247. this.uploadError = '';
  3248. const file = this.uploadFile;
  3249. const title = this.uploadTitle || file.name.replace(/\.[^.]+$/, '');
  3250. const description = this.uploadDescription || '用户上传的视频';
  3251. const tags = this.uploadTags.trim()
  3252. ? this.uploadTags.split(/[,,、\s]+/).filter(t => t.trim())
  3253. : [];
  3254. let uploadedEntry: any = null;
  3255. this.qiniuUpload.uploadFileWithProgress(file, file.name, file.type || 'video/mp4', 'video').pipe(
  3256. switchMap((event) => {
  3257. if (event.state === 'progress') {
  3258. this.uploadProgress = event.progress;
  3259. this.refreshView();
  3260. return of(null);
  3261. }
  3262. const url = event.url || '';
  3263. if (!url) {
  3264. throw new Error('上传失败:未返回视频 URL');
  3265. }
  3266. uploadedEntry = this.createUploadedVideoEntry(file, url, title, description, tags);
  3267. return this.http.post<any>('/backend/api/manifest', uploadedEntry);
  3268. })
  3269. ).subscribe({
  3270. next: (res) => {
  3271. if (!res) return;
  3272. this.isUploading = false;
  3273. const entry = res?.video || res?.data || uploadedEntry;
  3274. const newVideo = this.toManagedVideo(entry);
  3275. this.uploadProgress = 100;
  3276. this.managedVideos.unshift(newVideo);
  3277. this.updateCategoryCounts();
  3278. this.showUploadModal = false;
  3279. this.uploadFile = null;
  3280. this.uploadFileName = '';
  3281. this.showToast(`✅ 视频「${newVideo.title}」上传成功!`, 'success');
  3282. this.refreshView();
  3283. },
  3284. error: (err: any) => {
  3285. this.isUploading = false;
  3286. this.uploadError = err?.error?.error || err?.message || '上传失败';
  3287. this.refreshView();
  3288. }
  3289. });
  3290. }
  3291. // ==================== AI重塑 — 多步骤流程 ====================
  3292. // Step 1: 打开AI重塑模态框
  3293. aiRemixVideo(video: ManagedVideo): void {
  3294. if (video.isRemixing) return;
  3295. this.remixTargetVideo = video;
  3296. this.remixStep = 1;
  3297. this.remixTranscript = '';
  3298. this.remixBeautifiedTranscript = '';
  3299. this.remixStoryboard = [];
  3300. this.remixStyle = 'anime';
  3301. this.remixQuality = '720p';
  3302. this.remixFrames = 121;
  3303. this.remixAspectRatio = '16:9';
  3304. this.remixStatusText = '';
  3305. this.isRemixSubmitting = false;
  3306. this.remixResults = { total: 0, success: 0, failed: 0 };
  3307. this.remixStitchStatus = 'idle';
  3308. this.remixStitchUrl = '';
  3309. this.remixStitchError = '';
  3310. this.remixFinalVideoUrl = '';
  3311. this.remixMode = 'standard';
  3312. this.resetDigitalHumanState();
  3313. this.isWhisperRunning = false;
  3314. this.whisperStatusText = '';
  3315. this.showManualTranscriptInput = false;
  3316. this.showRemixModal = true;
  3317. // 自动尝试加载Whisper处理后的文件
  3318. this.loadWhisperFiles(video);
  3319. }
  3320. // 关闭重塑模态框
  3321. closeRemixModal(): void {
  3322. if (this.isRemixSubmitting) return;
  3323. this.showRemixModal = false;
  3324. this.remixTargetVideo = null;
  3325. this.resetDigitalHumanState();
  3326. }
  3327. // ========== AI重塑模式选择弹窗 ==========
  3328. openRemixModeChooser(video: ManagedVideo): void {
  3329. if (!video || video.isRemixing) return;
  3330. this.remixModeChooserVideo = video;
  3331. this.showRemixModeChooser = true;
  3332. }
  3333. closeRemixModeChooser(): void {
  3334. this.showRemixModeChooser = false;
  3335. this.remixModeChooserVideo = null;
  3336. }
  3337. selectRemixMode(mode: 'standard' | 'digital-human'): void {
  3338. const video = this.remixModeChooserVideo;
  3339. this.showRemixModeChooser = false;
  3340. this.remixModeChooserVideo = null;
  3341. if (!video) return;
  3342. if (mode === 'digital-human') {
  3343. // 数字人生成:跳转到数字人合成页,并把该视频作为「参考视频」自动加载 + 分析
  3344. this.setCurrentTab('digital-human');
  3345. this.startDhRefFromManagedVideo(video);
  3346. return;
  3347. }
  3348. // 标准AI重塑:跳转到视频生成页,并将该视频作为已上传文件自动完成第一步
  3349. this.setCurrentTab('video-generation');
  3350. this.startVgFromManagedVideo(video);
  3351. }
  3352. private async startVgFromManagedVideo(video: ManagedVideo): Promise<void> {
  3353. try {
  3354. this.vgReset();
  3355. const playUrl = this.getVideoPlayUrl(video);
  3356. const displayName = video.title || video.filename || `video-${video.id}`;
  3357. // 优先把已存在的视频抓取为 File 对象,便于 ≤20MB 走 Gemini 直接识别
  3358. let file: File | null = null;
  3359. if (playUrl) {
  3360. try {
  3361. const resp = await fetch(playUrl);
  3362. if (resp.ok) {
  3363. const blob = await resp.blob();
  3364. const mime = blob.type || 'video/mp4';
  3365. const fileName = video.filename || `${displayName}.mp4`;
  3366. file = new File([blob], fileName, { type: mime });
  3367. }
  3368. } catch (err) {
  3369. console.warn('从已存在视频构造 File 失败,将走音频提取链路:', err);
  3370. }
  3371. }
  3372. this.vgSourceFile = file;
  3373. this.vgSourceFileName = displayName;
  3374. this.vgSourceVideoUrl = playUrl;
  3375. this.vgVideoId = video.id;
  3376. this.vgStep = 2;
  3377. this.vgUploading = false;
  3378. this.vgUploadProgress = 100;
  3379. this.vgError = '';
  3380. // 复用上传成功后的后续流程:建任务 + 启动解析
  3381. this.vgCreateTask();
  3382. this.vgUpdateTaskProgress('vg-analyze', 15);
  3383. this.vgStartAnalysis();
  3384. this.cdr.detectChanges();
  3385. } catch (err: any) {
  3386. console.error('启动标准AI重塑失败:', err);
  3387. this.showToast(`❌ 启动标准AI重塑失败:${err?.message || '请重试'}`, 'error');
  3388. }
  3389. }
  3390. // ========================================================================
  3391. // 数字人合成页:参考视频(独立的上传 + 分析流程,与 vg* 完全隔离)
  3392. // ========================================================================
  3393. // 选择本地参考视频文件
  3394. dhRefSelectFile(event: Event): void {
  3395. const input = event.target as HTMLInputElement;
  3396. const file = input?.files?.[0];
  3397. if (!file) return;
  3398. if (!file.type.startsWith('video/')) {
  3399. this.showToast('请选择视频文件', 'warn');
  3400. return;
  3401. }
  3402. this.dhRefRevokeUrl();
  3403. this.dhRefFile = file;
  3404. this.dhRefFileName = file.name;
  3405. this.dhRefFileSize = file.size;
  3406. this.dhRefVideoUrl = URL.createObjectURL(file);
  3407. this.dhRefVideoId = '';
  3408. this.dhRefError = '';
  3409. this.dhRefTranscript = '';
  3410. this.dhRefAnalysisText = '';
  3411. this.refreshView();
  3412. }
  3413. // 清除参考视频与重塑状态
  3414. dhRefClear(): void {
  3415. this.dhRefRevokeUrl();
  3416. this.dhRefFile = null;
  3417. this.dhRefFileName = '';
  3418. this.dhRefFileSize = 0;
  3419. this.dhRefVideoUrl = '';
  3420. this.dhRefVideoId = '';
  3421. this.dhRefUploading = false;
  3422. this.dhRefUploadProgress = 0;
  3423. this.dhRefAnalyzing = false;
  3424. this.dhRefAnalysisText = '';
  3425. this.dhRefTranscript = '';
  3426. this.dhRefError = '';
  3427. this.dhRefRewriting = false;
  3428. this.dhRefRewriteError = '';
  3429. this.dhRefAutoRewrite = false;
  3430. this.refreshView();
  3431. }
  3432. private dhRefRevokeUrl(): void {
  3433. if (this.dhRefVideoUrl && this.dhRefVideoUrl.startsWith('blob:')) {
  3434. try { URL.revokeObjectURL(this.dhRefVideoUrl); } catch {}
  3435. }
  3436. }
  3437. // 从视频管理页选中视频后进入:直接复用已存在的视频文件,跳过上传,自动开始分析 + 重塑
  3438. private async startDhRefFromManagedVideo(video: ManagedVideo): Promise<void> {
  3439. try {
  3440. this.dhRefClear();
  3441. this.dhRefAutoRewrite = true;
  3442. const playUrl = this.getVideoPlayUrl(video);
  3443. const displayName = video.title || video.filename || `video-${video.id}`;
  3444. // 优先把已存在视频抓为 File(≤20MB 可走 Gemini 直传)
  3445. let file: File | null = null;
  3446. if (playUrl) {
  3447. try {
  3448. const resp = await fetch(playUrl);
  3449. if (resp.ok) {
  3450. const blob = await resp.blob();
  3451. const mime = blob.type || 'video/mp4';
  3452. const fileName = video.filename || `${displayName}.mp4`;
  3453. file = new File([blob], fileName, { type: mime });
  3454. }
  3455. } catch (err) {
  3456. console.warn('⚠️ 数字人参考视频:从已存在视频构造 File 失败:', err);
  3457. }
  3458. }
  3459. this.dhRefFile = file;
  3460. this.dhRefFileName = displayName;
  3461. this.dhRefFileSize = file ? file.size : 0;
  3462. this.dhRefVideoUrl = playUrl || '';
  3463. this.dhRefVideoId = video.id;
  3464. this.dhRefError = '';
  3465. this.refreshView();
  3466. this.dhRefStartAnalysis();
  3467. } catch (err: any) {
  3468. console.error('启动数字人参考视频失败:', err);
  3469. this.showToast(`❌ 启动数字人参考视频失败:${err?.message || '请重试'}`, 'error');
  3470. }
  3471. }
  3472. // 上传本地参考视频,再触发分析
  3473. dhRefUploadAndAnalyze(): void {
  3474. if (!this.dhRefFile || this.dhRefUploading) return;
  3475. this.dhRefUploading = true;
  3476. this.dhRefUploadProgress = 0;
  3477. this.dhRefError = '';
  3478. this.refreshView();
  3479. const file = this.dhRefFile;
  3480. const title = `数字人参考视频 - ${new Date().toLocaleString('zh-CN')}`;
  3481. let uploadedEntry: any = null;
  3482. this.qiniuUpload.uploadFileWithProgress(file, file.name, file.type || 'video/mp4', 'video').pipe(
  3483. switchMap((event) => {
  3484. if (event.state === 'progress') {
  3485. this.dhRefUploadProgress = event.progress;
  3486. this.cdr.detectChanges();
  3487. return of(null);
  3488. }
  3489. const url = event.url || '';
  3490. if (!url) throw new Error('上传失败:未返回视频 URL');
  3491. uploadedEntry = this.createUploadedVideoEntry(file, url, title, '数字人参考视频', ['数字人']);
  3492. return this.http.post<any>('/backend/api/manifest', uploadedEntry);
  3493. })
  3494. ).subscribe({
  3495. next: (res) => {
  3496. if (!res) return;
  3497. const entry = res?.video || res?.data || uploadedEntry;
  3498. this.dhRefUploading = false;
  3499. this.dhRefVideoId = entry.id;
  3500. const newVideo = this.toManagedVideo(entry);
  3501. if (!this.managedVideos.some(v => v.id === newVideo.id)) {
  3502. this.managedVideos.unshift(newVideo);
  3503. this.updateCategoryCounts();
  3504. }
  3505. this.dhRefStartAnalysis();
  3506. this.cdr.detectChanges();
  3507. },
  3508. error: (err) => {
  3509. this.dhRefUploading = false;
  3510. this.dhRefError = err?.error?.error || err?.message || '上传失败';
  3511. this.cdr.detectChanges();
  3512. }
  3513. });
  3514. }
  3515. // 启动分析:≤20MB 直传 Gemini,>20MB 提取音轨给 Gemini 音频识别,最后降级 Whisper
  3516. private dhRefStartAnalysis(): void {
  3517. this.dhRefAnalyzing = true;
  3518. this.dhRefTranscript = '';
  3519. this.dhRefAnalysisText = '';
  3520. this.refreshView();
  3521. const sizeMB = this.dhRefFile ? this.dhRefFile.size / 1024 / 1024 : 0;
  3522. if (this.dhRefFile && sizeMB <= 20) {
  3523. this.dhRefAnalysisText = `正在将视频 (${sizeMB.toFixed(1)}MB) 发送给 Gemini 进行视频理解...`;
  3524. this.refreshView();
  3525. this.dhRefRunGeminiVideo();
  3526. } else if (this.dhRefVideoId) {
  3527. this.dhRefAnalysisText = `视频 ${sizeMB.toFixed(1)}MB 超过 Gemini 视频限制,正在提取音轨...`;
  3528. this.refreshView();
  3529. this.dhRefRunAudioGemini();
  3530. } else {
  3531. this.dhRefAnalysisText = '使用 Whisper 语音识别...';
  3532. this.refreshView();
  3533. this.dhRefRunWhisperFallback();
  3534. }
  3535. }
  3536. private async dhRefRunGeminiVideo(): Promise<void> {
  3537. try {
  3538. const base64 = await this.llmService.fileToBase64(this.dhRefFile!);
  3539. const mimeType = this.dhRefFile!.type || 'video/mp4';
  3540. const prompt = this.buildAnalysisPrompt('video');
  3541. this.llmService.analyzeVideo(base64, mimeType, prompt, {
  3542. model: 'gemini-2.5-flash',
  3543. generationConfig: { maxOutputTokens: 8192 }
  3544. }).subscribe({
  3545. next: (result) => {
  3546. this.dhRefParseGeminiResult(result);
  3547. this.dhRefAnalyzing = false;
  3548. this.refreshView();
  3549. this.dhRefMaybeAutoRewrite();
  3550. },
  3551. error: (err) => {
  3552. console.warn('⚠️ Gemini 视频识别失败,降级 Whisper:', err);
  3553. this.dhRefAnalysisText = 'Gemini 识别失败,正在使用 Whisper 语音识别...';
  3554. this.refreshView();
  3555. this.dhRefRunWhisperFallback();
  3556. }
  3557. });
  3558. } catch (err) {
  3559. console.warn('⚠️ 视频文件读取失败:', err);
  3560. this.dhRefAnalysisText = '视频文件读取失败,正在使用 Whisper 语音识别...';
  3561. this.refreshView();
  3562. this.dhRefRunWhisperFallback();
  3563. }
  3564. }
  3565. private dhRefRunAudioGemini(): void {
  3566. const video = this.managedVideos.find(v => v.id === this.dhRefVideoId);
  3567. const source = this.dhRefFile || (video ? this.getVideoPlayUrl(video) : '');
  3568. if (!source) {
  3569. this.dhRefAnalysisText = '缺少可访问的视频文件,无法提取音轨';
  3570. this.refreshView();
  3571. this.dhRefRunWhisperFallback();
  3572. return;
  3573. }
  3574. from(this.browserFfmpeg.extractAudioForGemini(source, `dh-ref-${Date.now()}.m4a`)).subscribe({
  3575. next: (audio: BrowserAudioExtractionResult) => {
  3576. const audioSizeMB = audio.sizeMB || 0;
  3577. this.dhRefAnalysisText = `音轨提取完成 (${audioSizeMB.toFixed(1)}MB),正在 Gemini 音频识别...`;
  3578. this.refreshView();
  3579. if (audioSizeMB > 20) {
  3580. this.dhRefAnalysisText = '音频文件仍较大,改用 Whisper 识别...';
  3581. this.refreshView();
  3582. this.dhRefRunWhisperFallback();
  3583. return;
  3584. }
  3585. const prompt = this.buildAnalysisPrompt('audio');
  3586. this.llmService.analyzeAudio(audio.base64, audio.mimeType || 'audio/mp4', prompt, {
  3587. model: 'gemini-2.5-flash',
  3588. generationConfig: { maxOutputTokens: 8192 }
  3589. }).subscribe({
  3590. next: (result) => {
  3591. this.dhRefParseGeminiResult(result);
  3592. this.dhRefAnalyzing = false;
  3593. this.refreshView();
  3594. this.dhRefMaybeAutoRewrite();
  3595. },
  3596. error: (err) => {
  3597. console.warn('⚠️ Gemini 音频识别失败,降级 Whisper:', err);
  3598. this.dhRefAnalysisText = 'Gemini 音频识别失败,改用 Whisper...';
  3599. this.refreshView();
  3600. this.dhRefRunWhisperFallback();
  3601. }
  3602. });
  3603. },
  3604. error: (err) => {
  3605. const detail = err?.error?.error || err?.message || `HTTP ${err?.status}`;
  3606. console.warn('⚠️ 音轨提取失败:', detail, err);
  3607. this.dhRefAnalysisText = `音轨提取失败 (${detail}),改用 Whisper...`;
  3608. this.refreshView();
  3609. this.dhRefRunWhisperFallback();
  3610. }
  3611. });
  3612. }
  3613. private dhRefRunWhisperFallback(): void {
  3614. if (!this.dhRefVideoId) {
  3615. this.dhRefAnalyzing = false;
  3616. this.dhRefAnalysisText = '无法降级到 Whisper:参考视频尚未上传到服务端';
  3617. this.refreshView();
  3618. return;
  3619. }
  3620. this.http.post<any>('/backend/api/whisper/transcribe', {
  3621. videoId: this.dhRefVideoId,
  3622. language: 'Chinese',
  3623. model: 'large'
  3624. }).subscribe({
  3625. next: (res) => {
  3626. if (res?.success && res?.transcript) {
  3627. this.dhRefTranscript = res.transcript;
  3628. this.dhRefAnalysisText = 'Whisper 转录完成,正在 AI 分析内容...';
  3629. this.dhRefAutoFillTts();
  3630. this.refreshView();
  3631. this.dhRefDoTextAnalysis();
  3632. } else {
  3633. this.dhRefAnalyzing = false;
  3634. this.dhRefAnalysisText = '语音识别完成但未返回文字稿,请手动输入';
  3635. this.refreshView();
  3636. }
  3637. },
  3638. error: (err) => {
  3639. this.dhRefAnalyzing = false;
  3640. this.dhRefAnalysisText = `Whisper 识别失败: ${err?.error?.error || err?.message || '未知错误'}。请手动输入文字稿。`;
  3641. this.refreshView();
  3642. }
  3643. });
  3644. }
  3645. private dhRefDoTextAnalysis(): void {
  3646. const systemPrompt = `你是一个专业的视频内容分析师。请基于以下视频转录文字稿,提取:
  3647. 1. 视频主题和核心观点
  3648. 2. 目标受众
  3649. 3. 内容风格
  3650. 4. 关键知识点(3-5条)
  3651. 5. 改进方向
  3652. 请用简洁中文回复。`;
  3653. this.llmService.askWithSystem(systemPrompt, this.dhRefTranscript, { model: 'gemini-2.5-flash', max_tokens: 1024 }).subscribe({
  3654. next: (analysis) => {
  3655. this.dhRefAnalysisText = analysis || '分析完成';
  3656. this.dhRefAnalyzing = false;
  3657. this.refreshView();
  3658. this.dhRefMaybeAutoRewrite();
  3659. },
  3660. error: () => {
  3661. this.dhRefAnalysisText = '(AI 文本分析暂不可用,已完成 Whisper 转录)';
  3662. this.dhRefAnalyzing = false;
  3663. this.refreshView();
  3664. this.dhRefMaybeAutoRewrite();
  3665. }
  3666. });
  3667. }
  3668. private dhRefParseGeminiResult(raw: string): void {
  3669. const m = raw.match(/---TRANSCRIPT_START---([\s\S]*?)---TRANSCRIPT_END---/);
  3670. if (m) {
  3671. this.dhRefTranscript = m[1].trim();
  3672. const analysisPart = raw.substring(0, raw.indexOf('---TRANSCRIPT_START---')).trim();
  3673. this.dhRefAnalysisText = analysisPart.replace(/^【内容分析】\s*/, '') || '分析完成';
  3674. } else {
  3675. this.dhRefAnalysisText = raw || '分析完成';
  3676. }
  3677. this.dhRefAutoFillTts();
  3678. }
  3679. /** 把参考视频识别得到的文字稿自动填入 Step 2 口播文本(不覆盖用户已手输的内容) */
  3680. private dhRefAutoFillTts(): void {
  3681. const transcript = (this.dhRefTranscript || '').trim();
  3682. if (!transcript) return;
  3683. // 仅在口播文本为空时自动填入;用户已输入则保留
  3684. if (!this.dhTtsText || !this.dhTtsText.trim()) {
  3685. this.dhTtsText = transcript.slice(0, 600);
  3686. }
  3687. }
  3688. /** 文字稿手动编辑时,同步反映到口播文本(前提:当前口播仍等于上一次同步值) */
  3689. dhRefSyncToTts(newTranscript: string): void {
  3690. const next = (newTranscript || '').slice(0, 600);
  3691. this.dhTtsText = next;
  3692. }
  3693. /** 应用补充提示词预设;二次点击同一个则取消 */
  3694. dhApplyPromptPreset(value: string): void {
  3695. if (this.dhPrompt === value) {
  3696. this.dhPrompt = '';
  3697. } else {
  3698. this.dhPrompt = value;
  3699. }
  3700. this.refreshView();
  3701. }
  3702. private buildAnalysisPrompt(kind: 'video' | 'audio'): string {
  3703. const taskOne = kind === 'video'
  3704. ? `从画面和音频两个维度分析:1.主题/核心观点 2.画面描述 3.目标受众 4.内容风格 5.亮点(3-5条) 6.视觉风格 7.改进建议`
  3705. : `从音频分析:1.主题/核心观点 2.目标受众 3.内容风格 4.亮点(3-5条) 5.改进建议`;
  3706. return `你是一个专业的内容分析师。请完成两个任务:
  3707. ===== 任务一:内容分析 =====
  3708. ${taskOne}
  3709. ===== 任务二:完整语音转录 =====
  3710. 请将所有语音内容逐字转录为中文,忠实还原、不遗漏、不改写、不总结,按自然段落分段。
  3711. 请严格按以下格式输出(用分隔线区分两部分):
  3712. 【内容分析】
  3713. (任务一结果)
  3714. ---TRANSCRIPT_START---
  3715. (任务二完整转录)
  3716. ---TRANSCRIPT_END---`;
  3717. }
  3718. // 视频分析完成后自动触发(仅在通过 AI重塑入口或显式标记时)
  3719. private dhRefMaybeAutoRewrite(): void {
  3720. if (!this.dhRefAutoRewrite) return;
  3721. if (!this.dhRefTranscript || !this.dhRefTranscript.trim()) return;
  3722. this.dhRefAutoRewrite = false; // 仅触发一次
  3723. this.dhRefRunRewrite();
  3724. }
  3725. // 把当前文字稿 + 内容分析交给 AI 重写为口播文本与补充提示词
  3726. dhRefRunRewrite(): void {
  3727. if (!this.dhRefTranscript || !this.dhRefTranscript.trim()) {
  3728. this.dhRefRewriteError = '暂无可重塑的视频文字稿';
  3729. this.refreshView();
  3730. return;
  3731. }
  3732. this.dhRefRewriting = true;
  3733. this.dhRefRewriteError = '';
  3734. this.refreshView();
  3735. const systemPrompt = `你是一位短视频数字人编剧。基于用户提供的【原始视频文字稿】和【内容分析】,请输出严格的 JSON:
  3736. {
  3737. "ttsScript": "重塑后的口播文本,第一人称、自然口语、节奏适合数字人朗读,控制在 200 字以内",
  3738. "dhPrompt": "数字人生成的补充提示词,描述人物动作 / 镜头语言 / 风格要求,控制在 80 字以内"
  3739. }
  3740. 只返回纯 JSON 对象,不要使用 markdown 代码块、不要添加解释或前后缀。注意:JSON 字符串内部禁止出现真实换行,必须使用 \\n 转义。`;
  3741. const userInput = `【原始文字稿】\n${this.dhRefTranscript}\n\n【内容分析】\n${this.dhRefAnalysisText || '(无)'}`;
  3742. this.llmService.askWithSystem(systemPrompt, userInput, { model: 'gemini-2.5-flash', max_tokens: 2048 }).subscribe({
  3743. next: (text) => {
  3744. this.dhRefRewriting = false;
  3745. const cleaned = (text || '').replace(/^\s*```(?:json)?\s*/i, '').replace(/\s*```\s*$/i, '').trim();
  3746. const parsed = this.parseRewriteJson(cleaned);
  3747. if (parsed) {
  3748. const tts = typeof parsed.ttsScript === 'string' ? parsed.ttsScript.trim() : '';
  3749. const prompt = typeof parsed.dhPrompt === 'string' ? parsed.dhPrompt.trim() : '';
  3750. if (tts) this.dhTtsText = tts.slice(0, 600);
  3751. if (prompt) this.dhPrompt = prompt.slice(0, 200);
  3752. if (tts || prompt) {
  3753. this.showToast('✅ 已自动填充口播文本与补充提示词', 'success');
  3754. } else {
  3755. this.dhRefRewriteError = 'AI 未返回有效字段,请手动整理';
  3756. }
  3757. } else {
  3758. console.warn('⚠️ 解析重塑结果失败,原始返回:', cleaned);
  3759. this.dhRefRewriteError = '解析重塑结果失败,已将原始文本填入口播文本,请手动整理';
  3760. this.dhTtsText = (text || '').slice(0, 600);
  3761. this.showToast('⚠️ 重塑结果解析失败,已退回原文', 'warn');
  3762. }
  3763. this.refreshView();
  3764. },
  3765. error: (err) => {
  3766. this.dhRefRewriting = false;
  3767. this.dhRefRewriteError = `AI 重塑失败:${this.getErrorText(err, '请重试')}`;
  3768. this.refreshView();
  3769. }
  3770. });
  3771. }
  3772. /** 容错解析 LLM 返回的 JSON:支持 fenced 代码块、未转义换行、字段正则兜底 */
  3773. private parseRewriteJson(raw: string): { ttsScript?: string; dhPrompt?: string } | null {
  3774. if (!raw) return null;
  3775. // 1) 严格解析
  3776. try { return JSON.parse(raw); } catch {}
  3777. // 2) 截取首个 { ... } 区段
  3778. const braceStart = raw.indexOf('{');
  3779. const braceEnd = raw.lastIndexOf('}');
  3780. let candidate = braceStart >= 0 && braceEnd > braceStart ? raw.slice(braceStart, braceEnd + 1) : raw;
  3781. // 3) 把字符串内部的裸换行/回车/制表符转义
  3782. const sanitized = this.escapeRawControlCharsInJsonStrings(candidate);
  3783. try { return JSON.parse(sanitized); } catch {}
  3784. // 4) 正则兜底,逐字段抽取(兼容 "tts": "..." 中含 \" 转义)
  3785. const fieldRegex = (key: string) => new RegExp(`"${key}"\\s*:\\s*"((?:\\\\.|[^"\\\\])*)"`, 'i');
  3786. const ttsMatch = candidate.match(fieldRegex('ttsScript'));
  3787. const promptMatch = candidate.match(fieldRegex('dhPrompt'));
  3788. if (ttsMatch || promptMatch) {
  3789. const unescape = (s: string) => s.replace(/\\n/g, '\n').replace(/\\"/g, '"').replace(/\\\\/g, '\\');
  3790. return {
  3791. ttsScript: ttsMatch ? unescape(ttsMatch[1]) : undefined,
  3792. dhPrompt: promptMatch ? unescape(promptMatch[1]) : undefined,
  3793. };
  3794. }
  3795. // 5) 截断兜底:若仅有 ttsScript 开头但被截断,抓到截断处为止
  3796. const truncatedTts = candidate.match(/"ttsScript"\s*:\s*"((?:\\.|[^"\\])*)$/i);
  3797. if (truncatedTts) {
  3798. return { ttsScript: truncatedTts[1].replace(/\\n/g, '\n').replace(/\\"/g, '"') };
  3799. }
  3800. return null;
  3801. }
  3802. /** 在 JSON 字符串字面量内部把裸 \n \r \t 替换为转义形式,括号外的不动 */
  3803. private escapeRawControlCharsInJsonStrings(input: string): string {
  3804. let out = '';
  3805. let inString = false;
  3806. let escape = false;
  3807. for (let i = 0; i < input.length; i++) {
  3808. const ch = input[i];
  3809. if (inString) {
  3810. if (escape) { out += ch; escape = false; continue; }
  3811. if (ch === '\\') { out += ch; escape = true; continue; }
  3812. if (ch === '"') { inString = false; out += ch; continue; }
  3813. if (ch === '\n') { out += '\\n'; continue; }
  3814. if (ch === '\r') { out += '\\r'; continue; }
  3815. if (ch === '\t') { out += '\\t'; continue; }
  3816. out += ch;
  3817. } else {
  3818. if (ch === '"') { inString = true; out += ch; continue; }
  3819. out += ch;
  3820. }
  3821. }
  3822. return out;
  3823. }
  3824. getActiveRemixSteps(): RemixFlowStep[] {
  3825. if (this.remixMode === 'digital-human') {
  3826. return [
  3827. { step: 1, label: this.digitalHumanStepLabels[0] },
  3828. { step: 4, label: this.digitalHumanStepLabels[1] },
  3829. { step: 5, label: this.digitalHumanStepLabels[2] },
  3830. { step: 6, label: this.digitalHumanStepLabels[3] }
  3831. ];
  3832. }
  3833. return this.remixStepLabels.map((label, index) => ({ step: index + 1, label }));
  3834. }
  3835. setRemixMode(mode: 'standard' | 'digital-human'): void {
  3836. this.remixMode = mode;
  3837. this.remixDigitalHumanError = '';
  3838. if (mode === 'standard' && this.remixStep === 4 && this.remixStoryboard.length === 0) {
  3839. this.remixStep = 1;
  3840. }
  3841. }
  3842. private hydrateVoiceProfile(profile: any): VoiceProfile {
  3843. const status = profile?.status === null || profile?.status === undefined || profile?.status === ''
  3844. ? null
  3845. : Number(profile.status);
  3846. const synthesizedAudioUrl = String(profile?.synthesized_audio_url || '');
  3847. const demoAudio = String(profile?.demo_audio || '');
  3848. const latestAudioUrl = String(profile?.latest_audio_url || synthesizedAudioUrl || demoAudio || '');
  3849. return {
  3850. ...profile,
  3851. creation_mode: String(profile?.creation_mode || (profile?.timbre_id ? 'clone' : 'design')),
  3852. speaker_id: String(profile?.speaker_id || ''),
  3853. timbre_id: String(profile?.timbre_id || profile?.timbreId || ''),
  3854. sample_text: String(profile?.sample_text || ''),
  3855. text_prompt: String(profile?.text_prompt || ''),
  3856. source_audio_text: String(profile?.source_audio_text || ''),
  3857. source_audio_name: String(profile?.source_audio_name || ''),
  3858. source_audio_format: String(profile?.source_audio_format || ''),
  3859. language: Number(profile?.language ?? 0),
  3860. status,
  3861. status_label: String(profile?.status_label || (demoAudio || synthesizedAudioUrl ? '可用' : '未知')),
  3862. demo_audio: demoAudio,
  3863. available_training_times: profile?.available_training_times === null || profile?.available_training_times === undefined
  3864. ? null
  3865. : Number(profile.available_training_times),
  3866. image_prompt_name: String(profile?.image_prompt_name || ''),
  3867. x_api_resource_id: String(profile?.x_api_resource_id || ''),
  3868. model_version: String(profile?.model_version || ''),
  3869. icl_speaker_id: String(profile?.icl_speaker_id || ''),
  3870. occupied: !!profile?.occupied,
  3871. synthesized_audio_url: synthesizedAudioUrl,
  3872. synthesized_work_id: String(profile?.synthesized_work_id || ''),
  3873. last_synthesis_text: String(profile?.last_synthesis_text || ''),
  3874. latest_audio_url: latestAudioUrl,
  3875. ...this.buildVoiceSynthesisDraft(profile),
  3876. is_synthesizing: false,
  3877. message: String(profile?.message || ''),
  3878. request_id: String(profile?.request_id || ''),
  3879. created_at: new Date(profile?.created_at || Date.now()),
  3880. updated_at: profile?.updated_at ? new Date(profile.updated_at) : undefined
  3881. };
  3882. }
  3883. private upsertLocalVoiceProfile(profile: VoiceProfile): void {
  3884. const nextProfiles = [...this.voiceProfiles];
  3885. const existingIndex = nextProfiles.findIndex((item) => (
  3886. item.id === profile.id
  3887. || (!!profile.timbre_id && item.timbre_id === profile.timbre_id)
  3888. ));
  3889. if (existingIndex >= 0) {
  3890. nextProfiles[existingIndex] = {
  3891. ...nextProfiles[existingIndex],
  3892. ...profile,
  3893. draft_synthesis_text: profile.draft_synthesis_text ?? nextProfiles[existingIndex].draft_synthesis_text,
  3894. draft_synthesis_ssml: profile.draft_synthesis_ssml ?? nextProfiles[existingIndex].draft_synthesis_ssml,
  3895. draft_synthesis_x_api_resource_id: profile.draft_synthesis_x_api_resource_id ?? nextProfiles[existingIndex].draft_synthesis_x_api_resource_id,
  3896. draft_synthesis_model: profile.draft_synthesis_model ?? nextProfiles[existingIndex].draft_synthesis_model,
  3897. draft_synthesis_format: profile.draft_synthesis_format ?? nextProfiles[existingIndex].draft_synthesis_format,
  3898. draft_synthesis_sample_rate: profile.draft_synthesis_sample_rate ?? nextProfiles[existingIndex].draft_synthesis_sample_rate,
  3899. draft_synthesis_speech_rate: profile.draft_synthesis_speech_rate ?? nextProfiles[existingIndex].draft_synthesis_speech_rate,
  3900. draft_synthesis_loudness_rate: profile.draft_synthesis_loudness_rate ?? nextProfiles[existingIndex].draft_synthesis_loudness_rate,
  3901. draft_synthesis_emotion: profile.draft_synthesis_emotion ?? nextProfiles[existingIndex].draft_synthesis_emotion,
  3902. draft_synthesis_emotion_scale: profile.draft_synthesis_emotion_scale ?? nextProfiles[existingIndex].draft_synthesis_emotion_scale,
  3903. draft_synthesis_enable_subtitle: profile.draft_synthesis_enable_subtitle ?? nextProfiles[existingIndex].draft_synthesis_enable_subtitle,
  3904. draft_synthesis_silence_duration: profile.draft_synthesis_silence_duration ?? nextProfiles[existingIndex].draft_synthesis_silence_duration,
  3905. draft_synthesis_enable_language_detector: profile.draft_synthesis_enable_language_detector ?? nextProfiles[existingIndex].draft_synthesis_enable_language_detector,
  3906. draft_synthesis_disable_markdown_filter: profile.draft_synthesis_disable_markdown_filter ?? nextProfiles[existingIndex].draft_synthesis_disable_markdown_filter,
  3907. draft_synthesis_disable_emoji_filter: profile.draft_synthesis_disable_emoji_filter ?? nextProfiles[existingIndex].draft_synthesis_disable_emoji_filter,
  3908. draft_synthesis_explicit_language: profile.draft_synthesis_explicit_language ?? nextProfiles[existingIndex].draft_synthesis_explicit_language,
  3909. is_synthesizing: false
  3910. };
  3911. this.voiceProfiles = nextProfiles;
  3912. if (this.voiceSynthesisForm.profileId === nextProfiles[existingIndex].id) {
  3913. this.voiceSynthesisForm = this.buildVoiceSynthesisFormFromProfile(nextProfiles[existingIndex]);
  3914. }
  3915. return;
  3916. }
  3917. this.voiceProfiles = [{ ...profile, is_synthesizing: false }, ...nextProfiles];
  3918. if (!this.voiceSynthesisForm.profileId && !String(this.voiceSynthesisForm.speakerId || '').trim() && this.canSynthesizeVoiceProfile(profile)) {
  3919. this.voiceSynthesisForm = this.buildVoiceSynthesisFormFromProfile(profile);
  3920. }
  3921. }
  3922. private getVoiceCloneModelMeta(modelSource: any): { demoAudio: string; iclSpeakerId: string; xApiResourceId: string; modelVersion: string } {
  3923. const model = Array.isArray(modelSource) ? (modelSource.find((item) => !!item) || {}) : (modelSource || {});
  3924. const rawResourceId = Array.isArray(model?.x_api_resource_id)
  3925. ? model.x_api_resource_id.find((item: any) => String(item || '').trim()) || ''
  3926. : model?.x_api_resource_id;
  3927. return {
  3928. demoAudio: String(model?.demo_audio || '').trim(),
  3929. iclSpeakerId: String(model?.icl_speaker_id || '').trim(),
  3930. xApiResourceId: String(rawResourceId || '').trim(),
  3931. modelVersion: String(model?.version || model?.model_version || '').trim()
  3932. };
  3933. }
  3934. private buildVoiceProfileFromCloneApiResponse(response: any, fallback: {
  3935. displayName: string;
  3936. speakerId: string;
  3937. sampleText: string;
  3938. audioText: string;
  3939. sourceAudioName: string;
  3940. sourceAudioFormat: string;
  3941. language: number;
  3942. }): VoiceProfile | null {
  3943. const timbre = response?.data?.timbre;
  3944. if (!timbre || typeof timbre !== 'object') {
  3945. return null;
  3946. }
  3947. const modelMeta = this.getVoiceCloneModelMeta(timbre?.models);
  3948. return this.hydrateVoiceProfile({
  3949. id: String(timbre?.objectId || `voice-${Date.now()}`),
  3950. name: String(timbre?.name || fallback.displayName || '未命名音色'),
  3951. creation_mode: 'clone',
  3952. speaker_id: String(timbre?.speaker_id || fallback.speakerId || ''),
  3953. timbre_id: String(timbre?.objectId || ''),
  3954. sample_text: fallback.sampleText,
  3955. source_audio_text: fallback.audioText,
  3956. source_audio_name: fallback.sourceAudioName,
  3957. source_audio_format: fallback.sourceAudioFormat,
  3958. language: fallback.language,
  3959. status: timbre?.status === null || timbre?.status === undefined || timbre?.status === '' ? null : Number(timbre.status),
  3960. status_label: String(response?.data?.tip || (modelMeta.demoAudio ? '可用' : '未知')),
  3961. demo_audio: modelMeta.demoAudio,
  3962. occupied: !!timbre?.occupied,
  3963. x_api_resource_id: modelMeta.xApiResourceId,
  3964. model_version: modelMeta.modelVersion,
  3965. icl_speaker_id: modelMeta.iclSpeakerId,
  3966. latest_audio_url: modelMeta.demoAudio,
  3967. message: String(response?.data?.tip || ''),
  3968. created_at: timbre?.createdAt || new Date().toISOString(),
  3969. updated_at: timbre?.updatedAt || new Date().toISOString()
  3970. });
  3971. }
  3972. private applySynthesisResponseToProfile(profile: VoiceProfile, response: any, payload: {
  3973. text: string;
  3974. ssml: string;
  3975. xApiResourceId: string;
  3976. model: string;
  3977. format: string;
  3978. sampleRate: number;
  3979. speechRate: number;
  3980. loudnessRate: number;
  3981. emotion: string;
  3982. emotionScale: number;
  3983. enableSubtitle: boolean;
  3984. silenceDuration: number;
  3985. enableLanguageDetector: boolean;
  3986. disableMarkdownFilter: boolean;
  3987. disableEmojiFilter: boolean;
  3988. explicitLanguage: string;
  3989. }): VoiceProfile {
  3990. const audioUrl = String(response?.data?.audioUrl || '').trim();
  3991. const workId = String(response?.data?.workId || '').trim();
  3992. return this.hydrateVoiceProfile({
  3993. ...profile,
  3994. synthesized_audio_url: audioUrl || profile.synthesized_audio_url || '',
  3995. synthesized_work_id: workId || profile.synthesized_work_id || '',
  3996. latest_audio_url: audioUrl || profile.latest_audio_url || profile.demo_audio || '',
  3997. last_synthesis_text: payload.text,
  3998. last_synthesis_ssml: payload.ssml,
  3999. last_synthesis_x_api_resource_id: payload.xApiResourceId || profile.x_api_resource_id || '',
  4000. last_synthesis_model: payload.model,
  4001. last_synthesis_format: payload.format,
  4002. last_synthesis_sample_rate: payload.sampleRate,
  4003. last_synthesis_speech_rate: payload.speechRate,
  4004. last_synthesis_loudness_rate: payload.loudnessRate,
  4005. last_synthesis_emotion: payload.emotion,
  4006. last_synthesis_emotion_scale: payload.emotionScale,
  4007. last_synthesis_enable_subtitle: payload.enableSubtitle,
  4008. last_synthesis_silence_duration: payload.silenceDuration,
  4009. last_synthesis_enable_language_detector: payload.enableLanguageDetector,
  4010. last_synthesis_disable_markdown_filter: payload.disableMarkdownFilter,
  4011. last_synthesis_disable_emoji_filter: payload.disableEmojiFilter,
  4012. last_synthesis_explicit_language: payload.explicitLanguage,
  4013. updated_at: new Date().toISOString()
  4014. });
  4015. }
  4016. private syncVoiceProfileToBackend(profile: VoiceProfile | null | undefined): void {
  4017. if (!profile?.id) {
  4018. return;
  4019. }
  4020. this.http.post<any>('/backend/api/voice-profiles/sync', {
  4021. ...profile,
  4022. created_at: profile.created_at instanceof Date ? profile.created_at.toISOString() : profile.created_at,
  4023. updated_at: profile.updated_at instanceof Date ? profile.updated_at.toISOString() : profile.updated_at
  4024. }).subscribe({
  4025. next: (res) => {
  4026. if (res?.profile) {
  4027. this.upsertLocalVoiceProfile(this.hydrateVoiceProfile(res.profile));
  4028. this.refreshView();
  4029. }
  4030. },
  4031. error: (err) => {
  4032. console.warn('⚠️ 音色记录本地同步失败:', err);
  4033. }
  4034. });
  4035. }
  4036. private isVoiceSpeakerIdentifier(value: string): boolean {
  4037. const normalizedValue = String(value || '').trim();
  4038. return /^(S_|ICL_|icl_|saturn_|dit_)/.test(normalizedValue);
  4039. }
  4040. onVoiceSourceAudioSelected(event: Event): void {
  4041. const input = event.target as HTMLInputElement;
  4042. if (!input.files || input.files.length === 0) {
  4043. return;
  4044. }
  4045. const file = input.files[0];
  4046. const ext = (file.name.match(/\.[^.]+$/)?.[0] || '').toLowerCase();
  4047. const allowedTypes = ['audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/x-wav', 'audio/mp4', 'audio/x-m4a', 'audio/aac', 'audio/flac', 'audio/ogg', 'audio/opus', 'application/octet-stream'];
  4048. const allowedExts = ['.mp3', '.wav', '.m4a', '.aac', '.flac', '.ogg', '.opus', '.pcm'];
  4049. if ((!allowedTypes.includes(file.type) && !allowedExts.includes(ext)) || file.size <= 0) {
  4050. this.voiceDesignError = '音频样本仅支持 mp3、wav、m4a、aac、flac、ogg、opus、pcm 格式';
  4051. input.value = '';
  4052. this.refreshView();
  4053. return;
  4054. }
  4055. if (file.size > 20 * 1024 * 1024) {
  4056. this.voiceDesignError = '音频样本大小不能超过 20MB';
  4057. input.value = '';
  4058. this.refreshView();
  4059. return;
  4060. }
  4061. this.voiceSourceAudioFile = file;
  4062. this.voiceSourceAudioName = file.name;
  4063. this.voiceDesignError = '';
  4064. input.value = '';
  4065. this.refreshView();
  4066. }
  4067. clearVoiceSourceAudio(): void {
  4068. this.voiceSourceAudioFile = null;
  4069. this.voiceSourceAudioName = '';
  4070. this.refreshView();
  4071. }
  4072. onVoiceDesignImageSelected(event: Event): void {
  4073. const input = event.target as HTMLInputElement;
  4074. if (!input.files || input.files.length === 0) {
  4075. return;
  4076. }
  4077. const file = input.files[0];
  4078. if (!String(file.type || '').startsWith('image/') || file.size <= 0) {
  4079. this.voiceDesignError = '图片提示仅支持常见图片格式';
  4080. input.value = '';
  4081. this.refreshView();
  4082. return;
  4083. }
  4084. if (file.size > 10 * 1024 * 1024) {
  4085. this.voiceDesignError = '图片提示大小不能超过 10MB';
  4086. input.value = '';
  4087. this.refreshView();
  4088. return;
  4089. }
  4090. this.voiceDesignImageFile = file;
  4091. this.voiceDesignImageName = file.name;
  4092. this.voiceDesignError = '';
  4093. input.value = '';
  4094. this.refreshView();
  4095. }
  4096. clearVoiceDesignImage(): void {
  4097. this.voiceDesignImageFile = null;
  4098. this.voiceDesignImageName = '';
  4099. this.refreshView();
  4100. }
  4101. setVoiceCreateMode(mode: 'clone' | 'design' | 'synthesize'): void {
  4102. if (this.voiceCreateMode === mode) {
  4103. return;
  4104. }
  4105. this.voiceCreateMode = mode;
  4106. this.voiceDesignError = '';
  4107. if (mode === 'synthesize') {
  4108. this.syncVoiceSynthesisFormSelection();
  4109. }
  4110. this.refreshView();
  4111. }
  4112. private resetVoiceCreateForm(): void {
  4113. this.voiceForm = this.buildDefaultVoiceForm();
  4114. this.voiceSourceAudioFile = null;
  4115. this.voiceSourceAudioName = '';
  4116. this.voiceDesignImageFile = null;
  4117. this.voiceDesignImageName = '';
  4118. }
  4119. getVoiceProfileAudioUrl(profile: VoiceProfile | null | undefined): string {
  4120. if (!profile) {
  4121. return '';
  4122. }
  4123. return String(profile.latest_audio_url || profile.synthesized_audio_url || profile.demo_audio || '').trim();
  4124. }
  4125. canSynthesizeVoiceProfile(profile: VoiceProfile | null | undefined): boolean {
  4126. if (!profile) {
  4127. return false;
  4128. }
  4129. return !!String(profile.icl_speaker_id || profile.speaker_id || '').trim();
  4130. }
  4131. getSynthesisVoiceProfiles(): VoiceProfile[] {
  4132. return this.voiceProfiles.filter((profile) => this.canSynthesizeVoiceProfile(profile));
  4133. }
  4134. getSelectedVoiceSynthesisProfile(): VoiceProfile | null {
  4135. return this.getSynthesisVoiceProfiles().find((profile) => profile.id === this.voiceSynthesisForm.profileId) || null;
  4136. }
  4137. selectVoiceSynthesisProfile(profileId: string): void {
  4138. if (!profileId) {
  4139. this.voiceSynthesisForm = {
  4140. ...this.voiceSynthesisForm,
  4141. profileId: ''
  4142. };
  4143. this.refreshView();
  4144. return;
  4145. }
  4146. const nextProfile = this.voiceProfiles.find((profile) => profile.id === profileId) || null;
  4147. this.voiceSynthesisForm = this.buildVoiceSynthesisFormFromProfile(nextProfile);
  4148. this.refreshView();
  4149. }
  4150. openVoiceSynthesisWorkbench(profile: VoiceProfile): void {
  4151. if (!this.canSynthesizeVoiceProfile(profile)) {
  4152. this.showToast('❌ 当前音色缺少可用于语音合成的 speaker 标识', 'error');
  4153. return;
  4154. }
  4155. this.voiceCreateMode = 'synthesize';
  4156. this.voiceDesignError = '';
  4157. this.voiceSynthesisForm = this.buildVoiceSynthesisFormFromProfile(profile);
  4158. this.refreshView();
  4159. }
  4160. getVoiceProfileAudioLabel(profile: VoiceProfile | null | undefined): string {
  4161. if (!profile) {
  4162. return '暂无可用音频';
  4163. }
  4164. const audioUrl = this.getVoiceProfileAudioUrl(profile);
  4165. if (!audioUrl) {
  4166. return '暂无可用音频';
  4167. }
  4168. if (audioUrl === String(profile.synthesized_audio_url || '')) {
  4169. return '文本合成音频';
  4170. }
  4171. if (audioUrl === String(profile.demo_audio || '')) {
  4172. return '试听音频';
  4173. }
  4174. return '音色音频';
  4175. }
  4176. createVoiceProfile(): void {
  4177. if (this.isCreatingVoiceProfile) {
  4178. return;
  4179. }
  4180. if (this.voiceCreateMode === 'synthesize') {
  4181. this.submitVoiceSynthesisForm();
  4182. return;
  4183. }
  4184. if (this.voiceCreateMode === 'design') {
  4185. this.createVoiceDesignProfile();
  4186. return;
  4187. }
  4188. this.createVoiceCloneProfile();
  4189. }
  4190. private createVoiceCloneProfile(): void {
  4191. const speakerId = this.voiceForm.speakerId.trim();
  4192. const displayName = this.voiceForm.displayName.trim();
  4193. const audioText = this.voiceForm.audioText.trim();
  4194. const sampleText = this.voiceForm.sampleText.trim();
  4195. const synthesisText = this.voiceForm.synthesisText.trim();
  4196. const sourceAudioFile = this.voiceSourceAudioFile;
  4197. if (!displayName) {
  4198. this.voiceDesignError = '请输入音色名称';
  4199. this.refreshView();
  4200. return;
  4201. }
  4202. if (!speakerId) {
  4203. this.voiceDesignError = '请输入音色代号 speaker_id';
  4204. this.refreshView();
  4205. return;
  4206. }
  4207. if (!sourceAudioFile) {
  4208. this.voiceDesignError = '请上传用于复刻的音频样本';
  4209. this.refreshView();
  4210. return;
  4211. }
  4212. if (!sampleText) {
  4213. this.voiceDesignError = '请输入试听文本';
  4214. this.refreshView();
  4215. return;
  4216. }
  4217. if (sampleText.length < 4 || sampleText.length > 80) {
  4218. this.voiceDesignError = '试听文本长度需在 4-80 字之间';
  4219. this.refreshView();
  4220. return;
  4221. }
  4222. this.isCreatingVoiceProfile = true;
  4223. this.voiceDesignError = '';
  4224. const finalizeCloneFlow = (profile: VoiceProfile | null, toastType: 'success' | 'warn', toastMessage: string) => {
  4225. if (profile) {
  4226. profile.draft_synthesis_text = profile.last_synthesis_text || synthesisText;
  4227. this.upsertLocalVoiceProfile(profile);
  4228. this.syncVoiceProfileToBackend(profile);
  4229. if (this.getVoiceProfileAudioUrl(profile)) {
  4230. this.preferredVoiceProfileId = profile.id;
  4231. }
  4232. }
  4233. this.resetVoiceCreateForm();
  4234. this.isCreatingVoiceProfile = false;
  4235. this.showToast(toastMessage, toastType, 5000);
  4236. this.refreshView();
  4237. };
  4238. this.readFileAsBase64(sourceAudioFile).then((audioBase64) => {
  4239. const sourceAudioFormat = this.inferVoiceSourceAudioFormat(sourceAudioFile);
  4240. this.http.post<any>(`${this.voiceTtsBaseUrl}/voice_clone`, {
  4241. token: this.voiceApiToken,
  4242. name: displayName,
  4243. speaker_id: speakerId,
  4244. audioData: {
  4245. base64: audioBase64,
  4246. format: sourceAudioFormat,
  4247. ...(audioText ? { text: audioText } : {})
  4248. },
  4249. language: this.voiceForm.language || 0,
  4250. extra_params: {
  4251. demo_text: sampleText
  4252. }
  4253. }).subscribe({
  4254. next: (res) => {
  4255. const baseProfile: VoiceProfile | null = res?.profile
  4256. ? this.hydrateVoiceProfile(res.profile)
  4257. : this.buildVoiceProfileFromCloneApiResponse(res, {
  4258. displayName,
  4259. speakerId,
  4260. sampleText,
  4261. audioText,
  4262. sourceAudioName: sourceAudioFile.name,
  4263. sourceAudioFormat,
  4264. language: this.voiceForm.language || 0
  4265. });
  4266. if (!synthesisText || !baseProfile) {
  4267. finalizeCloneFlow(
  4268. baseProfile,
  4269. 'success',
  4270. '✅ 音色复刻完成,可在列表中继续合成文本并用于数字人生成'
  4271. );
  4272. return;
  4273. }
  4274. this.http.post<any>(`${this.voiceTtsBaseUrl}/unidirectional`, {
  4275. token: this.voiceApiToken,
  4276. text: synthesisText,
  4277. timbreId: baseProfile.timbre_id || '',
  4278. speaker_id: baseProfile.icl_speaker_id || baseProfile.speaker_id || '',
  4279. isStream: false,
  4280. x_api_resource_id: baseProfile.x_api_resource_id || ''
  4281. }).subscribe({
  4282. next: (synthesisRes) => {
  4283. const nextProfile: VoiceProfile | null = synthesisRes?.profile
  4284. ? this.hydrateVoiceProfile(synthesisRes.profile)
  4285. : this.applySynthesisResponseToProfile(baseProfile, synthesisRes, {
  4286. text: synthesisText,
  4287. ssml: '',
  4288. xApiResourceId: baseProfile.x_api_resource_id || '',
  4289. model: '',
  4290. format: 'mp3',
  4291. sampleRate: 24000,
  4292. speechRate: 0,
  4293. loudnessRate: 0,
  4294. emotion: '',
  4295. emotionScale: 4,
  4296. enableSubtitle: false,
  4297. silenceDuration: 0,
  4298. enableLanguageDetector: false,
  4299. disableMarkdownFilter: false,
  4300. disableEmojiFilter: false,
  4301. explicitLanguage: ''
  4302. });
  4303. finalizeCloneFlow(nextProfile, 'success', '✅ 音色复刻完成,并已生成首条文本音频');
  4304. },
  4305. error: () => {
  4306. finalizeCloneFlow(baseProfile, 'warn', '⚠️ 音色复刻完成,但首条文本合成失败,可稍后重试');
  4307. }
  4308. });
  4309. },
  4310. error: (err) => {
  4311. this.isCreatingVoiceProfile = false;
  4312. this.voiceDesignError = this.getErrorText(err, '音色复刻失败,请检查 token、speaker_id 与音频参数');
  4313. this.showToast(`❌ ${this.voiceDesignError}`, 'error');
  4314. this.refreshView();
  4315. }
  4316. });
  4317. }).catch(() => {
  4318. this.isCreatingVoiceProfile = false;
  4319. this.voiceDesignError = '音频文件读取失败,请重新选择音频样本';
  4320. this.showToast(`❌ ${this.voiceDesignError}`, 'error');
  4321. this.refreshView();
  4322. });
  4323. }
  4324. private createVoiceDesignProfile(): void {
  4325. const speakerId = this.voiceForm.speakerId.trim();
  4326. const displayName = this.voiceForm.displayName.trim();
  4327. const sampleText = this.voiceForm.sampleText.trim();
  4328. const textPrompt = this.voiceForm.textPrompt.trim();
  4329. if (!displayName) {
  4330. this.voiceDesignError = '请输入音色名称';
  4331. this.refreshView();
  4332. return;
  4333. }
  4334. if (!speakerId) {
  4335. this.voiceDesignError = '请输入音色代号 speaker_id';
  4336. this.refreshView();
  4337. return;
  4338. }
  4339. if (!sampleText) {
  4340. this.voiceDesignError = '请输入试听文本';
  4341. this.refreshView();
  4342. return;
  4343. }
  4344. if (sampleText.length > 300) {
  4345. this.voiceDesignError = '试听文本不能超过 300 字';
  4346. this.refreshView();
  4347. return;
  4348. }
  4349. if (textPrompt.length > 200) {
  4350. this.voiceDesignError = '文本提示词不能超过 200 字';
  4351. this.refreshView();
  4352. return;
  4353. }
  4354. if (!textPrompt && !this.voiceDesignImageFile) {
  4355. this.voiceDesignError = '文本提示词与图片提示不能同时为空';
  4356. this.refreshView();
  4357. return;
  4358. }
  4359. this.isCreatingVoiceProfile = true;
  4360. this.voiceDesignError = '';
  4361. const formData = new FormData();
  4362. formData.append('speakerId', speakerId);
  4363. formData.append('displayName', displayName);
  4364. formData.append('sampleText', sampleText);
  4365. formData.append('textPrompt', textPrompt);
  4366. formData.append('language', String(this.voiceForm.language || 0));
  4367. if (this.voiceDesignImageFile) {
  4368. formData.append('image', this.voiceDesignImageFile, this.voiceDesignImageFile.name);
  4369. }
  4370. this.http.post<any>('/backend/api/voice/design', formData).subscribe({
  4371. next: (res) => {
  4372. const profile: VoiceProfile | null = res?.profile
  4373. ? this.hydrateVoiceProfile(res.profile)
  4374. : null;
  4375. if (profile) {
  4376. this.upsertLocalVoiceProfile(profile);
  4377. if (this.getVoiceProfileAudioUrl(profile)) {
  4378. this.preferredVoiceProfileId = profile.id;
  4379. }
  4380. }
  4381. this.resetVoiceCreateForm();
  4382. this.isCreatingVoiceProfile = false;
  4383. this.showToast('✅ 音色设计完成,可直接试听并用于数字人生成', 'success', 5000);
  4384. this.refreshView();
  4385. },
  4386. error: (err) => {
  4387. this.isCreatingVoiceProfile = false;
  4388. this.voiceDesignError = this.getErrorText(err, '音色设计失败,请检查 speaker_id、提示词与图片参数');
  4389. this.showToast(`❌ ${this.voiceDesignError}`, 'error');
  4390. this.refreshView();
  4391. }
  4392. });
  4393. }
  4394. submitVoiceSynthesisForm(): void {
  4395. const profile = this.voiceProfiles.find((item) => item.id === this.voiceSynthesisForm.profileId) || null;
  4396. const manualVoiceId = String(this.voiceSynthesisForm.speakerId || '').trim();
  4397. if (!profile && !manualVoiceId) {
  4398. this.voiceDesignError = '请选择已有音色,或直接输入 timbreId / speaker_id';
  4399. this.refreshView();
  4400. return;
  4401. }
  4402. if (!profile) {
  4403. this.voiceDesignError = '';
  4404. if (this.isVoiceSpeakerIdentifier(manualVoiceId)) {
  4405. this.synthesizeVoiceBySpeakerId(manualVoiceId);
  4406. return;
  4407. }
  4408. const manualProfile = this.hydrateVoiceProfile({
  4409. id: `manual-${manualVoiceId}`,
  4410. name: `手动音色 ${manualVoiceId}`,
  4411. creation_mode: 'manual',
  4412. speaker_id: '',
  4413. timbre_id: manualVoiceId,
  4414. sample_text: '',
  4415. source_audio_text: '',
  4416. source_audio_name: '',
  4417. source_audio_format: '',
  4418. language: 0,
  4419. status: null,
  4420. status_label: '手动输入',
  4421. demo_audio: '',
  4422. x_api_resource_id: String(this.voiceSynthesisForm.xApiResourceId || '').trim(),
  4423. model_version: String(this.voiceSynthesisForm.model || '').trim(),
  4424. icl_speaker_id: '',
  4425. occupied: false,
  4426. created_at: new Date().toISOString(),
  4427. updated_at: new Date().toISOString()
  4428. });
  4429. manualProfile.draft_synthesis_text = this.voiceSynthesisForm.text;
  4430. manualProfile.draft_synthesis_ssml = this.voiceSynthesisForm.ssml;
  4431. manualProfile.draft_synthesis_x_api_resource_id = this.voiceSynthesisForm.xApiResourceId;
  4432. manualProfile.draft_synthesis_model = this.voiceSynthesisForm.model;
  4433. manualProfile.draft_synthesis_format = this.voiceSynthesisForm.format;
  4434. manualProfile.draft_synthesis_sample_rate = this.voiceSynthesisForm.sampleRate;
  4435. manualProfile.draft_synthesis_speech_rate = this.voiceSynthesisForm.speechRate;
  4436. manualProfile.draft_synthesis_loudness_rate = this.voiceSynthesisForm.loudnessRate;
  4437. manualProfile.draft_synthesis_emotion = this.voiceSynthesisForm.emotion;
  4438. manualProfile.draft_synthesis_emotion_scale = this.voiceSynthesisForm.emotionScale;
  4439. manualProfile.draft_synthesis_enable_subtitle = this.voiceSynthesisForm.enableSubtitle;
  4440. manualProfile.draft_synthesis_silence_duration = this.voiceSynthesisForm.silenceDuration;
  4441. manualProfile.draft_synthesis_enable_language_detector = this.voiceSynthesisForm.enableLanguageDetector;
  4442. manualProfile.draft_synthesis_disable_markdown_filter = this.voiceSynthesisForm.disableMarkdownFilter;
  4443. manualProfile.draft_synthesis_disable_emoji_filter = this.voiceSynthesisForm.disableEmojiFilter;
  4444. manualProfile.draft_synthesis_explicit_language = this.voiceSynthesisForm.explicitLanguage;
  4445. this.synthesizeVoiceProfile(manualProfile);
  4446. return;
  4447. }
  4448. this.voiceSynthesisForm.speakerId = String(profile.icl_speaker_id || profile.speaker_id || '').trim();
  4449. profile.draft_synthesis_text = this.voiceSynthesisForm.text;
  4450. profile.draft_synthesis_ssml = this.voiceSynthesisForm.ssml;
  4451. profile.draft_synthesis_x_api_resource_id = this.voiceSynthesisForm.xApiResourceId;
  4452. profile.draft_synthesis_model = this.voiceSynthesisForm.model;
  4453. profile.draft_synthesis_format = this.voiceSynthesisForm.format;
  4454. profile.draft_synthesis_sample_rate = this.voiceSynthesisForm.sampleRate;
  4455. profile.draft_synthesis_speech_rate = this.voiceSynthesisForm.speechRate;
  4456. profile.draft_synthesis_loudness_rate = this.voiceSynthesisForm.loudnessRate;
  4457. profile.draft_synthesis_emotion = this.voiceSynthesisForm.emotion;
  4458. profile.draft_synthesis_emotion_scale = this.voiceSynthesisForm.emotionScale;
  4459. profile.draft_synthesis_enable_subtitle = this.voiceSynthesisForm.enableSubtitle;
  4460. profile.draft_synthesis_silence_duration = this.voiceSynthesisForm.silenceDuration;
  4461. profile.draft_synthesis_enable_language_detector = this.voiceSynthesisForm.enableLanguageDetector;
  4462. profile.draft_synthesis_disable_markdown_filter = this.voiceSynthesisForm.disableMarkdownFilter;
  4463. profile.draft_synthesis_disable_emoji_filter = this.voiceSynthesisForm.disableEmojiFilter;
  4464. profile.draft_synthesis_explicit_language = this.voiceSynthesisForm.explicitLanguage;
  4465. this.voiceDesignError = '';
  4466. this.synthesizeVoiceProfile(profile);
  4467. }
  4468. private synthesizeVoiceBySpeakerId(speakerId: string): void {
  4469. if (this.isDirectVoiceSynthesizing) {
  4470. return;
  4471. }
  4472. const text = String(this.voiceSynthesisForm.text || '').trim();
  4473. const ssml = String(this.voiceSynthesisForm.ssml || '').trim();
  4474. if (!text && !ssml) {
  4475. this.voiceDesignError = '请输入要合成的文本内容或 SSML';
  4476. this.refreshView();
  4477. return;
  4478. }
  4479. const xApiResourceId = String(this.voiceSynthesisForm.xApiResourceId || '').trim();
  4480. const model = String(this.voiceSynthesisForm.model || '').trim();
  4481. const format = this.normalizeVoiceSynthesisFormat(this.voiceSynthesisForm.format);
  4482. const sampleRate = this.normalizeVoiceSynthesisSampleRate(this.voiceSynthesisForm.sampleRate);
  4483. const speechRate = this.clampVoiceSynthesisRate(this.voiceSynthesisForm.speechRate, 0);
  4484. const loudnessRate = this.clampVoiceSynthesisRate(this.voiceSynthesisForm.loudnessRate, 0);
  4485. const emotion = String(this.voiceSynthesisForm.emotion || '').trim();
  4486. const emotionScale = this.clampVoiceSynthesisEmotionScale(this.voiceSynthesisForm.emotionScale, 4);
  4487. const enableSubtitle = !!this.voiceSynthesisForm.enableSubtitle;
  4488. const silenceDuration = this.clampVoiceSynthesisSilenceDuration(this.voiceSynthesisForm.silenceDuration, 0);
  4489. const explicitLanguage = String(this.voiceSynthesisForm.explicitLanguage || '').trim();
  4490. this.voiceSynthesisForm = {
  4491. ...this.voiceSynthesisForm,
  4492. speakerId,
  4493. text,
  4494. ssml,
  4495. xApiResourceId,
  4496. model,
  4497. format,
  4498. sampleRate,
  4499. speechRate,
  4500. loudnessRate,
  4501. emotion,
  4502. emotionScale,
  4503. enableSubtitle,
  4504. silenceDuration,
  4505. explicitLanguage
  4506. };
  4507. this.voiceDesignError = '';
  4508. this.isDirectVoiceSynthesizing = true;
  4509. this.directVoiceSynthesisAudioUrl = '';
  4510. this.directVoiceSynthesisWorkId = '';
  4511. this.directVoiceSynthesisSpeakerId = speakerId;
  4512. this.refreshView();
  4513. this.http.post<any>(`${this.localVoiceTtsBaseUrl}/unidirectional`, {
  4514. token: this.voiceApiToken,
  4515. speaker_id: speakerId,
  4516. text,
  4517. ssml,
  4518. isStream: false,
  4519. x_api_resource_id: xApiResourceId,
  4520. model,
  4521. audio_params: {
  4522. format,
  4523. sample_rate: sampleRate,
  4524. speech_rate: speechRate,
  4525. loudness_rate: loudnessRate,
  4526. emotion,
  4527. emotion_scale: emotionScale,
  4528. enable_subtitle: enableSubtitle
  4529. },
  4530. additions: {
  4531. silence_duration: silenceDuration,
  4532. enable_language_detector: !!this.voiceSynthesisForm.enableLanguageDetector,
  4533. disable_markdown_filter: !!this.voiceSynthesisForm.disableMarkdownFilter,
  4534. disable_emoji_filter: !!this.voiceSynthesisForm.disableEmojiFilter,
  4535. ...(explicitLanguage ? { explicit_language: explicitLanguage } : {})
  4536. }
  4537. }).subscribe({
  4538. next: (res) => {
  4539. this.isDirectVoiceSynthesizing = false;
  4540. this.directVoiceSynthesisAudioUrl = String(res?.data?.audioUrl || '').trim();
  4541. this.directVoiceSynthesisWorkId = String(res?.data?.workId || '').trim();
  4542. this.directVoiceSynthesisSpeakerId = String(res?.speakerId || speakerId).trim();
  4543. if (res?.profile) {
  4544. const nextProfile = this.hydrateVoiceProfile(res.profile);
  4545. this.upsertLocalVoiceProfile(nextProfile);
  4546. this.syncVoiceProfileToBackend(nextProfile);
  4547. } else {
  4548. const matchedProfile = this.voiceProfiles.find((item) => (
  4549. String(item.icl_speaker_id || '').trim() === speakerId
  4550. || String(item.speaker_id || '').trim() === speakerId
  4551. ));
  4552. if (matchedProfile) {
  4553. const nextProfile = this.applySynthesisResponseToProfile(matchedProfile, res, {
  4554. text,
  4555. ssml,
  4556. xApiResourceId,
  4557. model,
  4558. format,
  4559. sampleRate,
  4560. speechRate,
  4561. loudnessRate,
  4562. emotion,
  4563. emotionScale,
  4564. enableSubtitle,
  4565. silenceDuration,
  4566. enableLanguageDetector: !!this.voiceSynthesisForm.enableLanguageDetector,
  4567. disableMarkdownFilter: !!this.voiceSynthesisForm.disableMarkdownFilter,
  4568. disableEmojiFilter: !!this.voiceSynthesisForm.disableEmojiFilter,
  4569. explicitLanguage
  4570. });
  4571. this.upsertLocalVoiceProfile(nextProfile);
  4572. this.syncVoiceProfileToBackend(nextProfile);
  4573. }
  4574. }
  4575. this.showToast(`✅ 已使用 speaker_id「${this.directVoiceSynthesisSpeakerId}」生成语音`, 'success');
  4576. this.refreshView();
  4577. },
  4578. error: (err) => {
  4579. this.isDirectVoiceSynthesizing = false;
  4580. this.voiceDesignError = this.getErrorText(err, '文本合成失败');
  4581. this.showToast(`❌ ${this.voiceDesignError}`, 'error');
  4582. this.refreshView();
  4583. }
  4584. });
  4585. }
  4586. synthesizeVoiceProfile(profile: VoiceProfile): void {
  4587. if (profile.is_synthesizing) {
  4588. return;
  4589. }
  4590. if (!this.canSynthesizeVoiceProfile(profile)) {
  4591. this.showToast('❌ 该音色记录缺少可用于语音合成的 speaker 标识,暂时无法进行文本合成', 'error');
  4592. return;
  4593. }
  4594. const text = String(profile.draft_synthesis_text || '').trim();
  4595. const ssml = String(profile.draft_synthesis_ssml || '').trim();
  4596. if (!text && !ssml) {
  4597. this.showToast('❌ 请输入要合成的文本内容或 SSML', 'error');
  4598. return;
  4599. }
  4600. const xApiResourceId = String(profile.draft_synthesis_x_api_resource_id || profile.x_api_resource_id || '').trim();
  4601. const model = String(profile.draft_synthesis_model || '').trim();
  4602. const format = this.normalizeVoiceSynthesisFormat(profile.draft_synthesis_format);
  4603. const sampleRate = this.normalizeVoiceSynthesisSampleRate(profile.draft_synthesis_sample_rate);
  4604. const speechRate = this.clampVoiceSynthesisRate(profile.draft_synthesis_speech_rate, 0);
  4605. const loudnessRate = this.clampVoiceSynthesisRate(profile.draft_synthesis_loudness_rate, 0);
  4606. const emotion = String(profile.draft_synthesis_emotion || '').trim();
  4607. const emotionScale = this.clampVoiceSynthesisEmotionScale(profile.draft_synthesis_emotion_scale, 4);
  4608. const enableSubtitle = !!profile.draft_synthesis_enable_subtitle;
  4609. const silenceDuration = this.clampVoiceSynthesisSilenceDuration(profile.draft_synthesis_silence_duration, 0);
  4610. const explicitLanguage = String(profile.draft_synthesis_explicit_language || '').trim();
  4611. profile.is_synthesizing = true;
  4612. this.refreshView();
  4613. this.http.post<any>(`${this.voiceTtsBaseUrl}/unidirectional`, {
  4614. token: this.voiceApiToken,
  4615. text,
  4616. ssml,
  4617. timbreId: profile.timbre_id || '',
  4618. speaker_id: profile.icl_speaker_id || profile.speaker_id || '',
  4619. isStream: false,
  4620. x_api_resource_id: xApiResourceId,
  4621. model,
  4622. audio_params: {
  4623. format,
  4624. sample_rate: sampleRate,
  4625. speech_rate: speechRate,
  4626. loudness_rate: loudnessRate,
  4627. emotion,
  4628. emotion_scale: emotionScale,
  4629. enable_subtitle: enableSubtitle
  4630. },
  4631. additions: {
  4632. silence_duration: silenceDuration,
  4633. enable_language_detector: !!profile.draft_synthesis_enable_language_detector,
  4634. disable_markdown_filter: !!profile.draft_synthesis_disable_markdown_filter,
  4635. disable_emoji_filter: !!profile.draft_synthesis_disable_emoji_filter,
  4636. ...(explicitLanguage ? { explicit_language: explicitLanguage } : {})
  4637. }
  4638. }).subscribe({
  4639. next: (res) => {
  4640. const nextProfile = res?.profile
  4641. ? this.hydrateVoiceProfile(res.profile)
  4642. : this.applySynthesisResponseToProfile(profile, res, {
  4643. text,
  4644. ssml,
  4645. xApiResourceId,
  4646. model,
  4647. format,
  4648. sampleRate,
  4649. speechRate,
  4650. loudnessRate,
  4651. emotion,
  4652. emotionScale,
  4653. enableSubtitle,
  4654. silenceDuration,
  4655. enableLanguageDetector: !!profile.draft_synthesis_enable_language_detector,
  4656. disableMarkdownFilter: !!profile.draft_synthesis_disable_markdown_filter,
  4657. disableEmojiFilter: !!profile.draft_synthesis_disable_emoji_filter,
  4658. explicitLanguage
  4659. });
  4660. nextProfile.draft_synthesis_text = text;
  4661. nextProfile.draft_synthesis_ssml = ssml;
  4662. nextProfile.draft_synthesis_x_api_resource_id = xApiResourceId;
  4663. nextProfile.draft_synthesis_model = model;
  4664. nextProfile.draft_synthesis_format = format;
  4665. nextProfile.draft_synthesis_sample_rate = sampleRate;
  4666. nextProfile.draft_synthesis_speech_rate = speechRate;
  4667. nextProfile.draft_synthesis_loudness_rate = loudnessRate;
  4668. nextProfile.draft_synthesis_emotion = emotion;
  4669. nextProfile.draft_synthesis_emotion_scale = emotionScale;
  4670. nextProfile.draft_synthesis_enable_subtitle = enableSubtitle;
  4671. nextProfile.draft_synthesis_silence_duration = silenceDuration;
  4672. nextProfile.draft_synthesis_enable_language_detector = !!profile.draft_synthesis_enable_language_detector;
  4673. nextProfile.draft_synthesis_disable_markdown_filter = !!profile.draft_synthesis_disable_markdown_filter;
  4674. nextProfile.draft_synthesis_disable_emoji_filter = !!profile.draft_synthesis_disable_emoji_filter;
  4675. nextProfile.draft_synthesis_explicit_language = explicitLanguage;
  4676. this.upsertLocalVoiceProfile(nextProfile);
  4677. this.syncVoiceProfileToBackend(nextProfile);
  4678. if (this.voiceSynthesisForm.profileId === nextProfile.id) {
  4679. this.voiceSynthesisForm = this.buildVoiceSynthesisFormFromProfile(nextProfile);
  4680. }
  4681. if (this.getVoiceProfileAudioUrl(nextProfile)) {
  4682. this.preferredVoiceProfileId = nextProfile.id;
  4683. }
  4684. this.showToast(`✅ 已为「${nextProfile.name}」生成文本音频`, 'success');
  4685. this.refreshView();
  4686. },
  4687. error: (err) => {
  4688. profile.is_synthesizing = false;
  4689. this.showToast(`❌ ${this.getErrorText(err, '文本合成失败')}`, 'error');
  4690. this.refreshView();
  4691. }
  4692. });
  4693. }
  4694. removeVoiceProfile(profile: VoiceProfile): void {
  4695. if (!confirm(`确定要删除音色「${profile.name}」吗?`)) {
  4696. return;
  4697. }
  4698. this.http.delete<any>(`/backend/voice-profiles/${profile.id}`).subscribe({
  4699. next: () => {
  4700. this.voiceProfiles = this.voiceProfiles.filter(item => item.id !== profile.id);
  4701. this.syncVoiceSynthesisFormSelection();
  4702. if (this.preferredVoiceProfileId === profile.id) {
  4703. this.preferredVoiceProfileId = '';
  4704. }
  4705. this.showToast(`🗑️ 已删除音色「${profile.name}」`, 'success');
  4706. this.refreshView();
  4707. },
  4708. error: (err) => {
  4709. this.showToast(`❌ ${this.getErrorText(err, '删除音色失败')}`, 'error');
  4710. }
  4711. });
  4712. }
  4713. onRemixDigitalHumanImageSelected(event: Event): void {
  4714. const input = event.target as HTMLInputElement;
  4715. if (!input.files || input.files.length === 0) {
  4716. return;
  4717. }
  4718. const file = input.files[0];
  4719. const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'];
  4720. const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  4721. const allowedExts = ['.jpg', '.jpeg', '.png', '.gif'];
  4722. if ((!allowedTypes.includes(file.type) && !allowedExts.includes(ext)) || file.size <= 0) {
  4723. this.remixDigitalHumanError = '仅支持 jpg、jpeg、png、gif 格式的形象图';
  4724. input.value = '';
  4725. this.refreshView();
  4726. return;
  4727. }
  4728. if (file.size > 20 * 1024 * 1024) {
  4729. this.remixDigitalHumanError = '形象图大小不能超过 20MB';
  4730. input.value = '';
  4731. this.refreshView();
  4732. return;
  4733. }
  4734. this.revokeDigitalHumanPreviewUrl();
  4735. this.remixDigitalHumanImageFile = file;
  4736. this.remixDigitalHumanImageName = file.name;
  4737. this.remixDigitalHumanImagePreviewUrl = URL.createObjectURL(file);
  4738. this.remixDigitalHumanImageAssetUrl = '';
  4739. this.remixDigitalHumanError = '';
  4740. input.value = '';
  4741. this.refreshView();
  4742. }
  4743. clearRemixDigitalHumanImage(): void {
  4744. this.revokeDigitalHumanPreviewUrl();
  4745. this.remixDigitalHumanImageFile = null;
  4746. this.remixDigitalHumanImageName = '';
  4747. this.remixDigitalHumanImageAssetUrl = '';
  4748. this.remixDigitalHumanError = '';
  4749. this.refreshView();
  4750. }
  4751. goToRemixGenerationConfig(): void {
  4752. if (this.remixMode === 'digital-human') {
  4753. if (!this.remixDigitalHumanImageFile) {
  4754. this.remixDigitalHumanError = '请先上传数字人形象图';
  4755. this.refreshView();
  4756. return;
  4757. }
  4758. if (this.remixPortraitPipelineRunning) {
  4759. this.remixDigitalHumanError = '形象图正在生成中,请稍候...';
  4760. this.refreshView();
  4761. return;
  4762. }
  4763. if (this.remixPortraitPrepareMode !== 'raw' && !this.remixGeneratedPortraitUrl) {
  4764. this.remixDigitalHumanError = '请先点击「生成形象图」完成 AI 处理,或切换到「直接使用上传图」';
  4765. this.refreshView();
  4766. return;
  4767. }
  4768. this.remixDigitalHumanError = '';
  4769. this.remixStep = 4;
  4770. this.refreshView();
  4771. return;
  4772. }
  4773. this.confirmTranscript();
  4774. }
  4775. private revokeDigitalHumanPreviewUrl(): void {
  4776. if (this.remixDigitalHumanImagePreviewUrl) {
  4777. URL.revokeObjectURL(this.remixDigitalHumanImagePreviewUrl);
  4778. this.remixDigitalHumanImagePreviewUrl = '';
  4779. }
  4780. }
  4781. private resetDigitalHumanState(): void {
  4782. this.revokeDigitalHumanPreviewUrl();
  4783. this.remixDigitalHumanImageFile = null;
  4784. this.remixDigitalHumanImageName = '';
  4785. this.remixDigitalHumanImageAssetUrl = '';
  4786. this.remixDigitalHumanPrompt = '';
  4787. this.remixDigitalHumanFastMode = false;
  4788. this.remixDigitalHumanResolution = '1080p';
  4789. this.remixDigitalHumanError = '';
  4790. this.remixDigitalHumanAudioSource = 'tts';
  4791. this.remixDigitalHumanTtsText = '';
  4792. this.remixDigitalHumanTtsTimbreId = '';
  4793. this.remixDigitalHumanTtsSynthesizing = false;
  4794. this.resetPortraitPipelineState();
  4795. }
  4796. // ===== 数字人形象准备:自拍优化 / 对标重塑 =====
  4797. setRemixPortraitPrepareMode(mode: 'raw' | 'normalize' | 'benchmark'): void {
  4798. if (this.remixPortraitPipelineRunning) {
  4799. return;
  4800. }
  4801. this.remixPortraitPrepareMode = mode;
  4802. // 切换模式时清空已生成结果,避免误用
  4803. this.remixGeneratedPortraitUrl = '';
  4804. this.remixGeneratedFullBodyUrl = '';
  4805. this.remixGeneratedBenchmarkSummary = '';
  4806. this.remixPortraitPipelineError = '';
  4807. this.remixPortraitPipelineStatus = '';
  4808. this.remixPortraitPipelineProgress = 0;
  4809. if (mode !== 'benchmark') {
  4810. this.clearRemixBenchmarkImage();
  4811. }
  4812. this.refreshView();
  4813. }
  4814. onRemixBenchmarkImageSelected(event: Event): void {
  4815. const input = event.target as HTMLInputElement;
  4816. if (!input.files || input.files.length === 0) {
  4817. return;
  4818. }
  4819. const file = input.files[0];
  4820. const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif', 'image/webp'];
  4821. const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  4822. const allowedExts = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
  4823. if ((!allowedTypes.includes(file.type) && !allowedExts.includes(ext)) || file.size <= 0) {
  4824. this.remixPortraitPipelineError = '对标场景图仅支持 jpg、jpeg、png、gif、webp 格式';
  4825. input.value = '';
  4826. this.refreshView();
  4827. return;
  4828. }
  4829. if (file.size > 20 * 1024 * 1024) {
  4830. this.remixPortraitPipelineError = '对标场景图大小不能超过 20MB';
  4831. input.value = '';
  4832. this.refreshView();
  4833. return;
  4834. }
  4835. this.revokeBenchmarkPreviewUrl();
  4836. this.remixBenchmarkImageFile = file;
  4837. this.remixBenchmarkImageName = file.name;
  4838. this.remixBenchmarkImagePreviewUrl = URL.createObjectURL(file);
  4839. this.remixPortraitPipelineError = '';
  4840. this.remixGeneratedPortraitUrl = '';
  4841. input.value = '';
  4842. this.refreshView();
  4843. }
  4844. clearRemixBenchmarkImage(): void {
  4845. this.revokeBenchmarkPreviewUrl();
  4846. this.remixBenchmarkImageFile = null;
  4847. this.remixBenchmarkImageName = '';
  4848. this.refreshView();
  4849. }
  4850. private revokeBenchmarkPreviewUrl(): void {
  4851. if (this.remixBenchmarkImagePreviewUrl) {
  4852. URL.revokeObjectURL(this.remixBenchmarkImagePreviewUrl);
  4853. this.remixBenchmarkImagePreviewUrl = '';
  4854. }
  4855. }
  4856. private resetPortraitPipelineState(): void {
  4857. this.remixPortraitPrepareMode = 'raw';
  4858. this.revokeBenchmarkPreviewUrl();
  4859. this.remixBenchmarkImageFile = null;
  4860. this.remixBenchmarkImageName = '';
  4861. this.remixPortraitPipelineRunning = false;
  4862. this.remixPortraitPipelineStatus = '';
  4863. this.remixPortraitPipelineProgress = 0;
  4864. this.remixPortraitPipelineError = '';
  4865. this.remixGeneratedPortraitUrl = '';
  4866. this.remixGeneratedFullBodyUrl = '';
  4867. this.remixGeneratedBenchmarkSummary = '';
  4868. }
  4869. /**
  4870. * 一键执行形象准备链路:
  4871. * - normalize: 仅 Step1 自拍 → 正面全身图
  4872. * - benchmark: Step1 + Step2 + Step3 对标重塑
  4873. */
  4874. runPortraitPipeline(): void {
  4875. if (this.remixPortraitPipelineRunning) {
  4876. return;
  4877. }
  4878. if (!this.remixDigitalHumanImageFile) {
  4879. this.remixPortraitPipelineError = '请先上传人物自拍/形象图';
  4880. this.refreshView();
  4881. return;
  4882. }
  4883. if (this.remixPortraitPrepareMode === 'benchmark' && !this.remixBenchmarkImageFile) {
  4884. this.remixPortraitPipelineError = '请上传一张对标账号的场景图';
  4885. this.refreshView();
  4886. return;
  4887. }
  4888. this.remixPortraitPipelineRunning = true;
  4889. this.remixPortraitPipelineError = '';
  4890. this.remixPortraitPipelineProgress = 0;
  4891. this.remixPortraitPipelineStatus = '正在上传素材...';
  4892. this.refreshView();
  4893. const selfieFile = this.remixDigitalHumanImageFile;
  4894. const benchmarkFile = this.remixPortraitPrepareMode === 'benchmark' ? this.remixBenchmarkImageFile : null;
  4895. // 1) 上传自拍 → URL
  4896. this.jimengService.uploadFileToParse(
  4897. selfieFile,
  4898. `portrait-selfie-${Date.now()}-${selfieFile.name}`,
  4899. selfieFile.type || 'image/jpeg'
  4900. ).subscribe({
  4901. next: (selfieUrl: string) => {
  4902. // 2) 如需对标,先上传对标图
  4903. const benchmarkUpload$ = benchmarkFile
  4904. ? this.jimengService.uploadFileToParse(
  4905. benchmarkFile,
  4906. `portrait-benchmark-${Date.now()}-${benchmarkFile.name}`,
  4907. benchmarkFile.type || 'image/jpeg'
  4908. )
  4909. : null;
  4910. const next = (benchmarkUrl: string | null) => {
  4911. this.portraitPipeline.buildBenchmarkedPortrait(selfieUrl, benchmarkUrl, (status, progress) => {
  4912. this.ngZone.run(() => {
  4913. this.remixPortraitPipelineStatus = status;
  4914. this.remixPortraitPipelineProgress = Math.round(progress);
  4915. this.refreshView();
  4916. });
  4917. }).subscribe({
  4918. next: (result: PortraitPipelineResult) => {
  4919. this.ngZone.run(() => {
  4920. this.remixGeneratedFullBodyUrl = result.fullBodyUrl;
  4921. this.remixGeneratedPortraitUrl = result.finalPortraitUrl;
  4922. this.remixGeneratedBenchmarkSummary = result.benchmarkPrompt?.merged || '';
  4923. this.remixPortraitPipelineRunning = false;
  4924. this.remixPortraitPipelineStatus = '形象图生成完成';
  4925. this.remixPortraitPipelineProgress = 100;
  4926. this.showToast('✅ 形象图生成完成,可继续配置数字人参数', 'success');
  4927. this.refreshView();
  4928. });
  4929. },
  4930. error: (err) => {
  4931. this.ngZone.run(() => {
  4932. this.remixPortraitPipelineRunning = false;
  4933. this.remixPortraitPipelineError = this.getErrorText(err, '形象图生成失败');
  4934. this.showToast(`❌ ${this.remixPortraitPipelineError}`, 'error');
  4935. this.refreshView();
  4936. });
  4937. }
  4938. });
  4939. };
  4940. if (benchmarkUpload$) {
  4941. benchmarkUpload$.subscribe({
  4942. next: (benchmarkUrl: string) => next(benchmarkUrl),
  4943. error: (err) => {
  4944. this.ngZone.run(() => {
  4945. this.remixPortraitPipelineRunning = false;
  4946. this.remixPortraitPipelineError = this.getErrorText(err, '对标场景图上传失败');
  4947. this.showToast(`❌ ${this.remixPortraitPipelineError}`, 'error');
  4948. this.refreshView();
  4949. });
  4950. }
  4951. });
  4952. } else {
  4953. next(null);
  4954. }
  4955. },
  4956. error: (err) => {
  4957. this.ngZone.run(() => {
  4958. this.remixPortraitPipelineRunning = false;
  4959. this.remixPortraitPipelineError = this.getErrorText(err, '形象图上传失败');
  4960. this.showToast(`❌ ${this.remixPortraitPipelineError}`, 'error');
  4961. this.refreshView();
  4962. });
  4963. }
  4964. });
  4965. }
  4966. resetGeneratedPortrait(): void {
  4967. if (this.remixPortraitPipelineRunning) {
  4968. return;
  4969. }
  4970. this.remixGeneratedPortraitUrl = '';
  4971. this.remixGeneratedFullBodyUrl = '';
  4972. this.remixGeneratedBenchmarkSummary = '';
  4973. this.remixPortraitPipelineStatus = '';
  4974. this.remixPortraitPipelineProgress = 0;
  4975. this.remixPortraitPipelineError = '';
  4976. this.refreshView();
  4977. }
  4978. // ===== 数字人共享表单:选项与回调(用于 <app-digital-human-form>)=====
  4979. get remixTimbreOptions(): TimbreOption[] {
  4980. return (this.vsClonedTimbreList || []).map(t => ({
  4981. id: t.objectId,
  4982. name: t.name || t.objectId
  4983. }));
  4984. }
  4985. readonly digitalHumanPromptPresets: PromptPreset[] = [
  4986. { label: '专业播报', value: '以新闻主播的语气朗读,吐字清晰、节奏稳定、表情自信端正。' },
  4987. { label: '亲切自然', value: '用朋友聊天的语气,亲切自然、面带微笑,语速适中略带轻松感。' },
  4988. { label: '科技感', value: '冷静理性的科技感口吻,节奏明快、抑扬有度,强调数据与关键词。' },
  4989. { label: '激情澎湃', value: '激情澎湃的演说家口吻,情感饱满、节奏起伏明显、富有感染力。' },
  4990. { label: '温柔治愈', value: '温柔轻缓的语气,气息柔和、节奏放慢,适合情感与生活类内容。' },
  4991. { label: '正式商务', value: '商务正式风格,语调克制、用词严谨,仪态端庄,适合企业宣传场景。' },
  4992. ];
  4993. /**
  4994. * 视频重塑里:<app-digital-human-form> 的 (request) 事件入口。
  4995. * 接管 startDigitalHumanGeneration 的全部任务管理逻辑,
  4996. * 内部链路改用 DigitalHumanService 编排执行。
  4997. */
  4998. onRemixDhRequest(req: DigitalHumanRequest): void {
  4999. const video = this.remixTargetVideo;
  5000. if (!video || this.isRemixSubmitting) {
  5001. return;
  5002. }
  5003. // 原视频音频时长校验(保留旧约束)
  5004. if (req.audio.source === 'original') {
  5005. const safeDuration = Number(video.duration || 0);
  5006. if (safeDuration > 60) {
  5007. this.remixDigitalHumanError = '原视频音频时长超过 60 秒,当前数字人接口不支持';
  5008. this.showToast(`❌ ${this.remixDigitalHumanError}`, 'error');
  5009. this.refreshView();
  5010. return;
  5011. }
  5012. }
  5013. // 同步音频来源到旧字段,让 step 5/6 已有 UI 仍能显示
  5014. this.remixDigitalHumanAudioSource = req.audio.source === 'tts' ? 'tts' : 'original';
  5015. this.remixDigitalHumanResolution = req.resolution || '1080p';
  5016. this.remixDigitalHumanFastMode = !!req.fastMode;
  5017. this.remixDigitalHumanPrompt = req.prompt || '';
  5018. if (req.audio.source === 'tts') {
  5019. this.remixDigitalHumanTtsText = req.audio.ttsText || '';
  5020. this.remixDigitalHumanTtsTimbreId = req.audio.ttsTimbreId || '';
  5021. }
  5022. // 注入原视频 ID(form 没有这个字段,由父组件补齐)
  5023. if (req.audio.source === 'original' && !req.audio.videoId) {
  5024. req.audio.videoId = video.id;
  5025. }
  5026. if (req.audio.source === 'original') {
  5027. req.audio.videoUrl = this.getVideoPlayUrl(video);
  5028. }
  5029. const styleName = '数字人生成';
  5030. this.isRemixSubmitting = true;
  5031. this.remixStep = 5;
  5032. video.isRemixing = true;
  5033. video.remixProgress = 0;
  5034. video.remixStyle = styleName;
  5035. this.remixResults = { total: 1, success: 0, failed: 0 };
  5036. this.remixStatusText = '正在准备数字人素材...';
  5037. this.remixStitchStatus = 'idle';
  5038. this.remixStitchError = '';
  5039. this.remixFinalVideoUrl = '';
  5040. this.currentRemixId = `REMIX-${Date.now()}`;
  5041. const newTask: Task = {
  5042. id: `TASK-${Date.now()}`,
  5043. keyword: `${video.title} - ${styleName}`,
  5044. status: 'processing',
  5045. step: 'generate',
  5046. progress: 0,
  5047. cost: 0,
  5048. created_at: new Date(),
  5049. updated_at: new Date(),
  5050. original_video_title: video.title,
  5051. duration: '数字人视频'
  5052. };
  5053. this.activeTasks.unshift(newTask);
  5054. this.currentRemixTaskId = newTask.id;
  5055. this.saveTask(newTask);
  5056. this.showToast('数字人任务已提交,可在「任务管理」中查看进度', 'success');
  5057. this.showRemixModal = false;
  5058. this.digitalHumanService.generate(req).subscribe({
  5059. next: (evt: DigitalHumanEvent) => {
  5060. this.ngZone.run(() => {
  5061. if (evt.type === 'progress') {
  5062. video.remixProgress = evt.progress;
  5063. this.remixStatusText = evt.status;
  5064. this.updateRemixTaskProgress('generate', evt.progress);
  5065. this.refreshView();
  5066. } else {
  5067. // result
  5068. video.remixProgress = 100;
  5069. this.remixResults.success = 1;
  5070. this.remixFinalVideoUrl = evt.videoUrl;
  5071. this.remixStatusText = '数字人视频生成完成';
  5072. this.remixDigitalHumanImageAssetUrl = evt.imageUrl;
  5073. this.createDigitalHumanVersion(video, evt.videoUrl);
  5074. this.completeRemixTask('completed', evt.videoUrl);
  5075. this.saveRemixSession('completed');
  5076. video.isRemixing = false;
  5077. this.isRemixSubmitting = false;
  5078. this.remixStep = 6;
  5079. this.showToast(`✅ 数字人视频已生成:${video.title}`, 'success', 6000);
  5080. this.refreshView();
  5081. }
  5082. });
  5083. },
  5084. error: (err: any) => {
  5085. this.ngZone.run(() => {
  5086. this.handleDigitalHumanGenerationError(video, this.getErrorText(err, '数字人生成失败'));
  5087. });
  5088. }
  5089. });
  5090. }
  5091. // 加载该视频关联的 Whisper 处理文件(通过后端读取)
  5092. loadWhisperFiles(video: ManagedVideo): void {
  5093. if (!video.whisper) {
  5094. console.log('ℹ️ 该视频无 Whisper 转录数据,跳过自动加载');
  5095. return;
  5096. }
  5097. const w = video.whisper;
  5098. // 优先加载美化文字稿,其次原始转录
  5099. const transcriptPath = w.beautified || w.transcript;
  5100. if (transcriptPath) {
  5101. this.http.get(`/backend/files/read`, { params: { path: transcriptPath }, responseType: 'text' }).subscribe({
  5102. next: (text) => {
  5103. this.remixTranscript = text;
  5104. if (w.beautified) this.remixBeautifiedTranscript = text;
  5105. console.log(`📄 已加载 Whisper 文字稿: ${transcriptPath}`);
  5106. },
  5107. error: () => console.log(`⚠️ 未能加载文字稿: ${transcriptPath}`)
  5108. });
  5109. }
  5110. // 加载分镜脚本
  5111. if (w.storyboard) {
  5112. this.http.get<any>(`/backend/files/read`, { params: { path: w.storyboard } }).subscribe({
  5113. next: (data: any) => {
  5114. if (Array.isArray(data)) {
  5115. this.remixStoryboard = data.map((seg: any) => ({
  5116. id: seg.id,
  5117. act: seg.act,
  5118. narration: seg.narration,
  5119. prompt: seg.prompt,
  5120. duration: seg.duration,
  5121. status: 'pending' as const
  5122. }));
  5123. console.log(`📝 已加载分镜脚本: ${this.remixStoryboard.length} 个片段`);
  5124. }
  5125. },
  5126. error: () => console.log(`⚠️ 未能加载分镜脚本: ${w.storyboard}`)
  5127. });
  5128. }
  5129. }
  5130. // 下一步
  5131. nextRemixStep(): void {
  5132. if (this.remixStep < 6) this.remixStep++;
  5133. }
  5134. // 上一步
  5135. prevRemixStep(): void {
  5136. if (this.remixStep > 1 && !this.isRemixSubmitting) this.remixStep--;
  5137. }
  5138. // 使用 Whisper 生成文字稿(通过本地后端)
  5139. generateTranscript(): void {
  5140. if (!this.remixTargetVideo || this.isWhisperRunning) return;
  5141. const video = this.remixTargetVideo;
  5142. this.isWhisperRunning = true;
  5143. this.whisperStatusText = '正在检查 Whisper 服务...';
  5144. // 先检查后端是否可用
  5145. this.http.get<any>('/backend/api/health').subscribe({
  5146. next: () => {
  5147. // 后端可用,调用 Whisper 转录
  5148. this.whisperStatusText = '正在调用 Whisper 语音识别,视频较长时可能需要数分钟...';
  5149. this.http.post<any>('/backend/api/whisper/transcribe', {
  5150. videoId: video.id,
  5151. language: 'Chinese',
  5152. model: 'base'
  5153. }).subscribe({
  5154. next: (res: any) => {
  5155. if (res?.success && res?.transcript) {
  5156. this.remixTranscript = res.transcript;
  5157. this.whisperStatusText = '✅ 识别完成!';
  5158. this.isWhisperRunning = false;
  5159. // 后端已自动更新 manifest,同步前端的 whisper 字段
  5160. if (res.whisper) {
  5161. video.whisper = res.whisper;
  5162. }
  5163. console.log('✅ Whisper 转录完成,manifest 已更新');
  5164. } else {
  5165. this.whisperStatusText = '识别完成但未返回文字稿';
  5166. this.isWhisperRunning = false;
  5167. this.showManualTranscriptInput = true;
  5168. }
  5169. },
  5170. error: (err) => {
  5171. console.error('Whisper 转录失败:', err);
  5172. const msg = err?.error?.error || err?.error?.hint || '转录过程出错';
  5173. this.whisperStatusText = `❌ ${msg}`;
  5174. this.isWhisperRunning = false;
  5175. this.showManualTranscriptInput = true;
  5176. }
  5177. });
  5178. },
  5179. error: () => {
  5180. // 后端不可用,降级为手动方案
  5181. this.onWhisperFallback(video);
  5182. }
  5183. });
  5184. }
  5185. // 后端不可用时的降级方案
  5186. private onWhisperFallback(video: ManagedVideo): void {
  5187. this.isWhisperRunning = false;
  5188. this.whisperStatusText = '';
  5189. const cmd = `whisper "data/videos/${video.filename}" --model base --language Chinese --output_dir "Whisper"`;
  5190. navigator.clipboard.writeText(cmd).then(() => {
  5191. alert(
  5192. `后端服务未启动。请先在终端运行:\n\nnpm run server\n\n` +
  5193. `或手动执行 Whisper 命令(已复制到剪贴板):\n\n${cmd}`
  5194. );
  5195. }).catch(() => {
  5196. alert(`后端服务未启动。请先运行 npm run server,或手动执行:\n\n${cmd}`);
  5197. });
  5198. this.showManualTranscriptInput = true;
  5199. }
  5200. // Step 1 → 2: 确认文字稿,进入AI美化
  5201. confirmTranscript(): void {
  5202. if (!this.remixTranscript.trim()) return;
  5203. this.remixStep = 2;
  5204. // 自动执行AI美化
  5205. this.beautifyTranscript();
  5206. }
  5207. // Step 2: AI美化文字稿(当前为本地处理,后续可接入LLM API)
  5208. beautifyTranscript(): void {
  5209. let text = this.remixTranscript;
  5210. // 去除口语化词汇
  5211. const fillerWords = ['嗯', '啊', '呢', '吧', '哦', '额', '那个', '就是说', '然后呢', '对吧'];
  5212. fillerWords.forEach(w => { text = text.replace(new RegExp(w, 'g'), ''); });
  5213. // 去除多余空格和空行
  5214. text = text.replace(/\s+/g, ' ').trim();
  5215. // 按句号/问号/感叹号分句,重新组织段落
  5216. const sentences = text.split(/(?<=[。!?.!?])/g).filter(s => s.trim());
  5217. const paragraphs: string[] = [];
  5218. let current = '';
  5219. sentences.forEach(s => {
  5220. current += s.trim();
  5221. if (current.length >= 60) {
  5222. paragraphs.push(current);
  5223. current = '';
  5224. }
  5225. });
  5226. if (current) paragraphs.push(current);
  5227. this.remixBeautifiedTranscript = paragraphs.join('\n\n');
  5228. if (!this.remixBeautifiedTranscript.trim()) {
  5229. this.remixBeautifiedTranscript = this.remixTranscript;
  5230. }
  5231. }
  5232. // Step 2 → 3: 确认美化文字稿,生成分镜脚本
  5233. confirmBeautified(): void {
  5234. if (!this.remixBeautifiedTranscript.trim()) return;
  5235. this.generateStoryboard();
  5236. this.remixStep = 3;
  5237. }
  5238. // Step 3: 根据美化文字稿生成分镜脚本(参考SKILL.md Stage 1)
  5239. generateStoryboard(): void {
  5240. const text = this.remixBeautifiedTranscript;
  5241. // 按约40-45个中文字(≈15秒语速)拆分为分镜段
  5242. const segmentCharLen = 42;
  5243. const segments: StoryboardSegment[] = [];
  5244. // 优先按段落分割
  5245. const paragraphs = text.split(/\n+/).filter(p => p.trim());
  5246. let charBuffer = '';
  5247. let segIndex = 0;
  5248. const pushSegment = (narration: string) => {
  5249. segIndex++;
  5250. const id = `S-${String(segIndex).padStart(2, '0')}`;
  5251. const act = segIndex === 1 ? '开场' : (segIndex <= 3 ? '引入' : '正文');
  5252. const stylePrompt = this.remixStyleOptions.find(s => s.id === this.remixStyle)?.prompt || '';
  5253. // 生成英文提示词:风格 + 场景描述
  5254. const prompt = `${stylePrompt}, cinematic scene depicting: ${narration.substring(0, 80)}`;
  5255. segments.push({
  5256. id,
  5257. act,
  5258. narration: narration.trim(),
  5259. prompt,
  5260. duration: this.remixFrames === 121 ? '5s' : '10s',
  5261. status: 'pending'
  5262. });
  5263. };
  5264. paragraphs.forEach(para => {
  5265. charBuffer += para;
  5266. while (charBuffer.length >= segmentCharLen) {
  5267. // 尝试在句子边界切割
  5268. let cutPos = segmentCharLen;
  5269. const searchRange = charBuffer.substring(0, segmentCharLen + 15);
  5270. const punctPos = Math.max(
  5271. searchRange.lastIndexOf('。'),
  5272. searchRange.lastIndexOf('!'),
  5273. searchRange.lastIndexOf('?'),
  5274. searchRange.lastIndexOf(','),
  5275. searchRange.lastIndexOf(';')
  5276. );
  5277. if (punctPos > segmentCharLen * 0.5) cutPos = punctPos + 1;
  5278. pushSegment(charBuffer.substring(0, cutPos));
  5279. charBuffer = charBuffer.substring(cutPos);
  5280. }
  5281. });
  5282. // 剩余部分
  5283. if (charBuffer.trim().length > 0) {
  5284. pushSegment(charBuffer);
  5285. }
  5286. this.remixStoryboard = segments;
  5287. console.log(`📝 分镜脚本生成完毕:${segments.length} 个片段`);
  5288. }
  5289. // Step 3 → 4: 确认分镜,进入参数配置
  5290. confirmStoryboard(): void {
  5291. if (this.remixStoryboard.length === 0) return;
  5292. this.remixStep = 4;
  5293. }
  5294. // Step 4 → 5: 开始批量生成
  5295. startBatchGeneration(): void {
  5296. if (this.isRemixSubmitting) return;
  5297. if (this.remixMode === 'digital-human') {
  5298. this.startDigitalHumanGeneration();
  5299. return;
  5300. }
  5301. if (this.remixStoryboard.length === 0) return;
  5302. const video = this.remixTargetVideo!;
  5303. const styleName = this.remixStyleOptions.find(s => s.id === this.remixStyle)?.name || this.remixStyle;
  5304. this.isRemixSubmitting = true;
  5305. this.remixStep = 5;
  5306. video.isRemixing = true;
  5307. video.remixProgress = 0;
  5308. video.remixStyle = styleName;
  5309. this.remixResults = { total: this.remixStoryboard.length, success: 0, failed: 0 };
  5310. this.remixStatusText = '正在提交生成任务...';
  5311. this.currentRemixId = `REMIX-${Date.now()}`;
  5312. // 创建持久化任务
  5313. const newTask: Task = {
  5314. id: `TASK-${Date.now()}`,
  5315. keyword: `${video.title} - ${styleName}`,
  5316. status: 'processing',
  5317. step: 'generate',
  5318. progress: 0,
  5319. cost: 0,
  5320. created_at: new Date(),
  5321. updated_at: new Date(),
  5322. original_video_title: video.title,
  5323. duration: `${this.remixStoryboard.length} 个片段`
  5324. };
  5325. this.activeTasks.unshift(newTask);
  5326. this.currentRemixTaskId = newTask.id;
  5327. this.saveTask(newTask);
  5328. // 显示 toast 并关闭模态框
  5329. this.showToast(`任务已提交,可在「任务管理」中查看进度`, 'success');
  5330. this.showRemixModal = false;
  5331. console.log(`🎨 开始批量生成 ${this.remixStoryboard.length} 个分镜视频, 任务ID: ${newTask.id}`);
  5332. // 逐个提交(串行,避免频率限制)
  5333. this.generateSegmentSequentially(0, video, styleName);
  5334. }
  5335. private startDigitalHumanGeneration(): void {
  5336. if (!this.remixTargetVideo || !this.remixDigitalHumanImageFile || this.isRemixSubmitting) {
  5337. return;
  5338. }
  5339. const video = this.remixTargetVideo;
  5340. const isTtsMode = this.remixDigitalHumanAudioSource === 'tts';
  5341. if (!isTtsMode) {
  5342. const safeDuration = Number(video.duration || 0);
  5343. if (safeDuration > 60) {
  5344. this.remixDigitalHumanError = '原视频音频时长超过 60 秒,当前数字人接口不支持';
  5345. this.showToast(`❌ ${this.remixDigitalHumanError}`, 'error');
  5346. this.refreshView();
  5347. return;
  5348. }
  5349. }
  5350. if (isTtsMode) {
  5351. if (!this.remixDigitalHumanTtsTimbreId.trim()) {
  5352. this.remixDigitalHumanError = '请输入或选择音色 ID(可在「语音合成」标签页中复刻获取)';
  5353. this.refreshView();
  5354. return;
  5355. }
  5356. if (!this.remixDigitalHumanTtsText.trim()) {
  5357. this.remixDigitalHumanError = '请输入要合成的语音文本';
  5358. this.refreshView();
  5359. return;
  5360. }
  5361. }
  5362. const styleName = '数字人生成';
  5363. this.isRemixSubmitting = true;
  5364. this.remixStep = 5;
  5365. video.isRemixing = true;
  5366. video.remixProgress = 0;
  5367. video.remixStyle = styleName;
  5368. this.remixResults = { total: 1, success: 0, failed: 0 };
  5369. this.remixStatusText = '正在准备数字人素材...';
  5370. this.remixStitchStatus = 'idle';
  5371. this.remixStitchError = '';
  5372. this.remixFinalVideoUrl = '';
  5373. this.currentRemixId = `REMIX-${Date.now()}`;
  5374. const newTask: Task = {
  5375. id: `TASK-${Date.now()}`,
  5376. keyword: `${video.title} - ${styleName}`,
  5377. status: 'processing',
  5378. step: 'generate',
  5379. progress: 0,
  5380. cost: 0,
  5381. created_at: new Date(),
  5382. updated_at: new Date(),
  5383. original_video_title: video.title,
  5384. duration: '数字人视频'
  5385. };
  5386. this.activeTasks.unshift(newTask);
  5387. this.currentRemixTaskId = newTask.id;
  5388. this.saveTask(newTask);
  5389. this.showToast('数字人任务已提交,可在「任务管理」中查看进度', 'success');
  5390. this.showRemixModal = false;
  5391. // 若已通过形象准备链路生成对标/规范化形象图,则直接复用其 URL,跳过原图上传
  5392. const ensureImage$: Observable<string> = this.remixGeneratedPortraitUrl
  5393. ? of(this.remixGeneratedPortraitUrl)
  5394. : this.jimengService.uploadFileToParse(
  5395. this.remixDigitalHumanImageFile,
  5396. `digital-human-${Date.now()}-${this.remixDigitalHumanImageFile.name}`,
  5397. this.remixDigitalHumanImageFile.type || 'image/jpeg'
  5398. );
  5399. ensureImage$.subscribe({
  5400. next: (imageUrl: string) => {
  5401. this.remixDigitalHumanImageAssetUrl = imageUrl;
  5402. video.remixProgress = 10;
  5403. this.updateRemixTaskProgress('generate', 10);
  5404. if (isTtsMode) {
  5405. this.remixStatusText = '形象图上传完成,正在合成语音...';
  5406. this.remixDigitalHumanTtsSynthesizing = true;
  5407. this.refreshView();
  5408. this.http.post<any>('https://server.fmode.cn/api/volcengine/tts/unidirectional', {
  5409. token: 'Bearer r:f0333969e312a40e4703e8fe4ed1c600',
  5410. text: this.remixDigitalHumanTtsText.trim(),
  5411. timbreId: this.remixDigitalHumanTtsTimbreId.trim(),
  5412. isStream: false,
  5413. audio_params: {
  5414. format: 'mp3',
  5415. sample_rate: 24000,
  5416. speech_rate: 0,
  5417. loudness_rate: 0
  5418. }
  5419. }).subscribe({
  5420. next: (res) => {
  5421. this.remixDigitalHumanTtsSynthesizing = false;
  5422. if (res?.code === 200 && res?.data?.audioUrl) {
  5423. video.remixProgress = 30;
  5424. this.remixStatusText = '语音合成完成,正在识别数字人主体...';
  5425. this.updateRemixTaskProgress('generate', 30);
  5426. this.startDigitalHumanGenerationWithAudio(video, imageUrl, res.data.audioUrl);
  5427. } else {
  5428. this.handleDigitalHumanGenerationError(video, res?.error?.message || '语音合成失败,请检查音色ID和文本');
  5429. }
  5430. },
  5431. error: (err) => {
  5432. this.remixDigitalHumanTtsSynthesizing = false;
  5433. this.handleDigitalHumanGenerationError(video, this.getErrorText(err, '语音合成请求失败'));
  5434. }
  5435. });
  5436. } else {
  5437. this.remixStatusText = '形象图上传完成,正在提取原视频音频...';
  5438. this.refreshView();
  5439. const source = this.getVideoPlayUrl(video);
  5440. from(this.browserFfmpeg.extractAudioBlob(
  5441. source,
  5442. `${video.filename.replace(/\.[^.]+$/, '') || 'source-audio'}.m4a`,
  5443. )).subscribe({
  5444. next: (audioFile: File) => {
  5445. video.remixProgress = 20;
  5446. this.remixStatusText = '音频提取完成,正在上传音频素材...';
  5447. this.updateRemixTaskProgress('generate', 20);
  5448. this.jimengService.uploadFileToParse(audioFile, audioFile.name, audioFile.type).subscribe({
  5449. next: (audioUrl: string) => {
  5450. video.remixProgress = 30;
  5451. this.remixStatusText = '素材准备完成,正在识别数字人主体...';
  5452. this.updateRemixTaskProgress('generate', 30);
  5453. this.startDigitalHumanGenerationWithAudio(video, imageUrl, audioUrl);
  5454. },
  5455. error: (err) => {
  5456. this.handleDigitalHumanGenerationError(video, err?.message || '上传音频素材失败');
  5457. }
  5458. });
  5459. },
  5460. error: (err: any) => {
  5461. this.handleDigitalHumanGenerationError(video, err?.message || '浏览器提取原视频音频失败');
  5462. }
  5463. });
  5464. }
  5465. },
  5466. error: (err) => {
  5467. this.handleDigitalHumanGenerationError(video, err?.message || '上传数字人形象图失败');
  5468. }
  5469. });
  5470. }
  5471. private startDigitalHumanGenerationWithAudio(video: ManagedVideo, imageUrl: string, audioUrl: string): void {
  5472. this.jimengService.identifyDigitalHuman(imageUrl).subscribe({
  5473. next: ({ workId }) => {
  5474. this.jimengService.pollDigitalHumanIdentifyUntilReady(workId, (status, progress) => {
  5475. const mappedProgress = Math.min(30 + progress * 0.2, 50);
  5476. video.remixProgress = mappedProgress;
  5477. this.remixStatusText = status;
  5478. this.updateRemixTaskProgress('generate', mappedProgress);
  5479. }).subscribe({
  5480. next: () => {
  5481. this.remixStatusText = '主体识别完成,开始生成数字人视频...';
  5482. video.remixProgress = 50;
  5483. this.updateRemixTaskProgress('generate', 50);
  5484. this.jimengService.generateDigitalHuman(workId, audioUrl, {
  5485. prompt: this.remixDigitalHumanPrompt,
  5486. peFastMode: this.remixDigitalHumanResolution === '720p' ? true : this.remixDigitalHumanFastMode,
  5487. outputResolution: this.remixDigitalHumanResolution,
  5488. maskUrl: []
  5489. }, (status, progress) => {
  5490. const mappedProgress = Math.min(50 + progress * 0.45, 95);
  5491. video.remixProgress = mappedProgress;
  5492. this.remixStatusText = status;
  5493. this.updateRemixTaskProgress('generate', mappedProgress);
  5494. }).subscribe({
  5495. next: (result) => {
  5496. video.remixProgress = 100;
  5497. this.remixResults.success = 1;
  5498. this.remixFinalVideoUrl = result.videoUrl;
  5499. this.remixStatusText = '数字人视频生成完成';
  5500. this.createDigitalHumanVersion(video, result.videoUrl);
  5501. this.completeRemixTask('completed', result.videoUrl);
  5502. this.saveRemixSession('completed');
  5503. video.isRemixing = false;
  5504. this.isRemixSubmitting = false;
  5505. this.remixStep = 6;
  5506. this.showToast(`✅ 数字人视频已生成:${video.title}`, 'success', 6000);
  5507. this.refreshView();
  5508. },
  5509. error: (err) => {
  5510. this.handleDigitalHumanGenerationError(video, err?.message || '数字人生成失败');
  5511. }
  5512. });
  5513. },
  5514. error: (err) => {
  5515. this.handleDigitalHumanGenerationError(video, err?.message || '数字人主体识别失败');
  5516. }
  5517. });
  5518. },
  5519. error: (err) => {
  5520. this.handleDigitalHumanGenerationError(video, err?.message || '提交数字人主体识别失败');
  5521. }
  5522. });
  5523. }
  5524. private handleDigitalHumanGenerationError(video: ManagedVideo, message: string): void {
  5525. video.isRemixing = false;
  5526. video.remixProgress = 0;
  5527. this.isRemixSubmitting = false;
  5528. this.remixResults.failed = 1;
  5529. this.remixStep = 6;
  5530. this.remixStatusText = message;
  5531. this.remixStitchStatus = 'failed';
  5532. this.remixStitchError = message;
  5533. this.completeRemixTask('failed', undefined, message);
  5534. this.saveRemixSession('failed');
  5535. this.showToast(`❌ ${message}`, 'error');
  5536. this.refreshView();
  5537. }
  5538. // 串行生成每个分镜段的视频
  5539. private generateSegmentSequentially(index: number, video: ManagedVideo, styleName: string): void {
  5540. if (index >= this.remixStoryboard.length) {
  5541. // 全部完成
  5542. this.onBatchGenerationComplete(video, styleName);
  5543. return;
  5544. }
  5545. const segment = this.remixStoryboard[index];
  5546. segment.status = 'generating';
  5547. const totalSegments = this.remixStoryboard.length;
  5548. this.remixStatusText = `正在生成第 ${index + 1}/${totalSegments} 个片段...`;
  5549. video.remixProgress = (index / totalSegments) * 100;
  5550. // 更新任务进度
  5551. this.updateRemixTaskProgress('generate', (index / totalSegments) * 80);
  5552. this.jimengService.remixVideo(
  5553. segment.prompt,
  5554. {
  5555. method: '1',
  5556. frames: this.remixFrames,
  5557. aspectRatio: this.remixAspectRatio,
  5558. quality: this.remixQuality
  5559. },
  5560. (status: string, progress: number) => {
  5561. // 单片段内进度映射到总进度
  5562. const segProgress = (index + progress / 100) / totalSegments * 100;
  5563. video.remixProgress = segProgress;
  5564. this.remixStatusText = `片段 ${index + 1}/${totalSegments}: ${status}`;
  5565. }
  5566. ).subscribe({
  5567. next: (result) => {
  5568. segment.status = 'completed';
  5569. segment.videoUrl = result.videoUrl;
  5570. segment.workId = result.workId;
  5571. this.remixResults.success++;
  5572. // 添加到生成结果
  5573. this.generatedResults.unshift({
  5574. id: `REMIX-${Date.now()}-${segment.id}`,
  5575. type: 'video',
  5576. url: result.videoUrl,
  5577. title: `${video.title} - ${styleName} [${segment.id}]`,
  5578. created_at: new Date(),
  5579. quality: this.remixQuality === 'pro' ? '1080P Pro' : '720P',
  5580. duration: this.remixFrames === 121 ? '5秒' : '10秒',
  5581. cost: this.remixQuality === 'pro' ? 5.0 : 1.4
  5582. });
  5583. console.log(`✅ 片段 ${segment.id} 完成: ${result.videoUrl}`);
  5584. // 自动保存当前会话
  5585. this.saveRemixSession('generating');
  5586. // 延迟1秒再提交下一个(避免频率限制)
  5587. setTimeout(() => this.generateSegmentSequentially(index + 1, video, styleName), 1000);
  5588. },
  5589. error: (err) => {
  5590. segment.status = 'failed';
  5591. segment.error = err.message || '生成失败';
  5592. this.remixResults.failed++;
  5593. console.error(`❌ 片段 ${segment.id} 失败:`, err);
  5594. this.saveRemixSession('generating');
  5595. // 失败也继续下一个
  5596. setTimeout(() => this.generateSegmentSequentially(index + 1, video, styleName), 1000);
  5597. }
  5598. });
  5599. }
  5600. // 批量生成完成 → 自动触发一键成片拼接
  5601. private onBatchGenerationComplete(video: ManagedVideo, styleName: string): void {
  5602. this.remixStep = 6;
  5603. this.remixStatusText = `片段生成完成:成功 ${this.remixResults.success}/${this.remixResults.total}`;
  5604. console.log(`🎉 批量生成完成: 成功${this.remixResults.success}, 失败${this.remixResults.failed}`);
  5605. // 更新任务进度到80%
  5606. this.updateRemixTaskProgress('generate', 80);
  5607. // 收集所有成功片段的视频URL
  5608. const successUrls = this.remixStoryboard
  5609. .filter(s => s.status === 'completed' && s.videoUrl)
  5610. .map(s => s.videoUrl!);
  5611. if (successUrls.length < 1) {
  5612. video.isRemixing = false;
  5613. video.remixProgress = 100;
  5614. this.isRemixSubmitting = false;
  5615. this.remixStitchStatus = 'failed';
  5616. this.remixStitchError = '没有成功的视频片段可以拼接';
  5617. this.remixStatusText = `生成完成,但没有可拼接的片段`;
  5618. this.completeRemixTask('failed', undefined, '所有片段生成失败');
  5619. this.saveRemixSession('failed');
  5620. this.showToast('任务失败:所有片段生成失败', 'error');
  5621. return;
  5622. }
  5623. // 一键成片功能暂时关闭(Quickly API 凭证过期),直接标记完成
  5624. // TODO: 待 Quickly 凭证更新后恢复自动拼接功能
  5625. this.remixStitchStatus = 'failed';
  5626. this.remixStitchError = '一键成片功能暂不可用(Quickly API 凭证过期),各片段可单独查看/下载';
  5627. this.remixStatusText = `片段生成完成:成功 ${successUrls.length} 个,一键成片暂不可用`;
  5628. video.isRemixing = false;
  5629. video.remixProgress = 100;
  5630. this.isRemixSubmitting = false;
  5631. const firstUrl = successUrls[0];
  5632. this.createRemixVersion(video, this.remixStyle, styleName, firstUrl);
  5633. this.completeRemixTask('completed', firstUrl);
  5634. this.saveRemixSession('completed');
  5635. this.showToast(`✅ AI重塑完成!「${video.title}」共 ${successUrls.length} 个片段`, 'success', 6000);
  5636. console.log(`✅ AI重塑完成(一键成片已跳过): ${successUrls.length} 个片段`);
  5637. }
  5638. // 结果页点击完成
  5639. finishRemix(): void {
  5640. this.showRemixModal = false;
  5641. this.remixTargetVideo = null;
  5642. this.resetDigitalHumanState();
  5643. this.setCurrentTab('results');
  5644. }
  5645. private createDigitalHumanVersion(video: ManagedVideo, videoUrl: string): void {
  5646. const remixVersion: RemixVersion = {
  5647. id: `REMIX-${Date.now()}`,
  5648. style: '数字人生成',
  5649. created_at: new Date(),
  5650. file_path: videoUrl,
  5651. thumbnail: this.remixDigitalHumanImageAssetUrl || video.thumbnail || 'assets/default-remix-thumb.jpg',
  5652. description: '使用上传形象图与原视频提取音频生成的数字人版本',
  5653. parameters: {
  5654. style: 'digital-human',
  5655. intensity: 1,
  5656. preserve_audio: true,
  5657. quality: this.remixDigitalHumanResolution === '1080p' ? 'high' : 'standard',
  5658. effects: ['digital-human']
  5659. }
  5660. };
  5661. if (!video.remixVersions) {
  5662. video.remixVersions = [];
  5663. }
  5664. video.remixVersions.unshift(remixVersion);
  5665. const durationSeconds = Math.min(Number(video.duration || 0) || 0, 60);
  5666. const estimatedCost = Math.round(durationSeconds * 100) / 100;
  5667. const qualityLabel = this.remixDigitalHumanResolution === '1080p' ? '1080P' : '720P';
  5668. this.saveResult({
  5669. type: 'video',
  5670. url: videoUrl,
  5671. title: `${video.title} - 数字人生成`,
  5672. quality: qualityLabel,
  5673. duration: durationSeconds > 0 ? `${durationSeconds} 秒` : '数字人视频',
  5674. cost: estimatedCost,
  5675. remixId: this.currentRemixId,
  5676. videoId: video.id,
  5677. segments: [{ id: 'DH-01', videoUrl, prompt: this.remixDigitalHumanPrompt, status: 'completed' }]
  5678. });
  5679. this.saveHistoryRecord({
  5680. keyword: `${video.title} - 数字人生成`,
  5681. original_video_title: video.title,
  5682. status: 'completed',
  5683. cost: estimatedCost,
  5684. duration: durationSeconds > 0 ? `${durationSeconds} 秒` : '数字人视频',
  5685. remixId: this.currentRemixId,
  5686. videoId: video.id,
  5687. styleName: '数字人生成',
  5688. resultUrl: videoUrl,
  5689. quality: qualityLabel,
  5690. segmentCount: 1,
  5691. successCount: 1
  5692. });
  5693. }
  5694. // 创建重塑版本 + 持久化结果和历史
  5695. private createRemixVersion(video: ManagedVideo, styleId: string, styleName: string, videoUrl?: string): void {
  5696. const remixVersion: RemixVersion = {
  5697. id: `REMIX-${Date.now()}`,
  5698. style: styleName,
  5699. created_at: new Date(),
  5700. file_path: videoUrl || `remix/${video.filename.replace('.mp4', `-${styleId}.mp4`)}`,
  5701. thumbnail: video.thumbnail || 'assets/default-remix-thumb.jpg',
  5702. description: `使用${styleName}风格重塑的视频版本`,
  5703. parameters: {
  5704. style: styleId,
  5705. intensity: 0.8,
  5706. preserve_audio: true,
  5707. quality: this.remixQuality === 'pro' ? 'ultra' : 'high',
  5708. effects: [styleId, 'enhancement']
  5709. }
  5710. };
  5711. if (!video.remixVersions) {
  5712. video.remixVersions = [];
  5713. }
  5714. video.remixVersions.unshift(remixVersion);
  5715. // 收集所有成功片段数据
  5716. const successSegments = this.remixStoryboard
  5717. .filter(s => s.status === 'completed' && s.videoUrl)
  5718. .map(s => ({ id: s.id, videoUrl: s.videoUrl!, prompt: s.prompt, status: s.status }));
  5719. // 计算费用估算
  5720. const costPerSecond = this.remixQuality === 'pro' ? 1.0 : this.remixQuality === '1080p' ? 0.63 : 0.28;
  5721. const estimatedCost = Math.round(this.remixResults.success * 5 * costPerSecond * 100) / 100;
  5722. // 质量显示
  5723. const qualityLabel = this.remixQuality === 'pro' ? 'Pro 1080P' : this.remixQuality === '1080p' ? '1080P' : '720P';
  5724. // 持久化:保存生成结果(包含所有片段)
  5725. this.saveResult({
  5726. type: 'video',
  5727. url: videoUrl || '',
  5728. title: `${video.title} - ${styleName}风格重塑`,
  5729. quality: qualityLabel,
  5730. duration: `${this.remixResults.success} 个片段`,
  5731. cost: estimatedCost,
  5732. remixId: this.currentRemixId,
  5733. videoId: video.id,
  5734. segments: successSegments
  5735. });
  5736. // 持久化:保存历史记录
  5737. this.saveHistoryRecord({
  5738. keyword: `${video.title} - ${styleName}`,
  5739. original_video_title: video.title,
  5740. status: this.remixResults.success > 0 ? 'completed' : 'failed',
  5741. cost: estimatedCost,
  5742. duration: `${this.remixResults.success}/${this.remixResults.total} 片段`,
  5743. remixId: this.currentRemixId,
  5744. videoId: video.id,
  5745. styleName: styleName,
  5746. resultUrl: videoUrl || successSegments[0]?.videoUrl || '',
  5747. quality: qualityLabel,
  5748. segmentCount: this.remixResults.total,
  5749. successCount: this.remixResults.success
  5750. });
  5751. console.log('重塑版本已创建:', remixVersion);
  5752. }
  5753. // 查看重塑版本
  5754. viewRemixVersions(video: ManagedVideo): void {
  5755. if (!video.remixVersions || video.remixVersions.length === 0) {
  5756. alert('该视频暂无重塑版本');
  5757. return;
  5758. }
  5759. console.log('查看重塑版本:', video.remixVersions);
  5760. let versionsList = `「${video.title}」的重塑版本:\n\n`;
  5761. video.remixVersions.forEach((version, index) => {
  5762. versionsList += `${index + 1}. ${version.style} - ${version.description}\n 创建时间: ${version.created_at.toLocaleString()}\n\n`;
  5763. });
  5764. alert(versionsList);
  5765. }
  5766. // 获取重塑状态文本
  5767. getRemixStatusText(video: ManagedVideo): string {
  5768. if (video.isRemixing && video.remixProgress !== undefined) {
  5769. return `重塑中... ${Math.round(video.remixProgress)}%`;
  5770. }
  5771. return 'AI重塑';
  5772. }
  5773. // 获取重塑状态颜色
  5774. getRemixStatusColor(video: ManagedVideo): string {
  5775. if (video.isRemixing) {
  5776. return 'btn-accent';
  5777. }
  5778. return 'btn-primary';
  5779. }
  5780. // ==================== 语音合成标签页方法 ====================
  5781. setVsTtsMode(mode: 'clone' | 'synthesize'): void {
  5782. this.vsTtsMode = mode;
  5783. this.vsCloneError = '';
  5784. this.vsSynthError = '';
  5785. this.refreshView();
  5786. }
  5787. onVsCloneAudioSelected(event: Event): void {
  5788. const input = event.target as HTMLInputElement;
  5789. if (!input.files || input.files.length === 0) return;
  5790. const file = input.files[0];
  5791. const allowedExts = ['.mp3', '.wav', '.m4a', '.ogg', '.aac', '.flac', '.wma'];
  5792. const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  5793. if (!allowedExts.includes(ext) || file.size <= 0) {
  5794. this.vsCloneError = '仅支持 mp3、wav、m4a、ogg、aac、flac、wma 格式的音频文件';
  5795. input.value = '';
  5796. this.refreshView();
  5797. return;
  5798. }
  5799. if (file.size > 50 * 1024 * 1024) {
  5800. this.vsCloneError = '音频文件不能超过 50MB';
  5801. input.value = '';
  5802. this.refreshView();
  5803. return;
  5804. }
  5805. this.vsCloneAudioFile = file;
  5806. this.vsCloneAudioName = file.name;
  5807. this.vsCloneAudioUrl = '';
  5808. this.vsCloneError = '';
  5809. input.value = '';
  5810. this.refreshView();
  5811. }
  5812. clearVsCloneAudio(): void {
  5813. this.vsCloneAudioFile = null;
  5814. this.vsCloneAudioName = '';
  5815. this.vsCloneAudioUrl = '';
  5816. this.vsCloneError = '';
  5817. this.refreshView();
  5818. }
  5819. private vsUploadCloneAudio(): Promise<string> {
  5820. return new Promise((resolve, reject) => {
  5821. if (!this.vsCloneAudioFile) {
  5822. reject(new Error('未选择音频文件'));
  5823. return;
  5824. }
  5825. if (this.vsCloneAudioUrl) {
  5826. resolve(this.vsCloneAudioUrl);
  5827. return;
  5828. }
  5829. this.vsCloneUploading = true;
  5830. this.refreshView();
  5831. const filename = `voice-clone-${Date.now()}-${this.vsCloneAudioFile.name}`;
  5832. this.qiniuUpload.uploadFile(this.vsCloneAudioFile, filename, this.vsCloneAudioFile.type, 'audio').subscribe({
  5833. next: (url) => {
  5834. this.vsCloneUploading = false;
  5835. if (!url) {
  5836. reject(new Error('上传音频失败,未返回可用 URL'));
  5837. return;
  5838. }
  5839. this.vsCloneAudioUrl = url;
  5840. this.refreshView();
  5841. resolve(url);
  5842. },
  5843. error: (err) => {
  5844. this.vsCloneUploading = false;
  5845. this.refreshView();
  5846. reject(new Error(this.getErrorText(err, '音频上传失败')));
  5847. }
  5848. });
  5849. });
  5850. }
  5851. vsStartClone(): void {
  5852. if (this.vsCloneLoading || this.vsCloneUploading) return;
  5853. const { name, audioText, language, demoText } = this.vsCloneForm;
  5854. if (!name.trim()) {
  5855. this.vsCloneError = '请输入音色名称';
  5856. this.refreshView();
  5857. return;
  5858. }
  5859. if (!this.vsCloneAudioFile) {
  5860. this.vsCloneError = '请先上传音频文件';
  5861. this.refreshView();
  5862. return;
  5863. }
  5864. if (!demoText.trim() || demoText.trim().length < 4 || demoText.trim().length > 80) {
  5865. this.vsCloneError = '试听文本长度需在 4-80 字之间';
  5866. this.refreshView();
  5867. return;
  5868. }
  5869. this.vsCloneLoading = true;
  5870. this.vsCloneError = '';
  5871. this.vsCloneResult = null;
  5872. this.refreshView();
  5873. this.vsUploadCloneAudio().then((audioUrl) => {
  5874. // 自动从后端挑选一个未训练的 speaker_id
  5875. this.http.post<any>('/backend/api/voice/auto-speaker-id', {}).subscribe({
  5876. next: (idRes) => {
  5877. const pickedSpeakerId = String(idRes?.speaker_id || '').trim();
  5878. if (!pickedSpeakerId) {
  5879. this.vsCloneLoading = false;
  5880. this.vsCloneError = idRes?.error || '未能获取可用的 speaker_id';
  5881. this.showToast(`❌ ${this.vsCloneError}`, 'error');
  5882. this.refreshView();
  5883. return;
  5884. }
  5885. this.showToast(`🎯 已自动分配 speaker_id:${pickedSpeakerId}`, 'info', 3000);
  5886. this.http.post<any>('https://server.fmode.cn/api/volcengine/tts/voice_clone', {
  5887. token: 'Bearer r:f0333969e312a40e4703e8fe4ed1c600',
  5888. name: name.trim(),
  5889. speaker_id: pickedSpeakerId,
  5890. audioData: {
  5891. url: audioUrl,
  5892. ...(audioText.trim() ? { text: audioText.trim() } : {})
  5893. },
  5894. language: language,
  5895. extra_params: {
  5896. demo_text: demoText.trim()
  5897. }
  5898. }).subscribe({
  5899. next: (res) => {
  5900. this.vsCloneLoading = false;
  5901. this.vsCloneResult = res;
  5902. if (res?.code === 200 && res?.data?.timbre) {
  5903. const timbre = res.data.timbre;
  5904. const newEntry = {
  5905. objectId: timbre.objectId,
  5906. name: timbre.name || name.trim(),
  5907. speakerId: timbre.speaker_id || pickedSpeakerId
  5908. };
  5909. const existingIndex = this.vsClonedTimbreList.findIndex(t => t.objectId === timbre.objectId);
  5910. if (existingIndex >= 0) {
  5911. // 同一 speaker_id 复刻会返回相同 objectId:更新现有条目(含名称)并置顶
  5912. const next = [...this.vsClonedTimbreList];
  5913. next.splice(existingIndex, 1);
  5914. next.unshift({ ...this.vsClonedTimbreList[existingIndex], ...newEntry });
  5915. this.vsClonedTimbreList = next;
  5916. } else {
  5917. this.vsClonedTimbreList = [newEntry, ...this.vsClonedTimbreList];
  5918. }
  5919. this.saveClonedTimbreList();
  5920. // 同步到本地后端,让 /api/voice/auto-speaker-id 后续能跳过此 speaker_id
  5921. const modelInfo = (Array.isArray(timbre.models) && timbre.models[0]) || {};
  5922. this.http.post('/backend/api/voice-profiles/sync', {
  5923. id: timbre.objectId,
  5924. timbre_id: timbre.objectId,
  5925. name: timbre.name || name.trim(),
  5926. speaker_id: timbre.speaker_id || pickedSpeakerId,
  5927. demo_audio: modelInfo.demo_audio || '',
  5928. latest_audio_url: modelInfo.demo_audio || '',
  5929. x_api_resource_id: modelInfo.x_api_resource_id || '',
  5930. icl_speaker_id: modelInfo.icl_speaker_id || '',
  5931. model_version: modelInfo.version || '',
  5932. status: timbre.status ?? null,
  5933. status_label: res?.data?.tip || '',
  5934. message: res?.data?.tip || '',
  5935. created_at: timbre.createdAt || undefined
  5936. }).subscribe({
  5937. next: () => {},
  5938. error: (e) => console.warn('voice-profiles/sync failed', e)
  5939. });
  5940. if (!this.vsSynthForm.timbreId) {
  5941. this.vsSynthForm.timbreId = timbre.objectId;
  5942. }
  5943. this.showToast(`✅ 音色「${timbre.name}」复刻成功`, 'success');
  5944. } else {
  5945. this.vsCloneError = res?.error?.message || '复刻失败,请检查参数';
  5946. this.showToast(`❌ ${this.vsCloneError}`, 'error');
  5947. }
  5948. this.refreshView();
  5949. },
  5950. error: (err) => {
  5951. this.vsCloneLoading = false;
  5952. this.vsCloneError = this.getErrorText(err, '音色复刻请求失败');
  5953. this.showToast(`❌ ${this.vsCloneError}`, 'error');
  5954. this.refreshView();
  5955. }
  5956. });
  5957. },
  5958. error: (err) => {
  5959. this.vsCloneLoading = false;
  5960. const errBody = err?.error;
  5961. this.vsCloneError = errBody?.error || this.getErrorText(err, '获取可用 speaker_id 失败');
  5962. this.showToast(`❌ ${this.vsCloneError}`, 'error');
  5963. this.refreshView();
  5964. }
  5965. });
  5966. }).catch((uploadErr) => {
  5967. this.vsCloneLoading = false;
  5968. this.vsCloneError = uploadErr?.message || '音频上传失败';
  5969. this.showToast(`❌ ${this.vsCloneError}`, 'error');
  5970. this.refreshView();
  5971. });
  5972. }
  5973. vsStartSynthesize(): void {
  5974. if (this.vsSynthLoading) return;
  5975. const { timbreId, voiceType, voiceSource, text, format, sampleRate, speechRate, loudnessRate } = this.vsSynthForm;
  5976. const usingOfficial = voiceSource === 'official';
  5977. const voiceId = usingOfficial ? (voiceType || '').trim() : (timbreId || '').trim();
  5978. if (!voiceId) {
  5979. this.vsSynthError = '请先选择声音模型';
  5980. this.refreshView();
  5981. return;
  5982. }
  5983. if (!text.trim()) {
  5984. this.vsSynthError = '请输入要合成的文本内容';
  5985. this.refreshView();
  5986. return;
  5987. }
  5988. this.vsSynthLoading = true;
  5989. this.vsSynthError = '';
  5990. this.vsSynthAudioUrl = '';
  5991. this.vsSynthWorkId = '';
  5992. this.refreshView();
  5993. const body: any = {
  5994. token: 'Bearer r:f0333969e312a40e4703e8fe4ed1c600',
  5995. text: text.trim(),
  5996. isStream: false,
  5997. audio_params: {
  5998. format: format || 'mp3',
  5999. sample_rate: sampleRate || 24000,
  6000. speech_rate: speechRate || 0,
  6001. loudness_rate: loudnessRate || 0
  6002. }
  6003. };
  6004. if (usingOfficial) {
  6005. // _uranus_bigtts 后缀对应豆包语音合成模型 2.0,需要 seed-tts-2.0 资源;
  6006. // 其它后缀回退到 seed-tts-1.0,可按需扩展。
  6007. body.volcengine_voice_type = voiceId;
  6008. body.x_api_resource_id = this.getOfficialTtsResourceId(voiceId);
  6009. } else {
  6010. body.timbreId = voiceId;
  6011. }
  6012. this.http.post<any>('https://server.fmode.cn/api/volcengine/tts/unidirectional', body).subscribe({
  6013. next: (res) => {
  6014. this.vsSynthLoading = false;
  6015. if (res?.code === 200 && res?.data?.audioUrl) {
  6016. this.vsSynthAudioUrl = res.data.audioUrl;
  6017. this.vsSynthWorkId = res.data.workId || '';
  6018. this.showToast('✅ 语音合成成功', 'success');
  6019. } else {
  6020. this.vsSynthError = res?.error?.message || '合成失败,请检查参数';
  6021. this.showToast(`❌ ${this.vsSynthError}`, 'error');
  6022. }
  6023. this.refreshView();
  6024. },
  6025. error: (err) => {
  6026. this.vsSynthLoading = false;
  6027. this.vsSynthError = this.getErrorText(err, '语音合成请求失败');
  6028. this.showToast(`❌ ${this.vsSynthError}`, 'error');
  6029. this.refreshView();
  6030. }
  6031. });
  6032. }
  6033. vsSelectClonedTimbre(objectId: string): void {
  6034. this.vsSynthForm.timbreId = objectId;
  6035. this.vsSynthForm.voiceSource = 'cloned';
  6036. this.vsSynthForm.voiceType = '';
  6037. const matched = this.vsClonedTimbreList.find(t => t.objectId === objectId);
  6038. this.vsSynthForm.voiceName = matched?.name || objectId;
  6039. this.vsTtsMode = 'synthesize';
  6040. this.vsSynthError = '';
  6041. this.refreshView();
  6042. }
  6043. // ==================== 数字人合成独立页面 ====================
  6044. onDhImageSelected(event: Event): void {
  6045. const input = event.target as HTMLInputElement;
  6046. if (!input.files || input.files.length === 0) return;
  6047. const file = input.files[0];
  6048. const allowedExts = ['.jpg', '.jpeg', '.png', '.gif'];
  6049. const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  6050. if (!allowedExts.includes(ext)) {
  6051. this.dhError = '仅支持 jpg、jpeg、png、gif 格式的形象图';
  6052. input.value = '';
  6053. this.refreshView();
  6054. return;
  6055. }
  6056. if (file.size > 20 * 1024 * 1024) {
  6057. this.dhError = '形象图大小不能超过 20MB';
  6058. input.value = '';
  6059. this.refreshView();
  6060. return;
  6061. }
  6062. this.dhRevokeImagePreview();
  6063. this.dhImageFile = file;
  6064. this.dhImageName = file.name;
  6065. this.dhImagePreviewUrl = URL.createObjectURL(file);
  6066. this.dhImageAssetUrl = '';
  6067. this.dhError = '';
  6068. input.value = '';
  6069. this.refreshView();
  6070. }
  6071. clearDhImage(): void {
  6072. this.dhRevokeImagePreview();
  6073. this.dhImageFile = null;
  6074. this.dhImageName = '';
  6075. this.dhImageAssetUrl = '';
  6076. this.dhError = '';
  6077. this.dhPreparedPortraitUrl = '';
  6078. this.dhPreparedFullBodyUrl = '';
  6079. this.dhPreparedBenchmarkSummary = '';
  6080. this.refreshView();
  6081. }
  6082. /** dh tab:<app-portrait-prepare> 的 (prepared) 事件回调 */
  6083. onDhPortraitPrepared(out: PortraitPrepareOutput): void {
  6084. this.dhPreparedPortraitUrl = out.portraitUrl;
  6085. this.dhPreparedFullBodyUrl = out.fullBodyUrl;
  6086. this.dhPreparedBenchmarkSummary = out.benchmarkSummary;
  6087. this.refreshView();
  6088. }
  6089. private dhRevokeImagePreview(): void {
  6090. if (this.dhImagePreviewUrl) {
  6091. URL.revokeObjectURL(this.dhImagePreviewUrl);
  6092. this.dhImagePreviewUrl = '';
  6093. }
  6094. }
  6095. onDhAudioSelected(event: Event): void {
  6096. const input = event.target as HTMLInputElement;
  6097. if (!input.files || input.files.length === 0) return;
  6098. const file = input.files[0];
  6099. const allowedExts = ['.mp3', '.wav', '.m4a', '.ogg', '.aac', '.flac', '.wma'];
  6100. const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  6101. if (!allowedExts.includes(ext)) {
  6102. this.dhError = '仅支持 MP3、WAV、M4A、OGG、AAC、FLAC、WMA 格式的音频';
  6103. input.value = '';
  6104. this.refreshView();
  6105. return;
  6106. }
  6107. if (file.size > 50 * 1024 * 1024) {
  6108. this.dhError = '音频文件大小不能超过 50MB';
  6109. input.value = '';
  6110. this.refreshView();
  6111. return;
  6112. }
  6113. this.dhUploadAudioFile = file;
  6114. this.dhUploadAudioName = file.name;
  6115. this.dhUploadAudioUrl = '';
  6116. this.dhError = '';
  6117. input.value = '';
  6118. this.refreshView();
  6119. }
  6120. clearDhAudio(): void {
  6121. this.dhUploadAudioFile = null;
  6122. this.dhUploadAudioName = '';
  6123. this.dhUploadAudioUrl = '';
  6124. this.dhError = '';
  6125. this.refreshView();
  6126. }
  6127. dhReset(): void {
  6128. this.dhRevokeImagePreview();
  6129. this.dhStep = 'form';
  6130. this.dhImageFile = null;
  6131. this.dhImageName = '';
  6132. this.dhImageAssetUrl = '';
  6133. this.dhAudioSource = 'tts';
  6134. this.dhTtsTimbreId = '';
  6135. this.dhTtsVoiceSource = 'cloned';
  6136. this.dhTtsVoiceType = '';
  6137. this.dhTtsVoiceName = '';
  6138. this.dhTtsText = '';
  6139. this.dhUploadAudioFile = null;
  6140. this.dhUploadAudioName = '';
  6141. this.dhUploadAudioUrl = '';
  6142. this.dhUploadingAudio = false;
  6143. this.dhPrompt = '';
  6144. this.dhFastMode = false;
  6145. this.dhResolution = '1080p';
  6146. this.dhError = '';
  6147. this.dhLoading = false;
  6148. this.dhStatusText = '';
  6149. this.dhProgress = 0;
  6150. this.dhResultVideoUrl = '';
  6151. this.dhSynthesizing = false;
  6152. this.refreshView();
  6153. }
  6154. // 数字人形象库:从生成结果中筛选数字人作品
  6155. getDigitalHumanResults(): GeneratedResult[] {
  6156. return (this.generatedResults || []).filter(r => {
  6157. const title = String(r?.title || '');
  6158. return title.includes('数字人合成') || title.includes('数字人');
  6159. });
  6160. }
  6161. private toDigitalHumanSnapshot(): Record<string, any> {
  6162. return {
  6163. imageName: this.dhImageName,
  6164. imageUrl: this.dhImageAssetUrl || this.dhPreparedPortraitUrl || '',
  6165. preparedPortraitUrl: this.dhPreparedPortraitUrl,
  6166. preparedFullBodyUrl: this.dhPreparedFullBodyUrl,
  6167. preparedBenchmarkSummary: this.dhPreparedBenchmarkSummary,
  6168. audioSource: this.dhAudioSource,
  6169. ttsTimbreId: this.dhTtsTimbreId,
  6170. ttsVoiceSource: this.dhTtsVoiceSource,
  6171. ttsVoiceType: this.dhTtsVoiceType,
  6172. ttsVoiceName: this.dhTtsVoiceName,
  6173. ttsText: this.dhTtsText,
  6174. uploadAudioName: this.dhUploadAudioName,
  6175. uploadAudioUrl: this.dhUploadAudioUrl,
  6176. prompt: this.dhPrompt,
  6177. fastMode: this.dhFastMode,
  6178. resolution: this.dhResolution,
  6179. step: this.dhStep,
  6180. progress: this.dhProgress,
  6181. statusText: this.dhStatusText,
  6182. resultVideoUrl: this.dhResultVideoUrl,
  6183. };
  6184. }
  6185. private deriveDigitalHumanDraftTitle(): string {
  6186. const script = (this.dhTtsText || '').replace(/\s+/g, ' ').trim();
  6187. if (script) return `数字人合成 · ${script.slice(0, 24)}`;
  6188. if (this.dhImageName) return `数字人合成 · ${this.dhImageName}`;
  6189. return `数字人合成 · ${new Date().toLocaleString('zh-CN')}`;
  6190. }
  6191. private syncDigitalHumanDraft(status: 'draft' | 'running' = 'draft'): void {
  6192. const title = this.deriveDigitalHumanDraftTitle();
  6193. this.pipelineSession.ensureActive('digital-human', () => this.toDigitalHumanSnapshot(), title);
  6194. this.pipelineSession.patch({
  6195. title,
  6196. snapshot: this.toDigitalHumanSnapshot(),
  6197. thumbnail: this.dhImageAssetUrl || this.dhPreparedPortraitUrl || undefined,
  6198. });
  6199. if (status === 'running') this.pipelineSession.markRunning();
  6200. }
  6201. private completeDigitalHumanDraft(videoUrl: string, imageUrl?: string, audioUrl?: string): void {
  6202. this.syncDigitalHumanDraft('running');
  6203. if (imageUrl) {
  6204. this.pipelineSession.upsertArtifact(
  6205. (a) => a.type === 'image' && a.title === '数字人形象图',
  6206. {
  6207. type: 'image',
  6208. url: imageUrl,
  6209. title: '数字人形象图',
  6210. extras: { imageName: this.dhImageName },
  6211. },
  6212. );
  6213. }
  6214. if (audioUrl) {
  6215. this.pipelineSession.upsertArtifact(
  6216. (a) => a.type === 'audio' && a.title === '数字人口播音频',
  6217. {
  6218. type: 'audio',
  6219. url: audioUrl,
  6220. title: '数字人口播音频',
  6221. extras: {
  6222. source: this.dhAudioSource,
  6223. voiceSource: this.dhAudioSource === 'tts' ? this.dhTtsVoiceSource : undefined,
  6224. voiceType: this.dhAudioSource === 'tts' ? this.dhTtsVoiceType : undefined,
  6225. voiceName: this.dhAudioSource === 'tts' ? this.dhTtsVoiceName : undefined,
  6226. timbreId: this.dhAudioSource === 'tts' ? this.dhTtsTimbreId : undefined,
  6227. audioName: this.dhUploadAudioName,
  6228. },
  6229. },
  6230. );
  6231. }
  6232. this.pipelineSession.patch({
  6233. title: this.deriveDigitalHumanDraftTitle(),
  6234. snapshot: this.toDigitalHumanSnapshot(),
  6235. thumbnail: imageUrl || this.dhImageAssetUrl || this.dhPreparedPortraitUrl || undefined,
  6236. });
  6237. this.pipelineSession.finalize(videoUrl, {
  6238. prompt: this.dhPrompt,
  6239. resolution: this.dhResolution,
  6240. audioSource: this.dhAudioSource,
  6241. ttsVoiceSource: this.dhAudioSource === 'tts' ? this.dhTtsVoiceSource : undefined,
  6242. ttsVoiceType: this.dhAudioSource === 'tts' ? this.dhTtsVoiceType : undefined,
  6243. ttsVoiceName: this.dhAudioSource === 'tts' ? this.dhTtsVoiceName : undefined,
  6244. ttsTimbreId: this.dhAudioSource === 'tts' ? this.dhTtsTimbreId : undefined,
  6245. });
  6246. }
  6247. // ========================================================================
  6248. // 数字人合成页:AI 对话助手 —— 让用户用自然语言要求 AI 改写口播稿 / 优化提示词
  6249. // ========================================================================
  6250. /** 发送一条对话给 AI,AI 基于当前 dhTtsText / dhPrompt 给出修改建议 */
  6251. dhChatSend(): void {
  6252. const userMsg = (this.dhChatInput || '').trim();
  6253. if (!userMsg || this.dhChatLoading) return;
  6254. this.dhChatMessages.push({ role: 'user', content: userMsg });
  6255. this.dhChatInput = '';
  6256. this.dhChatLoading = true;
  6257. this.dhChatError = '';
  6258. this.refreshView();
  6259. const systemPrompt = `你是一位短视频数字人口播脚本编辑助手。你需要根据用户的自然语言指令,在不偏离原意的前提下改写「口播文本」或「补充提示词」。
  6260. 【当前口播文本】
  6261. ${this.dhTtsText || '(空)'}
  6262. 【当前补充提示词】
  6263. ${this.dhPrompt || '(空)'}
  6264. 【输出格式】请只输出严格 JSON:
  6265. {
  6266. "explanation": "用一两句话向用户解释你做了什么修改(≤40字)",
  6267. "ttsScript": "新的口播文本;若用户本轮指令不需要改写口播,请返回空字符串",
  6268. "dhPrompt": "新的补充提示词;若用户本轮指令不需要改写提示词,请返回空字符串"
  6269. }
  6270. 要求:
  6271. - 字符串内不得出现真实换行,必须用 \\n 转义。
  6272. - 口播文本控制在 200 字以内,第一人称、自然口语。
  6273. - 补充提示词控制在 80 字以内,描述动作 / 镜头语言 / 风格。
  6274. - 只返回纯 JSON,禁止 markdown 代码块、禁止前后缀。`;
  6275. // 把最近若干轮历史拼成一段上下文,避免 token 爆炸
  6276. const history = this.dhChatMessages
  6277. .slice(-8, -1) // 不含本次刚 push 的用户消息
  6278. .map(m => `${m.role === 'user' ? '用户' : 'AI'}: ${m.content}`)
  6279. .join('\n');
  6280. const userInput = (history ? `【历史对话】\n${history}\n\n` : '') + `【本轮用户指令】\n${userMsg}`;
  6281. console.log('🗣️ [dhChatSend] 发送对话:', { userMsg, ttsLen: this.dhTtsText.length, promptLen: this.dhPrompt.length });
  6282. this.llmService.askWithSystem(systemPrompt, userInput, { model: 'gemini-2.5-flash', max_tokens: 2048 })
  6283. .pipe(
  6284. timeout(60000),
  6285. // ★ finalize 保证不论 next/error/throw/cancel,都强制解锁按钮并刷新视图
  6286. finalize(() => {
  6287. this.dhChatLoading = false;
  6288. this.refreshView();
  6289. })
  6290. )
  6291. .subscribe({
  6292. next: (text) => {
  6293. console.log('🗣️ [dhChatSend] 收到回复,长度:', (text || '').length);
  6294. const cleaned = (text || '').replace(/^\s*```(?:json)?\s*/i, '').replace(/\s*```\s*$/i, '').trim();
  6295. const parsed: any = this.parseRewriteJson(cleaned);
  6296. if (parsed) {
  6297. const explanation = typeof parsed.explanation === 'string' ? parsed.explanation.trim() : '';
  6298. const tts = typeof parsed.ttsScript === 'string' ? parsed.ttsScript.trim() : '';
  6299. const prompt = typeof parsed.dhPrompt === 'string' ? parsed.dhPrompt.trim() : '';
  6300. this.dhChatMessages.push({
  6301. role: 'assistant',
  6302. content: explanation || (tts || prompt ? '已为你生成修改建议,可点击下方按钮应用' : '我没有给出修改'),
  6303. suggestedTts: tts || undefined,
  6304. suggestedPrompt: prompt || undefined,
  6305. });
  6306. } else {
  6307. // 兜底:把原文当作 assistant 文本呈现,不自动应用
  6308. this.dhChatMessages.push({ role: 'assistant', content: cleaned || '(AI 无返回)' });
  6309. }
  6310. this.refreshView();
  6311. },
  6312. error: (err) => {
  6313. console.error('🗣️ [dhChatSend] 请求失败:', err);
  6314. this.dhChatLoading = false;
  6315. // 优先抽取上游具体错误(fmode 网关返回的 "无效的令牌..." 等)
  6316. const upstream = err?.error?.error?.message || err?.error?.message || err?.error?.error || err?.error || '';
  6317. const msg = (typeof upstream === 'string' && upstream) || err?.message || 'AI 对话请求失败';
  6318. this.dhChatError = msg;
  6319. this.dhChatMessages.push({ role: 'assistant', content: `⚠️ ${msg}` });
  6320. this.refreshView();
  6321. }
  6322. });
  6323. }
  6324. /** 应用 AI 建议到对应字段;field 控制只应用一项还是两项一起 */
  6325. dhChatApply(msgIndex: number, field: 'tts' | 'prompt' | 'both'): void {
  6326. const msg = this.dhChatMessages[msgIndex];
  6327. if (!msg || msg.role !== 'assistant') return;
  6328. if ((field === 'tts' || field === 'both') && msg.suggestedTts) {
  6329. this.dhTtsText = msg.suggestedTts.slice(0, 600);
  6330. msg.appliedTts = true;
  6331. }
  6332. if ((field === 'prompt' || field === 'both') && msg.suggestedPrompt) {
  6333. this.dhPrompt = msg.suggestedPrompt.slice(0, 200);
  6334. msg.appliedPrompt = true;
  6335. }
  6336. this.showToast('✅ 已应用 AI 建议', 'success', 2000);
  6337. this.refreshView();
  6338. }
  6339. /** 清空对话历史 */
  6340. dhChatClear(): void {
  6341. this.dhChatMessages = [];
  6342. this.dhChatError = '';
  6343. this.dhChatInput = '';
  6344. this.refreshView();
  6345. }
  6346. /** 快捷指令:一键发送预设的改写诉求 */
  6347. dhChatQuickAsk(preset: string): void {
  6348. if (this.dhChatLoading) return;
  6349. this.dhChatInput = preset;
  6350. this.dhChatSend();
  6351. }
  6352. /** 刷新数字人形象库(重新拉取生成结果) */
  6353. refreshDigitalHumanGallery(): void {
  6354. this.http.get<any[]>('/backend/api/results').subscribe({
  6355. next: (results) => {
  6356. this.generatedResults = (results || []).map(r => ({ ...r, created_at: new Date(r.created_at) }));
  6357. this.showToast('🔄 形象库已刷新', 'success', 2500);
  6358. this.refreshView();
  6359. },
  6360. error: () => {
  6361. this.showToast('❌ 刷新失败,请稍后重试', 'error');
  6362. }
  6363. });
  6364. }
  6365. dhStartGeneration(): void {
  6366. if (this.dhLoading) return;
  6367. // 验证形象图
  6368. if (!this.dhImageFile) {
  6369. this.dhError = '请先上传数字人形象图';
  6370. this.refreshView();
  6371. return;
  6372. }
  6373. // 验证音频来源
  6374. if (this.dhAudioSource === 'tts') {
  6375. if (!this.dhCurrentVoiceSelection) {
  6376. this.dhError = '请先选择声音模型';
  6377. this.refreshView();
  6378. return;
  6379. }
  6380. if (!this.dhTtsText.trim()) {
  6381. this.dhError = '请输入口播文本';
  6382. this.refreshView();
  6383. return;
  6384. }
  6385. } else {
  6386. if (!this.dhUploadAudioFile) {
  6387. this.dhError = '请上传音频文件';
  6388. this.refreshView();
  6389. return;
  6390. }
  6391. }
  6392. this.dhError = '';
  6393. this.dhLoading = true;
  6394. this.dhStep = 'generating';
  6395. this.dhProgress = 0;
  6396. this.dhStatusText = '正在准备数字人素材...';
  6397. this.dhResultVideoUrl = '';
  6398. this.syncDigitalHumanDraft('running');
  6399. this.refreshView();
  6400. // 通过 DigitalHumanService 串联:上传图 → tts/upload 音频 → identify → generate
  6401. // 若已通过 <app-portrait-prepare> 生成对标/规范化形象图,则直接复用其 URL
  6402. const req: DigitalHumanRequest = {
  6403. portrait: this.dhPreparedPortraitUrl
  6404. ? { imageUrl: this.dhPreparedPortraitUrl }
  6405. : { imageFile: this.dhImageFile! },
  6406. audio: this.dhAudioSource === 'tts'
  6407. ? {
  6408. source: 'tts',
  6409. ttsText: this.dhTtsText.trim(),
  6410. ttsTimbreId: this.dhTtsTimbreId.trim(),
  6411. ttsVoiceSource: this.dhTtsVoiceSource,
  6412. ttsVoiceType: this.dhTtsVoiceType.trim(),
  6413. }
  6414. : { source: 'upload', audioFile: this.dhUploadAudioFile! },
  6415. prompt: this.dhPrompt || '',
  6416. fastMode: this.dhFastMode,
  6417. resolution: this.dhResolution
  6418. };
  6419. this.digitalHumanService.generate(req).subscribe({
  6420. next: (evt: DigitalHumanEvent) => {
  6421. this.ngZone.run(() => {
  6422. if (evt.type === 'progress') {
  6423. this.dhProgress = evt.progress;
  6424. this.dhStatusText = evt.status;
  6425. // 同步老的子状态,让 checklist UI 仍能显示阶段
  6426. if (evt.stage === 'prepare-audio') {
  6427. this.dhSynthesizing = this.dhAudioSource === 'tts';
  6428. this.dhUploadingAudio = this.dhAudioSource === 'upload';
  6429. } else {
  6430. this.dhSynthesizing = false;
  6431. this.dhUploadingAudio = false;
  6432. }
  6433. this.refreshView();
  6434. } else {
  6435. // result
  6436. this.dhProgress = 100;
  6437. this.dhResultVideoUrl = evt.videoUrl;
  6438. this.dhImageAssetUrl = evt.imageUrl;
  6439. this.dhUploadAudioUrl = evt.audioUrl;
  6440. this.dhStatusText = '数字人视频生成完成!';
  6441. this.dhLoading = false;
  6442. this.dhStep = 'done';
  6443. this.dhSynthesizing = false;
  6444. this.dhUploadingAudio = false;
  6445. this.completeDigitalHumanDraft(evt.videoUrl, evt.imageUrl, evt.audioUrl);
  6446. this.showToast('✅ 数字人视频已生成', 'success', 6000);
  6447. // 保存到结果
  6448. this.saveResult({
  6449. type: 'video',
  6450. url: evt.videoUrl,
  6451. title: `数字人合成 - ${new Date().toLocaleString('zh-CN')}`,
  6452. quality: this.dhResolution === '1080p' ? '1080P' : '720P',
  6453. duration: '数字人视频',
  6454. cost: 0,
  6455. segments: [{ id: 'DH-01', videoUrl: evt.videoUrl, prompt: this.dhPrompt, status: 'completed' }]
  6456. });
  6457. this.saveHistoryRecord({
  6458. keyword: '数字人合成',
  6459. status: 'completed',
  6460. cost: 0,
  6461. duration: '数字人视频',
  6462. styleName: '数字人合成',
  6463. resultUrl: evt.videoUrl,
  6464. quality: this.dhResolution === '1080p' ? '1080P' : '720P',
  6465. segmentCount: 1,
  6466. successCount: 1
  6467. });
  6468. this.addDhVideoToManifest(evt.videoUrl);
  6469. this.refreshView();
  6470. }
  6471. });
  6472. },
  6473. error: (err: any) => {
  6474. this.ngZone.run(() => {
  6475. this.dhHandleError(this.getErrorText(err, '数字人视频生成失败'));
  6476. });
  6477. }
  6478. });
  6479. }
  6480. /** @deprecated 旧的同名方法已合并到 dhStartGeneration,保留以避免破坏现有调用。 */
  6481. private _legacyDhUploadFlow(): void {
  6482. if (!this.dhImageFile) return;
  6483. this.jimengService.uploadFileToParse(
  6484. this.dhImageFile,
  6485. `digital-human-${Date.now()}-${this.dhImageFile.name}`,
  6486. this.dhImageFile.type || 'image/jpeg'
  6487. ).subscribe({
  6488. next: (imageUrl: string) => {
  6489. this.dhImageAssetUrl = imageUrl;
  6490. this.dhProgress = 10;
  6491. this.refreshView();
  6492. if (this.dhAudioSource === 'tts') {
  6493. this.dhStatusText = '形象图上传完成,正在合成语音...';
  6494. this.dhSynthesizing = true;
  6495. this.refreshView();
  6496. this.http.post<any>('https://server.fmode.cn/api/volcengine/tts/unidirectional', {
  6497. token: this.voiceApiToken,
  6498. text: this.dhTtsText.trim(),
  6499. timbreId: this.dhTtsTimbreId.trim(),
  6500. isStream: false,
  6501. audio_params: {
  6502. format: 'mp3',
  6503. sample_rate: 24000,
  6504. speech_rate: 0,
  6505. loudness_rate: 0
  6506. }
  6507. }).subscribe({
  6508. next: (res) => {
  6509. this.dhSynthesizing = false;
  6510. if (res?.code === 200 && res?.data?.audioUrl) {
  6511. this.dhProgress = 25;
  6512. this.dhStatusText = '语音合成完成,正在识别数字人主体...';
  6513. this.refreshView();
  6514. this.dhGenerateWithAudio(imageUrl, res.data.audioUrl);
  6515. } else {
  6516. this.dhHandleError(res?.error?.message || '语音合成失败,请检查音色ID和文本');
  6517. }
  6518. },
  6519. error: (err) => {
  6520. this.dhSynthesizing = false;
  6521. this.dhHandleError(this.getErrorText(err, '语音合成请求失败'));
  6522. }
  6523. });
  6524. } else {
  6525. // 上传音频文件
  6526. this.dhStatusText = '形象图上传完成,正在上传音频文件...';
  6527. this.dhUploadingAudio = true;
  6528. this.refreshView();
  6529. const audioFile = this.dhUploadAudioFile!;
  6530. this.jimengService.uploadFileToParse(
  6531. audioFile,
  6532. `dh-audio-${Date.now()}-${audioFile.name}`,
  6533. audioFile.type || 'audio/mpeg'
  6534. ).subscribe({
  6535. next: (audioUrl: string) => {
  6536. this.dhUploadingAudio = false;
  6537. this.dhUploadAudioUrl = audioUrl;
  6538. this.dhProgress = 25;
  6539. this.dhStatusText = '音频上传完成,正在识别数字人主体...';
  6540. this.refreshView();
  6541. this.dhGenerateWithAudio(imageUrl, audioUrl);
  6542. },
  6543. error: (err) => {
  6544. this.dhUploadingAudio = false;
  6545. this.dhHandleError(err?.message || '上传音频文件失败');
  6546. }
  6547. });
  6548. }
  6549. },
  6550. error: (err) => {
  6551. this.dhHandleError(err?.message || '上传形象图失败');
  6552. }
  6553. });
  6554. }
  6555. private dhGenerateWithAudio(imageUrl: string, audioUrl: string): void {
  6556. console.log('🤖 数字人生成 - imageUrl:', imageUrl, 'audioUrl:', audioUrl);
  6557. this.jimengService.identifyDigitalHuman(imageUrl).subscribe({
  6558. next: ({ workId }) => {
  6559. this.jimengService.pollDigitalHumanIdentifyUntilReady(workId, (status, progress) => {
  6560. this.dhProgress = Math.min(25 + progress * 0.25, 50);
  6561. this.dhStatusText = status;
  6562. this.refreshView();
  6563. }).subscribe({
  6564. next: () => {
  6565. this.dhStatusText = '主体识别完成,开始生成数字人视频...';
  6566. this.dhProgress = 50;
  6567. this.refreshView();
  6568. this.jimengService.generateDigitalHuman(workId, audioUrl, {
  6569. prompt: this.dhPrompt,
  6570. peFastMode: this.dhResolution === '720p' ? true : this.dhFastMode,
  6571. outputResolution: this.dhResolution,
  6572. maskUrl: []
  6573. }, (status, progress) => {
  6574. this.dhProgress = Math.min(50 + progress * 0.45, 95);
  6575. this.dhStatusText = status;
  6576. this.refreshView();
  6577. }).subscribe({
  6578. next: (result) => {
  6579. this.dhProgress = 100;
  6580. this.dhResultVideoUrl = result.videoUrl;
  6581. this.dhStatusText = '数字人视频生成完成!';
  6582. this.dhLoading = false;
  6583. this.dhStep = 'done';
  6584. this.completeDigitalHumanDraft(result.videoUrl, this.dhImageAssetUrl || undefined, this.dhUploadAudioUrl || undefined);
  6585. this.showToast('✅ 数字人视频已生成', 'success', 6000);
  6586. // 保存到结果
  6587. this.saveResult({
  6588. type: 'video',
  6589. url: result.videoUrl,
  6590. title: `数字人合成 - ${new Date().toLocaleString('zh-CN')}`,
  6591. quality: this.dhResolution === '1080p' ? '1080P' : '720P',
  6592. duration: '数字人视频',
  6593. cost: 0,
  6594. segments: [{ id: 'DH-01', videoUrl: result.videoUrl, prompt: this.dhPrompt, status: 'completed' }]
  6595. });
  6596. this.saveHistoryRecord({
  6597. keyword: '数字人合成',
  6598. status: 'completed',
  6599. cost: 0,
  6600. duration: '数字人视频',
  6601. styleName: '数字人合成',
  6602. resultUrl: result.videoUrl,
  6603. quality: this.dhResolution === '1080p' ? '1080P' : '720P',
  6604. segmentCount: 1,
  6605. successCount: 1
  6606. });
  6607. // 同步到视频管理
  6608. this.addDhVideoToManifest(result.videoUrl);
  6609. this.refreshView();
  6610. },
  6611. error: (err) => this.dhHandleError(typeof err === 'string' ? err : err?.message || err?.error?.message || '数字人视频生成失败')
  6612. });
  6613. },
  6614. error: (err) => this.dhHandleError(typeof err === 'string' ? err : err?.message || err?.error?.message || '数字人主体识别失败')
  6615. });
  6616. },
  6617. error: (err) => this.dhHandleError(typeof err === 'string' ? err : err?.message || err?.error?.message || '提交数字人主体识别失败')
  6618. });
  6619. }
  6620. private dhHandleError(message: string): void {
  6621. this.dhLoading = false;
  6622. this.dhSynthesizing = false;
  6623. this.dhUploadingAudio = false;
  6624. this.dhProgress = 0;
  6625. this.dhStep = 'done';
  6626. this.dhStatusText = message;
  6627. this.dhError = message;
  6628. if (this.pipelineSession.active()?.pipelineId === 'digital-human') {
  6629. this.pipelineSession.fail(message);
  6630. }
  6631. this.showToast(`❌ ${message}`, 'error');
  6632. this.refreshView();
  6633. }
  6634. // ==================== 视频生成工作流 ====================
  6635. vgReset(): void {
  6636. this.vgStep = 1;
  6637. this.vgSourceFile = null;
  6638. this.vgSourceFileName = '';
  6639. this.vgSourceVideoUrl = '';
  6640. this.vgUploading = false;
  6641. this.vgUploadProgress = 0;
  6642. this.vgVideoId = '';
  6643. this.vgAnalyzing = false;
  6644. this.vgAnalysisText = '';
  6645. this.vgTranscript = '';
  6646. this.vgGeneratingScript = false;
  6647. this.vgScript = '';
  6648. this.vgScriptSegments = [];
  6649. this.vgGeneratingImages = false;
  6650. this.vgImageResults = [];
  6651. this.vgImageProgress = 0;
  6652. this.vgVoiceMode = 'system';
  6653. this.vgVoiceTimbreId = '';
  6654. this.vgVoiceName = '';
  6655. this.vgSynthesizing = false;
  6656. this.vgAudioUrls = [];
  6657. this.vgCompositing = false;
  6658. this.vgCompositingProgress = 0;
  6659. this.vgFinalVideoUrl = '';
  6660. this.vgError = '';
  6661. this.vgTaskId = '';
  6662. }
  6663. // 视频生成:创建任务(上传成功后调用)
  6664. private vgCreateTask(): void {
  6665. const tempId = `VG-${Date.now()}`;
  6666. const task: Task = {
  6667. id: tempId,
  6668. keyword: this.vgSourceFileName || '视频生成',
  6669. status: 'processing',
  6670. step: 'vg-upload',
  6671. progress: 10,
  6672. cost: 0,
  6673. created_at: new Date(),
  6674. updated_at: new Date(),
  6675. original_video_title: this.vgSourceFileName,
  6676. type: 'video-generation',
  6677. vgData: this.vgBuildSnapshot()
  6678. };
  6679. this.vgTaskId = tempId;
  6680. this.activeTasks.unshift(task);
  6681. // saveTask POST 后端会返回真实 id,回填后同步 vgTaskId
  6682. this.taskSaveReady = new Promise<void>((resolve) => {
  6683. this.http.post<any>('/backend/api/tasks', task).subscribe({
  6684. next: (res) => {
  6685. if (res?.task?.id) {
  6686. task.id = res.task.id;
  6687. this.vgTaskId = res.task.id;
  6688. }
  6689. this.updateTaskStats();
  6690. console.log('💾 视频生成任务已保存:', task.id);
  6691. resolve();
  6692. },
  6693. error: (err) => {
  6694. console.warn('⚠️ 任务保存失败:', err);
  6695. resolve();
  6696. }
  6697. });
  6698. });
  6699. this.updateTaskStats();
  6700. this.showToast('任务已创建,可在「任务管理」中查看和恢复进度', 'success');
  6701. }
  6702. // 视频生成:更新任务进度(每个步骤转换时调用)
  6703. private vgUpdateTaskProgress(step: Task['step'], progress: number, status: Task['status'] = 'processing'): void {
  6704. const task = this.activeTasks.find(t => t.id === this.vgTaskId || (t.type === 'video-generation' && t.vgData?.videoId === this.vgVideoId));
  6705. if (!task) return;
  6706. // 若任务已被用户取消,则不再覆盖回 processing 状态
  6707. if (task.id && this.canceledTaskIds.has(task.id)) {
  6708. return;
  6709. }
  6710. this.vgTaskId = task.id;
  6711. task.step = step;
  6712. task.progress = progress;
  6713. task.status = status;
  6714. task.updated_at = new Date();
  6715. task.error_message = status === 'failed' ? this.vgError : undefined;
  6716. task.vgData = this.vgBuildSnapshot();
  6717. if (status === 'completed' && this.vgFinalVideoUrl) {
  6718. task.result_url = this.vgFinalVideoUrl;
  6719. }
  6720. this.updateTask(task);
  6721. this.updateTaskStats();
  6722. }
  6723. // 视频生成:构建当前状态快照
  6724. private vgBuildSnapshot(): Task['vgData'] {
  6725. return {
  6726. videoId: this.vgVideoId,
  6727. sourceFileName: this.vgSourceFileName,
  6728. sourceVideoUrl: this.vgSourceVideoUrl,
  6729. step: this.vgStep,
  6730. transcript: this.vgTranscript,
  6731. analysisText: this.vgAnalysisText,
  6732. script: this.vgScript,
  6733. scriptSegments: this.vgScriptSegments,
  6734. imageResults: this.vgImageResults,
  6735. audioUrls: this.vgAudioUrls,
  6736. voiceMode: this.vgVoiceMode,
  6737. voiceSpeakerId: this.vgVoiceSpeakerId,
  6738. voiceTimbreId: this.vgVoiceTimbreId,
  6739. voiceName: this.vgVoiceName,
  6740. finalVideoUrl: this.vgFinalVideoUrl
  6741. };
  6742. }
  6743. // 视频生成:从任务恢复状态
  6744. vgResumeFromTask(task: Task): void {
  6745. if (!task.vgData) {
  6746. this.showToast('该任务没有可恢复的数据', 'warn');
  6747. return;
  6748. }
  6749. const d = task.vgData;
  6750. this.vgTaskId = task.id;
  6751. this.vgVideoId = d.videoId;
  6752. this.vgSourceFileName = d.sourceFileName;
  6753. this.vgSourceVideoUrl = d.sourceVideoUrl;
  6754. this.vgSourceFile = null; // File 对象无法持久化
  6755. this.vgStep = d.step;
  6756. this.vgTranscript = d.transcript;
  6757. this.vgAnalysisText = d.analysisText;
  6758. this.vgScript = d.script;
  6759. this.vgScriptSegments = d.scriptSegments || [];
  6760. this.vgImageResults = d.imageResults || [];
  6761. this.vgAudioUrls = d.audioUrls || [];
  6762. this.vgVoiceMode = d.voiceMode || 'system';
  6763. this.vgVoiceSpeakerId = d.voiceSpeakerId || 'zh_female_shuangkuai-am_16k';
  6764. this.vgVoiceTimbreId = d.voiceTimbreId || '';
  6765. this.vgVoiceName = d.voiceName || '';
  6766. this.vgFinalVideoUrl = d.finalVideoUrl || '';
  6767. this.vgError = '';
  6768. this.vgUploading = false;
  6769. this.vgAnalyzing = false;
  6770. this.vgGeneratingScript = false;
  6771. this.vgGeneratingImages = false;
  6772. this.vgSynthesizing = false;
  6773. this.vgCompositing = false;
  6774. // 切换到视频生成页
  6775. this.setCurrentTab('video-generation');
  6776. this.showToast(`已恢复任务:${d.sourceFileName},当前在第${d.step}步`, 'success');
  6777. this.refreshView();
  6778. }
  6779. // Step 1: 选择源视频文件
  6780. vgSelectFile(event: Event): void {
  6781. const input = event.target as HTMLInputElement;
  6782. const file = input?.files?.[0];
  6783. if (!file) return;
  6784. if (!file.type.startsWith('video/')) {
  6785. this.showToast('请选择视频文件', 'warn');
  6786. return;
  6787. }
  6788. this.vgSourceFile = file;
  6789. this.vgSourceFileName = file.name;
  6790. this.vgSourceVideoUrl = URL.createObjectURL(file);
  6791. this.vgError = '';
  6792. }
  6793. // Step 1 → 2: 上传视频并进入解析
  6794. vgUploadAndAnalyze(): void {
  6795. if (!this.vgSourceFile || this.vgUploading) return;
  6796. this.vgUploading = true;
  6797. this.vgUploadProgress = 0;
  6798. this.vgError = '';
  6799. const file = this.vgSourceFile;
  6800. const title = `视频生成源 - ${new Date().toLocaleString('zh-CN')}`;
  6801. let uploadedEntry: any = null;
  6802. this.qiniuUpload.uploadFileWithProgress(file, file.name, file.type || 'video/mp4', 'video').pipe(
  6803. switchMap((event) => {
  6804. if (event.state === 'progress') {
  6805. this.vgUploadProgress = event.progress;
  6806. this.cdr.detectChanges();
  6807. return of(null);
  6808. }
  6809. const url = event.url || '';
  6810. if (!url) throw new Error('上传失败:未返回视频 URL');
  6811. uploadedEntry = this.createUploadedVideoEntry(file, url, title, '视频生成源素材', ['视频生成']);
  6812. return this.http.post<any>('/backend/api/manifest', uploadedEntry);
  6813. })
  6814. ).subscribe({
  6815. next: (res) => {
  6816. if (!res) return;
  6817. const entry = res?.video || res?.data || uploadedEntry;
  6818. this.vgUploading = false;
  6819. this.vgVideoId = entry.id;
  6820. const newVideo = this.toManagedVideo(entry);
  6821. if (!this.managedVideos.some(v => v.id === newVideo.id)) {
  6822. this.managedVideos.unshift(newVideo);
  6823. this.updateCategoryCounts();
  6824. }
  6825. this.vgStep = 2;
  6826. this.vgCreateTask();
  6827. this.vgUpdateTaskProgress('vg-analyze', 15);
  6828. this.vgStartAnalysis();
  6829. this.cdr.detectChanges();
  6830. },
  6831. error: (err: any) => {
  6832. this.vgUploading = false;
  6833. this.vgError = err?.error?.error || err?.message || '上传失败';
  6834. this.cdr.detectChanges();
  6835. }
  6836. });
  6837. }
  6838. // Step 2: Gemini 视频识别(分析 + 转录),Whisper 作为降级方案
  6839. private vgStartAnalysis(): void {
  6840. this.vgAnalyzing = true;
  6841. this.vgTranscript = '';
  6842. this.vgAnalysisText = '';
  6843. this.refreshView();
  6844. const fileSizeMB = this.vgSourceFile ? this.vgSourceFile.size / 1024 / 1024 : 0;
  6845. if (this.vgSourceFile && fileSizeMB <= 20) {
  6846. // ≤20MB:Gemini 直接分析视频(画面+音频+转录)
  6847. this.vgAnalysisText = `正在将视频 (${fileSizeMB.toFixed(1)}MB) 发送给 Gemini 进行视频理解...`;
  6848. this.refreshView();
  6849. this.vgRunGeminiAnalysisAndTranscript();
  6850. } else if (this.vgVideoId) {
  6851. // >20MB:浏览器 ffmpeg.wasm 提取音轨 → Gemini 音频识别 + 转录
  6852. this.vgAnalysisText = `视频 ${fileSizeMB.toFixed(1)}MB 超过 Gemini 视频限制,正在提取音轨用 Gemini 音频识别...`;
  6853. this.refreshView();
  6854. this.vgRunAudioExtractAndGemini();
  6855. } else {
  6856. // 无文件 → Whisper 降级
  6857. this.vgAnalysisText = '使用 Whisper 语音识别...';
  6858. this.refreshView();
  6859. this.vgRunWhisperFallback();
  6860. }
  6861. }
  6862. // Gemini 一次请求:视频分析 + 精确转录
  6863. private async vgRunGeminiAnalysisAndTranscript(): Promise<void> {
  6864. try {
  6865. const base64 = await this.llmService.fileToBase64(this.vgSourceFile!);
  6866. const mimeType = this.vgSourceFile!.type || 'video/mp4';
  6867. const prompt = `你是一个专业的视频内容分析师。请仔细观看这个视频,完成以下两个任务:
  6868. ===== 任务一:视频内容分析 =====
  6869. 从画面和音频两个维度进行全面分析,提取:
  6870. 1. **视频主题和核心观点**:视频讲了什么
  6871. 2. **画面内容描述**:出现了哪些场景、人物、物体、文字
  6872. 3. **目标受众**:适合什么人群观看
  6873. 4. **内容风格**:教程/评测/新闻/故事/口播/Vlog等
  6874. 5. **关键知识点或亮点**(3-5条)
  6875. 6. **视觉风格评价**:画面质量、构图、色调、字幕等
  6876. 7. **建议的改进方向**
  6877. ===== 任务二:完整语音转录 =====
  6878. 请将视频中所有语音内容逐字转录为中文文本。要求:
  6879. - 忠实还原每一句话,不遗漏、不改写、不总结
  6880. - 保留说话人的原始用词和语气
  6881. - 按自然段落分段
  6882. - 如有专业术语或人名,请尽量准确
  6883. 请严格按以下格式输出(用分隔线区分两部分):
  6884. 【内容分析】
  6885. (这里输出任务一的分析结果)
  6886. ---TRANSCRIPT_START---
  6887. (这里输出任务二的完整语音转录文本,只包含转录内容,不要加任何说明)
  6888. ---TRANSCRIPT_END---`;
  6889. this.llmService.analyzeVideo(base64, mimeType, prompt, {
  6890. model: 'gemini-2.5-flash',
  6891. generationConfig: { maxOutputTokens: 8192 }
  6892. }).subscribe({
  6893. next: (result) => {
  6894. this.vgParseGeminiResult(result);
  6895. this.vgAnalyzing = false;
  6896. this.vgUpdateTaskProgress('vg-analyze', 25);
  6897. this.refreshView();
  6898. },
  6899. error: (err) => {
  6900. console.warn('⚠️ Gemini 视频识别失败,降级为 Whisper:', err);
  6901. this.vgAnalysisText = 'Gemini 识别失败,正在使用 Whisper 语音识别...';
  6902. this.refreshView();
  6903. this.vgRunWhisperFallback();
  6904. }
  6905. });
  6906. } catch (err) {
  6907. console.warn('⚠️ 视频文件读取失败:', err);
  6908. this.vgAnalysisText = '视频文件读取失败,正在使用 Whisper 语音识别...';
  6909. this.refreshView();
  6910. this.vgRunWhisperFallback();
  6911. }
  6912. }
  6913. // 解析 Gemini 返回结果:拆分「内容分析」和「转录文本」
  6914. private vgParseGeminiResult(raw: string): void {
  6915. const transcriptMatch = raw.match(/---TRANSCRIPT_START---([\s\S]*?)---TRANSCRIPT_END---/);
  6916. if (transcriptMatch) {
  6917. this.vgTranscript = transcriptMatch[1].trim();
  6918. // 分析部分 = 转录标记之前的内容
  6919. const analysisPart = raw.substring(0, raw.indexOf('---TRANSCRIPT_START---')).trim();
  6920. this.vgAnalysisText = analysisPart.replace(/^【内容分析】\s*/, '') || '分析完成';
  6921. console.log(`✅ Gemini 分析+转录完成 (转录 ${this.vgTranscript.length} 字)`);
  6922. } else {
  6923. // 没有找到转录标记,整体作为分析结果
  6924. this.vgAnalysisText = raw || '分析完成';
  6925. console.warn('⚠️ Gemini 未返回转录标记,需手动输入文字稿');
  6926. }
  6927. }
  6928. // >20MB 视频:浏览器 ffmpeg.wasm 提取音轨 → Gemini 音频识别(分析+转录)
  6929. private vgRunAudioExtractAndGemini(): void {
  6930. const video = this.managedVideos.find(v => v.id === this.vgVideoId);
  6931. const source = this.vgSourceFile || (video ? this.getVideoPlayUrl(video) : '');
  6932. if (!source) {
  6933. this.vgAnalysisText = '缺少可访问的视频文件,无法提取音轨';
  6934. this.refreshView();
  6935. this.vgRunWhisperFallback();
  6936. return;
  6937. }
  6938. from(this.browserFfmpeg.extractAudioForGemini(source, `vg-${Date.now()}.m4a`)).subscribe({
  6939. next: (audio: BrowserAudioExtractionResult) => {
  6940. const audioSizeMB = audio.sizeMB || 0;
  6941. console.log(`🎵 音轨提取完成 (${audioSizeMB}MB),发送给 Gemini 音频识别...`);
  6942. this.vgAnalysisText = `音轨提取完成 (${audioSizeMB.toFixed(1)}MB),正在 Gemini 音频识别...`;
  6943. this.refreshView();
  6944. if (audioSizeMB > 20) {
  6945. // 音频仍然过大,降级为 Whisper
  6946. console.warn('⚠️ 提取的音频仍超过 20MB,降级为 Whisper');
  6947. this.vgAnalysisText = '音频文件仍较大,改用 Whisper 识别...';
  6948. this.refreshView();
  6949. this.vgRunWhisperFallback();
  6950. return;
  6951. }
  6952. const prompt = `你是一个专业的音频内容分析师。请仔细听这段音频,完成以下两个任务:
  6953. ===== 任务一:内容分析 =====
  6954. 从音频内容进行分析,提取:
  6955. 1. **主题和核心观点**:音频讲了什么
  6956. 2. **目标受众**:适合什么人群
  6957. 3. **内容风格**:教程/评测/新闻/故事/口播等
  6958. 4. **关键知识点或亮点**(3-5条)
  6959. 5. **建议的改进方向**
  6960. ===== 任务二:完整语音转录 =====
  6961. 请将音频中所有语音内容逐字转录为中文文本。要求:
  6962. - 忠实还原每一句话,不遗漏、不改写、不总结
  6963. - 保留说话人的原始用词和语气
  6964. - 按自然段落分段
  6965. - 如有专业术语或人名,请尽量准确
  6966. 请严格按以下格式输出(用分隔线区分两部分):
  6967. 【内容分析】
  6968. (这里输出任务一的分析结果)
  6969. ---TRANSCRIPT_START---
  6970. (这里输出任务二的完整语音转录文本,只包含转录内容,不要加任何说明)
  6971. ---TRANSCRIPT_END---`;
  6972. this.llmService.analyzeAudio(audio.base64, audio.mimeType || 'audio/mp4', prompt, {
  6973. model: 'gemini-2.5-flash',
  6974. generationConfig: { maxOutputTokens: 8192 }
  6975. }).subscribe({
  6976. next: (result) => {
  6977. this.vgParseGeminiResult(result);
  6978. this.vgAnalyzing = false;
  6979. this.refreshView();
  6980. },
  6981. error: (err) => {
  6982. console.warn('⚠️ Gemini 音频识别失败,降级为 Whisper:', err);
  6983. this.vgAnalysisText = 'Gemini 音频识别失败,改用 Whisper...';
  6984. this.refreshView();
  6985. this.vgRunWhisperFallback();
  6986. }
  6987. });
  6988. },
  6989. error: (err) => {
  6990. const detail = err?.error?.error || err?.message || `HTTP ${err?.status}`;
  6991. console.warn('⚠️ 音轨提取失败:', detail, err);
  6992. this.vgAnalysisText = `音轨提取失败 (${detail}),改用 Whisper...`;
  6993. this.refreshView();
  6994. this.vgRunWhisperFallback();
  6995. }
  6996. });
  6997. }
  6998. // 降级方案:Whisper 转录 + GPT 文本分析
  6999. private vgRunWhisperFallback(): void {
  7000. this.http.post<any>('/backend/api/whisper/transcribe', {
  7001. videoId: this.vgVideoId,
  7002. language: 'Chinese',
  7003. model: 'large'
  7004. }).subscribe({
  7005. next: (res) => {
  7006. if (res?.success && res?.transcript) {
  7007. this.vgTranscript = res.transcript;
  7008. this.vgAnalysisText = 'Whisper 转录完成,正在 AI 分析内容...';
  7009. this.refreshView();
  7010. // 用 GPT 做文本分析
  7011. this.vgDoTextAnalysis();
  7012. } else {
  7013. this.vgAnalyzing = false;
  7014. this.vgAnalysisText = '语音识别完成但未返回文字稿,请手动输入';
  7015. this.refreshView();
  7016. }
  7017. },
  7018. error: (err) => {
  7019. this.vgAnalyzing = false;
  7020. this.vgAnalysisText = `Whisper 识别失败: ${err?.error?.error || err?.message || '未知错误'}。请手动输入文字稿。`;
  7021. this.refreshView();
  7022. }
  7023. });
  7024. }
  7025. private vgDoTextAnalysis(): void {
  7026. const systemPrompt = `你是一个专业的视频内容分析师。请分析以下视频的转录文字稿,提取:
  7027. 1. 视频主题和核心观点
  7028. 2. 目标受众
  7029. 3. 内容风格(教程/评测/新闻/故事等)
  7030. 4. 关键知识点或亮点(3-5条)
  7031. 5. 建议的改进方向
  7032. 请用简洁的中文回复。`;
  7033. this.llmService.askWithSystem(systemPrompt, this.vgTranscript, { model: 'gemini-2.5-flash', max_tokens: 1024 }).subscribe({
  7034. next: (analysis) => {
  7035. this.vgAnalysisText = analysis || '分析完成';
  7036. this.vgAnalyzing = false;
  7037. this.refreshView();
  7038. },
  7039. error: () => {
  7040. this.vgAnalysisText = '(AI 文本分析暂不可用,已完成 Whisper 转录)';
  7041. this.vgAnalyzing = false;
  7042. this.refreshView();
  7043. }
  7044. });
  7045. }
  7046. vgConfirmAnalysis(): void {
  7047. if (!this.vgTranscript.trim()) {
  7048. this.showToast('请先完成视频转录或手动输入文字稿', 'warn');
  7049. return;
  7050. }
  7051. this.vgStep = 3;
  7052. this.vgUpdateTaskProgress('vg-script', 30);
  7053. this.vgGenerateScript();
  7054. }
  7055. // Step 3: LLM 生成分镜脚本
  7056. private vgGenerateScript(): void {
  7057. this.vgGeneratingScript = true;
  7058. this.vgScript = '';
  7059. this.vgScriptSegments = [];
  7060. const systemPrompt = `你是一个专业的短视频脚本编剧。根据以下视频转录文字稿,生成一个完整的分镜脚本。
  7061. ⚠️ 最重要的要求:你必须完整覆盖原文的全部内容,不得遗漏任何段落或要点!将原文从头到尾全部改写为分镜旁白,确保信息量100%覆盖。
  7062. 要求:
  7063. 1. 根据内容长度自动决定片段数量(短文5-8段,长文8-15段),确保原文每一段内容都被覆盖到
  7064. 2. 每个片段包含:旁白文本(narration)、配图英文提示词(imagePrompt)、配图中文提示词(imagePromptCn)
  7065. 3. 旁白文本要求:必须包含原文中的所有关键信息、数据、观点,不能省略或概括,只做口语化改写
  7066. 4. 配图中文提示词(imagePromptCn)是最重要的配图生成依据,要求:
  7067. - 描述一幅完整的16:9横版信息图/示意图画面
  7068. - 必须全部用中文描述,图片中的所有文字标注都是中文
  7069. - 内容紧密关联该段旁白,提取关键数据、概念、流程等
  7070. - 风格:白色或浅色简洁背景,扁平化设计,信息图表/流程图/概念图
  7071. - 包含中文大标题、关键词、数据可视化、图标、箭头等元素
  7072. - 注意:提示词中不要出现"PPT"、"幻灯片"、"演示文稿"等字样,只描述画面内容本身
  7073. 5. 配图英文提示词(imagePrompt)是备选提示词,描述同样的画面内容
  7074. 请严格按以下 JSON 格式返回(不要包含其他文字,不要用 markdown 代码块包裹):
  7075. [
  7076. {"id": "S-01", "narration": "旁白文本...", "imagePrompt": "English: 16:9 infographic...", "imagePromptCn": "16:9横版信息图,白色背景,大标题"xxx",下方用流程图展示xxx的步骤..."},
  7077. {"id": "S-02", "narration": "旁白文本...", "imagePrompt": "English: 16:9 infographic...", "imagePromptCn": "16:9横版信息图,浅色背景,标题"xxx",用图标和箭头展示xxx的关系..."}
  7078. ]`;
  7079. this.llmService.askWithSystem(systemPrompt, this.vgTranscript, { model: 'gemini-2.5-flash', max_tokens: 16384 }).subscribe({
  7080. next: (result) => {
  7081. this.vgScript = result;
  7082. this.vgGeneratingScript = false;
  7083. this.vgParseScriptSegments(result);
  7084. this.vgUpdateTaskProgress('vg-script', 40);
  7085. this.refreshView();
  7086. },
  7087. error: (err) => {
  7088. this.vgGeneratingScript = false;
  7089. this.vgError = `脚本生成失败: ${err?.message || '请重试'}`;
  7090. this.vgUpdateTaskProgress('vg-script', 30, 'failed');
  7091. this.refreshView();
  7092. }
  7093. });
  7094. }
  7095. private vgParseScriptSegments(raw: string): void {
  7096. console.log('📝 原始脚本响应:', raw.substring(0, 500));
  7097. // 1. 去除 markdown code block 包裹
  7098. let cleaned = raw;
  7099. const codeBlockMatch = cleaned.match(/```(?:json)?\s*([\s\S]*?)```/);
  7100. if (codeBlockMatch) {
  7101. cleaned = codeBlockMatch[1].trim();
  7102. }
  7103. // 2. 尝试提取 JSON 数组
  7104. const jsonMatch = cleaned.match(/\[[\s\S]*\]/);
  7105. if (jsonMatch) {
  7106. cleaned = jsonMatch[0];
  7107. }
  7108. // 3. 修复常见 JSON 问题(尾部逗号)
  7109. cleaned = cleaned.replace(/,\s*([}\]])/g, '$1');
  7110. try {
  7111. const parsed = JSON.parse(cleaned);
  7112. if (Array.isArray(parsed) && parsed.length > 0) {
  7113. this.vgScriptSegments = parsed.map((item: any, i: number) => ({
  7114. id: item.id || `S-${String(i + 1).padStart(2, '0')}`,
  7115. narration: item.narration || '',
  7116. imagePrompt: item.imagePrompt || item.image_prompt || '',
  7117. imagePromptCn: item.imagePromptCn || item.image_prompt_cn || ''
  7118. }));
  7119. console.log(`✅ 脚本解析成功: ${this.vgScriptSegments.length} 个片段`);
  7120. return;
  7121. }
  7122. } catch (e) {
  7123. console.warn('⚠️ JSON.parse 失败:', (e as Error).message);
  7124. }
  7125. // 4. 逐对象提取 fallback:正则匹配每个 {...} 块
  7126. try {
  7127. const objMatches = cleaned.match(/\{[^{}]*\}/g);
  7128. if (objMatches && objMatches.length > 0) {
  7129. const segments: any[] = [];
  7130. for (const objStr of objMatches) {
  7131. try {
  7132. const obj = JSON.parse(objStr.replace(/,\s*}/g, '}'));
  7133. if (obj.narration) segments.push(obj);
  7134. } catch {}
  7135. }
  7136. if (segments.length > 0) {
  7137. this.vgScriptSegments = segments.map((item: any, i: number) => ({
  7138. id: item.id || `S-${String(i + 1).padStart(2, '0')}`,
  7139. narration: item.narration || '',
  7140. imagePrompt: item.imagePrompt || item.image_prompt || '',
  7141. imagePromptCn: item.imagePromptCn || item.image_prompt_cn || ''
  7142. }));
  7143. console.log(`✅ 逐对象解析成功: ${this.vgScriptSegments.length} 个片段`);
  7144. return;
  7145. }
  7146. }
  7147. } catch {}
  7148. // 5. 最终 fallback:保留原始文本供用户手动编辑
  7149. console.warn('⚠️ 脚本解析全部失败,显示原文供手动编辑');
  7150. this.vgScriptSegments = [{
  7151. id: 'S-01',
  7152. narration: raw.replace(/```[\s\S]*?```/g, '').trim(),
  7153. imagePrompt: 'Professional PPT slide illustration, clean white background, infographic style',
  7154. imagePromptCn: '(脚本自动解析失败,请手动拆分片段)'
  7155. }];
  7156. }
  7157. vgConfirmScript(): void {
  7158. if (this.vgScriptSegments.length === 0) {
  7159. this.showToast('请先生成或编辑脚本', 'warn');
  7160. return;
  7161. }
  7162. this.vgStep = 4;
  7163. this.vgUpdateTaskProgress('vg-image', 45);
  7164. // 初始化图片结果列表
  7165. this.vgImageResults = this.vgScriptSegments.map(seg => ({
  7166. id: seg.id,
  7167. prompt: seg.imagePromptCn || seg.imagePrompt,
  7168. imageUrl: '',
  7169. status: 'pending' as const
  7170. }));
  7171. }
  7172. // Step 4: 批量生成配图(使用即梦 API)
  7173. vgGenerateImages(): void {
  7174. if (this.vgGeneratingImages) return;
  7175. this.vgGeneratingImages = true;
  7176. this.vgImageProgress = 0;
  7177. const pending = this.vgImageResults.filter(r => r.status === 'pending');
  7178. if (pending.length === 0) {
  7179. this.vgGeneratingImages = false;
  7180. return;
  7181. }
  7182. let completed = 0;
  7183. const total = pending.length;
  7184. const RETRY_MAX = 5;
  7185. const RETRY_DELAY = 15000; // 并发超限时等 15 秒重试
  7186. const GAP_DELAY = 6000; // 每张图之间间隔 6 秒,避免并发
  7187. const generateNext = (index: number, retryCount: number = 0) => {
  7188. if (index >= pending.length) {
  7189. this.vgGeneratingImages = false;
  7190. this.vgUpdateTaskProgress('vg-image', 60);
  7191. this.showToast(`配图生成完成 (${completed}/${total})`, completed > 0 ? 'success' : 'warn');
  7192. this.refreshView();
  7193. return;
  7194. }
  7195. const item = pending[index];
  7196. item.status = 'generating';
  7197. this.refreshView();
  7198. this.jimengService.generateImage(item.prompt, 1920, 1080).subscribe({
  7199. next: (res: any) => {
  7200. const workId = res?.data?.workId || res?.workId;
  7201. if (!workId) {
  7202. item.status = 'failed';
  7203. completed++;
  7204. this.refreshView();
  7205. setTimeout(() => generateNext(index + 1), GAP_DELAY);
  7206. return;
  7207. }
  7208. this.jimengService.pollUntilComplete(workId, 'getText2ImgV31', (status: any, attempt: number) => {
  7209. this.vgImageProgress = Math.round(((completed + Math.min(attempt / 20, 0.9)) / total) * 100);
  7210. this.refreshView();
  7211. }).subscribe({
  7212. next: (result: any) => {
  7213. const imageUrl = result?.images?.[0] || result?.url || '';
  7214. item.imageUrl = imageUrl;
  7215. item.status = imageUrl ? 'done' : 'failed';
  7216. completed++;
  7217. this.vgImageProgress = Math.round((completed / total) * 100);
  7218. this.refreshView();
  7219. setTimeout(() => generateNext(index + 1), GAP_DELAY);
  7220. },
  7221. error: () => {
  7222. item.status = 'failed';
  7223. completed++;
  7224. this.refreshView();
  7225. setTimeout(() => generateNext(index + 1), GAP_DELAY);
  7226. }
  7227. });
  7228. },
  7229. error: (err) => {
  7230. const errMsg = err?.error?.error?.message || err?.error?.message || err?.message || '';
  7231. const isRetryable = errMsg.includes('并发超限') || err?.status === 500 || err?.status === 429;
  7232. if (isRetryable && retryCount < RETRY_MAX) {
  7233. const backoff = RETRY_DELAY * (retryCount + 1); // 递增退避: 15s, 30s, 45s...
  7234. console.warn(`⚠️ 配图 ${item.id} 请求失败(${errMsg || err?.status}),${backoff / 1000}s 后第${retryCount + 1}次重试...`);
  7235. item.status = 'pending';
  7236. this.refreshView();
  7237. setTimeout(() => generateNext(index, retryCount + 1), backoff);
  7238. } else {
  7239. console.error(`❌ 配图 ${item.id} 最终失败:`, errMsg || err?.status);
  7240. item.status = 'failed';
  7241. completed++;
  7242. this.refreshView();
  7243. setTimeout(() => generateNext(index + 1), GAP_DELAY);
  7244. }
  7245. }
  7246. });
  7247. };
  7248. generateNext(0);
  7249. }
  7250. vgConfirmImages(): void {
  7251. this.vgStep = 5;
  7252. this.vgUpdateTaskProgress('vg-voice', 65);
  7253. }
  7254. // Step 5: 语音配音
  7255. vgSynthesizeAll(): void {
  7256. if (this.vgSynthesizing) return;
  7257. this.vgSynthesizing = true;
  7258. this.vgAudioUrls = [];
  7259. this.vgError = '';
  7260. const segments = this.vgScriptSegments;
  7261. let index = 0;
  7262. const failures: string[] = [];
  7263. const synthNext = () => {
  7264. if (index >= segments.length) {
  7265. this.vgSynthesizing = false;
  7266. const voicedSegments = segments.filter((item) => item.narration.trim());
  7267. const total = voicedSegments.length || segments.length;
  7268. const firstFailure = failures[0] ? `首个错误:${failures[0]}` : '';
  7269. if (this.vgAudioUrls.length === total) {
  7270. this.vgUpdateTaskProgress('vg-voice', 80);
  7271. this.showToast(`配音完成 (${this.vgAudioUrls.length}/${total})`, 'success');
  7272. } else if (this.vgAudioUrls.length > 0) {
  7273. this.vgError = `配音部分完成:${this.vgAudioUrls.length}/${total} 段成功,失败 ${total - this.vgAudioUrls.length} 段。${firstFailure}`;
  7274. this.showToast(this.vgError, 'warn');
  7275. } else {
  7276. this.vgError = `配音失败:${total} 段均未生成音频。${firstFailure}`;
  7277. this.showToast(this.vgError, 'error');
  7278. }
  7279. this.refreshView();
  7280. return;
  7281. }
  7282. const seg = segments[index];
  7283. const text = seg.narration;
  7284. if (!text.trim()) {
  7285. index++;
  7286. synthNext();
  7287. return;
  7288. }
  7289. // 使用远程 TTS 合成(server.fmode.cn)
  7290. const payload: any = {
  7291. token: this.voiceApiToken,
  7292. text,
  7293. isStream: false,
  7294. audio_params: {
  7295. format: 'mp3',
  7296. sample_rate: 24000,
  7297. speech_rate: 0,
  7298. loudness_rate: 0
  7299. }
  7300. };
  7301. this.applyVoiceSelectionToTtsPayload(
  7302. payload,
  7303. this.vgVoiceMode,
  7304. this.vgVoiceSpeakerId || 'zh_female_shuangkuai-am_16k',
  7305. this.vgVoiceTimbreId || '',
  7306. );
  7307. this.http.post<any>(`${this.voiceTtsBaseUrl}/unidirectional`, payload).subscribe({
  7308. next: (res) => {
  7309. const audioUrl = res?.data?.audioUrl || '';
  7310. if (audioUrl) {
  7311. this.vgAudioUrls.push({ segId: seg.id, audioUrl });
  7312. } else {
  7313. const message = this.getErrorText(res, '未返回 audioUrl');
  7314. failures.push(`${seg.id}: ${message}`);
  7315. console.warn(`配音片段 ${seg.id}: 未返回 audioUrl`, res);
  7316. }
  7317. index++;
  7318. this.refreshView();
  7319. synthNext();
  7320. },
  7321. error: (err) => {
  7322. failures.push(`${seg.id}: ${this.getErrorText(err, 'TTS 请求失败')}`);
  7323. console.warn(`配音片段 ${seg.id} 失败:`, err);
  7324. index++;
  7325. synthNext();
  7326. }
  7327. });
  7328. };
  7329. synthNext();
  7330. }
  7331. vgConfirmVoice(): void {
  7332. this.vgStep = 6;
  7333. this.vgUpdateTaskProgress('vg-composite', 85);
  7334. }
  7335. // Step 6: 合成最终视频(图片+音频 → 视频)
  7336. vgComposite(): void {
  7337. this.vgCompositing = true;
  7338. this.vgCompositingProgress = 0;
  7339. this.vgFinalVideoUrl = '';
  7340. this.vgError = '';
  7341. this.refreshView();
  7342. // 构建片段数据:匹配图片和音频
  7343. const segments: { id: string; imageUrl: string; audioUrl: string; }[] = [];
  7344. for (const seg of this.vgScriptSegments) {
  7345. const img = this.vgImageResults.find(r => r.id === seg.id);
  7346. const audio = this.vgAudioUrls.find(a => a.segId === seg.id);
  7347. if (img?.imageUrl && audio?.audioUrl) {
  7348. segments.push({ id: seg.id, imageUrl: img.imageUrl, audioUrl: audio.audioUrl });
  7349. }
  7350. }
  7351. if (segments.length === 0) {
  7352. this.vgCompositing = false;
  7353. this.vgError = '没有可用的图片+音频配对,无法合成视频';
  7354. this.showToast(this.vgError, 'error');
  7355. this.refreshView();
  7356. return;
  7357. }
  7358. // 模拟进度(因为后端是同步处理,用定时器模拟进度条)
  7359. let fakeProgress = 0;
  7360. const progressTimer = setInterval(() => {
  7361. fakeProgress = Math.min(fakeProgress + 2, 90);
  7362. this.vgCompositingProgress = fakeProgress;
  7363. this.refreshView();
  7364. }, 1000);
  7365. this.http.post<any>('/backend/api/video/composite', {
  7366. segments,
  7367. title: this.vgSourceFileName?.replace(/\.[^.]+$/, '') || '视频生成'
  7368. }).subscribe({
  7369. next: (res) => {
  7370. clearInterval(progressTimer);
  7371. this.vgCompositingProgress = 100;
  7372. this.vgCompositing = false;
  7373. if (res?.success && res?.videoUrl) {
  7374. this.vgFinalVideoUrl = '/backend' + res.videoUrl;
  7375. this.vgUpdateTaskProgress('vg-composite', 100, 'completed');
  7376. this.showToast(`视频合成完成!共 ${res.segments} 个片段`, 'success');
  7377. } else {
  7378. this.vgError = '合成返回结果异常';
  7379. this.vgUpdateTaskProgress('vg-composite', 90, 'failed');
  7380. this.showToast(this.vgError, 'error');
  7381. }
  7382. this.refreshView();
  7383. },
  7384. error: (err) => {
  7385. clearInterval(progressTimer);
  7386. this.vgCompositing = false;
  7387. this.vgCompositingProgress = 0;
  7388. this.vgError = `视频合成失败: ${err?.error?.error || err?.message || '请重试'}`;
  7389. this.vgUpdateTaskProgress('vg-composite', 85, 'failed');
  7390. this.showToast(this.vgError, 'error');
  7391. this.refreshView();
  7392. }
  7393. });
  7394. }
  7395. // 回到上一步
  7396. vgPrevStep(): void {
  7397. if (this.vgStep > 1) this.vgStep--;
  7398. }
  7399. // ===== 卡片瀑布展开/折叠控制 =====
  7400. vgGetStepState(n: number): 'done' | 'active' | 'locked' {
  7401. if (n < this.vgStep) return 'done';
  7402. if (n === this.vgStep) return 'active';
  7403. return 'locked';
  7404. }
  7405. vgIsStepExpanded(n: number): boolean {
  7406. if (n > this.vgStep) return false; // 未解锁:永远折叠
  7407. if (n === this.vgStep) return true; // 当前步骤:始终展开
  7408. return this.vgUserExpandedSteps.has(n); // 已完成:仅在用户手动展开时显示
  7409. }
  7410. vgToggleStepExpand(n: number): void {
  7411. if (n >= this.vgStep) return; // 当前/未解锁不可切换
  7412. if (this.vgUserExpandedSteps.has(n)) this.vgUserExpandedSteps.delete(n);
  7413. else this.vgUserExpandedSteps.add(n);
  7414. }
  7415. // 跳转到某个已完成步骤进行编辑(同时展开它)
  7416. vgEditStep(n: number): void {
  7417. if (n > this.vgStep) return; // 不能跳到未解锁
  7418. if (n < this.vgStep) {
  7419. const downstream = this.vgStep - n;
  7420. const ok = confirm(`返回步骤 ${n}「${this.vgStepLabels[n - 1]}」编辑后,需要重新确认下游 ${downstream} 个步骤,相关结果(脚本/配图/配音/合成)可能会被覆盖。是否继续?`);
  7421. if (!ok) return;
  7422. }
  7423. this.vgStep = n;
  7424. // 同时把该步骤从用户展开集合中清除(active 步骤会自动展开)
  7425. this.vgUserExpandedSteps.delete(n);
  7426. }
  7427. // 重新生成脚本
  7428. vgRegenerateScript(): void {
  7429. this.vgGenerateScript();
  7430. }
  7431. private addDhVideoToManifest(videoUrl: string): void {
  7432. const now = new Date();
  7433. const id = `DH-${Date.now()}`;
  7434. const title = `数字人合成 - ${now.toLocaleString('zh-CN')}`;
  7435. const filename = videoUrl.split('/').pop() || `digital-human-${id}.mp4`;
  7436. const newEntry = {
  7437. id,
  7438. title,
  7439. filename,
  7440. filepath: videoUrl,
  7441. size: 0,
  7442. duration: 0,
  7443. created_at: now.toISOString(),
  7444. modified_at: now.toISOString(),
  7445. category: 'general',
  7446. tags: ['数字人', 'AI生成'],
  7447. description: `数字人合成视频 (${this.dhResolution})`,
  7448. source: 'generated',
  7449. metadata: {
  7450. resolution: this.dhResolution === '1080p' ? '1920x1080' : '1280x720',
  7451. format: 'mp4'
  7452. }
  7453. };
  7454. this.http.post<any>('/backend/api/manifest', newEntry).subscribe({
  7455. next: (res) => {
  7456. if (res?.success) {
  7457. this.managedVideos.unshift({
  7458. ...newEntry,
  7459. created_at: now,
  7460. modified_at: now,
  7461. source: 'generated' as const
  7462. } as ManagedVideo);
  7463. this.updateCategoryCounts();
  7464. console.log('📁 数字人视频已同步到视频管理:', id);
  7465. }
  7466. },
  7467. error: (err) => console.warn('⚠️ 同步视频管理失败:', err)
  7468. });
  7469. }
  7470. }