From b93cd3ba4669a32b9fedc3ee4e9a2d4f3ca8a42b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Hedenstr=C3=B6m?= <erik@hedenstroem.com> Date: Tue, 18 Jun 2024 13:24:20 +0000 Subject: [PATCH] Added OpenAI Whisper STT --- .gitlab-ci.yml | 7 ++ README.md | 100 +++++--------------------- openai_stt/__init__.py | 1 + openai_stt/manifest.json | 15 ++++ openai_stt/stt.py | 148 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 187 insertions(+), 84 deletions(-) create mode 100644 .gitlab-ci.yml create mode 100644 openai_stt/__init__.py create mode 100644 openai_stt/manifest.json create mode 100644 openai_stt/stt.py diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..56c2523 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,7 @@ +deploy: + script: + - export PATH=$PATH:/opt/host/bin:/opt/host/local/bin + - rm -rf /opt/host/homeassistant/custom_components/openai_stt + - cp -Rfv openai_stt /opt/host/homeassistant/custom_components + tags: + - shell diff --git a/README.md b/README.md index 4d9547f..b102f73 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,25 @@ -# Custom Compontents +# Custom Components +## OpenAI Whisper API STT +Integration works for Assist pipelines. -## Getting started +### Requirements -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +- A working Whisper API Key (Try your key with curl or something else) -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! +### Configuration -## Add your files +- Add your own API key +- language MUST be set AND has to be ISO-639-1 format +- There will be an error in the home assistant logs, that configuring stt is not allowed in configuration.yaml - you can ignore this -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +_configuration.yaml_: +```yaml +stt: + - platform: openai_stt + api_key: "" + model: "whisper-1" + language: "en" ``` -cd existing_repo -git remote add origin https://gitlab.hedenstroem.com/home-assistant/custom-compontents.git -git branch -M main -git push -uf origin main -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://gitlab.hedenstroem.com/home-assistant/custom-compontents/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. diff --git a/openai_stt/__init__.py b/openai_stt/__init__.py new file mode 100644 index 0000000..6a10f59 --- /dev/null +++ b/openai_stt/__init__.py @@ -0,0 +1 @@ +"""Custom integration for OpenAI Whisper API STT.""" diff --git a/openai_stt/manifest.json b/openai_stt/manifest.json new file mode 100644 index 0000000..f94123d --- /dev/null +++ b/openai_stt/manifest.json @@ -0,0 +1,15 @@ +{ + "domain": "openai_stt", + "name": "OpenAI Whisper API STT", + "codeowners": [ + "@erik" + ], + "dependencies": [], + "documentation": "https://gitlab.hedenstroem.com/home-assistant/custom-components", + "iot_class": "cloud_polling", + "issue_tracker": "https://gitlab.hedenstroem.com/home-assistant/custom-components/-/issues", + "requirements": [ + "aiohttp>=3.7.4" + ], + "version": "0.1.0" +} diff --git a/openai_stt/stt.py b/openai_stt/stt.py new file mode 100644 index 0000000..6c02352 --- /dev/null +++ b/openai_stt/stt.py @@ -0,0 +1,148 @@ +""" +Support for Whisper API STT. +""" +from typing import AsyncIterable +import aiohttp +import os +import tempfile +import voluptuous as vol +from homeassistant.components.tts import CONF_LANG +from homeassistant.components.stt import ( + AudioBitRates, + AudioChannels, + AudioCodecs, + AudioFormats, + AudioSampleRates, + Provider, + SpeechMetadata, + SpeechResult, + SpeechResultState, +) +from homeassistant.core import HomeAssistant +import homeassistant.helpers.config_validation as cv +import wave +import io + + +CONF_API_KEY = 'api_key' +DEFAULT_LANG = 'en-US' +OPENAI_STT_URL = "https://api.openai.com/v1/audio/transcriptions" +CONF_MODEL = 'model' +CONF_URL = 'url' +CONF_PROMPT = 'prompt' +CONF_TEMPERATURE = 'temperature' + +PLATFORM_SCHEMA = cv.PLATFORM_SCHEMA.extend({ + vol.Required(CONF_API_KEY): cv.string, + vol.Optional(CONF_LANG, default=DEFAULT_LANG): cv.string, + vol.Optional(CONF_MODEL, default='whisper-1'): cv.string, + vol.Optional(CONF_URL, default=None): cv.string, + vol.Optional(CONF_PROMPT, default=None): cv.string, + vol.Optional(CONF_TEMPERATURE, default=0): cv.positive_int, +}) + + +async def async_get_engine(hass, config, discovery_info=None): + """Set up Whisper API STT speech component.""" + api_key = config[CONF_API_KEY] + language = config.get(CONF_LANG, DEFAULT_LANG) + model = config.get(CONF_MODEL) + url = config.get('url') + prompt = config.get('prompt') + temperature = config.get('temperature') + return OpenAISTTProvider(hass, api_key, language, model, url, prompt, temperature) + + +class OpenAISTTProvider(Provider): + """The Whisper API STT provider.""" + + def __init__(self, hass, api_key, lang, model, url, prompt, temperature): + """Initialize Whisper API STT provider.""" + self.hass = hass + self._api_key = api_key + self._language = lang + self._model = model + self._url = url + self._prompt = prompt + self._temperature = temperature + + @property + def default_language(self) -> str: + """Return the default language.""" + return self._language.split(',')[0] + + @property + def supported_languages(self) -> list[str]: + """Return the list of supported languages.""" + return self._language.split(',') + + @property + def supported_formats(self) -> list[AudioFormats]: + """Return a list of supported formats.""" + return [AudioFormats.WAV] + + @property + def supported_codecs(self) -> list[AudioCodecs]: + """Return a list of supported codecs.""" + return [AudioCodecs.PCM] + + @property + def supported_bit_rates(self) -> list[AudioBitRates]: + """Return a list of supported bitrates.""" + return [AudioBitRates.BITRATE_16] + + @property + def supported_sample_rates(self) -> list[AudioSampleRates]: + """Return a list of supported samplerates.""" + return [AudioSampleRates.SAMPLERATE_16000] + + @property + def supported_channels(self) -> list[AudioChannels]: + """Return a list of supported channels.""" + return [AudioChannels.CHANNEL_MONO] + + async def async_process_audio_stream(self, metadata: SpeechMetadata, stream: AsyncIterable[bytes]) -> SpeechResult: + data = b'' + async for chunk in stream: + data += chunk + + if not data: + return SpeechResult("", SpeechResultState.ERROR) + + try: + with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_file: + with wave.open(temp_file, 'wb') as wav_file: + wav_file.setnchannels(metadata.channel) + wav_file.setsampwidth(2) # 2 bytes per sample + wav_file.setframerate(metadata.sample_rate) + wav_file.writeframes(data) + temp_file_path = temp_file.name + + + url = self._url or OPENAI_STT_URL + + headers = { + 'Authorization': f'Bearer {self._api_key}', + } + + file_to_send = open(temp_file_path, 'rb') + form = aiohttp.FormData() + form.add_field('file', file_to_send, filename='audio.wav', content_type='audio/wav') + form.add_field('language', self._language) + form.add_field('model', self._model) + + async with aiohttp.ClientSession() as session: + async with session.post(url, data=form, headers=headers) as response: + if response.status == 200: + json_response = await response.json() + return SpeechResult(json_response["text"], SpeechResultState.SUCCESS) + else: + text = await response.text() + return SpeechResult("", SpeechResultState.ERROR) + except Exception as e: + return SpeechResult("", SpeechResultState.ERROR) + finally: + if 'file_to_send' in locals(): + file_to_send.close() + if temp_file_path: + os.remove(temp_file_path) -- GitLab