[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# poetry\n#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.\n#   This is especially recommended for binary packages to ensure reproducibility, and is more\n#   commonly ignored for libraries.\n#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control\n#poetry.lock\n\n# pdm\n#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.\n#pdm.lock\n#   pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it\n#   in version control.\n#   https://pdm.fming.dev/#use-with-ide\n.pdm.toml\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n# PyCharm\n#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can\n#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore\n#  and can be added to the global gitignore or merged into this file.  For a more nuclear\n#  option (not recommended) you can uncomment the following to ignore the entire idea folder.\n#.idea/\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023 ochen1\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Insanely Fast Whisper (CLI)\n\n[![GitHub License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/ochen1/insanely-fast-whisper-cli/blob/main/LICENSE)\n[![Python Version](https://img.shields.io/badge/python-3.10-blue)](https://www.python.org/downloads/)\n\nPowered by 🤗 *Transformers* & *Optimum* and based on **[Vaibhavs10/insanely-fast-whisper](https://github.com/Vaibhavs10/insanely-fast-whisper)**.\n\n**TL;DR** - 🎙️ Transcribe **300** minutes (5 hours) of audio in less than **10** minutes - with [OpenAI's Whisper Large v2](https://huggingface.co/openai/whisper-large-v2). Blazingly fast transcription is now a reality!⚡️\n\n## Features\n\n✨ **ASR Model**: Choose from different 🤗 Hugging Face ASR models, including all sizes of [openai/whisper](https://github.com/openai/whisper) and even use an English-only variant (for non-large models).\n\n🚀 **Performance**: Customizable optimizations ASR processing with options for batch size, data type, and BetterTransformer, all from the comfort of your terminal! 😎\n\n📝 **Timestamps**: Get an SRT output file with accurate timestamps, allowing you to create subtitles for your audio or video content.\n\n## Installation\n\n- Clone git repository with `git clone https://github.com/ochen1/insanely-fast-whisper-cli`\n- Switch to that folder with `cd insanely-fast-whisper-cli/`\n- (optional) Create a new Python environment with `python -m venv venv`\n- (optional) Activate environment with `source venv/bin/activate`\n- Install packages from requirements with `pip install -r requirements.txt`\n- Run program with `python insanely-fast-whisper.py`\n\n## Usage\n\n```bash\ninsanely-fast-whisper --model openai/whisper-base --device cuda:0 --dtype float32 --batch-size 8 --better-transformer --chunk-length 30 your_audio_file.wav\n```\n\n- `model`: Specify the ASR model (default is \"openai/whisper-base\").\n- `device`: Choose the computation device (default is \"cuda:0\").\n- `dtype`: Set the data type for computation (\"float32\" or \"float16\").\n- `batch-size`: Adjust the batch size for processing (default is 8).\n- `better-transformer`: Use BetterTransformer for improved processing (flag).\n- `chunk-length`: Define audio chunk length in seconds (default is 30).\n\n## Example\n\nTranscribing an audio file with English-only Whisper model and returning timestamps:\n\n```bash\ninsanely-fast-whisper --model openai/whisper-base.en your_audio_file.wav\n```\n\n## Output\n\nThe tool will save an SRT transcription of your audio file in the current working directory.\n\n## License\n\nThis project is licensed under the [MIT License](https://github.com/ochen1/insanely-fast-whisper-cli/blob/main/LICENSE).\n\n## Acknowledgments\n\n- This tool is powered by Hugging Face's ASR models, primarily Whisper by OpenAI.\n- Optimizations are developed by [Vaibhavs10/insanely-fast-whisper](https://github.com/Vaibhavs10/insanely-fast-whisper).\n- Developed by [@ochen1](https://github.com/ochen1).\n\n## 📞 Contact\n\nHave questions or feedback? Feel free to create an issue!\n\n🌟 **Star this repository if you find it helpful!**\n\n[![Star History Chart](https://api.star-history.com/svg?repos=ochen1/insanely-fast-whisper-cli&type=Date)](https://star-history.com/#ochen1/insanely-fast-whisper-cli&Date)\n\n---\n\n[![GitHub Issues](https://img.shields.io/github/issues/ochen1/insanely-fast-whisper-cli.svg)](https://github.com/ochen1/insanely-fast-whisper-cli/issues)\n[![GitHub Pull Requests](https://img.shields.io/github/issues-pr/ochen1/insanely-fast-whisper-cli.svg)](https://github.com/ochen1/insanely-fast-whisper-cli/pulls)\n\n🚀 Happy transcribing with Insanely Fast Whisper! 🚀\n"
  },
  {
    "path": "insanely-fast-whisper.py",
    "content": "#!/usr/bin/env python3\n\nimport click\nimport os\nimport time\n\n@click.command()\n@click.option('--model', default='openai/whisper-base', help='ASR model to use for speech recognition. Default is \"openai/whisper-base\". Model sizes include base, small, medium, large, large-v2. Additionally, try appending \".en\" to model names for English-only applications (not available for large).')\n@click.option('--device', default='cuda:0', help='Device to use for computation. Default is \"cuda:0\". If you want to use CPU, specify \"cpu\".')\n@click.option('--dtype', default='float32', help='Data type for computation. Can be either \"float32\" or \"float16\". Default is \"float32\".')\n@click.option('--batch-size', type=int, default=8, help='Batch size for processing. This is the number of audio files processed at once. Default is 8.')\n@click.option('--better-transformer', is_flag=True, help='Flag to use BetterTransformer for processing. If set, BetterTransformer will be used.')\n@click.option('--chunk-length', type=int, default=30, help='Length of audio chunks to process at once, in seconds. Default is 30 seconds.')\n@click.argument('audio_file', type=str)\ndef asr_cli(model, device, dtype, batch_size, better_transformer, chunk_length, audio_file):\n    from transformers import pipeline\n    import torch\n\n    # Initialize the ASR pipeline\n    pipe = pipeline(\"automatic-speech-recognition\",\n                    model=model,\n                    device=device,\n                    torch_dtype=torch.float16 if dtype == \"float16\" else torch.float32)\n\n    if better_transformer:\n        pipe.model = pipe.model.to_bettertransformer()\n\n    # Perform ASR\n    click.echo(\"Model loaded.\")\n    start_time = time.perf_counter()\n    outputs = pipe(audio_file, chunk_length_s=chunk_length, batch_size=batch_size, return_timestamps=True)\n\n    # Output the results\n    click.echo(outputs)\n    click.echo(\"Transcription complete.\")\n    end_time = time.perf_counter()\n    elapsed_time = end_time - start_time\n    click.echo(f\"ASR took {elapsed_time:.2f} seconds.\")\n\n    # Save ASR chunks to an SRT file\n    audio_file_name = os.path.splitext(os.path.basename(audio_file))[0]\n    srt_filename = f\"{audio_file_name}.srt\"\n    with open(srt_filename, 'w', encoding=\"utf-8\") as srt_file:\n        prev = 0\n        for index, chunk in enumerate(outputs['chunks']):\n            prev, start_time = seconds_to_srt_time_format(prev, chunk['timestamp'][0])\n            prev, end_time = seconds_to_srt_time_format(prev, chunk['timestamp'][1])\n            srt_file.write(f\"{index + 1}\\n\")\n            srt_file.write(f\"{start_time} --> {end_time}\\n\")\n            srt_file.write(f\"{chunk['text'].strip()}\\n\\n\")\n\ndef seconds_to_srt_time_format(prev, seconds):\n    if not (isinstance(seconds, int) or isinstance(seconds, float)):\n        seconds = prev\n    else:\n        prev = seconds\n    hours = seconds // 3600\n    seconds %= 3600\n    minutes = seconds // 60\n    seconds %= 60\n    milliseconds = int((seconds - int(seconds)) * 1000)\n    hours = int(hours)\n    minutes = int(minutes)\n    seconds = int(seconds)\n    return (prev, f\"{hours:02d}:{minutes:02d}:{int(seconds):02d},{milliseconds:03d}\")\n\nif __name__ == '__main__':\n    asr_cli()\n"
  },
  {
    "path": "install-gfx1010.sh",
    "content": "echo \"Python <= 3.10 only!\"\nuv pip install -r requirements-gfx1010.txt --extra-index-url https://download.pytorch.org/whl/rocm5.2\necho\necho \"Example usage:\"\necho \"HSA_OVERRIDE_GFX_VERSION=10.3.0 python3 insanely-fast-whisper.py --model distil-whisper/distil-medium.en audio.mp3\"\n"
  },
  {
    "path": "requirements-gfx1010.txt",
    "content": "#accelerate\n#optimum\nclick\ntransformers\ntorch==1.13.1+rocm5.2\n"
  },
  {
    "path": "requirements.txt",
    "content": "torch\ntorchvision\ntorchaudio\ngit+https://github.com/huggingface/transformers\naccelerate\noptimum\nclick\n"
  }
]