Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+9
- README.md+108-3
- checkpoints/vocab.txtAdded+2545
- config.jsonAdded+16
- f5_tts/api.pyAdded+166
- f5_tts/configs/E2TTS_Base_train.yamlAdded+44
- f5_tts/configs/E2TTS_Small_train.yamlAdded+44
- f5_tts/configs/F5TTS_Base_train.yamlAdded+46
- f5_tts/configs/F5TTS_Small_train.yamlAdded+46
- f5_tts/eval/README.mdAdded+49
- f5_tts/eval/ecapa_tdnn.pyAdded+330
- f5_tts/eval/eval_infer_batch.pyAdded+207
- f5_tts/eval/eval_infer_batch.shAdded+13
- f5_tts/eval/eval_librispeech_test_clean.pyAdded+84
- f5_tts/eval/eval_seedtts_testset.pyAdded+84
- f5_tts/eval/utils_eval.pyAdded+405
- f5_tts/infer/README.mdAdded+193
- f5_tts/infer/SHARED.mdAdded+103
- f5_tts/infer/__pycache__/utils_infer.cpython-310.pycAdded
- f5_tts/infer/__pycache__/utils_infer.cpython-312.pycAdded
- f5_tts/infer/examples/basic/basic.tomlAdded+11
- f5_tts/infer/examples/basic/basic_ref_en.wavAdded+3
- f5_tts/infer/examples/basic/basic_ref_zh.wavAdded+3
- f5_tts/infer/examples/multi/country.flacAdded+3
- f5_tts/infer/examples/multi/main.flacAdded+3
- f5_tts/infer/examples/multi/story.tomlAdded+19
- f5_tts/infer/examples/multi/story.txtAdded+1
- f5_tts/infer/examples/multi/town.flacAdded+3
- f5_tts/infer/examples/vocab.txtAdded+2545
- f5_tts/infer/infer_batch_parallel.pyAdded+171
- f5_tts/infer/infer_cli.pyAdded+226
- f5_tts/infer/infer_cli_batch.pyAdded+245
- f5_tts/infer/infer_gradio.pyAdded+855
- f5_tts/infer/infer_gradio_orig.pyAdded+853
- f5_tts/infer/speech_edit.pyAdded+193
- f5_tts/infer/utils_infer.pyAdded+552
- f5_tts/model/__init__.pyAdded+10
- f5_tts/model/__pycache__/__init__.cpython-310.pycAdded
- f5_tts/model/__pycache__/cfm.cpython-310.pycAdded
- f5_tts/model/__pycache__/dataset.cpython-310.pycAdded
- f5_tts/model/__pycache__/modules.cpython-310.pycAdded
- f5_tts/model/__pycache__/trainer.cpython-310.pycAdded
- f5_tts/model/__pycache__/utils.cpython-310.pycAdded
- f5_tts/model/backbones/README.mdAdded+20
- f5_tts/model/backbones/__pycache__/dit.cpython-310.pycAdded
- f5_tts/model/backbones/__pycache__/mmdit.cpython-310.pycAdded
- f5_tts/model/backbones/__pycache__/unett.cpython-310.pycAdded
- f5_tts/model/backbones/dit.pyAdded+163
- f5_tts/model/backbones/mmdit.pyAdded+146
- f5_tts/model/backbones/unett.pyAdded+219
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines33343536373839404142434432 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textf5_tts/infer/examples/basic/basic_ref_en.wav filter=lfs diff=lfs merge=lfs -textf5_tts/infer/examples/basic/basic_ref_zh.wav filter=lfs diff=lfs merge=lfs -textf5_tts/infer/examples/multi/country.flac filter=lfs diff=lfs merge=lfs -textf5_tts/infer/examples/multi/main.flac filter=lfs diff=lfs merge=lfs -textf5_tts/infer/examples/multi/town.flac filter=lfs diff=lfs merge=lfs -textprompts/MAR_F_HAPPY_00001.wav filter=lfs diff=lfs merge=lfs -textprompts/PAN_F_HAPPY_00001.wav filter=lfs diff=lfs merge=lfs -textsamples/namaste.wav filter=lfs diff=lfs merge=lfs -textnamaste.wav filter=lfs diff=lfs merge=lfs -text
123---license: mit---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108---datasets:- ai4bharat/indicvoices_r- ai4bharat/Rasalanguage:- as- bn- gu- mr- hi- kn- ml- or- pa- ta- tepipeline_tag: text-to-speechlicense: mit---# **IndicF5: High-Quality Text-to-Speech for Indian Languages**We release **IndicF5**, a **near-human polyglot** **Text-to-Speech (TTS)** model trained on **1417 hours** of high-quality speech from **[Rasa](https://huggingface.co/datasets/ai4bharat/Rasa), [IndicTTS](https://www.iitm.ac.in/donlab/indictts/database), [LIMMITS](https://sites.google.com/view/limmits24/), and [IndicVoices-R](https://huggingface.co/datasets/ai4bharat/indicvoices_r)**.IndicF5 supports **11 Indian languages**:**Assamese, Bengali, Gujarati, Hindi, Kannada, Malayalam, Marathi, Odia, Punjabi, Tamil, Telugu.**NOTE - All rights goes to AI4Bharact, this repository is meant to improve the documentation and ease of installation.---## 🚀 Installation1. Install the ffmpeg library```bashsudo apt install ffmpeg```2. Create the environment and install dependencies:- CPU```bashuv pip install python=3.10source .venv/bin/activateuv pip install git+https://github.com/ai4bharat/IndicF5.git --torch-backend=cpuuv pip install torchcodec transformers==4.50.0 --torch-backend=cpu```- GPU```bashuv pip install python=3.10source .venv/bin/activateuv pip install git+https://github.com/ai4bharat/IndicF5.gituv pip install torchcodec transformers==4.50.0```## 🎙 UsageTo generate speech, you need to provide **three inputs**:1. **Text to synthesize** – The content you want the model to speak.2. **A reference prompt audio** – An example speech clip that guides the model’s prosody and speaker characteristics.3. **Text spoken in the reference prompt audio** – The transcript of the reference prompt audio.```pythonfrom transformers import AutoModelimport numpy as npimport soundfile as sf# Load IndicF5 from Hugging Facerepo_id = "Aditya02/IndicF5"model = AutoModel.from_pretrained(repo_id, trust_remote_code=True)# Generate speechaudio = model("नमस्ते! संगीत की तरह जीवन भी खूबसूरत होता है, बस इसे सही ताल में जीना आना चाहिए.",ref_audio_path="prompts/PAN_F_HAPPY_00001.wav",ref_text="ਭਹੰਪੀ ਵਿੱਚ ਸਮਾਰਕਾਂ ਦੇ ਭਵਨ ਨਿਰਮਾਣ ਕਲਾ ਦੇ ਵੇਰਵੇ ਗੁੰਝਲਦਾਰ ਅਤੇ ਹੈਰਾਨ ਕਰਨ ਵਾਲੇ ਹਨ, ਜੋ ਮੈਨੂੰ ਖੁਸ਼ ਕਰਦੇ ਹਨ।")# Normalize and save outputif audio.dtype == np.int16:audio = audio.astype(np.float32) / 32768.0sf.write("namaste.wav", np.array(audio, dtype=np.float32), samplerate=24000)print("Audio saved succesfully.")```You can find example prompt audios used [here](https://huggingface.co/ai4bharat/IndicF5/tree/main/prompts).## Terms of UseBy using this model, you agree to only clone voices for which you have explicit permission. Unauthorized voice cloning is strictly prohibited. Any misuse of this model is the responsibility of the user.## ReferencesWe would like to extend our gratitude to the authors of **[F5-TTS](https://github.com/SWivid/F5-TTS)** for their invaluable contributions and inspiration to this work. Their efforts have played a crucial role in advancing the field of text-to-speech synthesis.## 📖 CitationIf you use **IndicF5** in your research or projects, please consider citing it:### 🔹 BibTeX```bibtex@misc{AI4Bharat_IndicF5_2025,author = {Praveen S V and Srija Anand and Soma Siddhartha and Mitesh M. Khapra},title = {IndicF5: High-Quality Text-to-Speech for Indian Languages},year = {2025},url = {https://github.com/AI4Bharat/IndicF5},}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545 !"#$%&'()*+,-./0123456789:;=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]_aa1ai1ai2ai3ai4an1an3an4ang1ang2ang4ao1ao2ao3ao4bbaba1ba2ba3ba4bai1bai2bai3bai4ban1ban2ban3ban4bang1bang2bang3bang4bao1bao2bao3bao4beibei1bei2bei3bei4ben1ben2ben3ben4bengbeng1beng2beng3beng4bi1bi2bi3bi4bian1bian2bian3bian4biao1biao2biao3bie1bie2bie3bie4bin1bin4bing1bing2bing3bing4bobo1bo2bo3bo4bu2bu3bu4cca1cai1cai2cai3cai4can1can2can3can4cang1cang2cao1cao2cao3ce4cen1cen2ceng1ceng2ceng4cha1cha2cha3cha4chai1chai2chan1chan2chan3chan4chang1chang2chang3chang4chao1chao2chao3che1che2che3che4chen1chen2chen3chen4cheng1cheng2cheng3cheng4chi1chi2chi3chi4chong1chong2chong3chong4chou1chou2chou3chou4chu1chu2chu3chu4chua1chuai1chuai2chuai3chuai4chuan1chuan2chuan3chuan4chuang1chuang2chuang3chuang4chui1chui2chun1chun2chun3chuo1chuo4ci1ci2ci3ci4cong1cong2cou4cu1cu4cuan1cuan2cuan4cui1cui3cui4cun1cun2cun4cuo1cuo2cuo4ddada1da2da3da4dai1dai2dai3dai4dan1dan2dan3dan4dang1dang2dang3dang4dao1dao2dao3dao4dede1de2dei3den4deng1deng2deng3deng4di1di2di3di4dia3dian1dian2dian3dian4diao1diao3diao4die1die2die4ding1ding2ding3ding4diu1dong1dong3dong4dou1dou2dou3dou4du1du2du3du4duan1duan2duan3duan4dui1dui4dun1dun3dun4duo1duo2duo3duo4ee1e2e3e4ei2en1en4erer2er3er4ffa1fa2fa3fa4fan1fan2fan3fan4fang1fang2fang3fang4fei1fei2fei3fei4fen1fen2fen3fen4feng1feng2feng3feng4fo2fou2fou3fu1fu2fu3fu4gga1ga2ga3ga4gai1gai2gai3gai4gan1gan2gan3gan4gang1gang2gang3gang4gao1gao2gao3gao4ge1ge2ge3ge4gei2gei3gen1gen2gen3gen4geng1geng3geng4gong1gong3gong4gou1gou2gou3gou4gugu1gu2gu3gu4gua1gua2gua3gua4guai1guai2guai3guai4guan1guan2guan3guan4guang1guang2guang3guang4gui1gui2gui3gui4gun3gun4guo1guo2guo3guo4hha1ha2ha3hai1hai2hai3hai4han1han2han3han4hang1hang2hang4hao1hao2hao3hao4he1he2he4hei1hen2hen3hen4heng1heng2heng4hong1hong2hong3hong4hou1hou2hou3hou4hu1hu2hu3hu4hua1hua2hua4huai2huai4huan1huan2huan3huan4huang1huang2huang3huang4hui1hui2hui3hui4hun1hun2hun4huohuo1huo2huo3huo4ijji1ji2ji3ji4jiajia1jia2jia3jia4jian1jian2jian3jian4jiang1jiang2jiang3jiang4jiao1jiao2jiao3jiao4jie1jie2jie3jie4jin1jin2jin3jin4jing1jing2jing3jing4jiong3jiu1jiu2jiu3jiu4ju1ju2ju3ju4juan1juan2juan3juan4jue1jue2jue4jun1jun4kka1ka2ka3kai1kai2kai3kai4kan1kan2kan3kan4kang1kang2kang4kao1kao2kao3kao4ke1ke2ke3ke4ken3keng1kong1kong3kong4kou1kou2kou3kou4ku1ku2ku3ku4kua1kua3kua4kuai3kuai4kuan1kuan2kuan3kuang1kuang2kuang4kui1kui2kui3kui4kun1kun3kun4kuo4llala1la2la3la4lai2lai4lan2lan3lan4lang1lang2lang3lang4lao1lao2lao3lao4lele1le4leilei1lei2lei3lei4leng1leng2leng3leng4lili1li2li3li4lia3lian2lian3lian4liang2liang3liang4liao1liao2liao3liao4lie1lie2lie3lie4lin1lin2lin3lin4ling2ling3ling4liu1liu2liu3liu4long1long2long3long4lou1lou2lou3lou4lu1lu2lu3lu4luan2luan3luan4lun1lun2lun4luo1luo2luo3luo4lv2lv3lv4lve3lve4mmama1ma2ma3ma4mai2mai3mai4man1man2man3man4mang2mang3mao1mao2mao3mao4memei2mei3mei4menmen1men2men4mengmeng1meng2meng3meng4mi1mi2mi3mi4mian2mian3mian4miao1miao2miao3miao4mie1mie4min2min3ming2ming3ming4miu4mo1mo2mo3mo4mou1mou2mou3mu2mu3mu4nn2na1na2na3na4nai2nai3nai4nan1nan2nan3nan4nang1nang2nang3nao1nao2nao3nao4nene2ne4nei3nei4nen4neng2ni1ni2ni3ni4nian1nian2nian3nian4niang2niang4niao2niao3niao4nie1nie4nin2ning2ning3ning4niu1niu2niu3niu4nong2nong4nou4nu2nu3nu4nuan3nuo2nuo4nv2nv3nve4oo1o2ou1ou2ou3ou4ppa1pa2pa4pai1pai2pai3pai4pan1pan2pan4pang1pang2pang4pao1pao2pao3pao4pei1pei2pei4pen1pen2pen4peng1peng2peng3peng4pi1pi2pi3pi4pian1pian2pian4piao1piao2piao3piao4pie1pie2pie3pin1pin2pin3pin4ping1ping2po1po2po3po4pou1pu1pu2pu3pu4qqi1qi2qi3qi4qia1qia3qia4qian1qian2qian3qian4qiang1qiang2qiang3qiang4qiao1qiao2qiao3qiao4qie1qie2qie3qie4qin1qin2qin3qin4qing1qing2qing3qing4qiong1qiong2qiu1qiu2qiu3qu1qu2qu3qu4quan1quan2quan3quan4que1que2que4qun2rran2ran3rang1rang2rang3rang4rao2rao3rao4re2re3re4ren2ren3ren4reng1reng2ri4rong1rong2rong3rou2rou4ru2ru3ru4ruan2ruan3rui3rui4run4ruo4ssa1sa2sa3sa4sai1sai4san1san2san3san4sang1sang3sang4sao1sao2sao3sao4se4sen1seng1sha1sha2sha3sha4shai1shai2shai3shai4shan1shan3shan4shangshang1shang3shang4shao1shao2shao3shao4she1she2she3she4shei2shen1shen2shen3shen4sheng1sheng2sheng3sheng4shishi1shi2shi3shi4shou1shou2shou3shou4shu1shu2shu3shu4shua1shua2shua3shua4shuai1shuai3shuai4shuan1shuan4shuang1shuang3shui2shui3shui4shun3shun4shuo1shuo4si1si2si3si4song1song3song4sou1sou3sou4su1su2su4suan1suan4sui1sui2sui3sui4sun1sun3suosuo1suo2suo3tta1ta2ta3ta4tai1tai2tai4tan1tan2tan3tan4tang1tang2tang3tang4tao1tao2tao3tao4te4teng2ti1ti2ti3ti4tian1tian2tian3tiao1tiao2tiao3tiao4tie1tie2tie3tie4ting1ting2ting3tong1tong2tong3tong4toutou1tou2tou4tu1tu2tu3tu4tuan1tuan2tui1tui2tui3tui4tun1tun2tun4tuo1tuo2tuo3tuo4uvwwawa1wa2wa3wa4wai1wai3wai4wan1wan2wan3wan4wang1wang2wang3wang4wei1wei2wei3wei4wen1wen2wen3wen4weng1weng4wo1wo2wo3wo4wu1wu2wu3wu4xxi1xi2xi3xi4xia1xia2xia4xian1xian2xian3xian4xiang1xiang2xiang3xiang4xiao1xiao2xiao3xiao4xie1xie2xie3xie4xin1xin2xin4xing1xing2xing3xing4xiong1xiong2xiu1xiu3xiu4xuxu1xu2xu3xu4xuan1xuan2xuan3xuan4xue1xue2xue3xue4xun1xun2xun4yyaya1ya2ya3ya4yan1yan2yan3yan4yang1yang2yang3yang4yao1yao2yao3yao4ye1ye2ye3ye4yiyi1yi2yi3yi4yin1yin2yin3yin4ying1ying2ying3ying4yo1yong1yong2yong3yong4you1you2you3you4yu1yu2yu3yu4yuan1yuan2yuan3yuan4yue1yue4yun1yun2yun3yun4zza1za2za3zai1zai3zai4zan1zan2zan3zan4zang1zang4zao1zao2zao3zao4ze2ze4zei2zen3zeng1zeng4zha1zha2zha3zha4zhai1zhai2zhai3zhai4zhan1zhan2zhan3zhan4zhang1zhang2zhang3zhang4zhao1zhao2zhao3zhao4zhezhe1zhe2zhe3zhe4zhen1zhen2zhen3zhen4zheng1zheng2zheng3zheng4zhi1zhi2zhi3zhi4zhong1zhong2zhong3zhong4zhou1zhou2zhou3zhou4zhu1zhu2zhu3zhu4zhua1zhua2zhua3zhuai1zhuai3zhuai4zhuan1zhuan2zhuan3zhuan4zhuang1zhuang4zhui1zhui4zhun1zhun2zhun3zhuo1zhuo2zizi1zi2zi3zi4zong1zong2zong3zong4zou1zou2zou3zou4zu1zu2zu3zuan1zuan3zuan4zui2zui3zui4zun1zuozuo1zuo2zuo3zuo4{~¡¢£¥§¨©«®¯°±²³´µ·¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊÍÎÑÓÖרÚÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýĀāăąćČčĐđēėęěĝğħīįİıŁłńņňŋŌōőœřŚśŞşŠšŤťũūźŻżŽžơưǎǐǒǔǚșțɑɔɕəɛɜɡɣɪɫɴɹɾʃʊʌʒʔʰʷʻʾʿˈː˙˜ˢ́̅ΑΒΔΕΘΚΛΜΞΠΣΤΦΧΨΩάέήίαβγδεζηθικλμνξοπρςστυφχψωϊόύώϕϵЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяёіְִֵֶַָֹ
<^`|} ʼ̮ँंःअआइईउऊऋऍऎएऐऑऒओऔकखगघङचछजझञटठडढणतथदधनऩपफबभमयरऱलळऴवशषसहऺऻ़ऽािीुूृॄॅॆेैॉॊोौ्ॐ॒॑॔ॕॖक़ख़ग़ज़ड़ढ़फ़य़ॠ।॥०१२३४५६७८९॰ॲঁংঃঅআইঈউঊঋঌএঐওঔকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহ়ঽািীুূৃৄেৈোৌ্ৎৗড়ঢ়য়০১২৩৪৫৬৭৮৯ৰৱ৲৷৹৻ਂਃਅਆਇਈਉਊਏਐਓਔਕਖਗਘਙਚਛਜਝਞਟਠਡਢਣਤਥਦਧਨਪਫਬਭਮਯਰਲਲ਼ਵਸ਼ਸਹ਼ਾਿੀੁੂੇੈੋੌ੍ੑਖ਼ਗ਼ਜ਼ੜਫ਼ੰੱੲੳઁંઃઅઆઇઈઉઊઋઍએઐઑઓઔકખગઘચછજઝઞટઠડઢણતથદધનપફબભમયરલળવશષસહ઼ાિીુૂૃૄૅેૈૉોૌ્ૐૠ૧૨૪૫ଁଂଃଅଆଇଈଉଊଋଏଐଓଔକଖଗଘଙଚଛଜଝଞଟଠଡଢଣତଥଦଧନପଫବଭମଯରଲଳଵଶଷସହ଼ାିୀୁୂୃୄେୈୋୌ୍ୖୗଡ଼ଢ଼ୟୠ୦୧୨୪୫୬୮ୱஃஅஆஇஈஉஊஎஏஐஒஓஔகஙசஜஞடணதநனபமயரறலளழவஷஸஹாிீுூெேைொோௌ்ௗ௦ఁంఃఅఆఇఈఉఊఋఎఏఐఒఓఔకఖగఘఙచఛజఝఞటఠడఢణతథదధనపఫబభమయరఱలళవశషసహఽాిీుూృౄెేైొోౌ్ౕౖౙౠ౦౩ಂಃಅಆಇಈಉಊಋಎಏಐಒಓಔಕಖಗಘಙಚಛಜಝಞಟಠಡಢಣತಥದಧನಪಫಬಭಮಯರಱಲಳವಶಷಸಹ಼ಽಾಿೀುೂೃೆೇೈೊೋೌ್ೕೖೞೠ೦೧೨೩೪೫೬೭೮೯ംഃഅആഇഈഉഊഋഎഏഐഒഓഔകഖഗഘങചഛജഝഞടഠഡഢണതഥദധനപഫബഭമയരറലളഴവശഷസഹാിീുൂൃെേൈൊോൌ്ൎൗൟൺൻർൽൾൿ ›⇒📯읽임입있자작잔잖잘잡잤장재저전점정제져졌조족좀종좋죠주준줄중줘즈즐즘지진집짜짝쩌쪼쪽쫌쭈쯔찌찍차착찾책처천철체쳐쳤초촌추출춤춥춰치친칠침칩칼커켓코콩쿠퀴크큰큽키킨타태터턴털테토통투트특튼틀티팀파팔패페펜펭평포폭표품풍프플피필하학한할함합항해햇했행허험형혜호혼홀화회획후휴흐흔희히힘ﷺﷻ!,?�𠮶12345678910111213141516{ "architectures": [ "INF5Model" ], "auto_map": { "AutoConfig": "model.INF5Config", "AutoModel": "model.INF5Model" }, "ckpt_path": "checkpoints/model_best.pt", "model_type": "inf5", "remove_sil": true, "speed": 1.0, "torch_dtype": "float32", "transformers_version": "4.49.0", "vocab_path": "checkpoints/vocab.txt"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166import randomimport sysfrom importlib.resources import files
import soundfile as sfimport tqdmfrom cached_path import cached_path
from f5_tts.infer.utils_infer import ( hop_length, infer_process, load_model, load_vocoder, preprocess_ref_audio_text, remove_silence_for_generated_wav, save_spectrogram, transcribe, target_sample_rate,)from f5_tts.model import DiT, UNetTfrom f5_tts.model.utils import seed_everything
class F5TTS: def __init__( self, model_type="F5-TTS", ckpt_file="", vocab_file="", ode_method="euler", use_ema=True, vocoder_name="vocos", local_path=None, device=None, hf_cache_dir=None, ): # Initialize parameters self.final_wave = None self.target_sample_rate = target_sample_rate self.hop_length = hop_length self.seed = -1 self.mel_spec_type = vocoder_name
# Set device if device is not None: self.device = device else: import torch
self.device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
# Load models self.load_vocoder_model(vocoder_name, local_path=local_path, hf_cache_dir=hf_cache_dir) self.load_ema_model( model_type, ckpt_file, vocoder_name, vocab_file, ode_method, use_ema, hf_cache_dir=hf_cache_dir )
def load_vocoder_model(self, vocoder_name, local_path=None, hf_cache_dir=None): self.vocoder = load_vocoder(vocoder_name, local_path is not None, local_path, self.device, hf_cache_dir)
def load_ema_model(self, model_type, ckpt_file, mel_spec_type, vocab_file, ode_method, use_ema, hf_cache_dir=None): if model_type == "F5-TTS": if not ckpt_file: if mel_spec_type == "vocos": ckpt_file = str( cached_path("hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors", cache_dir=hf_cache_dir) ) elif mel_spec_type == "bigvgan": ckpt_file = str( cached_path("hf://SWivid/F5-TTS/F5TTS_Base_bigvgan/model_1250000.pt", cache_dir=hf_cache_dir) ) model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4) model_cls = DiT elif model_type == "E2-TTS": if not ckpt_file: ckpt_file = str( cached_path("hf://SWivid/E2-TTS/E2TTS_Base/model_1200000.safetensors", cache_dir=hf_cache_dir) ) model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4) model_cls = UNetT else: raise ValueError(f"Unknown model type: {model_type}")
self.ema_model = load_model( model_cls, model_cfg, ckpt_file, mel_spec_type, vocab_file, ode_method, use_ema, self.device )
def transcribe(self, ref_audio, language=None): return transcribe(ref_audio, language)
def export_wav(self, wav, file_wave, remove_silence=False): sf.write(file_wave, wav, self.target_sample_rate)
if remove_silence: remove_silence_for_generated_wav(file_wave)
def export_spectrogram(self, spect, file_spect): save_spectrogram(spect, file_spect)
def infer( self, ref_file, ref_text, gen_text, show_info=print, progress=tqdm, target_rms=0.1, cross_fade_duration=0.15, sway_sampling_coef=-1, cfg_strength=2, nfe_step=32, speed=1.0, fix_duration=None, remove_silence=False, file_wave=None, file_spect=None, seed=-1, ): if seed == -1: seed = random.randint(0, sys.maxsize) seed_everything(seed) self.seed = seed
ref_file, ref_text = preprocess_ref_audio_text(ref_file, ref_text, device=self.device)
wav, sr, spect = infer_process( ref_file, ref_text, gen_text, self.ema_model, self.vocoder, self.mel_spec_type, show_info=show_info, progress=progress, target_rms=target_rms, cross_fade_duration=cross_fade_duration, nfe_step=nfe_step, cfg_strength=cfg_strength, sway_sampling_coef=sway_sampling_coef, speed=speed, fix_duration=fix_duration, device=self.device, )
if file_wave is not None: self.export_wav(wav, file_wave, remove_silence)
if file_spect is not None: self.export_spectrogram(spect, file_spect)
return wav, sr, spect
if __name__ == "__main__": f5tts = F5TTS()
wav, sr, spect = f5tts.infer( ref_file=str(files("f5_tts").joinpath("infer/examples/basic/basic_ref_en.wav")), ref_text="some call me nature, others call me mother nature.", gen_text="""I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall. But always remember, I am mighty and enduring. Respect me and I'll nurture you; ignore me and you shall face the consequences.""", file_wave=str(files("f5_tts").joinpath("../../tests/api_out.wav")), file_spect=str(files("f5_tts").joinpath("../../tests/api_out.png")), seed=-1, # random seed = -1 )
print("seed :", f5tts.seed)1234567891011121314151617181920212223242526272829303132333435363738394041424344hydra: run: dir: ckpts/${model.name}_${model.mel_spec.mel_spec_type}_${model.tokenizer}_${datasets.name}/${now:%Y-%m-%d}/${now:%H-%M-%S} datasets: name: Emilia_ZH_EN # dataset name batch_size_per_gpu: 38400 # 8 GPUs, 8 * 38400 = 307200 batch_size_type: frame # "frame" or "sample" max_samples: 64 # max sequences per batch if use frame-wise batch_size. we set 32 for small models, 64 for base models num_workers: 16
optim: epochs: 15 learning_rate: 7.5e-5 num_warmup_updates: 20000 # warmup steps grad_accumulation_steps: 1 # note: updates = steps / grad_accumulation_steps max_grad_norm: 1.0 # gradient clipping bnb_optimizer: False # use bnb 8bit AdamW optimizer or not
model: name: E2TTS_Base tokenizer: pinyin tokenizer_path: None # if tokenizer = 'custom', define the path to the tokenizer you want to use (should be vocab.txt) arch: dim: 1024 depth: 24 heads: 16 ff_mult: 4 mel_spec: target_sample_rate: 24000 n_mel_channels: 100 hop_length: 256 win_length: 1024 n_fft: 1024 mel_spec_type: vocos # 'vocos' or 'bigvgan' vocoder: is_local: False # use local offline ckpt or not local_path: None # local vocoder path
ckpts: logger: wandb # wandb | tensorboard | None save_per_updates: 50000 # save checkpoint per steps last_per_steps: 5000 # save last checkpoint per steps save_dir: ckpts/${model.name}_${model.mel_spec.mel_spec_type}_${model.tokenizer}_${datasets.name}1234567891011121314151617181920212223242526272829303132333435363738394041424344hydra: run: dir: ckpts/${model.name}_${model.mel_spec.mel_spec_type}_${model.tokenizer}_${datasets.name}/${now:%Y-%m-%d}/${now:%H-%M-%S} datasets: name: Emilia_ZH_EN batch_size_per_gpu: 38400 # 8 GPUs, 8 * 38400 = 307200 batch_size_type: frame # "frame" or "sample" max_samples: 64 # max sequences per batch if use frame-wise batch_size. we set 32 for small models, 64 for base models num_workers: 16
optim: epochs: 15 learning_rate: 7.5e-5 num_warmup_updates: 20000 # warmup steps grad_accumulation_steps: 1 # note: updates = steps / grad_accumulation_steps max_grad_norm: 1.0 bnb_optimizer: False
model: name: E2TTS_Small tokenizer: pinyin tokenizer_path: None # if tokenizer = 'custom', define the path to the tokenizer you want to use (should be vocab.txt) arch: dim: 768 depth: 20 heads: 12 ff_mult: 4 mel_spec: target_sample_rate: 24000 n_mel_channels: 100 hop_length: 256 win_length: 1024 n_fft: 1024 mel_spec_type: vocos # 'vocos' or 'bigvgan' vocoder: is_local: False # use local offline ckpt or not local_path: None # local vocoder path
ckpts: logger: wandb # wandb | tensorboard | None save_per_updates: 50000 # save checkpoint per steps last_per_steps: 5000 # save last checkpoint per steps save_dir: ckpts/${model.name}_${model.mel_spec.mel_spec_type}_${model.tokenizer}_${datasets.name}12345678910111213141516171819202122232425262728293031323334353637383940414243444546hydra: run: dir: ckpts/${model.name}_${model.mel_spec.mel_spec_type}_${model.tokenizer}_${datasets.name}/${now:%Y-%m-%d}/${now:%H-%M-%S} datasets: name: Emilia_ZH_EN # dataset name batch_size_per_gpu: 38400 # 8 GPUs, 8 * 38400 = 307200 batch_size_type: frame # "frame" or "sample" max_samples: 64 # max sequences per batch if use frame-wise batch_size. we set 32 for small models, 64 for base models num_workers: 16
optim: epochs: 15 learning_rate: 7.5e-5 num_warmup_updates: 20000 # warmup steps grad_accumulation_steps: 1 # note: updates = steps / grad_accumulation_steps max_grad_norm: 1.0 # gradient clipping bnb_optimizer: False # use bnb 8bit AdamW optimizer or not
model: name: F5TTS_Base # model name tokenizer: pinyin # tokenizer type tokenizer_path: None # if tokenizer = 'custom', define the path to the tokenizer you want to use (should be vocab.txt) arch: dim: 1024 depth: 22 heads: 16 ff_mult: 2 text_dim: 512 conv_layers: 4 mel_spec: target_sample_rate: 24000 n_mel_channels: 100 hop_length: 256 win_length: 1024 n_fft: 1024 mel_spec_type: vocos # 'vocos' or 'bigvgan' vocoder: is_local: False # use local offline ckpt or not local_path: None # local vocoder path
ckpts: logger: wandb # wandb | tensorboard | None save_per_updates: 50000 # save checkpoint per steps last_per_steps: 5000 # save last checkpoint per steps save_dir: ckpts/${model.name}_${model.mel_spec.mel_spec_type}_${model.tokenizer}_${datasets.name}12345678910111213141516171819202122232425262728293031323334353637383940414243444546hydra: run: dir: ckpts/${model.name}_${model.mel_spec.mel_spec_type}_${model.tokenizer}_${datasets.name}/${now:%Y-%m-%d}/${now:%H-%M-%S} datasets: name: Emilia_ZH_EN batch_size_per_gpu: 38400 # 8 GPUs, 8 * 38400 = 307200 batch_size_type: frame # "frame" or "sample" max_samples: 64 # max sequences per batch if use frame-wise batch_size. we set 32 for small models, 64 for base models num_workers: 16
optim: epochs: 15 learning_rate: 7.5e-5 num_warmup_updates: 20000 # warmup steps grad_accumulation_steps: 1 # note: updates = steps / grad_accumulation_steps max_grad_norm: 1.0 # gradient clipping bnb_optimizer: False # use bnb 8bit AdamW optimizer or not
model: name: F5TTS_Small tokenizer: pinyin tokenizer_path: None # if tokenizer = 'custom', define the path to the tokenizer you want to use (should be vocab.txt) arch: dim: 768 depth: 18 heads: 12 ff_mult: 2 text_dim: 512 conv_layers: 4 mel_spec: target_sample_rate: 24000 n_mel_channels: 100 hop_length: 256 win_length: 1024 n_fft: 1024 mel_spec_type: vocos # 'vocos' or 'bigvgan' vocoder: is_local: False # use local offline ckpt or not local_path: None # local vocoder path
ckpts: logger: wandb # wandb | tensorboard | None save_per_updates: 50000 # save checkpoint per steps last_per_steps: 5000 # save last checkpoint per steps save_dir: ckpts/${model.name}_${model.mel_spec.mel_spec_type}_${model.tokenizer}_${datasets.name}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
# Evaluation
Install packages for evaluation:
```bashpip install -e .[eval]```
## Generating Samples for Evaluation
### Prepare Test Datasets
1. *Seed-TTS testset*: Download from [seed-tts-eval](https://github.com/BytedanceSpeech/seed-tts-eval).2. *LibriSpeech test-clean*: Download from [OpenSLR](http://www.openslr.org/12/).3. Unzip the downloaded datasets and place them in the `data/` directory.4. Update the path for *LibriSpeech test-clean* data in `src/f5_tts/eval/eval_infer_batch.py`5. Our filtered LibriSpeech-PC 4-10s subset: `data/librispeech_pc_test_clean_cross_sentence.lst`
### Batch Inference for Test Set
To run batch inference for evaluations, execute the following commands:
```bash# batch inference for evaluationsaccelerate config # if not set beforebash src/f5_tts/eval/eval_infer_batch.sh```
## Objective Evaluation on Generated Results
### Download Evaluation Model Checkpoints
1. Chinese ASR Model: [Paraformer-zh](https://huggingface.co/funasr/paraformer-zh)2. English ASR Model: [Faster-Whisper](https://huggingface.co/Systran/faster-whisper-large-v3)3. WavLM Model: Download from [Google Drive](https://drive.google.com/file/d/1-aE1NfzpRCLxA4GUxX9ITI3F9LlbtEGP/view).
Then update in the following scripts with the paths you put evaluation model ckpts to.
### Objective Evaluation
Update the path with your batch-inferenced results, and carry out WER / SIM evaluations:```bash# Evaluation for Seed-TTS test setpython src/f5_tts/eval/eval_seedtts_testset.py --gen_wav_dir <GEN_WAVE_DIR>
# Evaluation for LibriSpeech-PC test-clean (cross-sentence)python src/f5_tts/eval/eval_librispeech_test_clean.py --gen_wav_dir <GEN_WAVE_DIR> --librispeech_test_clean_path <TEST_CLEAN_PATH>```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330# just for speaker similarity evaluation, third-party code
# From https://github.com/microsoft/UniSpeech/blob/main/downstreams/speaker_verification/models/# part of the code is borrowed from https://github.com/lawlict/ECAPA-TDNN
import osimport torchimport torch.nn as nnimport torch.nn.functional as F
""" Res2Conv1d + BatchNorm1d + ReLU"""
class Res2Conv1dReluBn(nn.Module): """ in_channels == out_channels == channels """
def __init__(self, channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=True, scale=4): super().__init__() assert channels % scale == 0, "{} % {} != 0".format(channels, scale) self.scale = scale self.width = channels // scale self.nums = scale if scale == 1 else scale - 1
self.convs = [] self.bns = [] for i in range(self.nums): self.convs.append(nn.Conv1d(self.width, self.width, kernel_size, stride, padding, dilation, bias=bias)) self.bns.append(nn.BatchNorm1d(self.width)) self.convs = nn.ModuleList(self.convs) self.bns = nn.ModuleList(self.bns)
def forward(self, x): out = [] spx = torch.split(x, self.width, 1) for i in range(self.nums): if i == 0: sp = spx[i] else: sp = sp + spx[i] # Order: conv -> relu -> bn sp = self.convs[i](sp) sp = self.bns[i](F.relu(sp)) out.append(sp) if self.scale != 1: out.append(spx[self.nums]) out = torch.cat(out, dim=1)
return out
""" Conv1d + BatchNorm1d + ReLU"""
class Conv1dReluBn(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=True): super().__init__() self.conv = nn.Conv1d(in_channels, out_channels, kernel_size, stride, padding, dilation, bias=bias) self.bn = nn.BatchNorm1d(out_channels)
def forward(self, x): return self.bn(F.relu(self.conv(x)))
""" The SE connection of 1D case."""
class SE_Connect(nn.Module): def __init__(self, channels, se_bottleneck_dim=128): super().__init__() self.linear1 = nn.Linear(channels, se_bottleneck_dim) self.linear2 = nn.Linear(se_bottleneck_dim, channels)
def forward(self, x): out = x.mean(dim=2) out = F.relu(self.linear1(out)) out = torch.sigmoid(self.linear2(out)) out = x * out.unsqueeze(2)
return out
""" SE-Res2Block of the ECAPA-TDNN architecture."""
# def SE_Res2Block(channels, kernel_size, stride, padding, dilation, scale):# return nn.Sequential(# Conv1dReluBn(channels, 512, kernel_size=1, stride=1, padding=0),# Res2Conv1dReluBn(512, kernel_size, stride, padding, dilation, scale=scale),# Conv1dReluBn(512, channels, kernel_size=1, stride=1, padding=0),# SE_Connect(channels)# )
class SE_Res2Block(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation, scale, se_bottleneck_dim): super().__init__() self.Conv1dReluBn1 = Conv1dReluBn(in_channels, out_channels, kernel_size=1, stride=1, padding=0) self.Res2Conv1dReluBn = Res2Conv1dReluBn(out_channels, kernel_size, stride, padding, dilation, scale=scale) self.Conv1dReluBn2 = Conv1dReluBn(out_channels, out_channels, kernel_size=1, stride=1, padding=0) self.SE_Connect = SE_Connect(out_channels, se_bottleneck_dim)
self.shortcut = None if in_channels != out_channels: self.shortcut = nn.Conv1d( in_channels=in_channels, out_channels=out_channels, kernel_size=1, )
def forward(self, x): residual = x if self.shortcut: residual = self.shortcut(x)
x = self.Conv1dReluBn1(x) x = self.Res2Conv1dReluBn(x) x = self.Conv1dReluBn2(x) x = self.SE_Connect(x)
return x + residual
""" Attentive weighted mean and standard deviation pooling."""
class AttentiveStatsPool(nn.Module): def __init__(self, in_dim, attention_channels=128, global_context_att=False): super().__init__() self.global_context_att = global_context_att
# Use Conv1d with stride == 1 rather than Linear, then we don't need to transpose inputs. if global_context_att: self.linear1 = nn.Conv1d(in_dim * 3, attention_channels, kernel_size=1) # equals W and b in the paper else: self.linear1 = nn.Conv1d(in_dim, attention_channels, kernel_size=1) # equals W and b in the paper self.linear2 = nn.Conv1d(attention_channels, in_dim, kernel_size=1) # equals V and k in the paper
def forward(self, x): if self.global_context_att: context_mean = torch.mean(x, dim=-1, keepdim=True).expand_as(x) context_std = torch.sqrt(torch.var(x, dim=-1, keepdim=True) + 1e-10).expand_as(x) x_in = torch.cat((x, context_mean, context_std), dim=1) else: x_in = x
# DON'T use ReLU here! In experiments, I find ReLU hard to converge. alpha = torch.tanh(self.linear1(x_in)) # alpha = F.relu(self.linear1(x_in)) alpha = torch.softmax(self.linear2(alpha), dim=2) mean = torch.sum(alpha * x, dim=2) residuals = torch.sum(alpha * (x**2), dim=2) - mean**2 std = torch.sqrt(residuals.clamp(min=1e-9)) return torch.cat([mean, std], dim=1)
class ECAPA_TDNN(nn.Module): def __init__( self, feat_dim=80, channels=512, emb_dim=192, global_context_att=False, feat_type="wavlm_large", sr=16000, feature_selection="hidden_states", update_extract=False, config_path=None, ): super().__init__()
self.feat_type = feat_type self.feature_selection = feature_selection self.update_extract = update_extract self.sr = sr
torch.hub._validate_not_a_forked_repo = lambda a, b, c: True try: local_s3prl_path = os.path.expanduser("~/.cache/torch/hub/s3prl_s3prl_main") self.feature_extract = torch.hub.load(local_s3prl_path, feat_type, source="local", config_path=config_path) except: # noqa: E722 self.feature_extract = torch.hub.load("s3prl/s3prl", feat_type)
if len(self.feature_extract.model.encoder.layers) == 24 and hasattr( self.feature_extract.model.encoder.layers[23].self_attn, "fp32_attention" ): self.feature_extract.model.encoder.layers[23].self_attn.fp32_attention = False if len(self.feature_extract.model.encoder.layers) == 24 and hasattr( self.feature_extract.model.encoder.layers[11].self_attn, "fp32_attention" ): self.feature_extract.model.encoder.layers[11].self_attn.fp32_attention = False
self.feat_num = self.get_feat_num() self.feature_weight = nn.Parameter(torch.zeros(self.feat_num))
if feat_type != "fbank" and feat_type != "mfcc": freeze_list = ["final_proj", "label_embs_concat", "mask_emb", "project_q", "quantizer"] for name, param in self.feature_extract.named_parameters(): for freeze_val in freeze_list: if freeze_val in name: param.requires_grad = False break
if not self.update_extract: for param in self.feature_extract.parameters(): param.requires_grad = False
self.instance_norm = nn.InstanceNorm1d(feat_dim) # self.channels = [channels] * 4 + [channels * 3] self.channels = [channels] * 4 + [1536]
self.layer1 = Conv1dReluBn(feat_dim, self.channels[0], kernel_size=5, padding=2) self.layer2 = SE_Res2Block( self.channels[0], self.channels[1], kernel_size=3, stride=1, padding=2, dilation=2, scale=8, se_bottleneck_dim=128, ) self.layer3 = SE_Res2Block( self.channels[1], self.channels[2], kernel_size=3, stride=1, padding=3, dilation=3, scale=8, se_bottleneck_dim=128, ) self.layer4 = SE_Res2Block( self.channels[2], self.channels[3], kernel_size=3, stride=1, padding=4, dilation=4, scale=8, se_bottleneck_dim=128, )
# self.conv = nn.Conv1d(self.channels[-1], self.channels[-1], kernel_size=1) cat_channels = channels * 3 self.conv = nn.Conv1d(cat_channels, self.channels[-1], kernel_size=1) self.pooling = AttentiveStatsPool( self.channels[-1], attention_channels=128, global_context_att=global_context_att ) self.bn = nn.BatchNorm1d(self.channels[-1] * 2) self.linear = nn.Linear(self.channels[-1] * 2, emb_dim)
def get_feat_num(self): self.feature_extract.eval() wav = [torch.randn(self.sr).to(next(self.feature_extract.parameters()).device)] with torch.no_grad(): features = self.feature_extract(wav) select_feature = features[self.feature_selection] if isinstance(select_feature, (list, tuple)): return len(select_feature) else: return 1
def get_feat(self, x): if self.update_extract: x = self.feature_extract([sample for sample in x]) else: with torch.no_grad(): if self.feat_type == "fbank" or self.feat_type == "mfcc": x = self.feature_extract(x) + 1e-6 # B x feat_dim x time_len else: x = self.feature_extract([sample for sample in x])
if self.feat_type == "fbank": x = x.log()
if self.feat_type != "fbank" and self.feat_type != "mfcc": x = x[self.feature_selection] if isinstance(x, (list, tuple)): x = torch.stack(x, dim=0) else: x = x.unsqueeze(0) norm_weights = F.softmax(self.feature_weight, dim=-1).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1) x = (norm_weights * x).sum(dim=0) x = torch.transpose(x, 1, 2) + 1e-6
x = self.instance_norm(x) return x
def forward(self, x): x = self.get_feat(x)
out1 = self.layer1(x) out2 = self.layer2(out1) out3 = self.layer3(out2) out4 = self.layer4(out3)
out = torch.cat([out2, out3, out4], dim=1) out = F.relu(self.conv(out)) out = self.bn(self.pooling(out)) out = self.linear(out)
return out
def ECAPA_TDNN_SMALL( feat_dim, emb_dim=256, feat_type="wavlm_large", sr=16000, feature_selection="hidden_states", update_extract=False, config_path=None,): return ECAPA_TDNN( feat_dim=feat_dim, channels=512, emb_dim=emb_dim, feat_type=feat_type, sr=sr, feature_selection=feature_selection, update_extract=update_extract, config_path=config_path, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207import osimport sys
sys.path.append(os.getcwd())
import argparseimport timefrom importlib.resources import files
import torchimport torchaudiofrom accelerate import Acceleratorfrom tqdm import tqdm
from f5_tts.eval.utils_eval import ( get_inference_prompt, get_librispeech_test_clean_metainfo, get_seedtts_testset_metainfo,)from f5_tts.infer.utils_infer import load_checkpoint, load_vocoderfrom f5_tts.model import CFM, DiT, UNetTfrom f5_tts.model.utils import get_tokenizer
accelerator = Accelerator()device = f"cuda:{accelerator.process_index}"
# --------------------- Dataset Settings -------------------- #
target_sample_rate = 24000n_mel_channels = 100hop_length = 256win_length = 1024n_fft = 1024target_rms = 0.1
rel_path = str(files("f5_tts").joinpath("../../"))
def main(): # ---------------------- infer setting ---------------------- #
parser = argparse.ArgumentParser(description="batch inference")
parser.add_argument("-s", "--seed", default=None, type=int) parser.add_argument("-d", "--dataset", default="Emilia_ZH_EN") parser.add_argument("-n", "--expname", required=True) parser.add_argument("-c", "--ckptstep", default=1200000, type=int) parser.add_argument("-m", "--mel_spec_type", default="vocos", type=str, choices=["bigvgan", "vocos"]) parser.add_argument("-to", "--tokenizer", default="pinyin", type=str, choices=["pinyin", "char"])
parser.add_argument("-nfe", "--nfestep", default=32, type=int) parser.add_argument("-o", "--odemethod", default="euler") parser.add_argument("-ss", "--swaysampling", default=-1, type=float)
parser.add_argument("-t", "--testset", required=True)
args = parser.parse_args()
seed = args.seed dataset_name = args.dataset exp_name = args.expname ckpt_step = args.ckptstep ckpt_path = rel_path + f"/ckpts/{exp_name}/model_{ckpt_step}.pt" mel_spec_type = args.mel_spec_type tokenizer = args.tokenizer
nfe_step = args.nfestep ode_method = args.odemethod sway_sampling_coef = args.swaysampling
testset = args.testset
infer_batch_size = 1 # max frames. 1 for ddp single inference (recommended) cfg_strength = 2.0 speed = 1.0 use_truth_duration = False no_ref_audio = False
if exp_name == "F5TTS_Base": model_cls = DiT model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
elif exp_name == "E2TTS_Base": model_cls = UNetT model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
if testset == "ls_pc_test_clean": metalst = rel_path + "/data/librispeech_pc_test_clean_cross_sentence.lst" librispeech_test_clean_path = "<SOME_PATH>/LibriSpeech/test-clean" # test-clean path metainfo = get_librispeech_test_clean_metainfo(metalst, librispeech_test_clean_path)
elif testset == "seedtts_test_zh": metalst = rel_path + "/data/seedtts_testset/zh/meta.lst" metainfo = get_seedtts_testset_metainfo(metalst)
elif testset == "seedtts_test_en": metalst = rel_path + "/data/seedtts_testset/en/meta.lst" metainfo = get_seedtts_testset_metainfo(metalst)
# path to save genereted wavs output_dir = ( f"{rel_path}/" f"results/{exp_name}_{ckpt_step}/{testset}/" f"seed{seed}_{ode_method}_nfe{nfe_step}_{mel_spec_type}" f"{f'_ss{sway_sampling_coef}' if sway_sampling_coef else ''}" f"_cfg{cfg_strength}_speed{speed}" f"{'_gt-dur' if use_truth_duration else ''}" f"{'_no-ref-audio' if no_ref_audio else ''}" )
# -------------------------------------------------#
use_ema = True
prompts_all = get_inference_prompt( metainfo, speed=speed, tokenizer=tokenizer, target_sample_rate=target_sample_rate, n_mel_channels=n_mel_channels, hop_length=hop_length, mel_spec_type=mel_spec_type, target_rms=target_rms, use_truth_duration=use_truth_duration, infer_batch_size=infer_batch_size, )
# Vocoder model local = False if mel_spec_type == "vocos": vocoder_local_path = "../checkpoints/charactr/vocos-mel-24khz" elif mel_spec_type == "bigvgan": vocoder_local_path = "../checkpoints/bigvgan_v2_24khz_100band_256x" vocoder = load_vocoder(vocoder_name=mel_spec_type, is_local=local, local_path=vocoder_local_path)
# Tokenizer vocab_char_map, vocab_size = get_tokenizer(dataset_name, tokenizer)
# Model model = CFM( transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels), mel_spec_kwargs=dict( n_fft=n_fft, hop_length=hop_length, win_length=win_length, n_mel_channels=n_mel_channels, target_sample_rate=target_sample_rate, mel_spec_type=mel_spec_type, ), odeint_kwargs=dict( method=ode_method, ), vocab_char_map=vocab_char_map, ).to(device)
dtype = torch.float32 if mel_spec_type == "bigvgan" else None model = load_checkpoint(model, ckpt_path, device, dtype=dtype, use_ema=use_ema)
if not os.path.exists(output_dir) and accelerator.is_main_process: os.makedirs(output_dir)
# start batch inference accelerator.wait_for_everyone() start = time.time()
with accelerator.split_between_processes(prompts_all) as prompts: for prompt in tqdm(prompts, disable=not accelerator.is_local_main_process): utts, ref_rms_list, ref_mels, ref_mel_lens, total_mel_lens, final_text_list = prompt ref_mels = ref_mels.to(device) ref_mel_lens = torch.tensor(ref_mel_lens, dtype=torch.long).to(device) total_mel_lens = torch.tensor(total_mel_lens, dtype=torch.long).to(device)
# Inference with torch.inference_mode(): generated, _ = model.sample( cond=ref_mels, text=final_text_list, duration=total_mel_lens, lens=ref_mel_lens, steps=nfe_step, cfg_strength=cfg_strength, sway_sampling_coef=sway_sampling_coef, no_ref_audio=no_ref_audio, seed=seed, ) # Final result for i, gen in enumerate(generated): gen = gen[ref_mel_lens[i] : total_mel_lens[i], :].unsqueeze(0) gen_mel_spec = gen.permute(0, 2, 1).to(torch.float32) if mel_spec_type == "vocos": generated_wave = vocoder.decode(gen_mel_spec).cpu() elif mel_spec_type == "bigvgan": generated_wave = vocoder(gen_mel_spec).squeeze(0).cpu()
if ref_rms_list[i] < target_rms: generated_wave = generated_wave * ref_rms_list[i] / target_rms torchaudio.save(f"{output_dir}/{utts[i]}.wav", generated_wave, target_sample_rate)
accelerator.wait_for_everyone() if accelerator.is_main_process: timediff = time.time() - start print(f"Done batch inference in {timediff / 60 :.2f} minutes.")
if __name__ == "__main__": main()12345678910111213#!/bin/bash
# e.g. F5-TTS, 16 NFEaccelerate launch src/f5_tts/eval/eval_infer_batch.py -s 0 -n "F5TTS_Base" -t "seedtts_test_zh" -nfe 16accelerate launch src/f5_tts/eval/eval_infer_batch.py -s 0 -n "F5TTS_Base" -t "seedtts_test_en" -nfe 16accelerate launch src/f5_tts/eval/eval_infer_batch.py -s 0 -n "F5TTS_Base" -t "ls_pc_test_clean" -nfe 16
# e.g. Vanilla E2 TTS, 32 NFEaccelerate launch src/f5_tts/eval/eval_infer_batch.py -s 0 -n "E2TTS_Base" -t "seedtts_test_zh" -o "midpoint" -ss 0accelerate launch src/f5_tts/eval/eval_infer_batch.py -s 0 -n "E2TTS_Base" -t "seedtts_test_en" -o "midpoint" -ss 0accelerate launch src/f5_tts/eval/eval_infer_batch.py -s 0 -n "E2TTS_Base" -t "ls_pc_test_clean" -o "midpoint" -ss 0
# etc.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384# Evaluate with Librispeech test-clean, ~3s prompt to generate 4-10s audio (the way of valle/voicebox evaluation)
import sysimport osimport argparse
sys.path.append(os.getcwd())
import multiprocessing as mpfrom importlib.resources import files
import numpy as np
from f5_tts.eval.utils_eval import ( get_librispeech_test, run_asr_wer, run_sim,)
rel_path = str(files("f5_tts").joinpath("../../"))
def get_args(): parser = argparse.ArgumentParser() parser.add_argument("-e", "--eval_task", type=str, default="wer", choices=["sim", "wer"]) parser.add_argument("-l", "--lang", type=str, default="en") parser.add_argument("-g", "--gen_wav_dir", type=str, required=True) parser.add_argument("-p", "--librispeech_test_clean_path", type=str, required=True) parser.add_argument("-n", "--gpu_nums", type=int, default=8, help="Number of GPUs to use") parser.add_argument("--local", action="store_true", help="Use local custom checkpoint directory") return parser.parse_args()
def main(): args = get_args() eval_task = args.eval_task lang = args.lang librispeech_test_clean_path = args.librispeech_test_clean_path # test-clean path gen_wav_dir = args.gen_wav_dir metalst = rel_path + "/data/librispeech_pc_test_clean_cross_sentence.lst"
gpus = list(range(args.gpu_nums)) test_set = get_librispeech_test(metalst, gen_wav_dir, gpus, librispeech_test_clean_path)
## In LibriSpeech, some speakers utilized varying voice characteristics for different characters in the book, ## leading to a low similarity for the ground truth in some cases. # test_set = get_librispeech_test(metalst, gen_wav_dir, gpus, librispeech_test_clean_path, eval_ground_truth = True) # eval ground truth
local = args.local if local: # use local custom checkpoint dir asr_ckpt_dir = "../checkpoints/Systran/faster-whisper-large-v3" else: asr_ckpt_dir = "" # auto download to cache dir wavlm_ckpt_dir = "../checkpoints/UniSpeech/wavlm_large_finetune.pth"
# --------------------------- WER --------------------------- if eval_task == "wer": wers = [] with mp.Pool(processes=len(gpus)) as pool: args = [(rank, lang, sub_test_set, asr_ckpt_dir) for (rank, sub_test_set) in test_set] results = pool.map(run_asr_wer, args) for wers_ in results: wers.extend(wers_)
wer = round(np.mean(wers) * 100, 3) print(f"\nTotal {len(wers)} samples") print(f"WER : {wer}%")
# --------------------------- SIM --------------------------- if eval_task == "sim": sim_list = [] with mp.Pool(processes=len(gpus)) as pool: args = [(rank, sub_test_set, wavlm_ckpt_dir) for (rank, sub_test_set) in test_set] results = pool.map(run_sim, args) for sim_ in results: sim_list.extend(sim_)
sim = round(sum(sim_list) / len(sim_list), 3) print(f"\nTotal {len(sim_list)} samples") print(f"SIM : {sim}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384# Evaluate with Seed-TTS testset
import sysimport osimport argparse
sys.path.append(os.getcwd())
import multiprocessing as mpfrom importlib.resources import files
import numpy as np
from f5_tts.eval.utils_eval import ( get_seed_tts_test, run_asr_wer, run_sim,)
rel_path = str(files("f5_tts").joinpath("../../"))
def get_args(): parser = argparse.ArgumentParser() parser.add_argument("-e", "--eval_task", type=str, default="wer", choices=["sim", "wer"]) parser.add_argument("-l", "--lang", type=str, default="en", choices=["zh", "en"]) parser.add_argument("-g", "--gen_wav_dir", type=str, required=True) parser.add_argument("-n", "--gpu_nums", type=int, default=8, help="Number of GPUs to use") parser.add_argument("--local", action="store_true", help="Use local custom checkpoint directory") return parser.parse_args()
def main(): args = get_args() eval_task = args.eval_task lang = args.lang gen_wav_dir = args.gen_wav_dir metalst = rel_path + f"/data/seedtts_testset/{lang}/meta.lst" # seed-tts testset
# NOTE. paraformer-zh result will be slightly different according to the number of gpus, cuz batchsize is different # zh 1.254 seems a result of 4 workers wer_seed_tts gpus = list(range(args.gpu_nums)) test_set = get_seed_tts_test(metalst, gen_wav_dir, gpus)
local = args.local if local: # use local custom checkpoint dir if lang == "zh": asr_ckpt_dir = "../checkpoints/funasr" # paraformer-zh dir under funasr elif lang == "en": asr_ckpt_dir = "../checkpoints/Systran/faster-whisper-large-v3" else: asr_ckpt_dir = "" # auto download to cache dir wavlm_ckpt_dir = "../checkpoints/UniSpeech/wavlm_large_finetune.pth"
# --------------------------- WER ---------------------------
if eval_task == "wer": wers = [] with mp.Pool(processes=len(gpus)) as pool: args = [(rank, lang, sub_test_set, asr_ckpt_dir) for (rank, sub_test_set) in test_set] results = pool.map(run_asr_wer, args) for wers_ in results: wers.extend(wers_)
wer = round(np.mean(wers) * 100, 3) print(f"\nTotal {len(wers)} samples") print(f"WER : {wer}%")
# --------------------------- SIM --------------------------- if eval_task == "sim": sim_list = [] with mp.Pool(processes=len(gpus)) as pool: args = [(rank, sub_test_set, wavlm_ckpt_dir) for (rank, sub_test_set) in test_set] results = pool.map(run_sim, args) for sim_ in results: sim_list.extend(sim_)
sim = round(sum(sim_list) / len(sim_list), 3) print(f"\nTotal {len(sim_list)} samples") print(f"SIM : {sim}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405import mathimport osimport randomimport string
import torchimport torch.nn.functional as Fimport torchaudiofrom tqdm import tqdm
from f5_tts.eval.ecapa_tdnn import ECAPA_TDNN_SMALLfrom f5_tts.model.modules import MelSpecfrom f5_tts.model.utils import convert_char_to_pinyin
# seedtts testset metainfo: utt, prompt_text, prompt_wav, gt_text, gt_wavdef get_seedtts_testset_metainfo(metalst): f = open(metalst) lines = f.readlines() f.close() metainfo = [] for line in lines: if len(line.strip().split("|")) == 5: utt, prompt_text, prompt_wav, gt_text, gt_wav = line.strip().split("|") elif len(line.strip().split("|")) == 4: utt, prompt_text, prompt_wav, gt_text = line.strip().split("|") gt_wav = os.path.join(os.path.dirname(metalst), "wavs", utt + ".wav") if not os.path.isabs(prompt_wav): prompt_wav = os.path.join(os.path.dirname(metalst), prompt_wav) metainfo.append((utt, prompt_text, prompt_wav, gt_text, gt_wav)) return metainfo
# librispeech test-clean metainfo: gen_utt, ref_txt, ref_wav, gen_txt, gen_wavdef get_librispeech_test_clean_metainfo(metalst, librispeech_test_clean_path): f = open(metalst) lines = f.readlines() f.close() metainfo = [] for line in lines: ref_utt, ref_dur, ref_txt, gen_utt, gen_dur, gen_txt = line.strip().split("\t")
# ref_txt = ref_txt[0] + ref_txt[1:].lower() + '.' # if use librispeech test-clean (no-pc) ref_spk_id, ref_chaptr_id, _ = ref_utt.split("-") ref_wav = os.path.join(librispeech_test_clean_path, ref_spk_id, ref_chaptr_id, ref_utt + ".flac")
# gen_txt = gen_txt[0] + gen_txt[1:].lower() + '.' # if use librispeech test-clean (no-pc) gen_spk_id, gen_chaptr_id, _ = gen_utt.split("-") gen_wav = os.path.join(librispeech_test_clean_path, gen_spk_id, gen_chaptr_id, gen_utt + ".flac")
metainfo.append((gen_utt, ref_txt, ref_wav, " " + gen_txt, gen_wav))
return metainfo
# padded to max length mel batchdef padded_mel_batch(ref_mels): max_mel_length = torch.LongTensor([mel.shape[-1] for mel in ref_mels]).amax() padded_ref_mels = [] for mel in ref_mels: padded_ref_mel = F.pad(mel, (0, max_mel_length - mel.shape[-1]), value=0) padded_ref_mels.append(padded_ref_mel) padded_ref_mels = torch.stack(padded_ref_mels) padded_ref_mels = padded_ref_mels.permute(0, 2, 1) return padded_ref_mels
# get prompts from metainfo containing: utt, prompt_text, prompt_wav, gt_text, gt_wav
def get_inference_prompt( metainfo, speed=1.0, tokenizer="pinyin", polyphone=True, target_sample_rate=24000, n_fft=1024, win_length=1024, n_mel_channels=100, hop_length=256, mel_spec_type="vocos", target_rms=0.1, use_truth_duration=False, infer_batch_size=1, num_buckets=200, min_secs=3, max_secs=40,): prompts_all = []
min_tokens = min_secs * target_sample_rate // hop_length max_tokens = max_secs * target_sample_rate // hop_length
batch_accum = [0] * num_buckets utts, ref_rms_list, ref_mels, ref_mel_lens, total_mel_lens, final_text_list = ( [[] for _ in range(num_buckets)] for _ in range(6) )
mel_spectrogram = MelSpec( n_fft=n_fft, hop_length=hop_length, win_length=win_length, n_mel_channels=n_mel_channels, target_sample_rate=target_sample_rate, mel_spec_type=mel_spec_type, )
for utt, prompt_text, prompt_wav, gt_text, gt_wav in tqdm(metainfo, desc="Processing prompts..."): # Audio ref_audio, ref_sr = torchaudio.load(prompt_wav) ref_rms = torch.sqrt(torch.mean(torch.square(ref_audio))) if ref_rms < target_rms: ref_audio = ref_audio * target_rms / ref_rms assert ref_audio.shape[-1] > 5000, f"Empty prompt wav: {prompt_wav}, or torchaudio backend issue." if ref_sr != target_sample_rate: resampler = torchaudio.transforms.Resample(ref_sr, target_sample_rate) ref_audio = resampler(ref_audio)
# Text if len(prompt_text[-1].encode("utf-8")) == 1: prompt_text = prompt_text + " " text = [prompt_text + gt_text] if tokenizer == "pinyin": text_list = convert_char_to_pinyin(text, polyphone=polyphone) else: text_list = text
# Duration, mel frame length ref_mel_len = ref_audio.shape[-1] // hop_length if use_truth_duration: gt_audio, gt_sr = torchaudio.load(gt_wav) if gt_sr != target_sample_rate: resampler = torchaudio.transforms.Resample(gt_sr, target_sample_rate) gt_audio = resampler(gt_audio) total_mel_len = ref_mel_len + int(gt_audio.shape[-1] / hop_length / speed)
# # test vocoder resynthesis # ref_audio = gt_audio else: ref_text_len = len(prompt_text.encode("utf-8")) gen_text_len = len(gt_text.encode("utf-8")) total_mel_len = ref_mel_len + int(ref_mel_len / ref_text_len * gen_text_len / speed)
# to mel spectrogram ref_mel = mel_spectrogram(ref_audio) ref_mel = ref_mel.squeeze(0)
# deal with batch assert infer_batch_size > 0, "infer_batch_size should be greater than 0." assert ( min_tokens <= total_mel_len <= max_tokens ), f"Audio {utt} has duration {total_mel_len*hop_length//target_sample_rate}s out of range [{min_secs}, {max_secs}]." bucket_i = math.floor((total_mel_len - min_tokens) / (max_tokens - min_tokens + 1) * num_buckets)
utts[bucket_i].append(utt) ref_rms_list[bucket_i].append(ref_rms) ref_mels[bucket_i].append(ref_mel) ref_mel_lens[bucket_i].append(ref_mel_len) total_mel_lens[bucket_i].append(total_mel_len) final_text_list[bucket_i].extend(text_list)
batch_accum[bucket_i] += total_mel_len
if batch_accum[bucket_i] >= infer_batch_size: # print(f"\n{len(ref_mels[bucket_i][0][0])}\n{ref_mel_lens[bucket_i]}\n{total_mel_lens[bucket_i]}") prompts_all.append( ( utts[bucket_i], ref_rms_list[bucket_i], padded_mel_batch(ref_mels[bucket_i]), ref_mel_lens[bucket_i], total_mel_lens[bucket_i], final_text_list[bucket_i], ) ) batch_accum[bucket_i] = 0 ( utts[bucket_i], ref_rms_list[bucket_i], ref_mels[bucket_i], ref_mel_lens[bucket_i], total_mel_lens[bucket_i], final_text_list[bucket_i], ) = [], [], [], [], [], []
# add residual for bucket_i, bucket_frames in enumerate(batch_accum): if bucket_frames > 0: prompts_all.append( ( utts[bucket_i], ref_rms_list[bucket_i], padded_mel_batch(ref_mels[bucket_i]), ref_mel_lens[bucket_i], total_mel_lens[bucket_i], final_text_list[bucket_i], ) ) # not only leave easy work for last workers random.seed(666) random.shuffle(prompts_all)
return prompts_all
# get wav_res_ref_text of seed-tts test metalst# https://github.com/BytedanceSpeech/seed-tts-eval
def get_seed_tts_test(metalst, gen_wav_dir, gpus): f = open(metalst) lines = f.readlines() f.close()
test_set_ = [] for line in tqdm(lines): if len(line.strip().split("|")) == 5: utt, prompt_text, prompt_wav, gt_text, gt_wav = line.strip().split("|") elif len(line.strip().split("|")) == 4: utt, prompt_text, prompt_wav, gt_text = line.strip().split("|")
if not os.path.exists(os.path.join(gen_wav_dir, utt + ".wav")): continue gen_wav = os.path.join(gen_wav_dir, utt + ".wav") if not os.path.isabs(prompt_wav): prompt_wav = os.path.join(os.path.dirname(metalst), prompt_wav)
test_set_.append((gen_wav, prompt_wav, gt_text))
num_jobs = len(gpus) if num_jobs == 1: return [(gpus[0], test_set_)]
wav_per_job = len(test_set_) // num_jobs + 1 test_set = [] for i in range(num_jobs): test_set.append((gpus[i], test_set_[i * wav_per_job : (i + 1) * wav_per_job]))
return test_set
# get librispeech test-clean cross sentence test
def get_librispeech_test(metalst, gen_wav_dir, gpus, librispeech_test_clean_path, eval_ground_truth=False): f = open(metalst) lines = f.readlines() f.close()
test_set_ = [] for line in tqdm(lines): ref_utt, ref_dur, ref_txt, gen_utt, gen_dur, gen_txt = line.strip().split("\t")
if eval_ground_truth: gen_spk_id, gen_chaptr_id, _ = gen_utt.split("-") gen_wav = os.path.join(librispeech_test_clean_path, gen_spk_id, gen_chaptr_id, gen_utt + ".flac") else: if not os.path.exists(os.path.join(gen_wav_dir, gen_utt + ".wav")): raise FileNotFoundError(f"Generated wav not found: {gen_utt}") gen_wav = os.path.join(gen_wav_dir, gen_utt + ".wav")
ref_spk_id, ref_chaptr_id, _ = ref_utt.split("-") ref_wav = os.path.join(librispeech_test_clean_path, ref_spk_id, ref_chaptr_id, ref_utt + ".flac")
test_set_.append((gen_wav, ref_wav, gen_txt))
num_jobs = len(gpus) if num_jobs == 1: return [(gpus[0], test_set_)]
wav_per_job = len(test_set_) // num_jobs + 1 test_set = [] for i in range(num_jobs): test_set.append((gpus[i], test_set_[i * wav_per_job : (i + 1) * wav_per_job]))
return test_set
# load asr model
def load_asr_model(lang, ckpt_dir=""): if lang == "zh": from funasr import AutoModel
model = AutoModel( model=os.path.join(ckpt_dir, "paraformer-zh"), # vad_model = os.path.join(ckpt_dir, "fsmn-vad"), # punc_model = os.path.join(ckpt_dir, "ct-punc"), # spk_model = os.path.join(ckpt_dir, "cam++"), disable_update=True, ) # following seed-tts setting elif lang == "en": from faster_whisper import WhisperModel
model_size = "large-v3" if ckpt_dir == "" else ckpt_dir model = WhisperModel(model_size, device="cuda", compute_type="float16") return model
# WER Evaluation, the way Seed-TTS does
def run_asr_wer(args): rank, lang, test_set, ckpt_dir = args
if lang == "zh": import zhconv
torch.cuda.set_device(rank) elif lang == "en": os.environ["CUDA_VISIBLE_DEVICES"] = str(rank) else: raise NotImplementedError( "lang support only 'zh' (funasr paraformer-zh), 'en' (faster-whisper-large-v3), for now." )
asr_model = load_asr_model(lang, ckpt_dir=ckpt_dir)
from zhon.hanzi import punctuation
punctuation_all = punctuation + string.punctuation wers = []
from jiwer import compute_measures
for gen_wav, prompt_wav, truth in tqdm(test_set): if lang == "zh": res = asr_model.generate(input=gen_wav, batch_size_s=300, disable_pbar=True) hypo = res[0]["text"] hypo = zhconv.convert(hypo, "zh-cn") elif lang == "en": segments, _ = asr_model.transcribe(gen_wav, beam_size=5, language="en") hypo = "" for segment in segments: hypo = hypo + " " + segment.text
# raw_truth = truth # raw_hypo = hypo
for x in punctuation_all: truth = truth.replace(x, "") hypo = hypo.replace(x, "")
truth = truth.replace(" ", " ") hypo = hypo.replace(" ", " ")
if lang == "zh": truth = " ".join([x for x in truth]) hypo = " ".join([x for x in hypo]) elif lang == "en": truth = truth.lower() hypo = hypo.lower()
measures = compute_measures(truth, hypo) wer = measures["wer"]
# ref_list = truth.split(" ") # subs = measures["substitutions"] / len(ref_list) # dele = measures["deletions"] / len(ref_list) # inse = measures["insertions"] / len(ref_list)
wers.append(wer)
return wers
# SIM Evaluation
def run_sim(args): rank, test_set, ckpt_dir = args device = f"cuda:{rank}"
model = ECAPA_TDNN_SMALL(feat_dim=1024, feat_type="wavlm_large", config_path=None) state_dict = torch.load(ckpt_dir, weights_only=True, map_location=lambda storage, loc: storage) model.load_state_dict(state_dict["model"], strict=False)
use_gpu = True if torch.cuda.is_available() else False if use_gpu: model = model.cuda(device) model.eval()
sim_list = [] for wav1, wav2, truth in tqdm(test_set): wav1, sr1 = torchaudio.load(wav1) wav2, sr2 = torchaudio.load(wav2)
resample1 = torchaudio.transforms.Resample(orig_freq=sr1, new_freq=16000) resample2 = torchaudio.transforms.Resample(orig_freq=sr2, new_freq=16000) wav1 = resample1(wav1) wav2 = resample2(wav2)
if use_gpu: wav1 = wav1.cuda(device) wav2 = wav2.cuda(device) with torch.no_grad(): emb1 = model(wav1) emb2 = model(wav2)
sim = F.cosine_similarity(emb1, emb2)[0].item() # print(f"VSim score between two audios: {sim:.4f} (-1.0, 1.0).") sim_list.append(sim)
return sim_list123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193# Inference
The pretrained model checkpoints can be reached at [🤗 Hugging Face](https://huggingface.co/SWivid/F5-TTS) and [🤖 Model Scope](https://www.modelscope.cn/models/SWivid/F5-TTS_Emilia-ZH-EN), or will be automatically downloaded when running inference scripts.
**More checkpoints with whole community efforts can be found in [SHARED.md](SHARED.md), supporting more languages.**
Currently support **30s for a single** generation, which is the **total length** including both prompt and output audio. However, you can provide `infer_cli` and `infer_gradio` with longer text, will automatically do chunk generation. Long reference audio will be **clip short to ~15s**.
To avoid possible inference failures, make sure you have seen through the following instructions.
- Use reference audio <15s and leave some silence (e.g. 1s) at the end. Otherwise there is a risk of truncating in the middle of word, leading to suboptimal generation.- Uppercased letters will be uttered letter by letter, so use lowercased letters for normal words. - Add some spaces (blank: " ") or punctuations (e.g. "," ".") to explicitly introduce some pauses.- Preprocess numbers to Chinese letters if you want to have them read in Chinese, otherwise in English.- If the generation output is blank (pure silence), check for ffmpeg installation (various tutorials online, blogs, videos, etc.).- Try turn off use_ema if using an early-stage finetuned checkpoint (which goes just few updates).
## Gradio App
Currently supported features:
- Basic TTS with Chunk Inference- Multi-Style / Multi-Speaker Generation- Voice Chat powered by Qwen2.5-3B-Instruct
The cli command `f5-tts_infer-gradio` equals to `python src/f5_tts/infer/infer_gradio.py`, which launches a Gradio APP (web interface) for inference.
The script will load model checkpoints from Huggingface. You can also manually download files and update the path to `load_model()` in `infer_gradio.py`. Currently only load TTS models first, will load ASR model to do transcription if `ref_text` not provided, will load LLM model if use Voice Chat.
Could also be used as a component for larger application.```pythonimport gradio as grfrom f5_tts.infer.infer_gradio import app
with gr.Blocks() as main_app: gr.Markdown("# This is an example of using F5-TTS within a bigger Gradio app")
# ... other Gradio components
app.render()
main_app.launch()```
## CLI Inference
The cli command `f5-tts_infer-cli` equals to `python src/f5_tts/infer/infer_cli.py`, which is a command line tool for inference.
The script will load model checkpoints from Huggingface. You can also manually download files and use `--ckpt_file` to specify the model you want to load, or directly update in `infer_cli.py`.
For change vocab.txt use `--vocab_file` to provide your `vocab.txt` file.
Basically you can inference with flags:```bash# Leave --ref_text "" will have ASR model transcribe (extra GPU memory usage)f5-tts_infer-cli \--model "F5-TTS" \--ref_audio "ref_audio.wav" \--ref_text "The content, subtitle or transcription of reference audio." \--gen_text "Some text you want TTS model generate for you."
# Choose Vocoderf5-tts_infer-cli --vocoder_name bigvgan --load_vocoder_from_local --ckpt_file <YOUR_CKPT_PATH, eg:ckpts/F5TTS_Base_bigvgan/model_1250000.pt>f5-tts_infer-cli --vocoder_name vocos --load_vocoder_from_local --ckpt_file <YOUR_CKPT_PATH, eg:ckpts/F5TTS_Base/model_1200000.safetensors>```
And a `.toml` file would help with more flexible usage.
```bashf5-tts_infer-cli -c custom.toml```
For example, you can use `.toml` to pass in variables, refer to `src/f5_tts/infer/examples/basic/basic.toml`:
```toml# F5-TTS | E2-TTSmodel = "F5-TTS"ref_audio = "infer/examples/basic/basic_ref_en.wav"# If an empty "", transcribes the reference audio automatically.ref_text = "Some call me nature, others call me mother nature."gen_text = "I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall. But always remember, I am mighty and enduring."# File with text to generate. Ignores the text above.gen_file = ""remove_silence = falseoutput_dir = "tests"```
You can also leverage `.toml` file to do multi-style generation, refer to `src/f5_tts/infer/examples/multi/story.toml`.
```toml# F5-TTS | E2-TTSmodel = "F5-TTS"ref_audio = "infer/examples/multi/main.flac"# If an empty "", transcribes the reference audio automatically.ref_text = ""gen_text = ""# File with text to generate. Ignores the text above.gen_file = "infer/examples/multi/story.txt"remove_silence = trueoutput_dir = "tests"
[voices.town]ref_audio = "infer/examples/multi/town.flac"ref_text = ""
[voices.country]ref_audio = "infer/examples/multi/country.flac"ref_text = ""```You should mark the voice with `[main]` `[town]` `[country]` whenever you want to change voice, refer to `src/f5_tts/infer/examples/multi/story.txt`.
## Speech Editing
To test speech editing capabilities, use the following command:
```bashpython src/f5_tts/infer/speech_edit.py```
## Socket Realtime Client
To communicate with socket server you need to run ```bashpython src/f5_tts/socket_server.py```
<details><summary>Then create client to communicate</summary>
``` pythonimport socketimport numpy as npimport asyncioimport pyaudio
async def listen_to_voice(text, server_ip='localhost', server_port=9999): client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((server_ip, server_port))
async def play_audio_stream(): buffer = b'' p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paFloat32, channels=1, rate=24000, # Ensure this matches the server's sampling rate output=True, frames_per_buffer=2048)
try: while True: chunk = await asyncio.get_event_loop().run_in_executor(None, client_socket.recv, 1024) if not chunk: # End of stream break if b"END_OF_AUDIO" in chunk: buffer += chunk.replace(b"END_OF_AUDIO", b"") if buffer: audio_array = np.frombuffer(buffer, dtype=np.float32).copy() # Make a writable copy stream.write(audio_array.tobytes()) break buffer += chunk if len(buffer) >= 4096: audio_array = np.frombuffer(buffer[:4096], dtype=np.float32).copy() # Make a writable copy stream.write(audio_array.tobytes()) buffer = buffer[4096:] finally: stream.stop_stream() stream.close() p.terminate()
try: # Send only the text to the server await asyncio.get_event_loop().run_in_executor(None, client_socket.sendall, text.encode('utf-8')) await play_audio_stream() print("Audio playback finished.")
except Exception as e: print(f"Error in listen_to_voice: {e}")
finally: client_socket.close()
# Example usage: Replace this with your actual server IP and portasync def main(): await listen_to_voice("my name is jenny..", server_ip='localhost', server_port=9998)
# Run the main async functionasyncio.run(main())```
</details>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103<!-- omit in toc --># Shared Model Cards
<!-- omit in toc -->### **Prerequisites of using**- This document is serving as a quick lookup table for the community training/finetuning result, with various language support.- The models in this repository are open source and are based on voluntary contributions from contributors.- The use of models must be conditioned on respect for the respective creators. The convenience brought comes from their efforts.
<!-- omit in toc -->### **Welcome to share here**- Have a pretrained/finetuned result: model checkpoint (pruned best to facilitate inference, i.e. leave only `ema_model_state_dict`) and corresponding vocab file (for tokenization).- Host a public [huggingface model repository](https://huggingface.co/new) and upload the model related files.- Make a pull request adding a model card to the current page, i.e. `src\f5_tts\infer\SHARED.md`.
<!-- omit in toc -->### Supported Languages- [Multilingual](#multilingual) - [F5-TTS Base @ pretrain @ zh \& en](#f5-tts-base--pretrain--zh--en)- [English](#english)- [Finnish](#finnish) - [Finnish Common\_Voice Vox\_Populi @ finetune @ fi](#finnish-common_voice-vox_populi--finetune--fi)- [French](#french) - [French LibriVox @ finetune @ fr](#french-librivox--finetune--fr)- [Japanese](#japanese) - [F5-TTS Japanese @ pretrain/finetune @ ja](#f5-tts-japanese--pretrainfinetune--ja)- [Mandarin](#mandarin)- [Spanish](#spanish) - [F5-TTS Spanish @ pretrain/finetune @ es](#f5-tts-spanish--pretrainfinetune--es)
## Multilingual
#### F5-TTS Base @ pretrain @ zh & en|Model|🤗Hugging Face|Data (Hours)|Model License||:---:|:------------:|:-----------:|:-------------:||F5-TTS Base|[ckpt & vocab](https://huggingface.co/SWivid/F5-TTS/tree/main/F5TTS_Base)|[Emilia 95K zh&en](https://huggingface.co/datasets/amphion/Emilia-Dataset/tree/fc71e07)|cc-by-nc-4.0|
```bashMODEL_CKPT: hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensorsVOCAB_FILE: hf://SWivid/F5-TTS/F5TTS_Base/vocab.txt```
*Other infos, e.g. Author info, Github repo, Link to some sampled results, Usage instruction, Tutorial (Blog, Video, etc.) ...*
## English
## Finnish
#### Finnish Common_Voice Vox_Populi @ finetune @ fi|Model|🤗Hugging Face|Data|Model License||:---:|:------------:|:-----------:|:-------------:||F5-TTS Finnish|[ckpt & vocab](https://huggingface.co/AsmoKoskinen/F5-TTS_Finnish_Model)|[Common Voice](https://huggingface.co/datasets/mozilla-foundation/common_voice_17_0), [Vox Populi](https://huggingface.co/datasets/facebook/voxpopuli)|cc-by-nc-4.0|
```bashMODEL_CKPT: hf://AsmoKoskinen/F5-TTS_Finish_Model/model_common_voice_fi_vox_populi_fi_20241206.safetensorsVOCAB_FILE: hf://AsmoKoskinen/F5-TTS_Finish_Model/vocab.txt```
## French
#### French LibriVox @ finetune @ fr|Model|🤗Hugging Face|Data (Hours)|Model License||:---:|:------------:|:-----------:|:-------------:||F5-TTS French|[ckpt & vocab](https://huggingface.co/RASPIAUDIO/F5-French-MixedSpeakers-reduced)|[LibriVox](https://librivox.org/)|cc-by-nc-4.0|
```bashMODEL_CKPT: hf://RASPIAUDIO/F5-French-MixedSpeakers-reduced/model_last_reduced.ptVOCAB_FILE: hf://RASPIAUDIO/F5-French-MixedSpeakers-reduced/vocab.txt```
- [Online Inference with Hugging Face Space](https://huggingface.co/spaces/RASPIAUDIO/f5-tts_french).- [Tutorial video to train a new language model](https://www.youtube.com/watch?v=UO4usaOojys).- [Discussion about this training can be found here](https://github.com/SWivid/F5-TTS/issues/434).
## Japanese
#### F5-TTS Japanese @ pretrain/finetune @ ja|Model|🤗Hugging Face|Data (Hours)|Model License||:---:|:------------:|:-----------:|:-------------:||F5-TTS Japanese|[ckpt & vocab](https://huggingface.co/Jmica/F5TTS/tree/main/JA_8500000)|[Emilia 1.7k JA](https://huggingface.co/datasets/amphion/Emilia-Dataset/tree/fc71e07) & [Galgame Dataset 5.4k](https://huggingface.co/datasets/OOPPEENN/Galgame_Dataset)|cc-by-nc-4.0|
```bashMODEL_CKPT: hf://Jmica/F5TTS/JA_8500000/model_8499660.ptVOCAB_FILE: hf://Jmica/F5TTS/JA_8500000/vocab_updated.txt```
## Mandarin
## Spanish
#### F5-TTS Spanish @ pretrain/finetune @ es|Model|🤗Hugging Face|Data (Hours)|Model License||:---:|:------------:|:-----------:|:-------------:||F5-TTS Spanish|[ckpt & vocab](https://huggingface.co/jpgallegoar/F5-Spanish)|[Voxpopuli](https://huggingface.co/datasets/facebook/voxpopuli) & Crowdsourced & TEDx, 218 hours|cc0-1.0|
- @jpgallegoar [GitHub repo](https://github.com/jpgallegoar/Spanish-F5), Jupyter Notebook and Gradio usage for Spanish model.1234567891011# F5-TTS | E2-TTSmodel = "F5-TTS"ref_audio = "infer/examples/basic/basic_ref_en.wav"# If an empty "", transcribes the reference audio automatically.ref_text = "Some call me nature, others call me mother nature."gen_text = "I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall. But always remember, I am mighty and enduring."# File with text to generate. Ignores the text above.gen_file = ""remove_silence = falseoutput_dir = "tests"output_file = "infer_cli_out.wav"123version https://git-lfs.github.com/spec/v1oid sha256:b0e22048e72414fcc1e6b6342e47a774d748a195ed34e4a5b3fcf416707f2b71size 256018123version https://git-lfs.github.com/spec/v1oid sha256:96724a113240d1f82c6ded1334122f0176b96c9226ccd3c919e625bcfd2a3edesize 324558123version https://git-lfs.github.com/spec/v1oid sha256:bb15708b4b3875e37beec46591a5d89e1a9a63fdad3b8fe4a5c8738f4f554400size 180321123version https://git-lfs.github.com/spec/v1oid sha256:4abb1107771ce7e14926fde879b959dde6db6e572476b98684f04e45e978ab19size 27921912345678910111213141516171819# F5-TTS | E2-TTSmodel = "F5-TTS"ref_audio = "infer/examples/multi/main.flac"# If an empty "", transcribes the reference audio automatically.ref_text = ""gen_text = ""# File with text to generate. Ignores the text above.gen_file = "infer/examples/multi/story.txt"remove_silence = trueoutput_dir = "tests"
[voices.town]ref_audio = "infer/examples/multi/town.flac"ref_text = ""
[voices.country]ref_audio = "infer/examples/multi/country.flac"ref_text = ""
1A Town Mouse and a Country Mouse were acquaintances, and the Country Mouse one day invited his friend to come and see him at his home in the fields. The Town Mouse came, and they sat down to a dinner of barleycorns and roots, the latter of which had a distinctly earthy flavour. The fare was not much to the taste of the guest, and presently he broke out with [town] “My poor dear friend, you live here no better than the ants. Now, you should just see how I fare! My larder is a regular horn of plenty. You must come and stay with me, and I promise you you shall live on the fat of the land.” [main] So when he returned to town he took the Country Mouse with him, and showed him into a larder containing flour and oatmeal and figs and honey and dates. The Country Mouse had never seen anything like it, and sat down to enjoy the luxuries his friend provided: but before they had well begun, the door of the larder opened and someone came in. The two Mice scampered off and hid themselves in a narrow and exceedingly uncomfortable hole. Presently, when all was quiet, they ventured out again; but someone else came in, and off they scuttled again. This was too much for the visitor. [country] “Goodbye,” [main] said he, [country] “I’m off. You live in the lap of luxury, I can see, but you are surrounded by dangers; whereas at home I can enjoy my simple dinner of roots and corn in peace.”123version https://git-lfs.github.com/spec/v1oid sha256:e7d069b8ebd5180c3b30fde5d378f0a1ddac96722d62cf43537efc3c3f3a3ce8size 2293831234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545 !"#$%&'()*+,-./0123456789:;=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]_aa1ai1ai2ai3ai4an1an3an4ang1ang2ang4ao1ao2ao3ao4bbaba1ba2ba3ba4bai1bai2bai3bai4ban1ban2ban3ban4bang1bang2bang3bang4bao1bao2bao3bao4beibei1bei2bei3bei4ben1ben2ben3ben4bengbeng1beng2beng3beng4bi1bi2bi3bi4bian1bian2bian3bian4biao1biao2biao3bie1bie2bie3bie4bin1bin4bing1bing2bing3bing4bobo1bo2bo3bo4bu2bu3bu4cca1cai1cai2cai3cai4can1can2can3can4cang1cang2cao1cao2cao3ce4cen1cen2ceng1ceng2ceng4cha1cha2cha3cha4chai1chai2chan1chan2chan3chan4chang1chang2chang3chang4chao1chao2chao3che1che2che3che4chen1chen2chen3chen4cheng1cheng2cheng3cheng4chi1chi2chi3chi4chong1chong2chong3chong4chou1chou2chou3chou4chu1chu2chu3chu4chua1chuai1chuai2chuai3chuai4chuan1chuan2chuan3chuan4chuang1chuang2chuang3chuang4chui1chui2chun1chun2chun3chuo1chuo4ci1ci2ci3ci4cong1cong2cou4cu1cu4cuan1cuan2cuan4cui1cui3cui4cun1cun2cun4cuo1cuo2cuo4ddada1da2da3da4dai1dai2dai3dai4dan1dan2dan3dan4dang1dang2dang3dang4dao1dao2dao3dao4dede1de2dei3den4deng1deng2deng3deng4di1di2di3di4dia3dian1dian2dian3dian4diao1diao3diao4die1die2die4ding1ding2ding3ding4diu1dong1dong3dong4dou1dou2dou3dou4du1du2du3du4duan1duan2duan3duan4dui1dui4dun1dun3dun4duo1duo2duo3duo4ee1e2e3e4ei2en1en4erer2er3er4ffa1fa2fa3fa4fan1fan2fan3fan4fang1fang2fang3fang4fei1fei2fei3fei4fen1fen2fen3fen4feng1feng2feng3feng4fo2fou2fou3fu1fu2fu3fu4gga1ga2ga3ga4gai1gai2gai3gai4gan1gan2gan3gan4gang1gang2gang3gang4gao1gao2gao3gao4ge1ge2ge3ge4gei2gei3gen1gen2gen3gen4geng1geng3geng4gong1gong3gong4gou1gou2gou3gou4gugu1gu2gu3gu4gua1gua2gua3gua4guai1guai2guai3guai4guan1guan2guan3guan4guang1guang2guang3guang4gui1gui2gui3gui4gun3gun4guo1guo2guo3guo4hha1ha2ha3hai1hai2hai3hai4han1han2han3han4hang1hang2hang4hao1hao2hao3hao4he1he2he4hei1hen2hen3hen4heng1heng2heng4hong1hong2hong3hong4hou1hou2hou3hou4hu1hu2hu3hu4hua1hua2hua4huai2huai4huan1huan2huan3huan4huang1huang2huang3huang4hui1hui2hui3hui4hun1hun2hun4huohuo1huo2huo3huo4ijji1ji2ji3ji4jiajia1jia2jia3jia4jian1jian2jian3jian4jiang1jiang2jiang3jiang4jiao1jiao2jiao3jiao4jie1jie2jie3jie4jin1jin2jin3jin4jing1jing2jing3jing4jiong3jiu1jiu2jiu3jiu4ju1ju2ju3ju4juan1juan2juan3juan4jue1jue2jue4jun1jun4kka1ka2ka3kai1kai2kai3kai4kan1kan2kan3kan4kang1kang2kang4kao1kao2kao3kao4ke1ke2ke3ke4ken3keng1kong1kong3kong4kou1kou2kou3kou4ku1ku2ku3ku4kua1kua3kua4kuai3kuai4kuan1kuan2kuan3kuang1kuang2kuang4kui1kui2kui3kui4kun1kun3kun4kuo4llala1la2la3la4lai2lai4lan2lan3lan4lang1lang2lang3lang4lao1lao2lao3lao4lele1le4leilei1lei2lei3lei4leng1leng2leng3leng4lili1li2li3li4lia3lian2lian3lian4liang2liang3liang4liao1liao2liao3liao4lie1lie2lie3lie4lin1lin2lin3lin4ling2ling3ling4liu1liu2liu3liu4long1long2long3long4lou1lou2lou3lou4lu1lu2lu3lu4luan2luan3luan4lun1lun2lun4luo1luo2luo3luo4lv2lv3lv4lve3lve4mmama1ma2ma3ma4mai2mai3mai4man1man2man3man4mang2mang3mao1mao2mao3mao4memei2mei3mei4menmen1men2men4mengmeng1meng2meng3meng4mi1mi2mi3mi4mian2mian3mian4miao1miao2miao3miao4mie1mie4min2min3ming2ming3ming4miu4mo1mo2mo3mo4mou1mou2mou3mu2mu3mu4nn2na1na2na3na4nai2nai3nai4nan1nan2nan3nan4nang1nang2nang3nao1nao2nao3nao4nene2ne4nei3nei4nen4neng2ni1ni2ni3ni4nian1nian2nian3nian4niang2niang4niao2niao3niao4nie1nie4nin2ning2ning3ning4niu1niu2niu3niu4nong2nong4nou4nu2nu3nu4nuan3nuo2nuo4nv2nv3nve4oo1o2ou1ou2ou3ou4ppa1pa2pa4pai1pai2pai3pai4pan1pan2pan4pang1pang2pang4pao1pao2pao3pao4pei1pei2pei4pen1pen2pen4peng1peng2peng3peng4pi1pi2pi3pi4pian1pian2pian4piao1piao2piao3piao4pie1pie2pie3pin1pin2pin3pin4ping1ping2po1po2po3po4pou1pu1pu2pu3pu4qqi1qi2qi3qi4qia1qia3qia4qian1qian2qian3qian4qiang1qiang2qiang3qiang4qiao1qiao2qiao3qiao4qie1qie2qie3qie4qin1qin2qin3qin4qing1qing2qing3qing4qiong1qiong2qiu1qiu2qiu3qu1qu2qu3qu4quan1quan2quan3quan4que1que2que4qun2rran2ran3rang1rang2rang3rang4rao2rao3rao4re2re3re4ren2ren3ren4reng1reng2ri4rong1rong2rong3rou2rou4ru2ru3ru4ruan2ruan3rui3rui4run4ruo4ssa1sa2sa3sa4sai1sai4san1san2san3san4sang1sang3sang4sao1sao2sao3sao4se4sen1seng1sha1sha2sha3sha4shai1shai2shai3shai4shan1shan3shan4shangshang1shang3shang4shao1shao2shao3shao4she1she2she3she4shei2shen1shen2shen3shen4sheng1sheng2sheng3sheng4shishi1shi2shi3shi4shou1shou2shou3shou4shu1shu2shu3shu4shua1shua2shua3shua4shuai1shuai3shuai4shuan1shuan4shuang1shuang3shui2shui3shui4shun3shun4shuo1shuo4si1si2si3si4song1song3song4sou1sou3sou4su1su2su4suan1suan4sui1sui2sui3sui4sun1sun3suosuo1suo2suo3tta1ta2ta3ta4tai1tai2tai4tan1tan2tan3tan4tang1tang2tang3tang4tao1tao2tao3tao4te4teng2ti1ti2ti3ti4tian1tian2tian3tiao1tiao2tiao3tiao4tie1tie2tie3tie4ting1ting2ting3tong1tong2tong3tong4toutou1tou2tou4tu1tu2tu3tu4tuan1tuan2tui1tui2tui3tui4tun1tun2tun4tuo1tuo2tuo3tuo4uvwwawa1wa2wa3wa4wai1wai3wai4wan1wan2wan3wan4wang1wang2wang3wang4wei1wei2wei3wei4wen1wen2wen3wen4weng1weng4wo1wo2wo3wo4wu1wu2wu3wu4xxi1xi2xi3xi4xia1xia2xia4xian1xian2xian3xian4xiang1xiang2xiang3xiang4xiao1xiao2xiao3xiao4xie1xie2xie3xie4xin1xin2xin4xing1xing2xing3xing4xiong1xiong2xiu1xiu3xiu4xuxu1xu2xu3xu4xuan1xuan2xuan3xuan4xue1xue2xue3xue4xun1xun2xun4yyaya1ya2ya3ya4yan1yan2yan3yan4yang1yang2yang3yang4yao1yao2yao3yao4ye1ye2ye3ye4yiyi1yi2yi3yi4yin1yin2yin3yin4ying1ying2ying3ying4yo1yong1yong2yong3yong4you1you2you3you4yu1yu2yu3yu4yuan1yuan2yuan3yuan4yue1yue4yun1yun2yun3yun4zza1za2za3zai1zai3zai4zan1zan2zan3zan4zang1zang4zao1zao2zao3zao4ze2ze4zei2zen3zeng1zeng4zha1zha2zha3zha4zhai1zhai2zhai3zhai4zhan1zhan2zhan3zhan4zhang1zhang2zhang3zhang4zhao1zhao2zhao3zhao4zhezhe1zhe2zhe3zhe4zhen1zhen2zhen3zhen4zheng1zheng2zheng3zheng4zhi1zhi2zhi3zhi4zhong1zhong2zhong3zhong4zhou1zhou2zhou3zhou4zhu1zhu2zhu3zhu4zhua1zhua2zhua3zhuai1zhuai3zhuai4zhuan1zhuan2zhuan3zhuan4zhuang1zhuang4zhui1zhui4zhun1zhun2zhun3zhuo1zhuo2zizi1zi2zi3zi4zong1zong2zong3zong4zou1zou2zou3zou4zu1zu2zu3zuan1zuan3zuan4zui2zui3zui4zun1zuozuo1zuo2zuo3zuo4{~¡¢£¥§¨©«®¯°±²³´µ·¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊÍÎÑÓÖרÚÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýĀāăąćČčĐđēėęěĝğħīįİıŁłńņňŋŌōőœřŚśŞşŠšŤťũūźŻżŽžơưǎǐǒǔǚșțɑɔɕəɛɜɡɣɪɫɴɹɾʃʊʌʒʔʰʷʻʾʿˈː˙˜ˢ́̅ΑΒΔΕΘΚΛΜΞΠΣΤΦΧΨΩάέήίαβγδεζηθικλμνξοπρςστυφχψωϊόύώϕϵЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяёіְִֵֶַָֹּ־ׁאבגדהוזחטיכלםמןנסעפקרשתأبةتجحدرزسصطعقكلمنهويَُِْกขงจตทนปยรวสหอฮัาีึโใไ่้์ḍḤḥṁṃṅṇṚṛṢṣṬṭạảẤấầậắằẻẽếềểễệịọỏốồộớờởụủứữἀἁἈἐἔἰἱὀὁὐὲὸ���᾽ῆῇῶ‑‒–—―‖†‡•…‧′″⁄⁰⁴⁵⁶⁷⁸⁹₁₂₃€₱₹₽℃ℏℓ№ℝ™⅓⅔⅛→∂∈∑−∗√∞∫≈≠≡≤≥⋅⋯█♪⟨⟩、。《》「」【】あうえおかがきぎくぐけげこごさしじすずせぜそぞただちっつでとどなにねのはばひぶへべまみむめもゃやゆょよらりるれろわをんァアィイウェエオカガキクケゲコゴサザシジスズセゾタダチッツテデトドナニネノバパビピフプヘベペホボポマミムメモャヤュユョヨラリルレロワン・ーㄋㄍㄎㄏㄓㄕㄚㄜㄟㄤㄥㄧㄱㄴㄷㄹㅁㅂㅅㅈㅍㅎㅏㅓㅗㅜㅡㅣ㗎가각간갈감갑갓갔강같개거건걸겁것겉게겠겨결겼경계고곤골곱공과관광교구국굴귀귄그근글금기긴길까깍깔깜깨께꼬꼭꽃꾸꿔끔끗끝끼나난날남납내냐냥너넘넣네녁년녕노녹놀누눈느는늘니님닙다닥단달닭당대더덕던덥데도독동돼됐되된될두둑둥드들등디따딱딸땅때떤떨떻또똑뚱뛰뜻띠라락란람랍랑래랜러런럼렇레려력렵렸로록롬루르른를름릉리릴림마막만많말맑맙맛매머먹멍메면명몇모목몸못무문물뭐뭘미민밌밑바박밖반받발밤밥방배백밸뱀버번벌벚베벼벽별병보복본볼봐봤부분불비빔빛빠빨뼈뽀뿅쁘사산살삼샀상새색생서선설섭섰성세셔션셨소속손송수숙순술숫숭숲쉬쉽스슨습슷시식신실싫심십싶싸써쓰쓴씌씨씩씬아악안않알야약얀양얘어언얼엄업없었엉에여역연염엽영옆예옛오온올옷옹와왔왜요욕용우운울웃워원월웠위윙유육윤으은을음응의이익인일읽임입있자작잔잖잘잡잤장재저전점정제져졌조족좀종좋죠주준줄중줘즈즐즘지진집짜짝쩌쪼쪽쫌쭈쯔찌찍차착찾책처천철체쳐쳤초촌추출춤춥춰치친칠침칩칼커켓코콩쿠퀴크큰큽키킨타태터턴털테토통투트특튼틀티팀파팔패페펜펭평포폭표품풍프플피필하학한할함합항해햇했행허험형혜호혼홀화회획후휴흐흔희히힘ﷺﷻ!,?�𠮶123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171import argparseimport codecsimport osimport refrom pathlib import Path
import numpy as npimport soundfile as sfimport tomlifrom cached_path import cached_pathimport pandas as pdfrom tqdm import tqdm
from f5_tts.infer.utils_infer import ( infer_process, load_model, load_vocoder, preprocess_ref_audio_text, remove_silence_for_generated_wav,)from f5_tts.model import DiT, UNetT
def run_batch_inference(prompt_paths, prompt_texts, texts, languages, categories, model_obj, vocoder, mel_spec_type, remove_silence, speed, output_dir): count = 0 for ref_audio in prompt_paths: if not isinstance(ref_audio, str) or not os.path.isfile(ref_audio): print(f"Invalid ref_audio: {ref_audio}") count += 1 print(count) # raise ValueError(f"Invalid ref_audio: {ref_audio}")
for idx, (ref_audio, ref_text, text_gen, language, category) in tqdm(enumerate(zip(prompt_paths, prompt_texts, texts, languages, categories))): voices = {"main": {"ref_audio": ref_audio, "ref_text": ref_text}} for voice in voices: voices[voice]["ref_audio"], voices[voice]["ref_text"] = preprocess_ref_audio_text( voices[voice]["ref_audio"], voices[voice]["ref_text"] ) print("Voice:", voice) print("Ref_audio:", voices[voice]["ref_audio"]) print("Ref_text:", voices[voice]["ref_text"])
generated_audio_segments = [] reg1 = r"(?=\[\w+\])" chunks = re.split(reg1, text_gen) reg2 = r"\[(\w+)\]" for text in chunks: if not text.strip(): continue match = re.match(reg2, text) if match: voice = match[1] else: print("No voice tag found, using main.") voice = "main" if voice not in voices: print(f"Voice {voice} not found, using main.") voice = "main" text = re.sub(reg2, "", text) gen_text = text.strip() ref_audio = voices[voice]["ref_audio"] ref_text = voices[voice]["ref_text"] print(f"Voice: {voice}") audio, final_sample_rate, spectragram = infer_process( ref_audio, ref_text, gen_text, model_obj, vocoder, mel_spec_type=mel_spec_type, speed=speed ) generated_audio_segments.append(audio)
if generated_audio_segments: final_wave = np.concatenate(generated_audio_segments) filename = f"{language.upper()}_{category.upper()}_{idx}.wav" outfile_dir = os.path.join(output_dir, language) os.makedirs(outfile_dir, exist_ok=True) wave_path = Path(outfile_dir) / filename with open(wave_path, "wb") as f: sf.write(f.name, final_wave, final_sample_rate) if remove_silence: remove_silence_for_generated_wav(f.name) print(f"Generated audio saved to: {f.name}")
def main(): parser = argparse.ArgumentParser( prog="python3 infer-cli.py", description="Commandline interface for E2/F5 TTS with Advanced Batch Processing.", epilog="Specify options above to override one or more settings from config.", )
parser.add_argument( "-m", "--model", help="F5-TTS | E2-TTS", ) parser.add_argument( "-p", "--ckpt_file", help="The Checkpoint .pt", ) parser.add_argument( "-v", "--vocab_file", help="The vocab .txt", )
parser.add_argument( "-f", "--generate_csv", type=str, ) parser.add_argument( "-o", "--output_dir", type=str, help="Path to output folder..", ) parser.add_argument( "--remove_silence", help="Remove silence.", ) parser.add_argument("--vocoder_name", type=str, default="vocos", choices=["vocos", "bigvgan"], help="vocoder name") parser.add_argument( "--load_vocoder_from_local", action="store_true", help="load vocoder from local. Default: ../checkpoints/charactr/vocos-mel-24khz", ) parser.add_argument( "--speed", type=float, default=1.0, help="Adjust the speed of the audio generation (default: 1.0)", ) args = parser.parse_args()
# Read texts and prompts to generate filepath = args.generate_csv df = pd.read_csv(filepath) prompt_paths = df['prompt_path'].tolist() prompt_texts = df['prompt_text'].tolist() texts = df['text'].tolist() languages = df['language'].tolist() categories = df['category'].tolist()
# Model config model = args.model ckpt_file = args.ckpt_file vocab_file = args.vocab_file remove_silence = args.remove_silence speed = args.speed vocoder_name = args.vocoder_name mel_spec_type = args.vocoder_name if vocoder_name == "vocos": vocoder_local_path = "../checkpoints/vocos-mel-24khz" elif vocoder_name == "bigvgan": vocoder_local_path = "../checkpoints/bigvgan_v2_24khz_100band_256x" vocoder = load_vocoder(vocoder_name=mel_spec_type, is_local=args.load_vocoder_from_local, local_path=vocoder_local_path)
# load models model_cls = DiT model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4) print(f"Using {model}...") ema_model = load_model(model_cls, model_cfg, ckpt_file, mel_spec_type=mel_spec_type, vocab_file=vocab_file)
# Batch inference output_dir = args.output_dir if not os.path.exists(output_dir): os.makedirs(output_dir) run_batch_inference(prompt_paths, prompt_texts, texts, languages, categories, ema_model, vocoder, mel_spec_type, remove_silence, speed, output_dir)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226import argparseimport codecsimport osimport refrom importlib.resources import filesfrom pathlib import Path
import numpy as npimport soundfile as sfimport tomlifrom cached_path import cached_path
from f5_tts.infer.utils_infer import ( infer_process, load_model, load_vocoder, preprocess_ref_audio_text, remove_silence_for_generated_wav,)from f5_tts.model import DiT, UNetT
parser = argparse.ArgumentParser( prog="python3 infer-cli.py", description="Commandline interface for E2/F5 TTS with Advanced Batch Processing.", epilog="Specify options above to override one or more settings from config.",)parser.add_argument( "-c", "--config", help="Configuration file. Default=infer/examples/basic/basic.toml", default=os.path.join(files("f5_tts").joinpath("infer/examples/basic"), "basic.toml"),)parser.add_argument( "-m", "--model", help="F5-TTS | E2-TTS",)parser.add_argument( "-p", "--ckpt_file", help="The Checkpoint .pt",)parser.add_argument( "-v", "--vocab_file", help="The vocab .txt",)parser.add_argument("-r", "--ref_audio", type=str, help="Reference audio file < 15 seconds.")parser.add_argument("-s", "--ref_text", type=str, default="666", help="Subtitle for the reference audio.")parser.add_argument( "-t", "--gen_text", type=str, help="Text to generate.",)parser.add_argument( "-f", "--gen_file", type=str, help="File with text to generate. Ignores --gen_text",)parser.add_argument( "-o", "--output_dir", type=str, help="Path to output folder..",)parser.add_argument( "-w", "--output_file", type=str, help="Filename of output file..",)parser.add_argument( "--remove_silence", help="Remove silence.",)parser.add_argument("--vocoder_name", type=str, default="vocos", choices=["vocos", "bigvgan"], help="vocoder name")parser.add_argument( "--load_vocoder_from_local", action="store_true", help="load vocoder from local. Default: ../checkpoints/charactr/vocos-mel-24khz",)parser.add_argument( "--speed", type=float, default=1.0, help="Adjust the speed of the audio generation (default: 1.0)",)args = parser.parse_args()
config = tomli.load(open(args.config, "rb"))
ref_audio = args.ref_audio if args.ref_audio else config["ref_audio"]ref_text = args.ref_text if args.ref_text != "666" else config["ref_text"]gen_text = args.gen_text if args.gen_text else config["gen_text"]gen_file = args.gen_file if args.gen_file else config["gen_file"]
# patches for pip pkg userif "infer/examples/" in ref_audio: ref_audio = str(files("f5_tts").joinpath(f"{ref_audio}"))if "infer/examples/" in gen_file: gen_file = str(files("f5_tts").joinpath(f"{gen_file}"))if "voices" in config: for voice in config["voices"]: voice_ref_audio = config["voices"][voice]["ref_audio"] if "infer/examples/" in voice_ref_audio: config["voices"][voice]["ref_audio"] = str(files("f5_tts").joinpath(f"{voice_ref_audio}"))
if gen_file: gen_text = codecs.open(gen_file, "r", "utf-8").read()output_dir = args.output_dir if args.output_dir else config["output_dir"]output_file = args.output_file if args.output_file else config["output_file"]model = args.model if args.model else config["model"]ckpt_file = args.ckpt_file if args.ckpt_file else ""vocab_file = args.vocab_file if args.vocab_file else ""remove_silence = args.remove_silence if args.remove_silence else config["remove_silence"]speed = args.speed
wave_path = Path(output_dir) / output_file# spectrogram_path = Path(output_dir) / "infer_cli_out.png"
vocoder_name = args.vocoder_namemel_spec_type = args.vocoder_nameif vocoder_name == "vocos": vocoder_local_path = "../checkpoints/vocos-mel-24khz"elif vocoder_name == "bigvgan": vocoder_local_path = "../checkpoints/bigvgan_v2_24khz_100band_256x"
vocoder = load_vocoder(vocoder_name=mel_spec_type, is_local=args.load_vocoder_from_local, local_path=vocoder_local_path)
# load modelsif model == "F5-TTS": model_cls = DiT model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4) if ckpt_file == "": if vocoder_name == "vocos": repo_name = "F5-TTS" exp_name = "F5TTS_Base" ckpt_step = 1200000 ckpt_file = "/home/tts/ttsteam/repos/en_f5/F5-TTS/ckpts/expresso/model_356000.pt" # ckpt_file = f"ckpts/{exp_name}/model_{ckpt_step}.pt" # .pt | .safetensors; local path elif vocoder_name == "bigvgan": repo_name = "F5-TTS" exp_name = "F5TTS_Base_bigvgan" ckpt_step = 1250000 ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.pt"))
elif model == "E2-TTS": assert vocoder_name == "vocos", "E2-TTS only supports vocoder vocos" model_cls = UNetT model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4) if ckpt_file == "": repo_name = "E2-TTS" exp_name = "E2TTS_Base" ckpt_step = 1200000 ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.safetensors")) # ckpt_file = f"ckpts/{exp_name}/model_{ckpt_step}.pt" # .pt | .safetensors; local path
print(f"Using {model}...")ema_model = load_model(model_cls, model_cfg, ckpt_file, mel_spec_type=mel_spec_type, vocab_file=vocab_file)
def main_process(ref_audio, ref_text, text_gen, model_obj, mel_spec_type, remove_silence, speed): main_voice = {"ref_audio": ref_audio, "ref_text": ref_text} if "voices" not in config: voices = {"main": main_voice} else: voices = config["voices"] voices["main"] = main_voice for voice in voices: voices[voice]["ref_audio"], voices[voice]["ref_text"] = preprocess_ref_audio_text( voices[voice]["ref_audio"], voices[voice]["ref_text"] ) print("Voice:", voice) print("Ref_audio:", voices[voice]["ref_audio"]) print("Ref_text:", voices[voice]["ref_text"])
generated_audio_segments = [] reg1 = r"(?=\[\w+\])" chunks = re.split(reg1, text_gen) reg2 = r"\[(\w+)\]" for text in chunks: if not text.strip(): continue match = re.match(reg2, text) if match: voice = match[1] else: print("No voice tag found, using main.") voice = "main" if voice not in voices: print(f"Voice {voice} not found, using main.") voice = "main" text = re.sub(reg2, "", text) gen_text = text.strip() ref_audio = voices[voice]["ref_audio"] ref_text = voices[voice]["ref_text"] print(f"Voice: {voice}") audio, final_sample_rate, spectragram = infer_process( ref_audio, ref_text, gen_text, model_obj, vocoder, mel_spec_type=mel_spec_type, speed=speed ) generated_audio_segments.append(audio)
if generated_audio_segments: final_wave = np.concatenate(generated_audio_segments)
if not os.path.exists(output_dir): os.makedirs(output_dir)
with open(wave_path, "wb") as f: sf.write(f.name, final_wave, final_sample_rate) # Remove silence if remove_silence: remove_silence_for_generated_wav(f.name) print(f.name)
def main(): main_process(ref_audio, ref_text, gen_text, ema_model, mel_spec_type, remove_silence, speed)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245import argparseimport codecsimport osimport refrom importlib.resources import filesfrom pathlib import Path
import numpy as npimport soundfile as sfimport tomlifrom cached_path import cached_pathimport pandas as pd
from f5_tts.infer.utils_infer import ( infer_process, load_model, load_vocoder, preprocess_ref_audio_text, remove_silence_for_generated_wav,)from f5_tts.model import DiT, UNetT
parser = argparse.ArgumentParser( prog="python3 infer-cli.py", description="Commandline interface for E2/F5 TTS with Advanced Batch Processing.", epilog="Specify options above to override one or more settings from config.",)parser.add_argument( "-c", "--config", help="Configuration file. Default=infer/examples/basic/basic.toml", default=os.path.join(files("f5_tts").joinpath("infer/examples/basic"), "basic.toml"),)parser.add_argument( "-m", "--model", help="F5-TTS | E2-TTS",)parser.add_argument( "-p", "--ckpt_file", help="The Checkpoint .pt",)parser.add_argument( "-v", "--vocab_file", help="The vocab .txt",)parser.add_argument("-r", "--ref_audio", type=str, help="Reference audio file < 15 seconds.")parser.add_argument("-s", "--ref_text", type=str, default="666", help="Subtitle for the reference audio.")parser.add_argument( "-t", "--gen_text", type=str, help="Text to generate.",)parser.add_argument( "-f", "--gen_file", type=str, help="File with text to generate. Ignores --gen_text",)parser.add_argument( "-o", "--output_dir", type=str, help="Path to output folder..",)parser.add_argument( "-w", "--output_file", type=str, help="Filename of output file..",)parser.add_argument( "--remove_silence", help="Remove silence.",)parser.add_argument("--vocoder_name", type=str, default="vocos", choices=["vocos", "bigvgan"], help="vocoder name")parser.add_argument( "--load_vocoder_from_local", action="store_true", help="load vocoder from local. Default: ../checkpoints/charactr/vocos-mel-24khz",)parser.add_argument( "--speed", type=float, default=1.0, help="Adjust the speed of the audio generation (default: 1.0)",)args = parser.parse_args()
config = tomli.load(open(args.config, "rb"))
ref_audio = args.ref_audio if args.ref_audio else config["ref_audio"]ref_text = args.ref_text if args.ref_text != "666" else config["ref_text"]gen_file = args.gen_file if args.gen_file else config["gen_file"]
if gen_file: # Read texts from CSV file df = pd.read_csv(gen_file) text_list = df['text'].tolist()else: # If no file provided, use single text gen_text = args.gen_text if args.gen_text else config["gen_text"] text_list = [gen_text]output_dir = args.output_dir if args.output_dir else config["output_dir"]output_file = args.output_file if args.output_file else config["output_file"]model = args.model if args.model else config["model"]ckpt_file = args.ckpt_file if args.ckpt_file else ""vocab_file = args.vocab_file if args.vocab_file else ""remove_silence = args.remove_silence if args.remove_silence else config["remove_silence"]speed = args.speed
wave_path = Path(output_dir) / output_file# spectrogram_path = Path(output_dir) / "infer_cli_out.png"
# patches for pip pkg userif "infer/examples/" in ref_audio: ref_audio = str(files("f5_tts").joinpath(f"{ref_audio}"))if "infer/examples/" in gen_file: gen_file = str(files("f5_tts").joinpath(f"{gen_file}"))if "voices" in config: for voice in config["voices"]: voice_ref_audio = config["voices"][voice]["ref_audio"] if "infer/examples/" in voice_ref_audio: config["voices"][voice]["ref_audio"] = str(files("f5_tts").joinpath(f"{voice_ref_audio}"))
vocoder_name = args.vocoder_namemel_spec_type = args.vocoder_nameif vocoder_name == "vocos": vocoder_local_path = "../checkpoints/vocos-mel-24khz"elif vocoder_name == "bigvgan": vocoder_local_path = "../checkpoints/bigvgan_v2_24khz_100band_256x"
vocoder = load_vocoder(vocoder_name=mel_spec_type, is_local=args.load_vocoder_from_local, local_path=vocoder_local_path)
# load modelsif model == "F5-TTS": model_cls = DiT model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4) if ckpt_file == "": if vocoder_name == "vocos": repo_name = "F5-TTS" exp_name = "F5TTS_Base" ckpt_step = 1200000 ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.safetensors")) # ckpt_file = f"ckpts/{exp_name}/model_{ckpt_step}.pt" # .pt | .safetensors; local path elif vocoder_name == "bigvgan": repo_name = "F5-TTS" exp_name = "F5TTS_Base_bigvgan" ckpt_step = 1250000 ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.pt"))
elif model == "E2-TTS": assert vocoder_name == "vocos", "E2-TTS only supports vocoder vocos" model_cls = UNetT model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4) if ckpt_file == "": repo_name = "E2-TTS" exp_name = "E2TTS_Base" ckpt_step = 1200000 ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.safetensors")) # ckpt_file = f"ckpts/{exp_name}/model_{ckpt_step}.pt" # .pt | .safetensors; local path
print(f"Using {model}...")ema_model = load_model(model_cls, model_cfg, ckpt_file, mel_spec_type=mel_spec_type, vocab_file=vocab_file)
def main_process(ref_audio, ref_text, text_list, model_obj, mel_spec_type, remove_silence, speed): main_voice = {"ref_audio": ref_audio, "ref_text": ref_text} if "voices" not in config: voices = {"main": main_voice} else: voices = config["voices"] voices["main"] = main_voice for voice in voices: voices[voice]["ref_audio"], voices[voice]["ref_text"] = preprocess_ref_audio_text( voices[voice]["ref_audio"], voices[voice]["ref_text"] ) print("Voice:", voice) print("Ref_audio:", voices[voice]["ref_audio"]) print("Ref_text:", voices[voice]["ref_text"])
# Process each text in the list for idx, text_gen in enumerate(text_list): generated_audio_segments = [] reg1 = r"(?=\[\w+\])" chunks = re.split(reg1, text_gen) reg2 = r"\[(\w+)\]" for text in chunks: if not text.strip(): continue match = re.match(reg2, text) if match: voice = match[1] else: print("No voice tag found, using main.") voice = "main" if voice not in voices: print(f"Voice {voice} not found, using main.") voice = "main" text = re.sub(reg2, "", text) gen_text = text.strip() ref_audio = voices[voice]["ref_audio"] ref_text = voices[voice]["ref_text"] print(f"Voice: {voice}") audio, final_sample_rate, spectragram = infer_process( ref_audio, ref_text, gen_text, model_obj, vocoder, mel_spec_type=mel_spec_type, speed=speed ) generated_audio_segments.append(audio)
if generated_audio_segments: final_wave = np.concatenate(generated_audio_segments)
if not os.path.exists(output_dir): os.makedirs(output_dir)
# Get first 3 words from the text first_three_words = '_'.join(text_gen.split()[:3]) # Remove any special characters that might cause issues in filenames first_three_words = re.sub(r'[^\w\s-]', '', first_three_words) # Create filename with index and first 3 words filename = f"{Path(output_file).stem}__sentence{(idx+1):03d}_{first_three_words}{Path(output_file).suffix}"
wave_path = Path(output_dir) / filename
with open(wave_path, "wb") as f: sf.write(f.name, final_wave, final_sample_rate) # Remove silence if remove_silence: remove_silence_for_generated_wav(f.name) print(f"Generated audio saved to: {f.name}")
def main(): main_process(ref_audio, ref_text, text_list, ema_model, mel_spec_type, remove_silence, speed)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855# ruff: noqa: E402# Above allows ruff to ignore E402: module level import not at top of file
import osimport reimport shutilimport tempfilefrom datetime import datetimefrom collections import OrderedDictfrom importlib.resources import files
import clickimport gradio as grimport numpy as npimport soundfile as sfimport torchaudiofrom cached_path import cached_pathfrom transformers import AutoModelForCausalLM, AutoTokenizer
try: import spaces
USING_SPACES = Trueexcept ImportError: USING_SPACES = False
def gpu_decorator(func): if USING_SPACES: return spaces.GPU(func) else: return func
from f5_tts.model import DiT, UNetTfrom f5_tts.infer.utils_infer import ( load_vocoder, load_model, preprocess_ref_audio_text, infer_process, remove_silence_for_generated_wav, save_spectrogram,)
DEFAULT_TTS_MODEL = "F5-TTS"tts_model_choice = DEFAULT_TTS_MODEL
# load models
vocoder = load_vocoder()
def load_f5tts(ckpt_path=str(cached_path("hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors"))): F5TTS_model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
ckpt_path = "/home/tts/ttsteam/repos/F5-TTS/runs/indic_5/model_1176000.pt" vocab_path = "/home/tts/ttsteam/repos/F5-TTS/runs/indic_5/vocab.txt" return load_model(DiT, F5TTS_model_cfg, ckpt_path, vocab_file=vocab_path)
def load_e2tts(ckpt_path=str(cached_path("hf://SWivid/E2-TTS/E2TTS_Base/model_1200000.safetensors"))): E2TTS_model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4) return load_model(UNetT, E2TTS_model_cfg, ckpt_path)
def load_custom(ckpt_path: str, vocab_path="", model_cfg=None): ckpt_path, vocab_path = ckpt_path.strip(), vocab_path.strip() if ckpt_path.startswith("hf://"): ckpt_path = str(cached_path(ckpt_path)) if vocab_path.startswith("hf://"): vocab_path = str(cached_path(vocab_path)) if model_cfg is None: model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4) return load_model(DiT, model_cfg, ckpt_path, vocab_file=vocab_path)
F5TTS_ema_model = load_f5tts()E2TTS_ema_model = load_e2tts() if USING_SPACES else Nonecustom_ema_model, pre_custom_path = None, ""
chat_model_state = Nonechat_tokenizer_state = None
@gpu_decoratordef generate_response(messages, model, tokenizer): """Generate response using Qwen""" text = tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True, )
model_inputs = tokenizer([text], return_tensors="pt").to(model.device) generated_ids = model.generate( **model_inputs, max_new_tokens=512, temperature=0.7, top_p=0.95, )
generated_ids = [ output_ids[len(input_ids) :] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids) ] return tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
@gpu_decoratordef infer( ref_audio_orig, ref_text, gen_text, model, remove_silence, cross_fade_duration=0.15, speed=1, show_info=gr.Info): print("ref audio is: ", type(ref_audio_orig), ref_audio_orig) current_time = datetime.now().strftime("%Y%m%d_%H%M%S") shutil.copy(ref_audio_orig, os.path.join("/home/tts/ttsteam/repos/F5-TTS/runs/indic_5/infers", f"reference_audio_{current_time}.wav")) ref_audio, ref_text = preprocess_ref_audio_text(ref_audio_orig, ref_text, show_info=show_info)
if model == "F5-TTS": ema_model = F5TTS_ema_model elif model == "E2-TTS": global E2TTS_ema_model if E2TTS_ema_model is None: show_info("Loading E2-TTS model...") E2TTS_ema_model = load_e2tts() ema_model = E2TTS_ema_model elif isinstance(model, list) and model[0] == "Custom": assert not USING_SPACES, "Only official checkpoints allowed in Spaces." global custom_ema_model, pre_custom_path if pre_custom_path != model[1]: show_info("Loading Custom TTS model...") custom_ema_model = load_custom(model[1], vocab_path=model[2]) pre_custom_path = model[1] ema_model = custom_ema_model
final_wave, final_sample_rate, combined_spectrogram = infer_process( ref_audio, ref_text, gen_text, ema_model, vocoder, cross_fade_duration=cross_fade_duration, speed=speed, show_info=show_info, progress=gr.Progress(), )
# Remove silence if remove_silence: with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f: sf.write(f.name, final_wave, final_sample_rate) remove_silence_for_generated_wav(f.name) final_wave, _ = torchaudio.load(f.name) final_wave = final_wave.squeeze().cpu().numpy()
gen_time = datetime.now().strftime("%Y%m%d_%H%M%S") sf.write(os.path.join("/home/tts/ttsteam/repos/F5-TTS/runs/indic_5/infers", f"reference_audio_{current_time}_gen_{gen_time}.wav"), final_wave, final_sample_rate)
# Save the spectrogram with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_spectrogram: spectrogram_path = tmp_spectrogram.name save_spectrogram(combined_spectrogram, spectrogram_path)
return (final_sample_rate, final_wave), spectrogram_path, ref_text
with gr.Blocks() as app_credits: gr.Markdown("""# Credits
* [mrfakename](https://github.com/fakerybakery) for the original [online demo](https://huggingface.co/spaces/mrfakename/E2-F5-TTS)* [RootingInLoad](https://github.com/RootingInLoad) for initial chunk generation and podcast app exploration* [jpgallegoar](https://github.com/jpgallegoar) for multiple speech-type generation & voice chat""")with gr.Blocks() as app_tts: gr.Markdown("# Batched TTS") ref_audio_input = gr.Audio(label="Reference Audio", type="filepath") gen_text_input = gr.Textbox(label="Text to Generate", lines=10) generate_btn = gr.Button("Synthesize", variant="primary") with gr.Accordion("Advanced Settings", open=False): ref_text_input = gr.Textbox( label="Reference Text", info="Leave blank to automatically transcribe the reference audio. If you enter text it will override automatic transcription.", lines=2, ) remove_silence = gr.Checkbox( label="Remove Silences", info="The model tends to produce silences, especially on longer audio. We can manually remove silences if needed. Note that this is an experimental feature and may produce strange results. This will also increase generation time.", value=False, ) speed_slider = gr.Slider( label="Speed", minimum=0.3, maximum=3.0, value=1.0, step=0.1, info="Adjust the speed of the audio.", ) cross_fade_duration_slider = gr.Slider( label="Cross-Fade Duration (s)", minimum=0.0, maximum=1.0, value=0.15, step=0.01, info="Set the duration of the cross-fade between audio clips.", )
audio_output = gr.Audio(label="Synthesized Audio") spectrogram_output = gr.Image(label="Spectrogram")
@gpu_decorator def basic_tts( ref_audio_input, ref_text_input, gen_text_input, remove_silence, cross_fade_duration_slider, speed_slider, ): audio_out, spectrogram_path, ref_text_out = infer( ref_audio_input, ref_text_input, gen_text_input, tts_model_choice, remove_silence, cross_fade_duration_slider, speed_slider, ) return audio_out, spectrogram_path, gr.update(value=ref_text_out)
generate_btn.click( basic_tts, inputs=[ ref_audio_input, ref_text_input, gen_text_input, remove_silence, cross_fade_duration_slider, speed_slider, ], outputs=[audio_output, spectrogram_output, ref_text_input], )
def parse_speechtypes_text(gen_text): # Pattern to find {speechtype} pattern = r"\{(.*?)\}"
# Split the text by the pattern tokens = re.split(pattern, gen_text)
segments = []
current_style = "Regular"
for i in range(len(tokens)): if i % 2 == 0: # This is text text = tokens[i].strip() if text: segments.append({"style": current_style, "text": text}) else: # This is style style = tokens[i].strip() current_style = style
return segments
with gr.Blocks() as app_multistyle: # New section for multistyle generation gr.Markdown( """ # Multiple Speech-Type Generation
This section allows you to generate multiple speech types or multiple people's voices. Enter your text in the format shown below, and the system will generate speech using the appropriate type. If unspecified, the model will use the regular speech type. The current speech type will be used until the next speech type is specified. """ )
with gr.Row(): gr.Markdown( """ **Example Input:** {Regular} Hello, I'd like to order a sandwich please. {Surprised} What do you mean you're out of bread? {Sad} I really wanted a sandwich though... {Angry} You know what, darn you and your little shop! {Whisper} I'll just go back home and cry now. {Shouting} Why me?! """ )
gr.Markdown( """ **Example Input 2:** {Speaker1_Happy} Hello, I'd like to order a sandwich please. {Speaker2_Regular} Sorry, we're out of bread. {Speaker1_Sad} I really wanted a sandwich though... {Speaker2_Whisper} I'll give you the last one I was hiding. """ )
gr.Markdown( "Upload different audio clips for each speech type. The first speech type is mandatory. You can add additional speech types by clicking the 'Add Speech Type' button." )
# Regular speech type (mandatory) with gr.Row(): with gr.Column(): regular_name = gr.Textbox(value="Regular", label="Speech Type Name") regular_insert = gr.Button("Insert Label", variant="secondary") regular_audio = gr.Audio(label="Regular Reference Audio", type="filepath") regular_ref_text = gr.Textbox(label="Reference Text (Regular)", lines=2)
# Regular speech type (max 100) max_speech_types = 100 speech_type_rows = [] # 99 speech_type_names = [regular_name] # 100 speech_type_audios = [regular_audio] # 100 speech_type_ref_texts = [regular_ref_text] # 100 speech_type_delete_btns = [] # 99 speech_type_insert_btns = [regular_insert] # 100
# Additional speech types (99 more) for i in range(max_speech_types - 1): with gr.Row(visible=False) as row: with gr.Column(): name_input = gr.Textbox(label="Speech Type Name") delete_btn = gr.Button("Delete Type", variant="secondary") insert_btn = gr.Button("Insert Label", variant="secondary") audio_input = gr.Audio(label="Reference Audio", type="filepath") ref_text_input = gr.Textbox(label="Reference Text", lines=2) speech_type_rows.append(row) speech_type_names.append(name_input) speech_type_audios.append(audio_input) speech_type_ref_texts.append(ref_text_input) speech_type_delete_btns.append(delete_btn) speech_type_insert_btns.append(insert_btn)
# Button to add speech type add_speech_type_btn = gr.Button("Add Speech Type")
# Keep track of current number of speech types speech_type_count = gr.State(value=1)
# Function to add a speech type def add_speech_type_fn(speech_type_count): if speech_type_count < max_speech_types: speech_type_count += 1 # Prepare updates for the rows row_updates = [] for i in range(1, max_speech_types): if i < speech_type_count: row_updates.append(gr.update(visible=True)) else: row_updates.append(gr.update()) else: # Optionally, show a warning row_updates = [gr.update() for _ in range(1, max_speech_types)] return [speech_type_count] + row_updates
add_speech_type_btn.click( add_speech_type_fn, inputs=speech_type_count, outputs=[speech_type_count] + speech_type_rows )
# Function to delete a speech type def make_delete_speech_type_fn(index): def delete_speech_type_fn(speech_type_count): # Prepare updates row_updates = []
for i in range(1, max_speech_types): if i == index: row_updates.append(gr.update(visible=False)) else: row_updates.append(gr.update())
speech_type_count = max(1, speech_type_count)
return [speech_type_count] + row_updates
return delete_speech_type_fn
# Update delete button clicks for i, delete_btn in enumerate(speech_type_delete_btns): delete_fn = make_delete_speech_type_fn(i) delete_btn.click(delete_fn, inputs=speech_type_count, outputs=[speech_type_count] + speech_type_rows)
# Text input for the prompt gen_text_input_multistyle = gr.Textbox( label="Text to Generate", lines=10, placeholder="Enter the script with speaker names (or emotion types) at the start of each block, e.g.:\n\n{Regular} Hello, I'd like to order a sandwich please.\n{Surprised} What do you mean you're out of bread?\n{Sad} I really wanted a sandwich though...\n{Angry} You know what, darn you and your little shop!\n{Whisper} I'll just go back home and cry now.\n{Shouting} Why me?!", )
def make_insert_speech_type_fn(index): def insert_speech_type_fn(current_text, speech_type_name): current_text = current_text or "" speech_type_name = speech_type_name or "None" updated_text = current_text + f"{{{speech_type_name}}} " return gr.update(value=updated_text)
return insert_speech_type_fn
for i, insert_btn in enumerate(speech_type_insert_btns): insert_fn = make_insert_speech_type_fn(i) insert_btn.click( insert_fn, inputs=[gen_text_input_multistyle, speech_type_names[i]], outputs=gen_text_input_multistyle, )
with gr.Accordion("Advanced Settings", open=False): remove_silence_multistyle = gr.Checkbox( label="Remove Silences", value=True, )
# Generate button generate_multistyle_btn = gr.Button("Generate Multi-Style Speech", variant="primary")
# Output audio audio_output_multistyle = gr.Audio(label="Synthesized Audio")
@gpu_decorator def generate_multistyle_speech( gen_text, *args, ): speech_type_names_list = args[:max_speech_types] speech_type_audios_list = args[max_speech_types : 2 * max_speech_types] speech_type_ref_texts_list = args[2 * max_speech_types : 3 * max_speech_types] remove_silence = args[3 * max_speech_types] # Collect the speech types and their audios into a dict speech_types = OrderedDict()
ref_text_idx = 0 for name_input, audio_input, ref_text_input in zip( speech_type_names_list, speech_type_audios_list, speech_type_ref_texts_list ): if name_input and audio_input: speech_types[name_input] = {"audio": audio_input, "ref_text": ref_text_input} else: speech_types[f"@{ref_text_idx}@"] = {"audio": "", "ref_text": ""} ref_text_idx += 1
# Parse the gen_text into segments segments = parse_speechtypes_text(gen_text)
# For each segment, generate speech generated_audio_segments = [] current_style = "Regular"
for segment in segments: style = segment["style"] text = segment["text"]
if style in speech_types: current_style = style else: # If style not available, default to Regular current_style = "Regular"
ref_audio = speech_types[current_style]["audio"] ref_text = speech_types[current_style].get("ref_text", "")
# Generate speech for this segment audio_out, _, ref_text_out = infer( ref_audio, ref_text, text, tts_model_choice, remove_silence, 0, show_info=print ) # show_info=print no pull to top when generating sr, audio_data = audio_out
generated_audio_segments.append(audio_data) speech_types[current_style]["ref_text"] = ref_text_out
# Concatenate all audio segments if generated_audio_segments: final_audio_data = np.concatenate(generated_audio_segments) return [(sr, final_audio_data)] + [ gr.update(value=speech_types[style]["ref_text"]) for style in speech_types ] else: gr.Warning("No audio generated.") return [None] + [gr.update(value=speech_types[style]["ref_text"]) for style in speech_types]
generate_multistyle_btn.click( generate_multistyle_speech, inputs=[ gen_text_input_multistyle, ] + speech_type_names + speech_type_audios + speech_type_ref_texts + [ remove_silence_multistyle, ], outputs=[audio_output_multistyle] + speech_type_ref_texts, )
# Validation function to disable Generate button if speech types are missing def validate_speech_types(gen_text, regular_name, *args): speech_type_names_list = args[:max_speech_types]
# Collect the speech types names speech_types_available = set() if regular_name: speech_types_available.add(regular_name) for name_input in speech_type_names_list: if name_input: speech_types_available.add(name_input)
# Parse the gen_text to get the speech types used segments = parse_speechtypes_text(gen_text) speech_types_in_text = set(segment["style"] for segment in segments)
# Check if all speech types in text are available missing_speech_types = speech_types_in_text - speech_types_available
if missing_speech_types: # Disable the generate button return gr.update(interactive=False) else: # Enable the generate button return gr.update(interactive=True)
gen_text_input_multistyle.change( validate_speech_types, inputs=[gen_text_input_multistyle, regular_name] + speech_type_names, outputs=generate_multistyle_btn, )
with gr.Blocks() as app_chat: gr.Markdown( """# Voice ChatHave a conversation with an AI using your reference voice! 1. Upload a reference audio clip and optionally its transcript.2. Load the chat model.3. Record your message through your microphone.4. The AI will respond using the reference voice.""" )
if not USING_SPACES: load_chat_model_btn = gr.Button("Load Chat Model", variant="primary")
chat_interface_container = gr.Column(visible=False)
@gpu_decorator def load_chat_model(): global chat_model_state, chat_tokenizer_state if chat_model_state is None: show_info = gr.Info show_info("Loading chat model...") model_name = "Qwen/Qwen2.5-3B-Instruct" chat_model_state = AutoModelForCausalLM.from_pretrained( model_name, torch_dtype="auto", device_map="auto" ) chat_tokenizer_state = AutoTokenizer.from_pretrained(model_name) show_info("Chat model loaded.")
return gr.update(visible=False), gr.update(visible=True)
load_chat_model_btn.click(load_chat_model, outputs=[load_chat_model_btn, chat_interface_container])
else: chat_interface_container = gr.Column()
if chat_model_state is None: model_name = "Qwen/Qwen2.5-3B-Instruct" chat_model_state = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto") chat_tokenizer_state = AutoTokenizer.from_pretrained(model_name)
with chat_interface_container: with gr.Row(): with gr.Column(): ref_audio_chat = gr.Audio(label="Reference Audio", type="filepath") with gr.Column(): with gr.Accordion("Advanced Settings", open=False): remove_silence_chat = gr.Checkbox( label="Remove Silences", value=True, ) ref_text_chat = gr.Textbox( label="Reference Text", info="Optional: Leave blank to auto-transcribe", lines=2, ) system_prompt_chat = gr.Textbox( label="System Prompt", value="You are not an AI assistant, you are whoever the user says you are. You must stay in character. Keep your responses concise since they will be spoken out loud.", lines=2, )
chatbot_interface = gr.Chatbot(label="Conversation")
with gr.Row(): with gr.Column(): audio_input_chat = gr.Microphone( label="Speak your message", type="filepath", ) audio_output_chat = gr.Audio(autoplay=True) with gr.Column(): text_input_chat = gr.Textbox( label="Type your message", lines=1, ) send_btn_chat = gr.Button("Send Message") clear_btn_chat = gr.Button("Clear Conversation")
conversation_state = gr.State( value=[ { "role": "system", "content": "You are not an AI assistant, you are whoever the user says you are. You must stay in character. Keep your responses concise since they will be spoken out loud.", } ] )
# Modify process_audio_input to use model and tokenizer from state @gpu_decorator def process_audio_input(audio_path, text, history, conv_state): """Handle audio or text input from user"""
if not audio_path and not text.strip(): return history, conv_state, ""
if audio_path: text = preprocess_ref_audio_text(audio_path, text)[1]
if not text.strip(): return history, conv_state, ""
conv_state.append({"role": "user", "content": text}) history.append((text, None))
response = generate_response(conv_state, chat_model_state, chat_tokenizer_state)
conv_state.append({"role": "assistant", "content": response}) history[-1] = (text, response)
return history, conv_state, ""
@gpu_decorator def generate_audio_response(history, ref_audio, ref_text, remove_silence): """Generate TTS audio for AI response""" if not history or not ref_audio: return None
last_user_message, last_ai_response = history[-1] if not last_ai_response: return None
audio_result, _, ref_text_out = infer( ref_audio, ref_text, last_ai_response, tts_model_choice, remove_silence, cross_fade_duration=0.15, speed=1.0, show_info=print, # show_info=print no pull to top when generating ) return audio_result, gr.update(value=ref_text_out)
def clear_conversation(): """Reset the conversation""" return [], [ { "role": "system", "content": "You are not an AI assistant, you are whoever the user says you are. You must stay in character. Keep your responses concise since they will be spoken out loud.", } ]
def update_system_prompt(new_prompt): """Update the system prompt and reset the conversation""" new_conv_state = [{"role": "system", "content": new_prompt}] return [], new_conv_state
# Handle audio input audio_input_chat.stop_recording( process_audio_input, inputs=[audio_input_chat, text_input_chat, chatbot_interface, conversation_state], outputs=[chatbot_interface, conversation_state], ).then( generate_audio_response, inputs=[chatbot_interface, ref_audio_chat, ref_text_chat, remove_silence_chat], outputs=[audio_output_chat, ref_text_chat], ).then( lambda: None, None, audio_input_chat, )
# Handle text input text_input_chat.submit( process_audio_input, inputs=[audio_input_chat, text_input_chat, chatbot_interface, conversation_state], outputs=[chatbot_interface, conversation_state], ).then( generate_audio_response, inputs=[chatbot_interface, ref_audio_chat, ref_text_chat, remove_silence_chat], outputs=[audio_output_chat, ref_text_chat], ).then( lambda: None, None, text_input_chat, )
# Handle send button send_btn_chat.click( process_audio_input, inputs=[audio_input_chat, text_input_chat, chatbot_interface, conversation_state], outputs=[chatbot_interface, conversation_state], ).then( generate_audio_response, inputs=[chatbot_interface, ref_audio_chat, ref_text_chat, remove_silence_chat], outputs=[audio_output_chat, ref_text_chat], ).then( lambda: None, None, text_input_chat, )
# Handle clear button clear_btn_chat.click( clear_conversation, outputs=[chatbot_interface, conversation_state], )
# Handle system prompt change and reset conversation system_prompt_chat.change( update_system_prompt, inputs=system_prompt_chat, outputs=[chatbot_interface, conversation_state], )
with gr.Blocks() as app: gr.Markdown( """# Panchi TTS
**NOTE: Reference text will be automatically transcribed with Whisper if not provided. For best results, keep your reference clips short (<15s). Ensure the audio is fully uploaded before generating.**""" )
last_used_custom = files("f5_tts").joinpath("infer/.cache/last_used_custom.txt")
def load_last_used_custom(): try: with open(last_used_custom, "r") as f: return f.read().split(",") except FileNotFoundError: last_used_custom.parent.mkdir(parents=True, exist_ok=True) return [ "hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors", "hf://SWivid/F5-TTS/F5TTS_Base/vocab.txt", ]
def switch_tts_model(new_choice): global tts_model_choice if new_choice == "Custom": # override in case webpage is refreshed custom_ckpt_path, custom_vocab_path = load_last_used_custom() tts_model_choice = ["Custom", custom_ckpt_path, custom_vocab_path] return gr.update(visible=True, value=custom_ckpt_path), gr.update(visible=True, value=custom_vocab_path) else: tts_model_choice = new_choice return gr.update(visible=False), gr.update(visible=False)
def set_custom_model(custom_ckpt_path, custom_vocab_path): global tts_model_choice tts_model_choice = ["Custom", custom_ckpt_path, custom_vocab_path] with open(last_used_custom, "w") as f: f.write(f"{custom_ckpt_path},{custom_vocab_path}")
with gr.Row(): if not USING_SPACES: choose_tts_model = gr.Radio( choices=[DEFAULT_TTS_MODEL, "E2-TTS", "Custom"], label="Choose TTS Model", value=DEFAULT_TTS_MODEL ) else: choose_tts_model = gr.Radio( choices=[DEFAULT_TTS_MODEL, "E2-TTS"], label="Choose TTS Model", value=DEFAULT_TTS_MODEL ) custom_ckpt_path = gr.Dropdown( choices=["hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors"], value=load_last_used_custom()[0], allow_custom_value=True, label="MODEL CKPT: local_path | hf://user_id/repo_id/model_ckpt", visible=False, ) custom_vocab_path = gr.Dropdown( choices=["hf://SWivid/F5-TTS/F5TTS_Base/vocab.txt"], value=load_last_used_custom()[1], allow_custom_value=True, label="VOCAB FILE: local_path | hf://user_id/repo_id/vocab_file", visible=False, )
choose_tts_model.change( switch_tts_model, inputs=[choose_tts_model], outputs=[custom_ckpt_path, custom_vocab_path], show_progress="hidden", ) custom_ckpt_path.change( set_custom_model, inputs=[custom_ckpt_path, custom_vocab_path], show_progress="hidden", ) custom_vocab_path.change( set_custom_model, inputs=[custom_ckpt_path, custom_vocab_path], show_progress="hidden", )
gr.TabbedInterface( [app_tts, app_multistyle, app_chat, app_credits], ["Basic-TTS", "Multi-Speech", "Voice-Chat", "Credits"], )
@click.command()@click.option("--port", "-p", default=None, type=int, help="Port to run the app on")@click.option("--host", "-H", default=None, help="Host to run the app on")@click.option( "--share", "-s", default=False, is_flag=True, help="Share the app via Gradio share link",)@click.option("--api", "-a", default=True, is_flag=True, help="Allow API access")@click.option( "--root_path", "-r", default=None, type=str, help='The root path (or "mount point") of the application, if it\'s not served from the root ("/") of the domain. Often used when the application is behind a reverse proxy that forwards requests to the application, e.g. set "/myapp" or full URL for application served at "https://example.com/myapp".',)def main(port, host, share, api, root_path): global app print("Starting app...") app.queue(api_open=api).launch(server_name=host, server_port=port, share=share, show_api=api, root_path=root_path)
if __name__ == "__main__": if not USING_SPACES: main() else: app.queue().launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853# ruff: noqa: E402# Above allows ruff to ignore E402: module level import not at top of file
import reimport tempfilefrom collections import OrderedDictfrom importlib.resources import files
import clickimport gradio as grimport numpy as npimport soundfile as sfimport torchaudiofrom cached_path import cached_pathfrom transformers import AutoModelForCausalLM, AutoTokenizer
try: import spaces
USING_SPACES = Trueexcept ImportError: USING_SPACES = False
def gpu_decorator(func): if USING_SPACES: return spaces.GPU(func) else: return func
from f5_tts.model import DiT, UNetTfrom f5_tts.infer.utils_infer import ( load_vocoder, load_model, preprocess_ref_audio_text, infer_process, remove_silence_for_generated_wav, save_spectrogram,)
DEFAULT_TTS_MODEL = "F5-TTS"tts_model_choice = DEFAULT_TTS_MODEL
# load models
vocoder = load_vocoder()
def load_f5tts(ckpt_path=str(cached_path("hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors"))): F5TTS_model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
ckpt_path = "/home/tts/ttsteam/repos/F5-TTS/runs/indic_langs_11/ckpt/model_336000.pt" return load_model(DiT, F5TTS_model_cfg, ckpt_path)
def load_e2tts(ckpt_path=str(cached_path("hf://SWivid/E2-TTS/E2TTS_Base/model_1200000.safetensors"))): E2TTS_model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4) return load_model(UNetT, E2TTS_model_cfg, ckpt_path)
def load_custom(ckpt_path: str, vocab_path="", model_cfg=None): ckpt_path, vocab_path = ckpt_path.strip(), vocab_path.strip() if ckpt_path.startswith("hf://"): ckpt_path = str(cached_path(ckpt_path)) if vocab_path.startswith("hf://"): vocab_path = str(cached_path(vocab_path)) if model_cfg is None: model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4) return load_model(DiT, model_cfg, ckpt_path, vocab_file=vocab_path)
F5TTS_ema_model = load_f5tts()E2TTS_ema_model = load_e2tts() if USING_SPACES else Nonecustom_ema_model, pre_custom_path = None, ""
chat_model_state = Nonechat_tokenizer_state = None
@gpu_decoratordef generate_response(messages, model, tokenizer): """Generate response using Qwen""" text = tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True, )
model_inputs = tokenizer([text], return_tensors="pt").to(model.device) generated_ids = model.generate( **model_inputs, max_new_tokens=512, temperature=0.7, top_p=0.95, )
generated_ids = [ output_ids[len(input_ids) :] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids) ] return tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
@gpu_decoratordef infer( ref_audio_orig, ref_text, gen_text, model, remove_silence, cross_fade_duration=0.15, speed=1, show_info=gr.Info): ref_audio, ref_text = preprocess_ref_audio_text(ref_audio_orig, ref_text, show_info=show_info)
if model == "F5-TTS": ema_model = F5TTS_ema_model elif model == "E2-TTS": global E2TTS_ema_model if E2TTS_ema_model is None: show_info("Loading E2-TTS model...") E2TTS_ema_model = load_e2tts() ema_model = E2TTS_ema_model elif isinstance(model, list) and model[0] == "Custom": assert not USING_SPACES, "Only official checkpoints allowed in Spaces." global custom_ema_model, pre_custom_path if pre_custom_path != model[1]: show_info("Loading Custom TTS model...") custom_ema_model = load_custom(model[1], vocab_path=model[2]) pre_custom_path = model[1] ema_model = custom_ema_model
final_wave, final_sample_rate, combined_spectrogram = infer_process( ref_audio, ref_text, gen_text, ema_model, vocoder, cross_fade_duration=cross_fade_duration, speed=speed, show_info=show_info, progress=gr.Progress(), )
# Remove silence if remove_silence: with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f: sf.write(f.name, final_wave, final_sample_rate) remove_silence_for_generated_wav(f.name) final_wave, _ = torchaudio.load(f.name) final_wave = final_wave.squeeze().cpu().numpy()
# Save the spectrogram with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_spectrogram: spectrogram_path = tmp_spectrogram.name save_spectrogram(combined_spectrogram, spectrogram_path)
return (final_sample_rate, final_wave), spectrogram_path, ref_text
with gr.Blocks() as app_credits: gr.Markdown("""# Credits
* [mrfakename](https://github.com/fakerybakery) for the original [online demo](https://huggingface.co/spaces/mrfakename/E2-F5-TTS)* [RootingInLoad](https://github.com/RootingInLoad) for initial chunk generation and podcast app exploration* [jpgallegoar](https://github.com/jpgallegoar) for multiple speech-type generation & voice chat""")with gr.Blocks() as app_tts: gr.Markdown("# Batched TTS") ref_audio_input = gr.Audio(label="Reference Audio", type="filepath") gen_text_input = gr.Textbox(label="Text to Generate", lines=10) generate_btn = gr.Button("Synthesize", variant="primary") with gr.Accordion("Advanced Settings", open=False): ref_text_input = gr.Textbox( label="Reference Text", info="Leave blank to automatically transcribe the reference audio. If you enter text it will override automatic transcription.", lines=2, ) remove_silence = gr.Checkbox( label="Remove Silences", info="The model tends to produce silences, especially on longer audio. We can manually remove silences if needed. Note that this is an experimental feature and may produce strange results. This will also increase generation time.", value=False, ) speed_slider = gr.Slider( label="Speed", minimum=0.3, maximum=2.0, value=1.0, step=0.1, info="Adjust the speed of the audio.", ) cross_fade_duration_slider = gr.Slider( label="Cross-Fade Duration (s)", minimum=0.0, maximum=1.0, value=0.15, step=0.01, info="Set the duration of the cross-fade between audio clips.", )
audio_output = gr.Audio(label="Synthesized Audio") spectrogram_output = gr.Image(label="Spectrogram")
@gpu_decorator def basic_tts( ref_audio_input, ref_text_input, gen_text_input, remove_silence, cross_fade_duration_slider, speed_slider, ): audio_out, spectrogram_path, ref_text_out = infer( ref_audio_input, ref_text_input, gen_text_input, tts_model_choice, remove_silence, cross_fade_duration_slider, speed_slider, ) return audio_out, spectrogram_path, gr.update(value=ref_text_out)
generate_btn.click( basic_tts, inputs=[ ref_audio_input, ref_text_input, gen_text_input, remove_silence, cross_fade_duration_slider, speed_slider, ], outputs=[audio_output, spectrogram_output, ref_text_input], )
def parse_speechtypes_text(gen_text): # Pattern to find {speechtype} pattern = r"\{(.*?)\}"
# Split the text by the pattern tokens = re.split(pattern, gen_text)
segments = []
current_style = "Regular"
for i in range(len(tokens)): if i % 2 == 0: # This is text text = tokens[i].strip() if text: segments.append({"style": current_style, "text": text}) else: # This is style style = tokens[i].strip() current_style = style
return segments
with gr.Blocks() as app_multistyle: # New section for multistyle generation gr.Markdown( """ # Multiple Speech-Type Generation
This section allows you to generate multiple speech types or multiple people's voices. Enter your text in the format shown below, and the system will generate speech using the appropriate type. If unspecified, the model will use the regular speech type. The current speech type will be used until the next speech type is specified. """ )
with gr.Row(): gr.Markdown( """ **Example Input:** {Regular} Hello, I'd like to order a sandwich please. {Surprised} What do you mean you're out of bread? {Sad} I really wanted a sandwich though... {Angry} You know what, darn you and your little shop! {Whisper} I'll just go back home and cry now. {Shouting} Why me?! """ )
gr.Markdown( """ **Example Input 2:** {Speaker1_Happy} Hello, I'd like to order a sandwich please. {Speaker2_Regular} Sorry, we're out of bread. {Speaker1_Sad} I really wanted a sandwich though... {Speaker2_Whisper} I'll give you the last one I was hiding. """ )
gr.Markdown( "Upload different audio clips for each speech type. The first speech type is mandatory. You can add additional speech types by clicking the 'Add Speech Type' button." )
# Regular speech type (mandatory) with gr.Row(): with gr.Column(): regular_name = gr.Textbox(value="Regular", label="Speech Type Name") regular_insert = gr.Button("Insert Label", variant="secondary") regular_audio = gr.Audio(label="Regular Reference Audio", type="filepath") regular_ref_text = gr.Textbox(label="Reference Text (Regular)", lines=2)
# Regular speech type (max 100) max_speech_types = 100 speech_type_rows = [] # 99 speech_type_names = [regular_name] # 100 speech_type_audios = [regular_audio] # 100 speech_type_ref_texts = [regular_ref_text] # 100 speech_type_delete_btns = [] # 99 speech_type_insert_btns = [regular_insert] # 100
# Additional speech types (99 more) for i in range(max_speech_types - 1): with gr.Row(visible=False) as row: with gr.Column(): name_input = gr.Textbox(label="Speech Type Name") delete_btn = gr.Button("Delete Type", variant="secondary") insert_btn = gr.Button("Insert Label", variant="secondary") audio_input = gr.Audio(label="Reference Audio", type="filepath") ref_text_input = gr.Textbox(label="Reference Text", lines=2) speech_type_rows.append(row) speech_type_names.append(name_input) speech_type_audios.append(audio_input) speech_type_ref_texts.append(ref_text_input) speech_type_delete_btns.append(delete_btn) speech_type_insert_btns.append(insert_btn)
# Button to add speech type add_speech_type_btn = gr.Button("Add Speech Type")
# Keep track of current number of speech types speech_type_count = gr.State(value=1)
# Function to add a speech type def add_speech_type_fn(speech_type_count): if speech_type_count < max_speech_types: speech_type_count += 1 # Prepare updates for the rows row_updates = [] for i in range(1, max_speech_types): if i < speech_type_count: row_updates.append(gr.update(visible=True)) else: row_updates.append(gr.update()) else: # Optionally, show a warning row_updates = [gr.update() for _ in range(1, max_speech_types)] return [speech_type_count] + row_updates
add_speech_type_btn.click( add_speech_type_fn, inputs=speech_type_count, outputs=[speech_type_count] + speech_type_rows )
# Function to delete a speech type def make_delete_speech_type_fn(index): def delete_speech_type_fn(speech_type_count): # Prepare updates row_updates = []
for i in range(1, max_speech_types): if i == index: row_updates.append(gr.update(visible=False)) else: row_updates.append(gr.update())
speech_type_count = max(1, speech_type_count)
return [speech_type_count] + row_updates
return delete_speech_type_fn
# Update delete button clicks for i, delete_btn in enumerate(speech_type_delete_btns): delete_fn = make_delete_speech_type_fn(i) delete_btn.click(delete_fn, inputs=speech_type_count, outputs=[speech_type_count] + speech_type_rows)
# Text input for the prompt gen_text_input_multistyle = gr.Textbox( label="Text to Generate", lines=10, placeholder="Enter the script with speaker names (or emotion types) at the start of each block, e.g.:\n\n{Regular} Hello, I'd like to order a sandwich please.\n{Surprised} What do you mean you're out of bread?\n{Sad} I really wanted a sandwich though...\n{Angry} You know what, darn you and your little shop!\n{Whisper} I'll just go back home and cry now.\n{Shouting} Why me?!", )
def make_insert_speech_type_fn(index): def insert_speech_type_fn(current_text, speech_type_name): current_text = current_text or "" speech_type_name = speech_type_name or "None" updated_text = current_text + f"{{{speech_type_name}}} " return gr.update(value=updated_text)
return insert_speech_type_fn
for i, insert_btn in enumerate(speech_type_insert_btns): insert_fn = make_insert_speech_type_fn(i) insert_btn.click( insert_fn, inputs=[gen_text_input_multistyle, speech_type_names[i]], outputs=gen_text_input_multistyle, )
with gr.Accordion("Advanced Settings", open=False): remove_silence_multistyle = gr.Checkbox( label="Remove Silences", value=True, )
# Generate button generate_multistyle_btn = gr.Button("Generate Multi-Style Speech", variant="primary")
# Output audio audio_output_multistyle = gr.Audio(label="Synthesized Audio")
@gpu_decorator def generate_multistyle_speech( gen_text, *args, ): speech_type_names_list = args[:max_speech_types] speech_type_audios_list = args[max_speech_types : 2 * max_speech_types] speech_type_ref_texts_list = args[2 * max_speech_types : 3 * max_speech_types] remove_silence = args[3 * max_speech_types] # Collect the speech types and their audios into a dict speech_types = OrderedDict()
ref_text_idx = 0 for name_input, audio_input, ref_text_input in zip( speech_type_names_list, speech_type_audios_list, speech_type_ref_texts_list ): if name_input and audio_input: speech_types[name_input] = {"audio": audio_input, "ref_text": ref_text_input} else: speech_types[f"@{ref_text_idx}@"] = {"audio": "", "ref_text": ""} ref_text_idx += 1
# Parse the gen_text into segments segments = parse_speechtypes_text(gen_text)
# For each segment, generate speech generated_audio_segments = [] current_style = "Regular"
for segment in segments: style = segment["style"] text = segment["text"]
if style in speech_types: current_style = style else: # If style not available, default to Regular current_style = "Regular"
ref_audio = speech_types[current_style]["audio"] ref_text = speech_types[current_style].get("ref_text", "")
# Generate speech for this segment audio_out, _, ref_text_out = infer( ref_audio, ref_text, text, tts_model_choice, remove_silence, 0, show_info=print ) # show_info=print no pull to top when generating sr, audio_data = audio_out
generated_audio_segments.append(audio_data) speech_types[current_style]["ref_text"] = ref_text_out
# Concatenate all audio segments if generated_audio_segments: final_audio_data = np.concatenate(generated_audio_segments) return [(sr, final_audio_data)] + [ gr.update(value=speech_types[style]["ref_text"]) for style in speech_types ] else: gr.Warning("No audio generated.") return [None] + [gr.update(value=speech_types[style]["ref_text"]) for style in speech_types]
generate_multistyle_btn.click( generate_multistyle_speech, inputs=[ gen_text_input_multistyle, ] + speech_type_names + speech_type_audios + speech_type_ref_texts + [ remove_silence_multistyle, ], outputs=[audio_output_multistyle] + speech_type_ref_texts, )
# Validation function to disable Generate button if speech types are missing def validate_speech_types(gen_text, regular_name, *args): speech_type_names_list = args[:max_speech_types]
# Collect the speech types names speech_types_available = set() if regular_name: speech_types_available.add(regular_name) for name_input in speech_type_names_list: if name_input: speech_types_available.add(name_input)
# Parse the gen_text to get the speech types used segments = parse_speechtypes_text(gen_text) speech_types_in_text = set(segment["style"] for segment in segments)
# Check if all speech types in text are available missing_speech_types = speech_types_in_text - speech_types_available
if missing_speech_types: # Disable the generate button return gr.update(interactive=False) else: # Enable the generate button return gr.update(interactive=True)
gen_text_input_multistyle.change( validate_speech_types, inputs=[gen_text_input_multistyle, regular_name] + speech_type_names, outputs=generate_multistyle_btn, )
with gr.Blocks() as app_chat: gr.Markdown( """# Voice ChatHave a conversation with an AI using your reference voice! 1. Upload a reference audio clip and optionally its transcript.2. Load the chat model.3. Record your message through your microphone.4. The AI will respond using the reference voice.""" )
if not USING_SPACES: load_chat_model_btn = gr.Button("Load Chat Model", variant="primary")
chat_interface_container = gr.Column(visible=False)
@gpu_decorator def load_chat_model(): global chat_model_state, chat_tokenizer_state if chat_model_state is None: show_info = gr.Info show_info("Loading chat model...") model_name = "Qwen/Qwen2.5-3B-Instruct" chat_model_state = AutoModelForCausalLM.from_pretrained( model_name, torch_dtype="auto", device_map="auto" ) chat_tokenizer_state = AutoTokenizer.from_pretrained(model_name) show_info("Chat model loaded.")
return gr.update(visible=False), gr.update(visible=True)
load_chat_model_btn.click(load_chat_model, outputs=[load_chat_model_btn, chat_interface_container])
else: chat_interface_container = gr.Column()
if chat_model_state is None: model_name = "Qwen/Qwen2.5-3B-Instruct" chat_model_state = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto") chat_tokenizer_state = AutoTokenizer.from_pretrained(model_name)
with chat_interface_container: with gr.Row(): with gr.Column(): ref_audio_chat = gr.Audio(label="Reference Audio", type="filepath") with gr.Column(): with gr.Accordion("Advanced Settings", open=False): remove_silence_chat = gr.Checkbox( label="Remove Silences", value=True, ) ref_text_chat = gr.Textbox( label="Reference Text", info="Optional: Leave blank to auto-transcribe", lines=2, ) system_prompt_chat = gr.Textbox( label="System Prompt", value="You are not an AI assistant, you are whoever the user says you are. You must stay in character. Keep your responses concise since they will be spoken out loud.", lines=2, )
chatbot_interface = gr.Chatbot(label="Conversation")
with gr.Row(): with gr.Column(): audio_input_chat = gr.Microphone( label="Speak your message", type="filepath", ) audio_output_chat = gr.Audio(autoplay=True) with gr.Column(): text_input_chat = gr.Textbox( label="Type your message", lines=1, ) send_btn_chat = gr.Button("Send Message") clear_btn_chat = gr.Button("Clear Conversation")
conversation_state = gr.State( value=[ { "role": "system", "content": "You are not an AI assistant, you are whoever the user says you are. You must stay in character. Keep your responses concise since they will be spoken out loud.", } ] )
# Modify process_audio_input to use model and tokenizer from state @gpu_decorator def process_audio_input(audio_path, text, history, conv_state): """Handle audio or text input from user"""
if not audio_path and not text.strip(): return history, conv_state, ""
if audio_path: text = preprocess_ref_audio_text(audio_path, text)[1]
if not text.strip(): return history, conv_state, ""
conv_state.append({"role": "user", "content": text}) history.append((text, None))
response = generate_response(conv_state, chat_model_state, chat_tokenizer_state)
conv_state.append({"role": "assistant", "content": response}) history[-1] = (text, response)
return history, conv_state, ""
@gpu_decorator def generate_audio_response(history, ref_audio, ref_text, remove_silence): """Generate TTS audio for AI response""" if not history or not ref_audio: return None
last_user_message, last_ai_response = history[-1] if not last_ai_response: return None
audio_result, _, ref_text_out = infer( ref_audio, ref_text, last_ai_response, tts_model_choice, remove_silence, cross_fade_duration=0.15, speed=1.0, show_info=print, # show_info=print no pull to top when generating ) return audio_result, gr.update(value=ref_text_out)
def clear_conversation(): """Reset the conversation""" return [], [ { "role": "system", "content": "You are not an AI assistant, you are whoever the user says you are. You must stay in character. Keep your responses concise since they will be spoken out loud.", } ]
def update_system_prompt(new_prompt): """Update the system prompt and reset the conversation""" new_conv_state = [{"role": "system", "content": new_prompt}] return [], new_conv_state
# Handle audio input audio_input_chat.stop_recording( process_audio_input, inputs=[audio_input_chat, text_input_chat, chatbot_interface, conversation_state], outputs=[chatbot_interface, conversation_state], ).then( generate_audio_response, inputs=[chatbot_interface, ref_audio_chat, ref_text_chat, remove_silence_chat], outputs=[audio_output_chat, ref_text_chat], ).then( lambda: None, None, audio_input_chat, )
# Handle text input text_input_chat.submit( process_audio_input, inputs=[audio_input_chat, text_input_chat, chatbot_interface, conversation_state], outputs=[chatbot_interface, conversation_state], ).then( generate_audio_response, inputs=[chatbot_interface, ref_audio_chat, ref_text_chat, remove_silence_chat], outputs=[audio_output_chat, ref_text_chat], ).then( lambda: None, None, text_input_chat, )
# Handle send button send_btn_chat.click( process_audio_input, inputs=[audio_input_chat, text_input_chat, chatbot_interface, conversation_state], outputs=[chatbot_interface, conversation_state], ).then( generate_audio_response, inputs=[chatbot_interface, ref_audio_chat, ref_text_chat, remove_silence_chat], outputs=[audio_output_chat, ref_text_chat], ).then( lambda: None, None, text_input_chat, )
# Handle clear button clear_btn_chat.click( clear_conversation, outputs=[chatbot_interface, conversation_state], )
# Handle system prompt change and reset conversation system_prompt_chat.change( update_system_prompt, inputs=system_prompt_chat, outputs=[chatbot_interface, conversation_state], )
with gr.Blocks() as app: gr.Markdown( """# E2/F5 TTS
This is a local web UI for F5 TTS with advanced batch processing support. This app supports the following TTS models:
* [F5-TTS](https://arxiv.org/abs/2410.06885) (A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching)* [E2 TTS](https://arxiv.org/abs/2406.18009) (Embarrassingly Easy Fully Non-Autoregressive Zero-Shot TTS)
The checkpoints currently support English and Chinese.
If you're having issues, try converting your reference audio to WAV or MP3, clipping it to 15s with ✂ in the bottom right corner (otherwise might have non-optimal auto-trimmed result).
**NOTE: Reference text will be automatically transcribed with Whisper if not provided. For best results, keep your reference clips short (<15s). Ensure the audio is fully uploaded before generating.**""" )
last_used_custom = files("f5_tts").joinpath("infer/.cache/last_used_custom.txt")
def load_last_used_custom(): try: with open(last_used_custom, "r") as f: return f.read().split(",") except FileNotFoundError: last_used_custom.parent.mkdir(parents=True, exist_ok=True) return [ "hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors", "hf://SWivid/F5-TTS/F5TTS_Base/vocab.txt", ]
def switch_tts_model(new_choice): global tts_model_choice if new_choice == "Custom": # override in case webpage is refreshed custom_ckpt_path, custom_vocab_path = load_last_used_custom() tts_model_choice = ["Custom", custom_ckpt_path, custom_vocab_path] return gr.update(visible=True, value=custom_ckpt_path), gr.update(visible=True, value=custom_vocab_path) else: tts_model_choice = new_choice return gr.update(visible=False), gr.update(visible=False)
def set_custom_model(custom_ckpt_path, custom_vocab_path): global tts_model_choice tts_model_choice = ["Custom", custom_ckpt_path, custom_vocab_path] with open(last_used_custom, "w") as f: f.write(f"{custom_ckpt_path},{custom_vocab_path}")
with gr.Row(): if not USING_SPACES: choose_tts_model = gr.Radio( choices=[DEFAULT_TTS_MODEL, "E2-TTS", "Custom"], label="Choose TTS Model", value=DEFAULT_TTS_MODEL ) else: choose_tts_model = gr.Radio( choices=[DEFAULT_TTS_MODEL, "E2-TTS"], label="Choose TTS Model", value=DEFAULT_TTS_MODEL ) custom_ckpt_path = gr.Dropdown( choices=["hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors"], value=load_last_used_custom()[0], allow_custom_value=True, label="MODEL CKPT: local_path | hf://user_id/repo_id/model_ckpt", visible=False, ) custom_vocab_path = gr.Dropdown( choices=["hf://SWivid/F5-TTS/F5TTS_Base/vocab.txt"], value=load_last_used_custom()[1], allow_custom_value=True, label="VOCAB FILE: local_path | hf://user_id/repo_id/vocab_file", visible=False, )
choose_tts_model.change( switch_tts_model, inputs=[choose_tts_model], outputs=[custom_ckpt_path, custom_vocab_path], show_progress="hidden", ) custom_ckpt_path.change( set_custom_model, inputs=[custom_ckpt_path, custom_vocab_path], show_progress="hidden", ) custom_vocab_path.change( set_custom_model, inputs=[custom_ckpt_path, custom_vocab_path], show_progress="hidden", )
gr.TabbedInterface( [app_tts, app_multistyle, app_chat, app_credits], ["Basic-TTS", "Multi-Speech", "Voice-Chat", "Credits"], )
@click.command()@click.option("--port", "-p", default=None, type=int, help="Port to run the app on")@click.option("--host", "-H", default=None, help="Host to run the app on")@click.option( "--share", "-s", default=False, is_flag=True, help="Share the app via Gradio share link",)@click.option("--api", "-a", default=True, is_flag=True, help="Allow API access")@click.option( "--root_path", "-r", default=None, type=str, help='The root path (or "mount point") of the application, if it\'s not served from the root ("/") of the domain. Often used when the application is behind a reverse proxy that forwards requests to the application, e.g. set "/myapp" or full URL for application served at "https://example.com/myapp".',)def main(port, host, share, api, root_path): global app print("Starting app...") app.queue(api_open=api).launch(server_name=host, server_port=port, share=share, show_api=api, root_path=root_path)
if __name__ == "__main__": if not USING_SPACES: main() else: app.queue().launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193import os
os.environ["PYTOCH_ENABLE_MPS_FALLBACK"] = "1" # for MPS device compatibility
import torchimport torch.nn.functional as Fimport torchaudio
from f5_tts.infer.utils_infer import load_checkpoint, load_vocoder, save_spectrogramfrom f5_tts.model import CFM, DiT, UNetTfrom f5_tts.model.utils import convert_char_to_pinyin, get_tokenizer
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
# --------------------- Dataset Settings -------------------- #
target_sample_rate = 24000n_mel_channels = 100hop_length = 256win_length = 1024n_fft = 1024mel_spec_type = "vocos" # 'vocos' or 'bigvgan'target_rms = 0.1
tokenizer = "pinyin"dataset_name = "Emilia_ZH_EN"
# ---------------------- infer setting ---------------------- #
seed = None # int | None
exp_name = "F5TTS_Base" # F5TTS_Base | E2TTS_Baseckpt_step = 1200000
nfe_step = 32 # 16, 32cfg_strength = 2.0ode_method = "euler" # euler | midpointsway_sampling_coef = -1.0speed = 1.0
if exp_name == "F5TTS_Base": model_cls = DiT model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
elif exp_name == "E2TTS_Base": model_cls = UNetT model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
ckpt_path = f"ckpts/{exp_name}/model_{ckpt_step}.safetensors"output_dir = "tests"
# [leverage https://github.com/MahmoudAshraf97/ctc-forced-aligner to get char level alignment]# pip install git+https://github.com/MahmoudAshraf97/ctc-forced-aligner.git# [write the origin_text into a file, e.g. tests/test_edit.txt]# ctc-forced-aligner --audio_path "src/f5_tts/infer/examples/basic/basic_ref_en.wav" --text_path "tests/test_edit.txt" --language "zho" --romanize --split_size "char"# [result will be saved at same path of audio file]# [--language "zho" for Chinese, "eng" for English]# [if local ckpt, set --alignment_model "../checkpoints/mms-300m-1130-forced-aligner"]
audio_to_edit = "src/f5_tts/infer/examples/basic/basic_ref_en.wav"origin_text = "Some call me nature, others call me mother nature."target_text = "Some call me optimist, others call me realist."parts_to_edit = [ [1.42, 2.44], [4.04, 4.9],] # stard_ends of "nature" & "mother nature", in secondsfix_duration = [ 1.2, 1,] # fix duration for "optimist" & "realist", in seconds
# audio_to_edit = "src/f5_tts/infer/examples/basic/basic_ref_zh.wav"# origin_text = "对,这就是我,万人敬仰的太乙真人。"# target_text = "对,那就是你,万人敬仰的太白金星。"# parts_to_edit = [[0.84, 1.4], [1.92, 2.4], [4.26, 6.26], ]# fix_duration = None # use origin text duration
# -------------------------------------------------#
use_ema = True
if not os.path.exists(output_dir): os.makedirs(output_dir)
# Vocoder modellocal = Falseif mel_spec_type == "vocos": vocoder_local_path = "../checkpoints/charactr/vocos-mel-24khz"elif mel_spec_type == "bigvgan": vocoder_local_path = "../checkpoints/bigvgan_v2_24khz_100band_256x"vocoder = load_vocoder(vocoder_name=mel_spec_type, is_local=local, local_path=vocoder_local_path)
# Tokenizervocab_char_map, vocab_size = get_tokenizer(dataset_name, tokenizer)
# Modelmodel = CFM( transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels), mel_spec_kwargs=dict( n_fft=n_fft, hop_length=hop_length, win_length=win_length, n_mel_channels=n_mel_channels, target_sample_rate=target_sample_rate, mel_spec_type=mel_spec_type, ), odeint_kwargs=dict( method=ode_method, ), vocab_char_map=vocab_char_map,).to(device)
dtype = torch.float32 if mel_spec_type == "bigvgan" else Nonemodel = load_checkpoint(model, ckpt_path, device, dtype=dtype, use_ema=use_ema)
# Audioaudio, sr = torchaudio.load(audio_to_edit)if audio.shape[0] > 1: audio = torch.mean(audio, dim=0, keepdim=True)rms = torch.sqrt(torch.mean(torch.square(audio)))if rms < target_rms: audio = audio * target_rms / rmsif sr != target_sample_rate: resampler = torchaudio.transforms.Resample(sr, target_sample_rate) audio = resampler(audio)offset = 0audio_ = torch.zeros(1, 0)edit_mask = torch.zeros(1, 0, dtype=torch.bool)for part in parts_to_edit: start, end = part part_dur = end - start if fix_duration is None else fix_duration.pop(0) part_dur = part_dur * target_sample_rate start = start * target_sample_rate audio_ = torch.cat((audio_, audio[:, round(offset) : round(start)], torch.zeros(1, round(part_dur))), dim=-1) edit_mask = torch.cat( ( edit_mask, torch.ones(1, round((start - offset) / hop_length), dtype=torch.bool), torch.zeros(1, round(part_dur / hop_length), dtype=torch.bool), ), dim=-1, ) offset = end * target_sample_rate# audio = torch.cat((audio_, audio[:, round(offset):]), dim = -1)edit_mask = F.pad(edit_mask, (0, audio.shape[-1] // hop_length - edit_mask.shape[-1] + 1), value=True)audio = audio.to(device)edit_mask = edit_mask.to(device)
# Texttext_list = [target_text]if tokenizer == "pinyin": final_text_list = convert_char_to_pinyin(text_list)else: final_text_list = [text_list]print(f"text : {text_list}")print(f"pinyin: {final_text_list}")
# Durationref_audio_len = 0duration = audio.shape[-1] // hop_length
# Inferencewith torch.inference_mode(): generated, trajectory = model.sample( cond=audio, text=final_text_list, duration=duration, steps=nfe_step, cfg_strength=cfg_strength, sway_sampling_coef=sway_sampling_coef, seed=seed, edit_mask=edit_mask, ) print(f"Generated mel: {generated.shape}")
# Final result generated = generated.to(torch.float32) generated = generated[:, ref_audio_len:, :] gen_mel_spec = generated.permute(0, 2, 1) if mel_spec_type == "vocos": generated_wave = vocoder.decode(gen_mel_spec).cpu() elif mel_spec_type == "bigvgan": generated_wave = vocoder(gen_mel_spec).squeeze(0).cpu()
if rms < target_rms: generated_wave = generated_wave * rms / target_rms
save_spectrogram(gen_mel_spec[0].cpu().numpy(), f"{output_dir}/speech_edit_out.png") torchaudio.save(f"{output_dir}/speech_edit_out.wav", generated_wave, target_sample_rate) print(f"Generated wav: {generated_wave.shape}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552# A unified script for inference process# Make adjustments inside functions, and consider both gradio and cli scripts if need to change func output formatimport osimport sys
os.environ["PYTOCH_ENABLE_MPS_FALLBACK"] = "1" # for MPS device compatibilitysys.path.append(f"../../{os.path.dirname(os.path.abspath(__file__))}/third_party/BigVGAN/")
import hashlibimport reimport tempfilefrom importlib.resources import files
import matplotlib
matplotlib.use("Agg")
import matplotlib.pylab as pltimport numpy as npimport torchimport torchaudioimport tqdmfrom huggingface_hub import snapshot_download, hf_hub_downloadfrom pydub import AudioSegment, silencefrom transformers import pipelinefrom vocos import Vocos
from f5_tts.model import CFMfrom f5_tts.model.utils import ( get_tokenizer, convert_char_to_pinyin,)
_ref_audio_cache = {}
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
# -----------------------------------------
target_sample_rate = 24000n_mel_channels = 100hop_length = 256win_length = 1024n_fft = 1024mel_spec_type = "vocos"target_rms = 0.1cross_fade_duration = 0.15ode_method = "euler"nfe_step = 32 # 16, 32cfg_strength = 2.0sway_sampling_coef = -1.0speed = 1.0fix_duration = None
# -----------------------------------------
# chunk text into smaller pieces
def chunk_text(text, max_chars=135): """ Splits the input text into chunks, each with a maximum number of characters.
Args: text (str): The text to be split. max_chars (int): The maximum number of characters per chunk.
Returns: List[str]: A list of text chunks. """ chunks = [] current_chunk = "" # Split the text into sentences based on punctuation followed by whitespace sentences = re.split(r"(?<=[;:,.!?])\s+|(?<=[;:,。!?])", text)
for sentence in sentences: if len(current_chunk.encode("utf-8")) + len(sentence.encode("utf-8")) <= max_chars: current_chunk += sentence + " " if sentence and len(sentence[-1].encode("utf-8")) == 1 else sentence else: if current_chunk: chunks.append(current_chunk.strip()) current_chunk = sentence + " " if sentence and len(sentence[-1].encode("utf-8")) == 1 else sentence
if current_chunk: chunks.append(current_chunk.strip())
return chunks
# load vocoderdef load_vocoder(vocoder_name="vocos", is_local=False, local_path="", device=device, hf_cache_dir=None): if vocoder_name == "vocos": # vocoder = Vocos.from_pretrained("charactr/vocos-mel-24khz").to(device) if is_local: print(f"Load vocos from local path {local_path}") config_path = f"{local_path}/config.yaml" model_path = f"{local_path}/pytorch_model.bin" else: print("Download Vocos from huggingface charactr/vocos-mel-24khz") repo_id = "charactr/vocos-mel-24khz" config_path = hf_hub_download(repo_id=repo_id, cache_dir=hf_cache_dir, filename="config.yaml") model_path = hf_hub_download(repo_id=repo_id, cache_dir=hf_cache_dir, filename="pytorch_model.bin") vocoder = Vocos.from_hparams(config_path) state_dict = torch.load(model_path, map_location="cpu", weights_only=True) from vocos.feature_extractors import EncodecFeatures
if isinstance(vocoder.feature_extractor, EncodecFeatures): encodec_parameters = { "feature_extractor.encodec." + key: value for key, value in vocoder.feature_extractor.encodec.state_dict().items() } state_dict.update(encodec_parameters) vocoder.load_state_dict(state_dict) vocoder = vocoder.eval().to(device) elif vocoder_name == "bigvgan": try: from third_party.BigVGAN import bigvgan except ImportError: print("You need to follow the README to init submodule and change the BigVGAN source code.") if is_local: """download from https://huggingface.co/nvidia/bigvgan_v2_24khz_100band_256x/tree/main""" vocoder = bigvgan.BigVGAN.from_pretrained(local_path, use_cuda_kernel=False) else: local_path = snapshot_download(repo_id="nvidia/bigvgan_v2_24khz_100band_256x", cache_dir=hf_cache_dir) vocoder = bigvgan.BigVGAN.from_pretrained(local_path, use_cuda_kernel=False)
vocoder.remove_weight_norm() vocoder = vocoder.eval().to(device) return vocoder
# load asr pipeline
asr_pipe = None
def initialize_asr_pipeline(device: str = device, dtype=None): if dtype is None: dtype = ( torch.float16 if "cuda" in device and torch.cuda.get_device_properties(device).major >= 6 and not torch.cuda.get_device_name().endswith("[ZLUDA]") else torch.float32 ) global asr_pipe asr_pipe = pipeline( "automatic-speech-recognition", model="openai/whisper-large-v3-turbo", torch_dtype=dtype, device=device, )
# transcribe
def transcribe(ref_audio, language=None): global asr_pipe if asr_pipe is None: initialize_asr_pipeline(device=device) return asr_pipe( ref_audio, chunk_length_s=30, batch_size=128, generate_kwargs={"task": "transcribe", "language": language} if language else {"task": "transcribe"}, return_timestamps=False, )["text"].strip()
# load model checkpoint for inference
def load_checkpoint(model, ckpt_path, device: str, dtype=None, use_ema=True): if dtype is None: dtype = torch.float32 # dtype = ( # torch.float16 # if "cuda" in device # and torch.cuda.get_device_properties(device).major >= 6 # and not torch.cuda.get_device_name().endswith("[ZLUDA]") # else torch.float32 # ) model = model.to(dtype)
ckpt_type = ckpt_path.split(".")[-1] if ckpt_type == "safetensors": from safetensors.torch import load_file
checkpoint = load_file(ckpt_path, device=device) else: checkpoint = torch.load(ckpt_path, map_location=device, weights_only=True)
if use_ema: if ckpt_type == "safetensors": checkpoint = {"ema_model_state_dict": checkpoint} checkpoint["model_state_dict"] = { k.replace("ema_model.", ""): v for k, v in checkpoint["ema_model_state_dict"].items() if k not in ["initted", "step"] }
# patch for backward compatibility, 305e3ea for key in ["mel_spec.mel_stft.mel_scale.fb", "mel_spec.mel_stft.spectrogram.window"]: if key in checkpoint["model_state_dict"]: del checkpoint["model_state_dict"][key]
model.load_state_dict(checkpoint["model_state_dict"]) else: if ckpt_type == "safetensors": checkpoint = {"model_state_dict": checkpoint} model.load_state_dict(checkpoint["model_state_dict"])
del checkpoint torch.cuda.empty_cache()
return model.to(device)
# load model for inference
def load_model( model_cls, model_cfg, ckpt_path, mel_spec_type=mel_spec_type, vocab_file="", ode_method=ode_method, use_ema=True, device=device,): if vocab_file == "": vocab_file = str(files("f5_tts").joinpath("infer/examples/vocab.txt")) tokenizer = "custom"
print("\nvocab : ", vocab_file) print("token : ", tokenizer) print("model : ", ckpt_path, "\n")
vocab_char_map, vocab_size = get_tokenizer(vocab_file, tokenizer) model = CFM( transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels), mel_spec_kwargs=dict( n_fft=n_fft, hop_length=hop_length, win_length=win_length, n_mel_channels=n_mel_channels, target_sample_rate=target_sample_rate, mel_spec_type=mel_spec_type, ), odeint_kwargs=dict( method=ode_method, ), vocab_char_map=vocab_char_map, ).to(device)
dtype = torch.float32 if mel_spec_type == "bigvgan" else None model = load_checkpoint(model, ckpt_path, device, dtype=dtype, use_ema=use_ema)
return model
def remove_silence_edges(audio, silence_threshold=-42): # Remove silence from the start non_silent_start_idx = silence.detect_leading_silence(audio, silence_threshold=silence_threshold) audio = audio[non_silent_start_idx:]
# Remove silence from the end non_silent_end_duration = audio.duration_seconds for ms in reversed(audio): if ms.dBFS > silence_threshold: break non_silent_end_duration -= 0.001 trimmed_audio = audio[: int(non_silent_end_duration * 1000)]
return trimmed_audio
# preprocess reference audio and text
def preprocess_ref_audio_text(ref_audio_orig, ref_text, clip_short=True, show_info=print, device=device): # show_info("Converting audio...") with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f: aseg = AudioSegment.from_file(ref_audio_orig)
if clip_short: # 1. try to find long silence for clipping non_silent_segs = silence.split_on_silence( aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=1000, seek_step=10 ) non_silent_wave = AudioSegment.silent(duration=0) for non_silent_seg in non_silent_segs: if len(non_silent_wave) > 6000 and len(non_silent_wave + non_silent_seg) > 15000: show_info("Audio is over 15s, clipping short. (1)") break non_silent_wave += non_silent_seg
# 2. try to find short silence for clipping if 1. failed if len(non_silent_wave) > 15000: non_silent_segs = silence.split_on_silence( aseg, min_silence_len=100, silence_thresh=-40, keep_silence=1000, seek_step=10 ) non_silent_wave = AudioSegment.silent(duration=0) for non_silent_seg in non_silent_segs: if len(non_silent_wave) > 6000 and len(non_silent_wave + non_silent_seg) > 15000: show_info("Audio is over 15s, clipping short. (2)") break non_silent_wave += non_silent_seg
aseg = non_silent_wave
# 3. if no proper silence found for clipping if len(aseg) > 15000: aseg = aseg[:15000] show_info("Audio is over 15s, clipping short. (3)")
aseg = remove_silence_edges(aseg) + AudioSegment.silent(duration=50) aseg.export(f.name, format="wav") ref_audio = f.name
# Compute a hash of the reference audio file with open(ref_audio, "rb") as audio_file: audio_data = audio_file.read() audio_hash = hashlib.md5(audio_data).hexdigest()
if not ref_text.strip(): global _ref_audio_cache if audio_hash in _ref_audio_cache: # Use cached asr transcription show_info("Using cached reference text...") ref_text = _ref_audio_cache[audio_hash] else: show_info("No reference text provided, transcribing reference audio...") ref_text = transcribe(ref_audio) # Cache the transcribed text (not caching custom ref_text, enabling users to do manual tweak) _ref_audio_cache[audio_hash] = ref_text else: # show_info("Using custom reference text...") pass
# Ensure ref_text ends with a proper sentence-ending punctuation if not ref_text.endswith(". ") and not ref_text.endswith("。"): if ref_text.endswith("."): ref_text += " " else: ref_text += ". "
# print("\nref_text ", ref_text)
return ref_audio, ref_text
# infer process: chunk text -> infer batches [i.e. infer_batch_process()]
def infer_process( ref_audio, ref_text, gen_text, model_obj, vocoder, mel_spec_type=mel_spec_type, show_info=print, progress=tqdm, target_rms=target_rms, cross_fade_duration=cross_fade_duration, nfe_step=nfe_step, cfg_strength=cfg_strength, sway_sampling_coef=sway_sampling_coef, speed=speed, fix_duration=fix_duration, device=device,): # Split the input text into batches audio, sr = torchaudio.load(ref_audio) max_chars = int(len(ref_text.encode("utf-8")) / (audio.shape[-1] / sr) * (25 - audio.shape[-1] / sr)) gen_text_batches = chunk_text(gen_text, max_chars=max_chars) # for i, gen_text in enumerate(gen_text_batches): # print(f"gen_text {i}", gen_text) # print("\n")
# show_info(f"Generating audio in {len(gen_text_batches)} batches...") return infer_batch_process( (audio, sr), ref_text, gen_text_batches, model_obj, vocoder, mel_spec_type=mel_spec_type, progress=progress, target_rms=target_rms, cross_fade_duration=cross_fade_duration, nfe_step=nfe_step, cfg_strength=cfg_strength, sway_sampling_coef=sway_sampling_coef, speed=speed, fix_duration=fix_duration, device=device, )
# infer batches
def infer_batch_process( ref_audio, ref_text, gen_text_batches, model_obj, vocoder, mel_spec_type="vocos", progress=tqdm, target_rms=0.1, cross_fade_duration=0.15, nfe_step=32, cfg_strength=2.0, sway_sampling_coef=-1, speed=1, fix_duration=None, device=None,): audio, sr = ref_audio if audio.shape[0] > 1: audio = torch.mean(audio, dim=0, keepdim=True)
rms = torch.sqrt(torch.mean(torch.square(audio))) if rms < target_rms: audio = audio * target_rms / rms if sr != target_sample_rate: resampler = torchaudio.transforms.Resample(sr, target_sample_rate) audio = resampler(audio) audio = audio.to(device)
generated_waves = [] spectrograms = []
if len(ref_text[-1].encode("utf-8")) == 1: ref_text = ref_text + " " # for i, gen_text in enumerate(progress.tqdm(gen_text_batches)): for i, gen_text in enumerate(gen_text_batches): # Prepare the text text_list = [ref_text + gen_text] final_text_list = convert_char_to_pinyin(text_list)
ref_audio_len = audio.shape[-1] // hop_length if fix_duration is not None: duration = int(fix_duration * target_sample_rate / hop_length) else: # Calculate duration ref_text_len = len(ref_text.encode("utf-8")) gen_text_len = len(gen_text.encode("utf-8")) duration = ref_audio_len + int(ref_audio_len / ref_text_len * gen_text_len / speed) # print("ref_text_len:", ref_text_len) # print("gen_text_len:", gen_text_len) # print("duration:", duration) # inference with torch.inference_mode(): generated, _ = model_obj.sample( cond=audio, text=final_text_list, duration=duration, steps=nfe_step, cfg_strength=cfg_strength, sway_sampling_coef=sway_sampling_coef, )
generated = generated.to(torch.float32) generated = generated[:, ref_audio_len:, :] generated_mel_spec = generated.permute(0, 2, 1) if mel_spec_type == "vocos": generated_wave = vocoder.decode(generated_mel_spec) elif mel_spec_type == "bigvgan": generated_wave = vocoder(generated_mel_spec) if rms < target_rms: generated_wave = generated_wave * rms / target_rms
# wav -> numpy generated_wave = generated_wave.squeeze().cpu().numpy()
generated_waves.append(generated_wave) spectrograms.append(generated_mel_spec[0].cpu().numpy())
# Combine all generated waves with cross-fading if cross_fade_duration <= 0: # Simply concatenate final_wave = np.concatenate(generated_waves) else: final_wave = generated_waves[0] for i in range(1, len(generated_waves)): prev_wave = final_wave next_wave = generated_waves[i]
# Calculate cross-fade samples, ensuring it does not exceed wave lengths cross_fade_samples = int(cross_fade_duration * target_sample_rate) cross_fade_samples = min(cross_fade_samples, len(prev_wave), len(next_wave))
if cross_fade_samples <= 0: # No overlap possible, concatenate final_wave = np.concatenate([prev_wave, next_wave]) continue
# Overlapping parts prev_overlap = prev_wave[-cross_fade_samples:] next_overlap = next_wave[:cross_fade_samples]
# Fade out and fade in fade_out = np.linspace(1, 0, cross_fade_samples) fade_in = np.linspace(0, 1, cross_fade_samples)
# Cross-faded overlap cross_faded_overlap = prev_overlap * fade_out + next_overlap * fade_in
# Combine new_wave = np.concatenate( [prev_wave[:-cross_fade_samples], cross_faded_overlap, next_wave[cross_fade_samples:]] )
final_wave = new_wave
# Create a combined spectrogram combined_spectrogram = np.concatenate(spectrograms, axis=1)
return final_wave, target_sample_rate, combined_spectrogram
# remove silence from generated wav
def remove_silence_for_generated_wav(filename): aseg = AudioSegment.from_file(filename) non_silent_segs = silence.split_on_silence( aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=500, seek_step=10 ) non_silent_wave = AudioSegment.silent(duration=0) for non_silent_seg in non_silent_segs: non_silent_wave += non_silent_seg aseg = non_silent_wave aseg.export(filename, format="wav")
# save spectrogram
def save_spectrogram(spectrogram, path): plt.figure(figsize=(12, 4)) plt.imshow(spectrogram, origin="lower", aspect="auto") plt.colorbar() plt.savefig(path) plt.close()12345678910from f5_tts.model.cfm import CFM
from f5_tts.model.backbones.unett import UNetTfrom f5_tts.model.backbones.dit import DiTfrom f5_tts.model.backbones.mmdit import MMDiT
from f5_tts.model.trainer import Trainer
__all__ = ["CFM", "UNetT", "DiT", "MMDiT", "Trainer"]1234567891011121314151617181920## Backbones quick introduction
### unett.py- flat unet transformer- structure same as in e2-tts & voicebox paper except using rotary pos emb- update: allow possible abs pos emb & convnextv2 blocks for embedded text before concat
### dit.py- adaln-zero dit- embedded timestep as condition- concatted noised_input + masked_cond + embedded_text, linear proj in- possible abs pos emb & convnextv2 blocks for embedded text before concat- possible long skip connection (first layer to last layer)
### mmdit.py- sd3 structure- timestep as condition- left stream: text embedded and applied a abs pos emb- right stream: masked_cond & noised_input concatted and with same conv pos emb as unett123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163"""ein notation:b - batchn - sequencent - text sequencenw - raw wave lengthd - dimension"""
from __future__ import annotations
import torchfrom torch import nnimport torch.nn.functional as F
from x_transformers.x_transformers import RotaryEmbedding
from f5_tts.model.modules import ( TimestepEmbedding, ConvNeXtV2Block, ConvPositionEmbedding, DiTBlock, AdaLayerNormZero_Final, precompute_freqs_cis, get_pos_embed_indices,)
# Text embedding
class TextEmbedding(nn.Module): def __init__(self, text_num_embeds, text_dim, conv_layers=0, conv_mult=2): super().__init__() self.text_embed = nn.Embedding(text_num_embeds + 1, text_dim) # use 0 as filler token
if conv_layers > 0: self.extra_modeling = True self.precompute_max_pos = 4096 # ~44s of 24khz audio self.register_buffer("freqs_cis", precompute_freqs_cis(text_dim, self.precompute_max_pos), persistent=False) self.text_blocks = nn.Sequential( *[ConvNeXtV2Block(text_dim, text_dim * conv_mult) for _ in range(conv_layers)] ) else: self.extra_modeling = False
def forward(self, text: int["b nt"], seq_len, drop_text=False): # noqa: F722 text = text + 1 # use 0 as filler token. preprocess of batch pad -1, see list_str_to_idx() text = text[:, :seq_len] # curtail if character tokens are more than the mel spec tokens batch, text_len = text.shape[0], text.shape[1] text = F.pad(text, (0, seq_len - text_len), value=0)
if drop_text: # cfg for text text = torch.zeros_like(text)
text = self.text_embed(text) # b n -> b n d
# possible extra modeling if self.extra_modeling: # sinus pos emb batch_start = torch.zeros((batch,), dtype=torch.long) pos_idx = get_pos_embed_indices(batch_start, seq_len, max_pos=self.precompute_max_pos) text_pos_embed = self.freqs_cis[pos_idx] text = text + text_pos_embed
# convnextv2 blocks text = self.text_blocks(text)
return text
# noised input audio and context mixing embedding
class InputEmbedding(nn.Module): def __init__(self, mel_dim, text_dim, out_dim): super().__init__() self.proj = nn.Linear(mel_dim * 2 + text_dim, out_dim) self.conv_pos_embed = ConvPositionEmbedding(dim=out_dim)
def forward(self, x: float["b n d"], cond: float["b n d"], text_embed: float["b n d"], drop_audio_cond=False): # noqa: F722 if drop_audio_cond: # cfg for cond audio cond = torch.zeros_like(cond)
x = self.proj(torch.cat((x, cond, text_embed), dim=-1)) x = self.conv_pos_embed(x) + x return x
# Transformer backbone using DiT blocks
class DiT(nn.Module): def __init__( self, *, dim, depth=8, heads=8, dim_head=64, dropout=0.1, ff_mult=4, mel_dim=100, text_num_embeds=256, text_dim=None, conv_layers=0, long_skip_connection=False, ): super().__init__()
self.time_embed = TimestepEmbedding(dim) if text_dim is None: text_dim = mel_dim self.text_embed = TextEmbedding(text_num_embeds, text_dim, conv_layers=conv_layers) self.input_embed = InputEmbedding(mel_dim, text_dim, dim)
self.rotary_embed = RotaryEmbedding(dim_head)
self.dim = dim self.depth = depth
self.transformer_blocks = nn.ModuleList( [DiTBlock(dim=dim, heads=heads, dim_head=dim_head, ff_mult=ff_mult, dropout=dropout) for _ in range(depth)] ) self.long_skip_connection = nn.Linear(dim * 2, dim, bias=False) if long_skip_connection else None
self.norm_out = AdaLayerNormZero_Final(dim) # final modulation self.proj_out = nn.Linear(dim, mel_dim)
def forward( self, x: float["b n d"], # nosied input audio # noqa: F722 cond: float["b n d"], # masked cond audio # noqa: F722 text: int["b nt"], # text # noqa: F722 time: float["b"] | float[""], # time step # noqa: F821 F722 drop_audio_cond, # cfg for cond audio drop_text, # cfg for text mask: bool["b n"] | None = None, # noqa: F722 ): batch, seq_len = x.shape[0], x.shape[1] if time.ndim == 0: time = time.repeat(batch)
# t: conditioning time, c: context (text + masked cond audio), x: noised input audio t = self.time_embed(time) text_embed = self.text_embed(text, seq_len, drop_text=drop_text) x = self.input_embed(x, cond, text_embed, drop_audio_cond=drop_audio_cond)
rope = self.rotary_embed.forward_from_seq_len(seq_len)
if self.long_skip_connection is not None: residual = x
for block in self.transformer_blocks: x = block(x, t, mask=mask, rope=rope)
if self.long_skip_connection is not None: x = self.long_skip_connection(torch.cat((x, residual), dim=-1))
x = self.norm_out(x, t) output = self.proj_out(x)
return output123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146"""ein notation:b - batchn - sequencent - text sequencenw - raw wave lengthd - dimension"""
from __future__ import annotations
import torchfrom torch import nn
from x_transformers.x_transformers import RotaryEmbedding
from f5_tts.model.modules import ( TimestepEmbedding, ConvPositionEmbedding, MMDiTBlock, AdaLayerNormZero_Final, precompute_freqs_cis, get_pos_embed_indices,)
# text embedding
class TextEmbedding(nn.Module): def __init__(self, out_dim, text_num_embeds): super().__init__() self.text_embed = nn.Embedding(text_num_embeds + 1, out_dim) # will use 0 as filler token
self.precompute_max_pos = 1024 self.register_buffer("freqs_cis", precompute_freqs_cis(out_dim, self.precompute_max_pos), persistent=False)
def forward(self, text: int["b nt"], drop_text=False) -> int["b nt d"]: # noqa: F722 text = text + 1 if drop_text: text = torch.zeros_like(text) text = self.text_embed(text)
# sinus pos emb batch_start = torch.zeros((text.shape[0],), dtype=torch.long) batch_text_len = text.shape[1] pos_idx = get_pos_embed_indices(batch_start, batch_text_len, max_pos=self.precompute_max_pos) text_pos_embed = self.freqs_cis[pos_idx]
text = text + text_pos_embed
return text
# noised input & masked cond audio embedding
class AudioEmbedding(nn.Module): def __init__(self, in_dim, out_dim): super().__init__() self.linear = nn.Linear(2 * in_dim, out_dim) self.conv_pos_embed = ConvPositionEmbedding(out_dim)
def forward(self, x: float["b n d"], cond: float["b n d"], drop_audio_cond=False): # noqa: F722 if drop_audio_cond: cond = torch.zeros_like(cond) x = torch.cat((x, cond), dim=-1) x = self.linear(x) x = self.conv_pos_embed(x) + x return x
# Transformer backbone using MM-DiT blocks
class MMDiT(nn.Module): def __init__( self, *, dim, depth=8, heads=8, dim_head=64, dropout=0.1, ff_mult=4, text_num_embeds=256, mel_dim=100, ): super().__init__()
self.time_embed = TimestepEmbedding(dim) self.text_embed = TextEmbedding(dim, text_num_embeds) self.audio_embed = AudioEmbedding(mel_dim, dim)
self.rotary_embed = RotaryEmbedding(dim_head)
self.dim = dim self.depth = depth
self.transformer_blocks = nn.ModuleList( [ MMDiTBlock( dim=dim, heads=heads, dim_head=dim_head, dropout=dropout, ff_mult=ff_mult, context_pre_only=i == depth - 1, ) for i in range(depth) ] ) self.norm_out = AdaLayerNormZero_Final(dim) # final modulation self.proj_out = nn.Linear(dim, mel_dim)
def forward( self, x: float["b n d"], # nosied input audio # noqa: F722 cond: float["b n d"], # masked cond audio # noqa: F722 text: int["b nt"], # text # noqa: F722 time: float["b"] | float[""], # time step # noqa: F821 F722 drop_audio_cond, # cfg for cond audio drop_text, # cfg for text mask: bool["b n"] | None = None, # noqa: F722 ): batch = x.shape[0] if time.ndim == 0: time = time.repeat(batch)
# t: conditioning (time), c: context (text + masked cond audio), x: noised input audio t = self.time_embed(time) c = self.text_embed(text, drop_text=drop_text) x = self.audio_embed(x, cond, drop_audio_cond=drop_audio_cond)
seq_len = x.shape[1] text_len = text.shape[1] rope_audio = self.rotary_embed.forward_from_seq_len(seq_len) rope_text = self.rotary_embed.forward_from_seq_len(text_len)
for block in self.transformer_blocks: c, x = block(x, c, t, mask=mask, rope=rope_audio, c_rope=rope_text)
x = self.norm_out(x, t) output = self.proj_out(x)
return output123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219"""ein notation:b - batchn - sequencent - text sequencenw - raw wave lengthd - dimension"""
from __future__ import annotationsfrom typing import Literal
import torchfrom torch import nnimport torch.nn.functional as F
from x_transformers import RMSNormfrom x_transformers.x_transformers import RotaryEmbedding
from f5_tts.model.modules import ( TimestepEmbedding, ConvNeXtV2Block, ConvPositionEmbedding, Attention, AttnProcessor, FeedForward, precompute_freqs_cis, get_pos_embed_indices,)
# Text embedding
class TextEmbedding(nn.Module): def __init__(self, text_num_embeds, text_dim, conv_layers=0, conv_mult=2): super().__init__() self.text_embed = nn.Embedding(text_num_embeds + 1, text_dim) # use 0 as filler token
if conv_layers > 0: self.extra_modeling = True self.precompute_max_pos = 4096 # ~44s of 24khz audio self.register_buffer("freqs_cis", precompute_freqs_cis(text_dim, self.precompute_max_pos), persistent=False) self.text_blocks = nn.Sequential( *[ConvNeXtV2Block(text_dim, text_dim * conv_mult) for _ in range(conv_layers)] ) else: self.extra_modeling = False
def forward(self, text: int["b nt"], seq_len, drop_text=False): # noqa: F722 text = text + 1 # use 0 as filler token. preprocess of batch pad -1, see list_str_to_idx() text = text[:, :seq_len] # curtail if character tokens are more than the mel spec tokens batch, text_len = text.shape[0], text.shape[1] text = F.pad(text, (0, seq_len - text_len), value=0)
if drop_text: # cfg for text text = torch.zeros_like(text)
text = self.text_embed(text) # b n -> b n d
# possible extra modeling if self.extra_modeling: # sinus pos emb batch_start = torch.zeros((batch,), dtype=torch.long) pos_idx = get_pos_embed_indices(batch_start, seq_len, max_pos=self.precompute_max_pos) text_pos_embed = self.freqs_cis[pos_idx] text = text + text_pos_embed
# convnextv2 blocks text = self.text_blocks(text)
return text
# noised input audio and context mixing embedding
class InputEmbedding(nn.Module): def __init__(self, mel_dim, text_dim, out_dim): super().__init__() self.proj = nn.Linear(mel_dim * 2 + text_dim, out_dim) self.conv_pos_embed = ConvPositionEmbedding(dim=out_dim)
def forward(self, x: float["b n d"], cond: float["b n d"], text_embed: float["b n d"], drop_audio_cond=False): # noqa: F722 if drop_audio_cond: # cfg for cond audio cond = torch.zeros_like(cond)
x = self.proj(torch.cat((x, cond, text_embed), dim=-1)) x = self.conv_pos_embed(x) + x return x
# Flat UNet Transformer backbone
class UNetT(nn.Module): def __init__( self, *, dim, depth=8, heads=8, dim_head=64, dropout=0.1, ff_mult=4, mel_dim=100, text_num_embeds=256, text_dim=None, conv_layers=0, skip_connect_type: Literal["add", "concat", "none"] = "concat", ): super().__init__() assert depth % 2 == 0, "UNet-Transformer's depth should be even."
self.time_embed = TimestepEmbedding(dim) if text_dim is None: text_dim = mel_dim self.text_embed = TextEmbedding(text_num_embeds, text_dim, conv_layers=conv_layers) self.input_embed = InputEmbedding(mel_dim, text_dim, dim)
self.rotary_embed = RotaryEmbedding(dim_head)
# transformer layers & skip connections
self.dim = dim self.skip_connect_type = skip_connect_type needs_skip_proj = skip_connect_type == "concat"
self.depth = depth self.layers = nn.ModuleList([])
for idx in range(depth): is_later_half = idx >= (depth // 2)
attn_norm = RMSNorm(dim) attn = Attention( processor=AttnProcessor(), dim=dim, heads=heads, dim_head=dim_head, dropout=dropout, )
ff_norm = RMSNorm(dim) ff = FeedForward(dim=dim, mult=ff_mult, dropout=dropout, approximate="tanh")
skip_proj = nn.Linear(dim * 2, dim, bias=False) if needs_skip_proj and is_later_half else None
self.layers.append( nn.ModuleList( [ skip_proj, attn_norm, attn, ff_norm, ff, ] ) )
self.norm_out = RMSNorm(dim) self.proj_out = nn.Linear(dim, mel_dim)
def forward( self, x: float["b n d"], # nosied input audio # noqa: F722 cond: float["b n d"], # masked cond audio # noqa: F722 text: int["b nt"], # text # noqa: F722 time: float["b"] | float[""], # time step # noqa: F821 F722 drop_audio_cond, # cfg for cond audio drop_text, # cfg for text mask: bool["b n"] | None = None, # noqa: F722 ): batch, seq_len = x.shape[0], x.shape[1] if time.ndim == 0: time = time.repeat(batch)
# t: conditioning time, c: context (text + masked cond audio), x: noised input audio t = self.time_embed(time) text_embed = self.text_embed(text, seq_len, drop_text=drop_text) x = self.input_embed(x, cond, text_embed, drop_audio_cond=drop_audio_cond)
# postfix time t to input x, [b n d] -> [b n+1 d] x = torch.cat([t.unsqueeze(1), x], dim=1) # pack t to x if mask is not None: mask = F.pad(mask, (1, 0), value=1)
rope = self.rotary_embed.forward_from_seq_len(seq_len + 1)
# flat unet transformer skip_connect_type = self.skip_connect_type skips = [] for idx, (maybe_skip_proj, attn_norm, attn, ff_norm, ff) in enumerate(self.layers): layer = idx + 1
# skip connection logic is_first_half = layer <= (self.depth // 2) is_later_half = not is_first_half
if is_first_half: skips.append(x)
if is_later_half: skip = skips.pop() if skip_connect_type == "concat": x = torch.cat((x, skip), dim=-1) x = maybe_skip_proj(x) elif skip_connect_type == "add": x = x + skip
# attention and feedforward blocks x = attn(attn_norm(x), rope=rope, mask=mask) + x x = ff(ff_norm(x)) + x
assert len(skips) == 0
x = self.norm_out(x)[:, 1:, :] # unpack t from x
return self.proj_out(x).gitattributes+9
README.md+108-3
checkpoints/vocab.txtAdded+2545
config.jsonAdded+16
f5_tts/api.pyAdded+166
f5_tts/configs/E2TTS_Base_train.yamlAdded+44
f5_tts/configs/E2TTS_Small_train.yamlAdded+44
f5_tts/configs/F5TTS_Base_train.yamlAdded+46
f5_tts/configs/F5TTS_Small_train.yamlAdded+46
f5_tts/eval/README.mdAdded+49
f5_tts/eval/ecapa_tdnn.pyAdded+330
f5_tts/eval/eval_infer_batch.pyAdded+207
f5_tts/eval/eval_infer_batch.shAdded+13
f5_tts/eval/eval_librispeech_test_clean.pyAdded+84
f5_tts/eval/eval_seedtts_testset.pyAdded+84
f5_tts/eval/utils_eval.pyAdded+405
f5_tts/infer/README.mdAdded+193
f5_tts/infer/SHARED.mdAdded+103
f5_tts/infer/__pycache__/utils_infer.cpython-310.pycAdded
f5_tts/infer/__pycache__/utils_infer.cpython-312.pycAdded
f5_tts/infer/examples/basic/basic.tomlAdded+11
f5_tts/infer/examples/basic/basic_ref_en.wavAdded+3
f5_tts/infer/examples/basic/basic_ref_zh.wavAdded+3
f5_tts/infer/examples/multi/country.flacAdded+3
f5_tts/infer/examples/multi/main.flacAdded+3
f5_tts/infer/examples/multi/story.tomlAdded+19
f5_tts/infer/examples/multi/story.txtAdded+1
f5_tts/infer/examples/multi/town.flacAdded+3
f5_tts/infer/examples/vocab.txtAdded+2545
f5_tts/infer/infer_batch_parallel.pyAdded+171
f5_tts/infer/infer_cli.pyAdded+226
f5_tts/infer/infer_cli_batch.pyAdded+245
f5_tts/infer/infer_gradio.pyAdded+855
f5_tts/infer/infer_gradio_orig.pyAdded+853
f5_tts/infer/speech_edit.pyAdded+193
f5_tts/infer/utils_infer.pyAdded+552
f5_tts/model/__init__.pyAdded+10
f5_tts/model/__pycache__/__init__.cpython-310.pycAdded
f5_tts/model/__pycache__/cfm.cpython-310.pycAdded
f5_tts/model/__pycache__/dataset.cpython-310.pycAdded
f5_tts/model/__pycache__/modules.cpython-310.pycAdded
f5_tts/model/__pycache__/trainer.cpython-310.pycAdded
f5_tts/model/__pycache__/utils.cpython-310.pycAdded
f5_tts/model/backbones/README.mdAdded+20
f5_tts/model/backbones/__pycache__/dit.cpython-310.pycAdded
f5_tts/model/backbones/__pycache__/mmdit.cpython-310.pycAdded
f5_tts/model/backbones/__pycache__/unett.cpython-310.pycAdded
f5_tts/model/backbones/dit.pyAdded+163
f5_tts/model/backbones/mmdit.pyAdded+146
f5_tts/model/backbones/unett.pyAdded+219