init
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+2
- LICENSEAdded+21
- README.mdAdded+379
- SimulEval/.github/workflows/main.ymlAdded+46
- SimulEval/.gitignoreAdded+139
- SimulEval/CHANGELOG.mdAdded+10
- SimulEval/CODE_OF_CONDUCT.mdAdded+45
- SimulEval/CONTRIBUTING.mdAdded+20
- SimulEval/LICENSEAdded+427
- SimulEval/README.mdAdded+35
- SimulEval/docs/MakefileAdded+20
- SimulEval/docs/conf.pyAdded+40
- SimulEval/docs/index.rstAdded+30
- SimulEval/docs/installation.rstAdded+21
- SimulEval/docs/make.batAdded+41
- SimulEval/docs/quick_start.rstAdded+49
- SimulEval/docs/requirements.txtAdded+2
- SimulEval/docs/tutorials/remote_evaluation.rstAdded+44
- SimulEval/docs/tutorials/speech_to_speech.rstAdded+2
- SimulEval/docs/tutorials/speech_to_text.rstAdded+2
- SimulEval/docs/user_guide/agent.rstAdded+198
- SimulEval/docs/user_guide/dataloader.rstAdded+5
- SimulEval/docs/user_guide/evaluator.rstAdded+44
- SimulEval/docs/user_guide/introduction.rstAdded+35
- SimulEval/examples/quick_start/DockerfileAdded+10
- SimulEval/examples/quick_start/agent_pipeline.pyAdded+39
- SimulEval/examples/quick_start/agent_with_configs.pyAdded+39
- SimulEval/examples/quick_start/agent_with_new_metrics.pyAdded+47
- SimulEval/examples/quick_start/dict.txtAdded+26
- SimulEval/examples/quick_start/first_agent.pyAdded+26
- SimulEval/examples/quick_start/readme.mdAdded+47
- SimulEval/examples/quick_start/source.txtAdded+10
- SimulEval/examples/quick_start/target.txtAdded+10
- SimulEval/examples/speech_to_speech/english_counter_agent.pyAdded+69
- SimulEval/examples/speech_to_speech/eval.shAdded+6
- SimulEval/examples/speech_to_speech/readme.mdAdded+66
- SimulEval/examples/speech_to_speech/reference/de.txtAdded+1
- SimulEval/examples/speech_to_speech/reference/en.txtAdded+1
- SimulEval/examples/speech_to_speech/reference/ja.txtAdded+1
- SimulEval/examples/speech_to_speech/reference/zh.txtAdded+1
- SimulEval/examples/speech_to_speech/source.txtAdded+1
- SimulEval/examples/speech_to_speech/test.wavAdded+3
- SimulEval/setup.cfgAdded+2
- SimulEval/setup.pyAdded+43
- SimulEval/simuleval/__init__.pyAdded+5
- SimulEval/simuleval/agents/__init__.pyAdded+16
- SimulEval/simuleval/agents/actions.pyAdded+60
- SimulEval/simuleval/agents/agent.pyAdded+216
- SimulEval/simuleval/agents/pipeline.pyAdded+90
- SimulEval/simuleval/agents/service.pyAdded+59
1234*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.avro filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text123456*.7z filter=lfs diff=lfs merge=lfs -text*.pdf filter=lfs diff=lfs merge=lfs -text*.mov filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.avro filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021MIT License
Copyright (c) 2024 ICTNLP
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379# StreamSpeech
[](https://arxiv.org/abs/2406.03049)[](https://ictnlp.github.io/StreamSpeech-site/)[](https://huggingface.co/ICTNLP/StreamSpeech_Models/tree/main)[](https://hits.seeyoufarm.com)
[](https://x.com/Gorden_Sun/status/1798742796524007845) [](https://x.com/imxiaohu/status/1798999363987124355)
> **Authors**: **[Shaolei Zhang](https://zhangshaolei1998.github.io/), [Qingkai Fang](https://fangqingkai.github.io/), [Shoutao Guo](https://scholar.google.com.hk/citations?user=XwHtPyAAAAAJ&hl), [Zhengrui Ma](https://scholar.google.com.hk/citations?user=dUgq6tEAAAAJ), [Min Zhang](https://scholar.google.com.hk/citations?user=CncXH-YAAAAJ), [Yang Feng*](https://people.ucas.edu.cn/~yangfeng?language=en)**
Code for ACL 2024 paper "[StreamSpeech: Simultaneous Speech-to-Speech Translation with Multi-task Learning](https://arxiv.org/pdf/2406.03049)".
<p align="center" width="100%"><img src="./assets/streamspeech.png" alt="StreamSpeech" style="width: 70%; min-width: 300px; display: block; margin: auto;"></p><p align="center"> 🎧 Listen to <a href="https://ictnlp.github.io/StreamSpeech-site/">StreamSpeech's translated speech</a> 🎧 </p>
💡**Highlight**:1. StreamSpeech achieves **SOTA performance** on both offline and simultaneous speech-to-speech translation.2. StreamSpeech performs **streaming ASR**, **simultaneous speech-to-text translation** and **simultaneous speech-to-speech translation** via an "All in One" seamless model.3. StreamSpeech can present intermediate results (i.e., ASR or translation results) during simultaneous translation, offering a more comprehensive low-latency communication experience.
## 🔥News- [2025.06.17] We are excited to extend the "All-in-One" feature of StreamSpeech to more general multimodal interactions via developing **Stream-Omni**. 👉Refer to [paper](https://arxiv.org/abs/2506.13642), [code & demo](https://github.com/ictnlp/Stream-Omni), [model](https://huggingface.co/ICTNLP/stream-omni-8b) for more details. - Stream-Omni is an GPT-4o-like language-vision-speech chatbot that simultaneously supports interactions across any combination of text, vision, and speech modalities. - Stream-Omni can simultaneously produce intermediate textual results (e.g., ASR transcriptions and model responses) during speech interactions, like the advanced voice service of GPT-4o.
- [2024.06.17] Add [Web GUI demo](./demo), now you can experience StreamSpeech in your local browser.- [2024.06.05] [Paper](https://arxiv.org/pdf/2406.03049), [code](https://github.com/ictnlp/StreamSpeech), [models](https://huggingface.co/ICTNLP/StreamSpeech_Models/tree/main) and [demo](https://ictnlp.github.io/StreamSpeech-site/) of StreamSpeech are available!
## ⭐Features
### Support 8 Tasks- **Offline**: Speech Recognition (ASR)✅, Speech-to-Text Translation (S2TT)✅, Speech-to-Speech Translation (S2ST)✅, Speech Synthesis (TTS)✅- **Simultaneous**: Streaming ASR✅, Simultaneous S2TT✅, Simultaneous S2ST✅, Real-time TTS✅ under any latency (with one model)
### GUI Demo
https://github.com/ictnlp/StreamSpeech/assets/34680227/4d9bdabf-af66-4320-ae7d-0f23e721cd71<p align="center"> Simultaneously provide ASR, translation, and synthesis results via a seamless model</p>
### Case
> **Speech Input**: [example/wavs/common_voice_fr_17301936.mp3](./example/wavs/common_voice_fr_17301936.mp3)>> **Transcription** (ground truth): jai donc lexpérience des années passées jen dirai un mot tout à lheure>> **Translation** (ground truth): i therefore have the experience of the passed years i'll say a few words about that later
| StreamSpeech | Simultaneous | Offline || ----------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ || **Speech Recognition** | jai donc expérience des années passé jen dirairai un mot tout à lheure | jai donc lexpérience des années passé jen dirairai un mot tout à lheure || **Speech-to-Text Translation** | i therefore have an experience of last years i will tell a word later | so i have the experience in the past years i'll say a word later || **Speech-to-Speech Translation** | <video src='https://github.com/zhangshaolei1998/StreamSpeech_dev/assets/34680227/ed41ba13-353b-489b-acfa-85563d0cc2cb' width="30%"/> | <video src='https://github.com/zhangshaolei1998/StreamSpeech_dev/assets/34680227/ca482ba6-76da-4619-9dfd-24aa2eb3339a' width="30%"/> || **Text-to-Speech Synthesis** (*incrementally synthesize speech word by word*) | <video src='https://github.com/zhangshaolei1998/StreamSpeech_dev/assets/34680227/294f1310-eace-4914-be30-5cd798e8592e' width="30%"/> | <video src='https://github.com/zhangshaolei1998/StreamSpeech_dev/assets/34680227/52854163-7fc5-4622-a5a6-c133cbd99e58' width="30%"/> |
## ⚙Requirements
- Python == 3.10, PyTorch == 2.0.1, Install fairseq & SimulEval
```bash cd fairseq pip install --editable ./ --no-build-isolation cd SimulEval pip install --editable ./ ```
## 🚀Quick Start
### 1. Model Download
#### (1) StreamSpeech Models
| Language | UnitY | StreamSpeech (offline) | StreamSpeech (simultaneous) || -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ || Fr-En | unity.fr-en.pt [[Huggingface](https://huggingface.co/ICTNLP/StreamSpeech_Models/blob/main/unity.fr-en.pt)] [[Baidu](https://pan.baidu.com/s/10uGYgl0xTej9FP43iKx7Cg?pwd=nkvu)] | streamspeech.offline.fr-en.pt [[Huggingface](https://huggingface.co/ICTNLP/StreamSpeech_Models/blob/main/streamspeech.offline.fr-en.pt)] [[Baidu](https://pan.baidu.com/s/1GFckHGP5SNLuOEj6mbIWhQ?pwd=pwgq)] | streamspeech.simultaneous.fr-en.pt [[Huggingface](https://huggingface.co/ICTNLP/StreamSpeech_Models/blob/main/streamspeech.simultaneous.fr-en.pt)] [[Baidu](https://pan.baidu.com/s/1edCPFljogyDHgGXkUV8_3w?pwd=8gg3)] || Es-En | unity.es-en.pt [[Huggingface](https://huggingface.co/ICTNLP/StreamSpeech_Models/blob/main/unity.es-en.pt)] [[Baidu](https://pan.baidu.com/s/1RwIEHye8jjw3kiIgrCHA3A?pwd=hde4)] | streamspeech.offline.es-en.pt [[Huggingface](https://huggingface.co/ICTNLP/StreamSpeech_Models/blob/main/streamspeech.offline.es-en.pt)] [[Baidu](https://pan.baidu.com/s/1T89G4NC4J0Ofzcsc8Rt2Ww?pwd=yuhd)] | streamspeech.simultaneous.es-en.pt [[Huggingface](https://huggingface.co/ICTNLP/StreamSpeech_Models/blob/main/streamspeech.simultaneous.es-en.pt)] [[Baidu](https://pan.baidu.com/s/1NbLEVcYWHIdqqLD17P1s9g?pwd=p1pc)] || De-En | unity.de-en.pt [[Huggingface](https://huggingface.co/ICTNLP/StreamSpeech_Models/blob/main/unity.de-en.pt)] [[Baidu](https://pan.baidu.com/s/1Mg_PBeZ5acEDhl5wRJ_-7w?pwd=egvv)] | streamspeech.offline.de-en.pt [[Huggingface](https://huggingface.co/ICTNLP/StreamSpeech_Models/blob/main/streamspeech.offline.de-en.pt)] [[Baidu](https://pan.baidu.com/s/1mTE4eHuVLJPB7Yg9AackEg?pwd=6ga8)] | streamspeech.simultaneous.de-en.pt [[Huggingface](https://huggingface.co/ICTNLP/StreamSpeech_Models/blob/main/streamspeech.simultaneous.de-en.pt)] [[Baidu](https://pan.baidu.com/s/1DYPMg3mdDopLY70BYQTduQ?pwd=r7kw)] |
#### (2) Unit-based HiFi-GAN Vocoder
| Unit config | Unit size | Vocoder language | Dataset | Model || ----------------- | --------- | ---------------- | --------------------------------------------------- | ------------------------------------------------------------ || mHuBERT, layer 11 | 1000 | En | [LJSpeech](https://keithito.com/LJ-Speech-Dataset/) | [ckpt](https://dl.fbaipublicfiles.com/fairseq/speech_to_speech/vocoder/code_hifigan/mhubert_vp_en_es_fr_it3_400k_layer11_km1000_lj/g_00500000), [config](https://dl.fbaipublicfiles.com/fairseq/speech_to_speech/vocoder/code_hifigan/mhubert_vp_en_es_fr_it3_400k_layer11_km1000_lj/config.json) |
### 2. Prepare Data and Config (only for test/inference)
#### (1) Config Files
Replace `/data/zhangshaolei/StreamSpeech` in files [configs/fr-en/config_gcmvn.yaml](./configs/fr-en/config_gcmvn.yaml) and [configs/fr-en/config_mtl_asr_st_ctcst.yaml](./configs/fr-en/config_mtl_asr_st_ctcst.yaml) with your local address of StreamSpeech repo.
#### (2) Test Data
Prepare test data following [SimulEval](https://github.com/facebookresearch/SimulEval) format. [example/](./example) provides an example:
- [wav_list.txt](./example/wav_list.txt): Each line records the path of a source speech.- [target.txt](./example/target.txt): Each line records the reference text, e.g., target translation or source transcription (used to calculate the metrics).
### 3. Inference with SimulEval
Run these scripts to inference StreamSpeech on streaming ASR, simultaneous S2TT and simultaneous S2ST.
> `--source-segment-size`: set the chunk size (millisecond) to any value to control the latency
<details><summary>Simultaneous Speech-to-Speech Translation</summary>
`--output-asr-translation`: whether to output the intermediate ASR and translated text results during simultaneous speech-to-speech translation.
```shellexport CUDA_VISIBLE_DEVICES=0
ROOT=/data/zhangshaolei/StreamSpeech # path to StreamSpeech repoPRETRAIN_ROOT=/data/zhangshaolei/pretrain_models VOCODER_CKPT=$PRETRAIN_ROOT/unit-based_HiFi-GAN_vocoder/mHuBERT.layer11.km1000.en/g_00500000 # path to downloaded Unit-based HiFi-GAN VocoderVOCODER_CFG=$PRETRAIN_ROOT/unit-based_HiFi-GAN_vocoder/mHuBERT.layer11.km1000.en/config.json # path to downloaded Unit-based HiFi-GAN Vocoder
LANG=frfile=streamspeech.simultaneous.${LANG}-en.pt # path to downloaded StreamSpeech modeloutput_dir=$ROOT/res/streamspeech.simultaneous.${LANG}-en/simul-s2st
chunk_size=320 #msPYTHONPATH=$ROOT/fairseq simuleval --data-bin ${ROOT}/configs/${LANG}-en \ --user-dir ${ROOT}/researches/ctc_unity --agent-dir ${ROOT}/agent \ --source example/wav_list.txt --target example/target.txt \ --model-path $file \ --config-yaml config_gcmvn.yaml --multitask-config-yaml config_mtl_asr_st_ctcst.yaml \ --agent $ROOT/agent/speech_to_speech.streamspeech.agent.py \ --vocoder $VOCODER_CKPT --vocoder-cfg $VOCODER_CFG --dur-prediction \ --output $output_dir/chunk_size=$chunk_size \ --source-segment-size $chunk_size \ --quality-metrics ASR_BLEU --target-speech-lang en --latency-metrics AL AP DAL StartOffset EndOffset LAAL ATD NumChunks DiscontinuitySum DiscontinuityAve DiscontinuityNum RTF \ --device gpu --computation-aware \ --output-asr-translation True```
You should get the following outputs:
```fairseq plugins loaded...fairseq plugins loaded...fairseq plugins loaded...fairseq plugins loaded...2024-06-06 09:45:46 | INFO | fairseq.tasks.speech_to_speech | dictionary size: 1,004import agents...Removing weight norm...2024-06-06 09:45:50 | INFO | agent.tts.vocoder | loaded CodeHiFiGAN checkpoint from /data/zhangshaolei/pretrain_models/unit-based_HiFi-GAN_vocoder/mHuBERT.layer11.km1000.en/g_005000002024-06-06 09:45:50 | INFO | simuleval.utils.agent | System will run on device: gpu.2024-06-06 09:45:50 | INFO | simuleval.dataloader | Evaluating from speech to speech. 0%| | 0/2 [00:00<?, ?it/s]Streaming ASR: Streaming ASR: Streaming ASR: jeSimultaneous translation: i wouldStreaming ASR: je voudraisSimultaneous translation: i would like toStreaming ASR: je voudrais soumettreSimultaneous translation: i would like to subStreaming ASR: je voudrais soumettre cetteSimultaneous translation: i would like to submitStreaming ASR: je voudrais soumettre cette idéeSimultaneous translation: i would like to submit thisStreaming ASR: je voudrais soumettre cette idée à laSimultaneous translation: i would like to submit this idea toStreaming ASR: je voudrais soumettre cette idée à la réflexionSimultaneous translation: i would like to submit this idea to theStreaming ASR: je voudrais soumettre cette idée à la réflexion deSimultaneous translation: i would like to submit this idea to the reflectionStreaming ASR: je voudrais soumettre cette idée à la réflexion de lassembléeSimultaneous translation: i would like to submit this idea to the reflection ofStreaming ASR: je voudrais soumettre cette idée à la réflexion de lassemblée nationaleSimultaneous translation: i would like to submit this idea to the reflection of theStreaming ASR: je voudrais soumettre cette idée à la réflexion de lassemblée nationaleSimultaneous translation: i would like to submit this idea to the reflection of the national assembly 50%|███████████████████████████████████████████████████████████████████████████████████ | 1/2 [00:04<00:04, 4.08s/it]Streaming ASR: Streaming ASR: Streaming ASR: Streaming ASR: Streaming ASR: jai doncSimultaneous translation: i thereforeStreaming ASR: jai doncStreaming ASR: jai donc expérience desSimultaneous translation: i therefore have an experienceStreaming ASR: jai donc expérience des annéesStreaming ASR: jai donc expérience des années passéSimultaneous translation: i therefore have an experience of lastStreaming ASR: jai donc expérience des années passé jenSimultaneous translation: i therefore have an experience of last yearsStreaming ASR: jai donc expérience des années passé jen dirairaiSimultaneous translation: i therefore have an experience of last years i willStreaming ASR: jai donc expérience des années passé jen dirairai un motSimultaneous translation: i therefore have an experience of last years i will tell aStreaming ASR: jai donc expérience des années passé jen dirairai un mot tout à lheureSimultaneous translation: i therefore have an experience of last years i will tell a wordStreaming ASR: jai donc expérience des années passé jen dirairai un mot tout à lheureSimultaneous translation: i therefore have an experience of last years i will tell a word later100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2/2 [00:06<00:00, 3.02s/it]2024-06-06 09:45:56 | WARNING | simuleval.scorer.asr_bleu | Beta feature: Evaluating speech output. Faieseq is required.2024-06-06 09:46:12 | INFO | fairseq.tasks.audio_finetuning | Using dict_path : /data/zhangshaolei/.cache/ust_asr/en/dict.ltr.txtTranscribing predictions: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2/2 [00:01<00:00, 1.63it/s]2024-06-06 09:46:21 | INFO | simuleval.sentence_level_evaluator | Results: ASR_BLEU AL AL_CA AP AP_CA DAL DAL_CA StartOffset StartOffset_CA EndOffset EndOffset_CA LAAL LAAL_CA ATD ATD_CA NumChunks NumChunks_CA DiscontinuitySum DiscontinuitySum_CA DiscontinuityAve DiscontinuityAve_CA DiscontinuityNum DiscontinuityNum_CA RTF RTF_CA 15.448 1724.895 2913.508 0.425 0.776 1358.812 3137.55 1280.0 2213.906 1366.0 1366.0 1724.895 2913.508 1440.146 3389.374 9.5 9.5 110.0 110.0 55.0 55.0 1 1 1.326 1.326
```
Logs and evaluation results are stored in ` $output_dir/chunk_size=$chunk_size`:
```$output_dir/chunk_size=$chunk_size├── wavs/│ ├── 0_pred.wav # generated speech│ ├── 1_pred.wav │ ├── 0_pred.txt # asr transcription for ASR-BLEU tookit│ ├── 1_pred.txt ├── config.yaml├── asr_transcripts.txt # ASR-BLEU transcription results├── metrics.tsv├── scores.tsv├── asr_cmd.bash└── instances.log # logs of Simul-S2ST```
</details>
<details><summary>Simultaneous Speech-to-Text Translation</summary>
```shellexport CUDA_VISIBLE_DEVICES=0
ROOT=/data/zhangshaolei/StreamSpeech # path to StreamSpeech repo
LANG=frfile=streamspeech.simultaneous.${LANG}-en.pt # path to downloaded StreamSpeech modeloutput_dir=$ROOT/res/streamspeech.simultaneous.${LANG}-en/simul-s2tt
chunk_size=320 #msPYTHONPATH=$ROOT/fairseq simuleval --data-bin ${ROOT}/configs/${LANG}-en \ --user-dir ${ROOT}/researches/ctc_unity --agent-dir ${ROOT}/agent \ --source example/wav_list.txt --target example/target.txt \ --model-path $file \ --config-yaml config_gcmvn.yaml --multitask-config-yaml config_mtl_asr_st_ctcst.yaml \ --agent $ROOT/agent/speech_to_text.s2tt.streamspeech.agent.py\ --output $output_dir/chunk_size=$chunk_size \ --source-segment-size $chunk_size \ --quality-metrics BLEU --latency-metrics AL AP DAL StartOffset EndOffset LAAL ATD NumChunks RTF \ --device gpu --computation-aware ```</details>
<details><summary>Streaming ASR</summary>
```shellexport CUDA_VISIBLE_DEVICES=0
ROOT=/data/zhangshaolei/StreamSpeech # path to StreamSpeech repo
LANG=frfile=streamspeech.simultaneous.${LANG}-en.pt # path to downloaded StreamSpeech modeloutput_dir=$ROOT/res/streamspeech.simultaneous.${LANG}-en/streaming-asr
chunk_size=320 #msPYTHONPATH=$ROOT/fairseq simuleval --data-bin ${ROOT}/configs/${LANG}-en \ --user-dir ${ROOT}/researches/ctc_unity --agent-dir ${ROOT}/agent \ --source example/wav_list.txt --target example/source.txt \ --model-path $file \ --config-yaml config_gcmvn.yaml --multitask-config-yaml config_mtl_asr_st_ctcst.yaml \ --agent $ROOT/agent/speech_to_text.asr.streamspeech.agent.py\ --output $output_dir/chunk_size=$chunk_size \ --source-segment-size $chunk_size \ --quality-metrics BLEU --latency-metrics AL AP DAL StartOffset EndOffset LAAL ATD NumChunks RTF \ --device gpu --computation-aware ```</details>
## 🎈Develop Your Own StreamSpeech
### 1. Data Preprocess
- Follow [`./preprocess_scripts`](./preprocess_scripts) to process CVSS-C data.
### 2. Training
> [!Note]> You can directly use the [downloaded StreamSpeech model](#1-model-download) for evaluation and skip training.
<p align="center" width="100%"><img src="./assets/model.png" alt="model" style="width: 100%; min-width: 300px; display: block; margin: auto;"></p>
- Follow [`researches/ctc_unity/train_scripts/train.simul-s2st.sh`](./researches/ctc_unity/train_scripts/train.simul-s2st.sh) to train StreamSpeech for simultaneous speech-to-speech translation.- Follow [`researches/ctc_unity/train_scripts/train.offline-s2st.sh`](./researches/ctc_unity/train_scripts/train.offline-s2st.sh) to train StreamSpeech for offline speech-to-speech translation.- We also provide some other StreamSpeech variants and baseline implementations.
| Model | --user-dir | --arch | Description || ----------------- | -------------------------- | --------------------------------- | ------------------------------------------------------------ || **Translatotron 2** | `researches/translatotron` | `s2spect2_conformer_modified` | [Translatotron 2](https://proceedings.mlr.press/v162/jia22b.html) || **UnitY** | `researches/translatotron` | `unity_conformer_modified` | [UnitY](https://aclanthology.org/2023.acl-long.872/) || **Uni-UnitY** | `researches/uni_unity` | `uni_unity_conformer` | Change all encoders in UnitY into unidirectional || **Chunk-UnitY** | `researches/chunk_unity` | `chunk_unity_conformer` | Change the Conformer in UnitY into Chunk-based Conformer || **StreamSpeech** | `researches/ctc_unity` | `streamspeech` | StreamSpeech || **StreamSpeech (cascade)** | `researches/ctc_unity` | `streamspeech_cascade` | Cascaded StreamSpeech of S2TT and TTS. TTS module can be used independently for real-time TTS given incremental text. || **HMT** | `researches/hmt` | `hmt_transformer_iwslt_de_en` | [HMT](https://openreview.net/forum?id=9y0HFvaAYD6): strong simultaneous text-to-text translation method || **DiSeg** | `researches/diseg` | `convtransformer_espnet_base_seg` | [DiSeg](https://aclanthology.org/2023.findings-acl.485/): strong simultaneous speech-to-text translation method |
> [!Tip]> The `train_scripts/` and `test_scripts/` in directory `--user-dir` give the training and testing scripts for each model.> Refer to official repo of [UnitY](https://github.com/facebookresearch/fairseq/blob/main/fairseq/models/speech_to_speech/s2s_conformer_unity.py), [Translatotron 2](https://github.com/facebookresearch/fairseq/blob/main/fairseq/models/speech_to_speech/s2s_conformer_translatotron2.py), [HMT](https://github.com/ictnlp/HMT) and [DiSeg](https://github.com/ictnlp/DiSeg) for more details.
### 3. Evaluation
#### (1) Offline Evaluation
Follow [`pred.offline-s2st.sh`](./researches/ctc_unity/test_scripts/pred.offline-s2st.sh) to evaluate the offline performance of StreamSpeech on ASR, S2TT and S2ST.
#### (2) Simultaneous Evaluation
A trained StreamSpeech model can be used for streaming ASR, simultaneous speech-to-text translation and simultaneous speech-to-speech translation. We provide [agent/](./agent) for these three tasks:
- `agent/speech_to_speech.streamspeech.agent.py`: simultaneous speech-to-speech translation- `agent/speech_to_text.s2tt.streamspeech.agent.py`: simultaneous speech-to-text translation- `agent/speech_to_text.asr.streamspeech.agent.py`: streaming ASR
Follow [`simuleval.simul-s2st.sh`](./researches/ctc_unity/test_scripts/simuleval.simul-s2st.sh), [`simuleval.simul-s2tt.sh`](./researches/ctc_unity/test_scripts/simuleval.simul-s2tt.sh), [`simuleval.streaming-asr.sh`](./researches/ctc_unity/test_scripts/simuleval.streaming-asr.sh) to evaluate StreamSpeech.
### 4. Our Results
Our project page ([https://ictnlp.github.io/StreamSpeech-site/](https://ictnlp.github.io/StreamSpeech-site/)) provides some translated speech generated by StreamSpeech, listen to it 🎧.
#### (1) Offline Speech-to-Speech Translation ( ASR-BLEU: quality )
<p align="center" width="100%"><img src="./assets/offline_results.png" alt="offline" style="width: 100%; min-width: 300px; display: block; margin: auto;"></p>
#### (2) Simultaneous Speech-to-Speech Translation ( AL: latency | ASR-BLEU: quality )
<p align="center" width="100%"><img src="./assets/simultaneous_results.png" alt="simul" style="width: 100%; min-width: 300px; display: block; margin: auto;"></p>
#### (3) Simultaneous Speech-to-Text Translation ( AL: latency | BLEU: quality )
<p align="center" width="100%"><img src="./assets/s2tt.png" alt="simul" style="width: 38%; min-width: 300px; display: block; margin: auto;"></p>
#### (4) Streaming ASR ( AL: latency | WER: quality )
<p align="center" width="100%"><img src="./assets/asr.png" alt="simul" style="width: 50%; min-width: 300px; display: block; margin: auto;"></p>
## 🖋Citation
If you have any questions, please feel free to submit an issue or contact `zhangshaolei20z@ict.ac.cn`.
If our work is useful for you, please cite as:
```@inproceedings{streamspeech, title={StreamSpeech: Simultaneous Speech-to-Speech Translation with Multi-task Learning}, author={Shaolei Zhang and Qingkai Fang and Shoutao Guo and Zhengrui Ma and Min Zhang and Yang Feng}, year={2024}, booktitle = {Proceedings of the 62th Annual Meeting of the Association for Computational Linguistics (Long Papers)}, publisher = {Association for Computational Linguistics}}```12345678910111213141516171819202122232425262728293031323334353637383940414243444546# This workflow will install Python dependencies, run tests and lint with a variety of Python versions# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
name: build
on: push: branches: - main pull_request:
jobs: build:
runs-on: ubuntu-latest strategy: matrix: python-version: [3.7, 3.8]
steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version}} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | sudo apt-get install libsndfile1 python -m pip install --upgrade pip pip install flake8 pytest black pip install -e . if [ -f requirements.txt ]; then pip install -r requirements.txt; fi - name: Lint with black run: black --check --diff . - name: Lint with flake8 run: | # stop the build if there are Python syntax errors or undefined names flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics - name: Test with pytest run: | pytest simuleval/test/test_agent.py pytest simuleval/test/test_agent_pipeline.py pytest simuleval/test/test_evaluator.py pytest simuleval/test/test_remote_evaluation.py123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py,cover.hypothesis/.pytest_cache/cover/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuilder.pybuilder/target/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:# .python-version
# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# SageMath parsed files*.sage.py
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/.vscode123456789101.0.0 (September 25, 2020)
* Initial release.
1.0.1 (February 8, 2021)
* Change CLI command * Change `simuleval-server` to `simuleval --server-only` * Change `simuleval-client` to `simuleval --client-only`* Fix some typos123456789101112131415161718192021222324252627282930313233343536373839404142434445# Open Source Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
Using welcoming and inclusive languageBeing respectful of differing viewpoints and experiencesGracefully accepting constructive criticismFocusing on what is best for the communityShowing empathy towards other community membersExamples of unacceptable behavior by participants include:
The use of sexualized language or imagery and unwelcome sexual attention or advancesTrolling, insulting/derogatory comments, and personal or political attacksPublic or private harassmentPublishing others’ private information, such as a physical or electronic address, without explicit permissionOther conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at opensource-conduct@fb.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project’s leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org1234567891011121314151617181920# Contributing to Facebook AI SimulEvalWe want to make contributing to this project as easy and transparent aspossible.
## Pull RequestsWe actively welcome your pull requests.
1. Fork the repo and create your branch from `master`.2. If you've added code that should be tested, add tests.3. If you've changed APIs, update the documentation.4. Ensure the test suite passes.5. Make sure your code lints.
## IssuesWe use GitHub issues to track public bugs. Please ensure your description isclear and has sufficient instructions to be able to reproduce the issue.
## LicenseBy contributing to Facebook AI SimulEval, you agree that your contributions willbe licensed under the LICENSE file in the root directory of this source tree.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427Attribution-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm anddoes not provide legal services or legal advice. Distribution ofCreative Commons public licenses does not create a lawyer-client orother relationship. Creative Commons makes its licenses and relatedinformation available on an "as-is" basis. Creative Commons gives nowarranties regarding its licenses, any material licensed under theirterms and conditions, or any related information. Creative Commonsdisclaims all liability for damages resulting from their use to thefullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms andconditions that creators and other rights holders may use to shareoriginal works of authorship and other material subject to copyrightand certain other rights specified in the public license below. Thefollowing considerations are for informational purposes only, are notexhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More_considerations for the public: wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-ShareAlike 4.0 International PublicLicense
By exercising the Licensed Rights (defined below), You accept and agreeto be bound by the terms and conditions of this Creative CommonsAttribution-ShareAlike 4.0 International Public License ("PublicLicense"). To the extent this Public License may be interpreted as acontract, You are granted the Licensed Rights in consideration of Youracceptance of these terms and conditions, and the Licensor grants Yousuch rights in consideration of benefits the Licensor receives frommaking the Licensed Material available under these terms andconditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike.
h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. Term. The term of this Public License is specified in Section 6(a).
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
b. Additional offer from the Licensor -- Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to thefollowing conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified form), You must:
a. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights thatapply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material,
including for purposes of Section 3(b); and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does notreplace Your obligations under this Public License where the LicensedRights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its publiclicenses. Notwithstanding, Creative Commons may elect to apply one ofits public licenses to material it publishes and in those instanceswill be considered the “Licensor.” The text of the Creative Commonspublic licenses is dedicated to the public domain under the CC0 PublicDomain Dedication. Except for the limited purpose of indicating thatmaterial is shared under a Creative Commons public license or asotherwise permitted by the Creative Commons policies published atcreativecommons.org/policies, Creative Commons does not authorize theuse of the trademark "Creative Commons" or any other trademark or logoof Creative Commons without its prior written consent including,without limitation, in connection with any unauthorized modificationsto any of its public licenses or any other arrangements,understandings, or agreements concerning use of licensed material. Forthe avoidance of doubt, this paragraph does not form part of thepublic licenses.
Creative Commons may be contacted at creativecommons.org.1234567891011121314151617181920212223242526272829303132333435# SimulEval[](https://github.com/facebookresearch/SimulEval/actions)
SimulEval is a general evaluation framework for simultaneous translation on text and speech. Full documentation can be found [here](https://simuleval.readthedocs.io/en/v1.1.0/).
## Installation```git clone https://github.com/facebookresearch/SimulEval.gitcd SimulEvalpip install -e .```
## Quick StartFollowing is the evaluation of a [dummy agent](examples/quick_start) which operates wait-k (k = 3) policy and generates random words until the length of the generated words is the same as the number of all the source words.```shellcd examples/quick_startsimuleval --source source.txt --target target.txt --agent first_agent.py```
# License
SimulEval is licensed under Creative Commons BY-SA 4.0.
# Citation
Please cite as:
```bibtex@inproceedings{simuleval2020, title = {Simuleval: An evaluation toolkit for simultaneous translation}, author = {Xutai Ma, Mohammad Javad Dousti, Changhan Wang, Jiatao Gu, Juan Pino}, booktitle = {Proceedings of the EMNLP}, year = {2020},}```1234567891011121314151617181920# Minimal makefile for Sphinx documentation#
# You can set these variables from the command line, and also# from the environment for the first two.SPHINXOPTS ?=SPHINXBUILD ?= sphinx-buildSOURCEDIR = .BUILDDIR = build
# Put it first so that "make" without argument is like "make help".help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).%: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)12345678910111213141516171819202122232425262728293031323334353637383940# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
# Configuration file for the Sphinx documentation builder.## For the full list of built-in configuration values, see the documentation:# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = "SimulEval"copyright = "Facebook AI Research (FAIR)"author = "Facebook AI Research (FAIR)"release = "1.1.0"
# -- General configuration ---------------------------------------------------# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = [ "sphinx_rtd_theme", "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinx.ext.viewcode", "sphinx.ext.napoleon", "sphinxarg.ext",]
# templates_path = ['_templates']exclude_patterns = []
# -- Options for HTML output -------------------------------------------------# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = "sphinx_rtd_theme"# html_static_path = ['_static']123456789101112131415161718192021222324252627282930SimulEval documentation=======================
SimulEval is a general evaluation framework for simultaneous translation.
.. toctree:: :maxdepth: 2 :glob: :caption: Get started
installation quick_start
.. toctree:: :maxdepth: 2 :caption: User's guide
user_guide/introduction user_guide/agent user_guide/evaluator user_guide/dataloader
.. toctree:: :maxdepth: 2 :caption: Tutorials
tutorials/remote_evaluation tutorials/speech_to_text tutorials/speech_to_speech
123456789101112131415161718192021Installation============
From pip--------
.. code-block:: bash
pip install simuleval
From source-----------
.. code-block:: bash
git clone https://github.com/facebookresearch/SimulEval.git cd SimulEval pip install -e .
1234567891011121314151617181920212223242526272829303132333435363738394041:: Copyright (c) Facebook, Inc. and its affiliates.:: All rights reserved.:::: This source code is licensed under the license found in the:: LICENSE file in the root directory of this source tree.
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build)set SOURCEDIR=sourceset BUILDDIR=build
%SPHINXBUILD% >NUL 2>NULif errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.https://www.sphinx-doc.org/ exit /b 1)
if "%1" == "" goto help
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%goto end
:help%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:endpopd12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849.. _first-agent:
Quick Start===========
This section will introduce a minimal example on how to use SimulEval for simultaneous translation evaluation.The code in the example can be found in :code:`examples/quick_start`.
The agent in SimulEval is core for simultaneous evaluation.It's a carrier of user's simultaneous system.The user has to implement the agent based on their system for evaluation.The example simultaneous system is a dummy wait-k agent, which
- Runs `wait-k <https://aclanthology.org/P19-1289/>`_ policy.- Generates random characters the policy decide to write.- Stops the generation k predictions after source input. For simplicity, we just set :code:`k=3` in this example.
The implementation of this agent is shown as follow.
.. literalinclude:: ../examples/quick_start/first_agent.py :language: python :lines: 6-
There two essential components for an agent:
- :code:`states`: The attribute keeps track of the source and target information.- :code:`policy`: The method makes decisions when the there is a new source segment.
Once the agent is implemented and saved at :code:`first_agent.py`,run the following command for latency evaluation on:
.. code-block:: bash
simuleval --source source.txt --reference target.txt --agent first_agent.py
where :code:`--source` is the input file while :code:`--target` is the reference file.
By default, the SimulEval will give the following output --- one quality and three latency metrics.
.. code-block:: bash
2022-12-05 13:43:58 | INFO | simuleval.cli | Evaluate system: DummyWaitkTextAgent 2022-12-05 13:43:58 | INFO | simuleval.dataloader | Evaluating from text to text. 2022-12-05 13:43:58 | INFO | simuleval.sentence_level_evaluator | Results: BLEU AL AP DAL 1.541 3.0 0.688 3.0
The average lagging is expected since we are running an wait-3 system where the source and target always have the same length.Notice that we have a very low yet random BLEU score. It's because we are randomly generate the output.12sphinx-argparse==0.4.0-e .1234567891011121314151617181920212223242526272829303132333435363738394041424344Remote Evaluation=================
Stand Alone Agent-----------------The agent can run in stand alone mode,by using :code:`--standalone` option.The SimulEval will kickoff a server that host the agent.For instance, with the agent in :ref:`first-agent`,
.. code-block:: bash
> simuleval --standalone --remote-port 8888 --agent first_agent.py.py 2022-12-06 19:12:26 | INFO | simuleval.cli | Evaluate system: DummyWaitkTextAgent 2022-12-06 19:12:26 | INFO | simuleval.agent_server | Simultaneous Translation Server Started (process id 53902). Listening to port 8888
For detailed RESTful APIs, please see (TODO)
Docker-----------------You can also use a docker image to run the simuleval.An minimal example of :code:`Dockerfile` is
.. literalinclude:: ../../examples/quick_start/Dockerfile :language: docker
Build and run the docker image:
.. code-block:: bash
cd examples/quick_start && docker build -t simuleval_agent . docker run -p 8888:8888 simuleval_agent:latest
Remote Evaluation------------------If there is an agent server or docker image available,(let's say the one we just kickoff at localhost:8888)We can start a remote evaluator as follow. For simplicity we assume they are on the same machine
.. code-block:: bash
simuleval --remote-eval --remote-port 8888 \ --source source.txt --target target.txt \ --source-type text --target-type text12Speech-to-Speech================12Speech-to-Text==============123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198Agent=====
To evaluate the simultaneous translation system,the users need to implement agent class which operate the system logics.This section will introduce how to implement an agent.
Source-Target Types-------------------First of all,we must declare the source and target types of the agent class.It can be done by inheriting from
- One of the following four built-in agent types
- :class:`simuleval.agents.TextToTextAgent` - :class:`simuleval.agents.SpeechToTextAgent` - :class:`simuleval.agents.TextToSpeechAgent` - :class:`simuleval.agents.SpeechToSpeechAgent`
- Or :class:`simuleval.agents.GenericAgent`, with explicit declaration of :code:`source_type` and :code:`target_type`.
The follow two examples are equivalent.
.. code-block:: python
from simuleval import simuleval from simuleval.agents import GenericAgent
class MySpeechToTextAgent(GenericAgent): source_type = "Speech" target_type = "Text" ....
.. code-block:: python
from simuleval.agents import SpeechToSpeechAgent
class MySpeechToTextAgent(SpeechToSpeechAgent): ....
.. _agent_policy:
Policy------
The agent must have a :code:`policy` method which must return one of two actions, :code:`ReadAction` and :code:`WriteAction`.For example, an agent with a :code:`policy` method should look like this
.. code-block:: python
class MySpeechToTextAgent(SpeechToSpeechAgent): def policy(self): if do_we_need_more_input(self.states): return ReadAction() else: prediction = generate_a_token(self.states) finished = is_sentence_finished(self.states) return WriteAction(prediction, finished=finished)
.. .. autoclass:: simuleval.agents.actions.WriteAction
.. .. autoclass:: simuleval.agents.actions.ReadAction
States------------Each agent has the attribute the :code:`states` to keep track of the progress of decoding.The :code:`states` attribute will be reset at the beginning of each sentence.SimulEval provide an built-in states :class:`simuleval.agents.states.AgentStates`,which has some basic attributes such source and target sequences.The users can also define customized states with :code:`Agent.build_states` method:
.. code-block:: python
from simuleval.agents.states import AgentStates from dataclasses import dataclass
@dataclass class MyComplicatedStates(AgentStates) some_very_useful_variable: int
def reset(self): super().reset() # also remember to reset the value some_very_useful_variable = 0
class MySpeechToTextAgent(SpeechToSpeechAgent): def build_states(self): return MyComplicatedStates(0)
def policy(self): some_very_useful_variable = self.states.some_very_useful_variable ... self.states.some_very_useful_variable = new_value ...
.. .. autoclass:: simuleval.agents.states.AgentStates :members:
Pipeline--------The simultaneous system can consist several different components.For instance, a simultaneous speech-to-text translation can have a streaming automatic speech recognition system and simultaneous text-to-text translation system.SimulEval introduces the agent pipeline to support this function.The following is a minimal example.We concatenate two wait-k systems with different rates (:code:`k=2` and :code:`k=3`)Note that if there are more than one agent class define,the :code:`@entrypoint` decorator has to be used to determine the entry point
.. literalinclude:: ../../examples/quick_start/agent_pipeline.py :language: python :lines: 7-
Customized Arguments-----------------------
It is often the case that we need to pass some customized arguments for the system to configure different settings.The agent class has a built-in static method :code:`add_args` for this purpose.The following is an updated version of the dummy agent from :ref:`first-agent`.
.. literalinclude:: ../../examples/quick_start/agent_with_configs.py :language: python :lines: 6-
Then just simply pass the arguments through command line as follow.
.. code-block:: bash
simuleval \ --source source.txt --source target.txt \ # data arguments --agent dummy_waitk_text_agent_v2.py \ --waitk 3 --vocab data/dict.txt # agent arguments
Load Agents from Python Class-----------------------------
If you have the agent class in the python environment, for instance
.. literalinclude:: ../../examples/quick_start/agent_with_configs.py :language: python :lines: 6-
You can also start the evaluation with following command
.. code-block:: bash
simuleval \ --source source.txt --source target.txt \ # data arguments --agent-class DummyWaitkTextAgent \ --waitk 3 --vocab data/dict.txt # agent arguments
Load Agents from Directory--------------------------
Agent can also be loaded from a directory, which will be referred to as system directory.The system directory should have everything required to start the agent. Again use the following agent as example
.. literalinclude:: ../../examples/quick_start/agent_with_configs.py :language: python :lines: 6-
and the system directory has
.. code-block:: bash
> ls ${system_dir} main.yaml dict.txt
Where the `main.yaml` has all the command line options. The path will be the relative path to the `${system_dir}`.
.. code-block:: yaml
waitk: 3 vocab: dict.txt
The agent can then be started as following
.. code-block:: bash
simuleval \ --source source.txt --source target.txt \ # data arguments --system-dir ${system_dir}
By default, the `main.yaml` will be read. You can also have multiple YAML files in the system directory and pass them through command line arguments
.. code-block:: bash > ls ${system_dir} main.yaml dict.txt v1.yaml
> simuleval \ --source source.txt --source target.txt \ # data arguments --system-dir ${system_dir} --system-config v1.yaml12345Dataloader===========There are two ways to load data.
.. autoclass:: simuleval.data.dataloader.GenericDataloader1234567891011121314151617181920212223242526272829303132333435363738394041424344Evaluator=========
The evaluation in SimulEval implemented as the Evaluator shown below.It runs on sentence level, and will score the translation on quality and latency.The user can use :code:`--quality-metrics` and :code:`--latency-metrics` to choose the metrics.The final results along with the logs will be saved at :code:`--output` if given.
.. autoclass:: simuleval.evaluator.evaluator.SentenceLevelEvaluator
Quality Scorers---------------
.. autoclass:: simuleval.evaluator.scorers.quality_scorer.SacreBLEUScorer.. autoclass:: simuleval.evaluator.scorers.quality_scorer.ASRSacreBLEUScorer
Latency Scorers---------------
.. autoclass:: simuleval.evaluator.scorers.latency_scorer.ALScorer :members:
.. autoclass:: simuleval.evaluator.scorers.latency_scorer.APScorer :members:
.. autoclass:: simuleval.evaluator.scorers.latency_scorer.DALScorer :members:
Customized Scorers------------------To add customized scorers, the user can use :code:`@register_latency_scorer` or :code:`@register_quality_scorer` to decorate a scorer class.and use :code:`--quality-metrics` and :code:`--latency-metrics` to call the scorer. For example:
.. literalinclude:: ../../examples/quick_start/agent_with_new_metrics.py :lines: 6-
.. code-block:: bash
> simuleval --source source.txt --target target.txt --agent agent_with_new_metrics.py --latency-metrics RTF 2022-12-06 12:56:01 | INFO | simuleval.cli | Evaluate system: DummyWaitkTextAgent 2022-12-06 12:56:01 | INFO | simuleval.dataloader | Evaluating from text to text. 2022-12-06 12:56:01 | INFO | simuleval.sentence_level_evaluator | Results: BLEU RTF 1.593 1.0781234567891011121314151617181920212223242526272829303132333435Introduction============Different from offline translation system, the evaluation of simultaneous translation requires incremental decoding with an streaming input.The simultaneous introduce the a front-end / back-end setup, shown as follow.
The back-end contains one or multiple user-defined agents which make decisions of whether to generate prediction at a certain point.The agent can also considered as queue, where the input are keep pushed in and policy decides the timing to pop the output.
The front-end on the other side, represent the source of input and recipient of the system prediction.In deployment, the front-end can be web page or cell phone app.In SimulEval, the front-end is the evaluator , which feeds streaming input to back-end, receive prediction and track the delays.The front-end and back-end can run separately for different purpose.
The evaluation process can summarized as follow pseudocode
.. code-block:: python
for instance in evaluator.instances: while not instance.finished: input_segment = instance.send_source() prediction = agent.pushpop(input_segment) if prediction is not None: instance.receive_prediction(prediction)
results = [scorer.score() for scorer in evaluate.scorers]
The common usage of SimulEval is as follow
.. code-block:: bash
simuleval DATALOADER_OPTIONS EVALUATOR_OPTIONS --agent $AGENT_FILE AGENT_OPTIONS
We will introduce the usage of the toolkit based on these three major components: Agent, Dataloader and Evaluator.12345678910FROM python:3.8RUN apt-get update \&& apt-get upgrade -y \&& apt-get install -y \&& apt-get -y install apt-utils gcc libpq-dev libsndfile-devRUN git clone https://github.com/facebookresearch/SimulEval.gitWORKDIR SimulEvalRUN git checkout v1.1.0RUN pip install -e .CMD ["simuleval", "--standalone", "--remote-port", "8888", "--agent", "examples/quick_start/first_agent.py.py"]123456789101112131415161718192021222324252627282930313233343536373839# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
import randomfrom simuleval.utils import entrypointfrom simuleval.agents import TextToTextAgentfrom simuleval.agents.actions import ReadAction, WriteActionfrom simuleval.agents import AgentPipeline
class DummyWaitkTextAgent(TextToTextAgent): waitk = 0 vocab = [chr(i) for i in range(ord("A"), ord("Z") + 1)]
def policy(self): lagging = len(self.states.source) - len(self.states.target)
if lagging >= self.waitk or self.states.source_finished: prediction = random.choice(self.vocab)
return WriteAction(prediction, finished=(lagging <= 1)) else: return ReadAction()
class DummyWait2TextAgent(DummyWaitkTextAgent): waitk = 2
class DummyWait4TextAgent(DummyWaitkTextAgent): waitk = 4
@entrypointclass DummyPipeline(AgentPipeline): pipeline = [DummyWait2TextAgent, DummyWait4TextAgent]123456789101112131415161718192021222324252627282930313233343536373839# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
import randomfrom simuleval.utils import entrypointfrom simuleval.agents import TextToTextAgentfrom simuleval.agents.actions import ReadAction, WriteActionfrom argparse import Namespace, ArgumentParser
@entrypointclass DummyWaitkTextAgent(TextToTextAgent): def __init__(self, args: Namespace): """Initialize your agent here. For example loading model, vocab, etc """ super().__init__(args) self.waitk = args.waitk with open(args.vocab) as f: self.vocab = [line.strip() for line in f]
@staticmethod def add_args(parser: ArgumentParser): """Add customized command line arguments""" parser.add_argument("--waitk", type=int, default=3) parser.add_argument("--vocab", type=str)
def policy(self): lagging = len(self.states.source) - len(self.states.target)
if lagging >= self.waitk or self.states.source_finished: prediction = random.choice(self.vocab)
return WriteAction(prediction, finished=(lagging <= 1)) else: return ReadAction()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
import randomfrom statistics import meanfrom simuleval.utils import entrypointfrom simuleval.evaluator.scorers.latency_scorer import ( register_latency_scorer, LatencyScorer,)from simuleval.agents import TextToTextAgentfrom simuleval.agents.actions import ReadAction, WriteAction
@register_latency_scorer("RTF")class RTFScorer(LatencyScorer): """Real time factor
Usage: --latency-metrics RTF """
def __call__(self, instances) -> float: scores = [] for ins in instances.values(): scores.append(ins.delays[-1] / ins.source_length)
return mean(scores)
@entrypointclass DummyWaitkTextAgent(TextToTextAgent): waitk = 3 vocab = [chr(i) for i in range(ord("A"), ord("Z") + 1)]
def policy(self): lagging = len(self.states.source) - len(self.states.target)
if lagging >= self.waitk or self.states.source_finished: prediction = random.choice(self.vocab)
return WriteAction(prediction, finished=(lagging <= 1)) else: return ReadAction()1234567891011121314151617181920212223242526ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567891011121314151617181920212223242526# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
import randomfrom simuleval.utils import entrypointfrom simuleval.agents import TextToTextAgentfrom simuleval.agents.actions import ReadAction, WriteAction
@entrypointclass DummyWaitkTextAgent(TextToTextAgent): waitk = 3 vocab = [chr(i) for i in range(ord("A"), ord("Z") + 1)]
def policy(self): lagging = len(self.states.source) - len(self.states.target)
if lagging >= self.waitk or self.states.source_finished: prediction = random.choice(self.vocab)
return WriteAction(prediction, finished=(lagging <= 1)) else: return ReadAction()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# Quick StartFollowing are some minimal examples to use SimulEval. More details can be found [here](https://simuleval.readthedocs.io/en/v1.1.0/quick_start.html).
## First AgentTo evaluate a text-to-text wait-3 system with random output:
```> simuleval --source source.txt --target target.txt --agent first_agent.py
2022-12-05 13:43:58 | INFO | simuleval.cli | Evaluate system: DummyWaitkTextAgent2022-12-05 13:43:58 | INFO | simuleval.dataloader | Evaluating from text to text.2022-12-05 13:43:58 | INFO | simuleval.sentence_level_evaluator | Results:BLEU AL AP DAL1.541 3.0 0.688 3.0
```
## Agent with Command Line Arguments```simuleval --source source.txt --target target.txt --agent agent_with_configs.py --waitk 3 --vocab dict.txt```
## Agent Pipeline```simuleval --source source.txt --target target.txt --agent agent_pipeline.py```
## Agent with New Metrics```simuleval --source source.txt --target target.txt --agent agent_with_new_metrics.py```
## Standalone Agent & Remote EvaluationStart an agent server:```simuleval --standalone --remote-port 8888 --agent agent_with_new_metrics.py```Or with docker```docker build -t simuleval_agent .docker run -p 8888:8888 simuleval_agent:latest```
Start a remote evaluator:```simuleval --remote-eval --source source.txt --target target.txt --source-type text --target-type text --remote-port 8888```12345678910Z U S N B Y X Q L O TM A J F P G O Y V R H M Z O T AM O W A O I D H H B O FN Q N I P C O H A AG B O J H P W C I A L VP T Z D E E N T B Y G Z R KF S H U K R W K S B R K M B B Q F C O UM H O L W Z G J Y X J B IA V B F E S F E W Q C SF N O I E Z B R S C V N S12345678910Z U S N B Y X Q L O TM A J F P G O Y V R H M Z O T AM O W A O I D H H B O FN Q N I P C O H A AG B O J H P W C I A L VP T Z D E E N T B Y G Z R KF S H U K R W K S B R K M B B Q F C O UM H O L W Z G J Y X J B IA V B F E S F E W Q C SF N O I E Z B R S C V N S123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869from simuleval.utils import entrypointfrom simuleval.data.segments import SpeechSegmentfrom simuleval.agents import SpeechToSpeechAgentfrom simuleval.agents.actions import WriteAction, ReadActionfrom fairseq.checkpoint_utils import load_model_ensemble_and_task_from_hf_hubfrom fairseq.models.text_to_speech.hub_interface import TTSHubInterface
class TTSModel: def __init__(self): models, cfg, task = load_model_ensemble_and_task_from_hf_hub( "facebook/fastspeech2-en-ljspeech", arg_overrides={"vocoder": "hifigan", "fp16": False}, ) TTSHubInterface.update_cfg_with_data_cfg(cfg, task.data_cfg) self.tts_generator = task.build_generator(models, cfg) self.tts_task = task self.tts_model = models[0] self.tts_model.to("cpu") self.tts_generator.vocoder.to("cpu")
def synthesize(self, text): sample = TTSHubInterface.get_model_input(self.tts_task, text) if sample["net_input"]["src_lengths"][0] == 0: return [], 0 for key in sample["net_input"].keys(): if sample["net_input"][key] is not None: sample["net_input"][key] = sample["net_input"][key].to("cpu")
wav, rate = TTSHubInterface.get_prediction( self.tts_task, self.tts_model, self.tts_generator, sample ) wav = wav.tolist() return wav, rate
@entrypointclass EnglishSpeechCounter(SpeechToSpeechAgent): """ Incrementally feed text to this offline Fastspeech2 TTS model, with a minimum numbers of phonemes every chunk. """
def __init__(self, args): super().__init__(args) self.wait_seconds = args.wait_seconds self.tts_model = TTSModel()
@staticmethod def add_args(parser): parser.add_argument("--wait-seconds", default=1, type=int)
def policy(self): length_in_seconds = round( len(self.states.source) / self.states.source_sample_rate ) if not self.states.source_finished and length_in_seconds < self.wait_seconds: return ReadAction() samples, fs = self.tts_model.synthesize(f"{length_in_seconds} mississippi")
# A SpeechSegment has to be returned for speech-to-speech translation system return WriteAction( SpeechSegment( content=samples, sample_rate=fs, finished=self.states.source_finished, ), finished=self.states.source_finished, )123456simuleval \ --agent english_counter_agent.py --output output \ --source source.txt --target reference/en.txt --source-segment-size 1000\ --quality-metrics WHISPER_ASR_BLEU \ --target-speech-lang en --transcript-lowercase --transcript-non-punctuation --whisper-model-size large \ --latency-metrics StartOffset EndOffset ATD123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566## Simultaneous Speech-to-Speech Translation
This tutorial provides a minimal example on how to evaluate a simultaneous speech-to-speech translation system.
### Requirements
To run this example, the following package is required
- [`whisper`](https://github.com/openai/whisper): for quality evaluation (`WHISPER_ASR_BLEU`).
### Agent
The speech-to-speech agent ([english_counter_agent.py](english_counter_agent.py)) in this example is a counter, which generates a piece of audio every second after an initial wait.The policy of the agent is show follow. The agent will wait for `self.wait_seconds` seconds,and generate the audio of `{length_in_seconds} mississippi` every second afterward.
```python def policy(self): length_in_seconds = round( len(self.states.source) / self.states.source_sample_rate ) if not self.states.source_finished and length_in_seconds < self.wait_seconds: return ReadAction() print(length_in_seconds) samples, fs = self.tts_model.synthesize(f"{length_in_seconds} mississippi")
# A SpeechSegment has to be returned for speech-to-speech translation system return WriteAction( SpeechSegment( content=samples, sample_rate=fs, finished=self.states.source_finished, ), finished=self.states.source_finished, )```
Notice that for speech output agent, the `WriteAction` has to contain a `SpeechSegment` class.
### Evaluation
The following command will start an evaluation
```bashsimuleval \ --agent english_counter_agent.py --output output \ --source source.txt --target reference/en.txt --source-segment-size 1000\ --quality-metrics WHISPER_ASR_BLEU \ --target-speech-lang en --transcript-lowercase --transcript-non-punctuation\ --latency-metrics StartOffset EndOffset ATD```
For quality evaluation, we use ASR_BLEU, that is transcribing the speech output and compute BLEU score with the reference text. To use this feature, `whisper` has to be installed.
We use three metrics for latency evaluation
- `StartOffset`: The starting offset of translation comparing with source audio- `EndOffset`: The ending offset of translation comparing with source audio- `ATD`: Average Token Delay
The results of the evaluation should be as following. The transcripts and alignments can be found in the `output` directory.
``` WHISPER_ASR_BLEU StartOffset EndOffset ATD 100.0 1000.0 1490.703 1248.261```1ein Mississippi zwei Mississippi drei Mississippi vier Mississippi fünf Mississippi sechs Mississippi sieben Mississippi1one mississippi two mississippi three mississippi four mississippi five mississippi six mississippi seven mississippi11 ミシシッピ 2 ミシシッピ 3 ミシシッピ 4 ミシシッピ 5 ミシシッピ 6 ミシシッピ 7 ミシシッピ1一密西西比二密西西比三密西西比四密西西比五密西西比六密西西比七密西西比1test.wav123version https://git-lfs.github.com/spec/v1oid sha256:354152b48e1575f4ca3590b76700d46ef302dca9c183b5526f810c636c5d88f7size 30212412[tool:pytest]flake8-max-line-length = 12712345678910111213141516171819202122232425262728293031323334353637383940414243# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
import setuptools
setuptools.setup( python_requires=">3.7.0", name="simuleval", version="1.1.0", author="Xutai Ma", entry_points={ "console_scripts": [ "simuleval = simuleval.cli:main", ], }, install_requires=[ "pytest", "pytest-cov", "sacrebleu==2.3.1", "tornado", "soundfile", "pandas", "requests", "pytest-flake8", "textgrid", "tqdm==4.64.1", "pyyaml", "bitarray==2.6.0", "yt-dlp", "pydub", ], package=setuptools.find_packages( exclude=[ "examples", "examples.*", "docs", "docs.*", ] ),)12345# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.12345678910111213141516# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
from .agent import ( # noqa GenericAgent, SpeechToTextAgent, SpeechToSpeechAgent, TextToSpeechAgent, TextToTextAgent,)from .states import AgentStates # noqafrom .actions import Action, ReadAction, WriteAction # noqafrom .pipeline import AgentPipeline # noqa123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
from typing import Union, Listfrom dataclasses import dataclassfrom simuleval.data.segments import Segment
class Action: """ Abstract Action class """
def is_read(self) -> bool: """ Whether the action is a read action
Returns: bool: True if the action is a read action. """ assert NotImplementedError
class ReadAction(Action): """ Action to return when policy decide to read one more source segment. The only way to use it is to return :code:`ReadAction()` """
def is_read(self) -> bool: return True
def __repr__(self) -> str: return "ReadAction()"
@dataclassclass WriteAction(Action): """ Action to return when policy decide to generate a prediction
Args: content (Union[str, List[float]]): The prediction. finished (bool): Indicates if current sentence is finished.
.. note:: For text the prediction a str; for speech, it's a list.
"""
content: Union[str, List[float], Segment] finished: bool
def is_read(self) -> bool: return False
def __repr__(self) -> str: return f"WriteAction({self.content}, finished={self.finished})"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
from inspect import signaturefrom argparse import Namespace, ArgumentParserfrom simuleval.data.segments import Segment, TextSegment, SpeechSegment, EmptySegmentfrom typing import Optionalfrom .states import AgentStatesfrom .actions import Action
SEGMENT_TYPE_DICT = {"text": TextSegment, "speech": SpeechSegment}
class GenericAgent: """ Generic Agent class. """
source_type = None target_type = None
def __init__(self, args: Optional[Namespace] = None) -> None: if args is not None: self.args = args assert self.source_type assert self.target_type self.device = "cpu"
self.states = self.build_states() self.reset()
def build_states(self) -> AgentStates: """ Build states instance for agent
Returns: AgentStates: agent states """ return AgentStates()
def reset(self) -> None: """ Reset agent, called every time when a new sentence coming in. """ self.states.reset()
def policy(self, states: Optional[AgentStates] = None) -> Action: """ The policy to make decision every time when the system has new input. The function has to return an Action instance
Args: states (Optional[AgentStates]): an optional states for stateless agent
Returns: Action: The actions to make at certain point.
.. note:
WriteAction means that the system has a prediction. ReadAction means that the system needs more source. When states are provided, the agent will become stateless and ignore self.states. """ assert NotImplementedError
def push( self, source_segment: Segment, states: Optional[AgentStates] = None ) -> None: """ The function to process the incoming information.
Args: source_info (dict): incoming information dictionary states (Optional[AgentStates]): an optional states for stateless agent """ if states is None: states = self.states states.update_source(source_segment)
def pop(self, states: Optional[AgentStates] = None) -> Segment: """ The function to generate system output. By default, it first runs policy, and than returns the output segment. If the policy decide to read, it will return an empty segment.
Args: states (Optional[AgentStates]): an optional states for stateless agent
Returns: Segment: segment to return. """ if len(signature(self.policy).parameters) == 0: is_stateless = False if states: raise RuntimeError("Feeding states to stateful agents.") else: is_stateless = True
if states is None: states = self.states
if states.target_finished: return EmptySegment(finished=True)
if is_stateless: action = self.policy(states) else: action = self.policy()
if not isinstance(action, Action): raise RuntimeError( f"The return value of {self.policy.__qualname__} is not an {Action.__qualname__} instance" ) if action.is_read(): return EmptySegment() else: if isinstance(action.content, Segment): return action.content
segment = SEGMENT_TYPE_DICT[self.target_type]( index=0, content=action.content, finished=action.finished ) states.update_target(segment) return segment
def pushpop( self, segment: Segment, states: Optional[AgentStates] = None ) -> Segment: """ Operate pop immediately after push.
Args: segment (Segment): input segment
Returns: Segment: output segment """ self.push(segment, states) return self.pop(states)
@staticmethod def add_args(parser: ArgumentParser): """ Add agent arguments to parser. Has to be a static method.
Args: parser (ArgumentParser): cli argument parser """ pass
@classmethod def from_args(cls, args): return cls(args)
def to(self, device: str, *args, **kwargs) -> None: """ Move agent to specified device.
Args: device (str): Device to move agent to. """ pass
def __repr__(self) -> str: return f"{self.__class__.__name__}[{self.source_type} -> {self.target_type}]"
def __str__(self) -> str: return self.__repr__()
class SpeechToTextAgent(GenericAgent): """ Same as generic agent, but with explicit types speech -> text """
source_type: str = "speech" target_type: str = "text"
class SpeechToSpeechAgent(GenericAgent): """ Same as generic agent, but with explicit types speech -> speech """
source_type: str = "speech" target_type: str = "speech"
class TextToSpeechAgent(GenericAgent): """ Same as generic agent, but with explicit types text -> speech """
source_type: str = "text" target_type: str = "speech"
class TextToTextAgent(GenericAgent): """ Same as generic agent, but with explicit types text -> text """
source_type: str = "text" target_type: str = "text"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
from typing import List, Optionalfrom simuleval.data.segments import Segmentfrom .agent import GenericAgent, AgentStates
class AgentPipeline(GenericAgent): """A pipeline of agents
Attributes: pipeline (list): a list of agent classes.
"""
pipeline: List = []
def __init__(self, module_list: List[GenericAgent]) -> None: self.module_list = module_list self.check_pipeline_types()
def check_pipeline_types(self): if len(self.pipeline) > 1: for i in range(1, len(self.pipeline)): if ( self.module_list[i].source_type != self.module_list[i - 1].target_type ): raise RuntimeError( f"{self.module_list[i]}.source_type({self.module_list[i].source_type}) != {self.pipeline[i-1]}.target_type({self.pipeline[i - 1].target_type}" # noqa F401 )
@property def source_type(self) -> Optional[str]: return self.module_list[0].source_type
@property def target_type(self) -> Optional[str]: return self.module_list[-1].target_type
def reset(self) -> None: for module in self.module_list: module.reset()
def build_states(self) -> List[AgentStates]: return [module.build_states() for module in self.module_list]
def push( self, segment: Segment, states: Optional[List[Optional[AgentStates]]] = None ) -> None: if states is None: states = [None for _ in self.module_list] else: assert len(states) == len(self.module_list)
for index, module in enumerate(self.module_list[:-1]): segment = module.pushpop(segment, states[index]) self.module_list[-1].push(segment, states[-1])
def pop(self, states: Optional[List[Optional[AgentStates]]] = None) -> Segment: if states is None: last_states = None else: assert len(states) == len(self.module_list) last_states = states[-1]
return self.module_list[-1].pop(last_states)
@classmethod def add_args(cls, parser) -> None: for module_class in cls.pipeline: module_class.add_args(parser)
@classmethod def from_args(cls, args): assert len(cls.pipeline) > 0 return cls([module_class.from_args(args) for module_class in cls.pipeline])
def __repr__(self) -> str: pipline_str = "\n\t".join( "\t".join(str(module).splitlines(True)) for module in self.module_list ) return f"{self.__class__.__name__}(\n\t{pipline_str}\n)"
def __str__(self) -> str: return self.__repr__()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.import osimport jsonimport loggingfrom tornado import web, ioloopfrom simuleval.data.segments import segment_from_json_stringfrom simuleval import options
logger = logging.getLogger("simuleval.agent_server")
class SystemHandler(web.RequestHandler): def initialize(self, system): self.system = system
def get(self): self.write(json.dumps({"info": str(self.system)}))
class ResetHandle(SystemHandler): def post(self): self.system.reset()
class OutputHandler(SystemHandler): def get(self): output_segment = self.system.pop() self.write(output_segment.json())
class InputHandler(SystemHandler): def put(self): segment = segment_from_json_string(self.request.body) self.system.push(segment)
def start_agent_service(system): parser = options.general_parser() options.add_evaluator_args(parser) args, _ = parser.parse_known_args() app = web.Application( [ (r"/reset", ResetHandle, {"system": system}), (r"/input", InputHandler, {"system": system}), (r"/output", OutputHandler, {"system": system}), (r"/", SystemHandler, {"system": system}), ], debug=False, )
app.listen(args.remote_port, max_buffer_size=1024**3)
logger.info( f"Simultaneous Translation Server Started (process id {os.getpid()}). Listening to port {args.remote_port} " ) ioloop.IOLoop.current().start().gitattributes+2
LICENSEAdded+21
README.mdAdded+379
SimulEval/.github/workflows/main.ymlAdded+46
SimulEval/.gitignoreAdded+139
SimulEval/CHANGELOG.mdAdded+10
SimulEval/CODE_OF_CONDUCT.mdAdded+45
SimulEval/CONTRIBUTING.mdAdded+20
SimulEval/LICENSEAdded+427
SimulEval/README.mdAdded+35
SimulEval/docs/MakefileAdded+20
SimulEval/docs/conf.pyAdded+40
SimulEval/docs/index.rstAdded+30
SimulEval/docs/installation.rstAdded+21
SimulEval/docs/make.batAdded+41
SimulEval/docs/quick_start.rstAdded+49
SimulEval/docs/requirements.txtAdded+2
SimulEval/docs/tutorials/remote_evaluation.rstAdded+44
SimulEval/docs/tutorials/speech_to_speech.rstAdded+2
SimulEval/docs/tutorials/speech_to_text.rstAdded+2
SimulEval/docs/user_guide/agent.rstAdded+198
SimulEval/docs/user_guide/dataloader.rstAdded+5
SimulEval/docs/user_guide/evaluator.rstAdded+44
SimulEval/docs/user_guide/introduction.rstAdded+35
SimulEval/examples/quick_start/DockerfileAdded+10
SimulEval/examples/quick_start/agent_pipeline.pyAdded+39
SimulEval/examples/quick_start/agent_with_configs.pyAdded+39
SimulEval/examples/quick_start/agent_with_new_metrics.pyAdded+47
SimulEval/examples/quick_start/dict.txtAdded+26
SimulEval/examples/quick_start/first_agent.pyAdded+26
SimulEval/examples/quick_start/readme.mdAdded+47
SimulEval/examples/quick_start/source.txtAdded+10
SimulEval/examples/quick_start/target.txtAdded+10
SimulEval/examples/speech_to_speech/english_counter_agent.pyAdded+69
SimulEval/examples/speech_to_speech/eval.shAdded+6
SimulEval/examples/speech_to_speech/readme.mdAdded+66
SimulEval/examples/speech_to_speech/reference/de.txtAdded+1
SimulEval/examples/speech_to_speech/reference/en.txtAdded+1
SimulEval/examples/speech_to_speech/reference/ja.txtAdded+1
SimulEval/examples/speech_to_speech/reference/zh.txtAdded+1
SimulEval/examples/speech_to_speech/source.txtAdded+1
SimulEval/examples/speech_to_speech/test.wavAdded+3
SimulEval/setup.cfgAdded+2
SimulEval/setup.pyAdded+43
SimulEval/simuleval/__init__.pyAdded+5
SimulEval/simuleval/agents/__init__.pyAdded+16
SimulEval/simuleval/agents/actions.pyAdded+60
SimulEval/simuleval/agents/agent.pyAdded+216
SimulEval/simuleval/agents/pipeline.pyAdded+90
SimulEval/simuleval/agents/service.pyAdded+59