Eric Z commited on
Commit
26d3d03
·
1 Parent(s): f007505

minor tweaks for key and readme

Browse files
Files changed (3) hide show
  1. .vscode/launch.json +2 -1
  2. README.md +31 -11
  3. stream_app.py +41 -24
.vscode/launch.json CHANGED
@@ -9,7 +9,8 @@
9
  "type": "debugpy",
10
  "request": "launch",
11
  "program": "${file}",
12
- "console": "integratedTerminal"
 
13
  }
14
  ]
15
  }
 
9
  "type": "debugpy",
10
  "request": "launch",
11
  "program": "${file}",
12
+ "console": "integratedTerminal",
13
+ "args": ["--log_file", "/Users/quinone/Documents/projects/audio-stream/prompts.log"]
14
  }
15
  ]
16
  }
README.md CHANGED
@@ -4,16 +4,41 @@ This project is a Gradio-based application that allows users to interact with an
4
 
5
  ## Table of Contents
6
 
7
- - [Prerequisites](#prerequisites)
8
  - [Usage](#usage)
9
  - [Features](#features)
10
  - [Configuration](#configuration)
11
  - [Deployment](#deployment)
12
  - [License](#license)
13
 
14
- ## Prerequisites
15
-
16
- - Python 3.7 or higher
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  - [Gradio](https://www.gradio.app/) library
18
  - [OpenAI](https://openai.com/) API key
19
  - [Whisper](https://github.com/openai/whisper) library (for speech recognition)
@@ -35,20 +60,15 @@ This project is a Gradio-based application that allows users to interact with an
35
 
36
  ## Configuration
37
 
38
- The application can be configured using command-line arguments or environment variables. The available configuration options include:
39
-
40
- - `--model`: The OpenAI model to use for language tasks.
41
- - `--temperature`: The temperature parameter for the OpenAI model.
42
- - `--max_tokens`: The maximum number of tokens to generate.
43
- - `--port`: The port number for the Gradio application.
44
 
45
  ## Deployment
46
 
47
  The application can be deployed to various platforms, such as:
48
 
49
  - **Local Machine**: Run the application on your local machine using the instructions in the [Usage](#usage) section.
50
- - **Cloud Platform**: Deploy the application to a cloud platform like AWS, Google Cloud, or Azure.
51
  - **Docker**: Package the application in a Docker container for easy deployment and scaling.
 
52
 
53
 
54
  ## License
 
4
 
5
  ## Table of Contents
6
 
7
+ - [Install](#install)
8
  - [Usage](#usage)
9
  - [Features](#features)
10
  - [Configuration](#configuration)
11
  - [Deployment](#deployment)
12
  - [License](#license)
13
 
14
+ ## Install
15
+ Installation and environment setup is currently done locally, but with a little effort, we could
16
+ make a docker image.
17
+
18
+ 1. Install miniconda or anaconda [here](https://docs.conda.io/en/latest/miniconda.html)
19
+ 2. Create a new environment with the following command:
20
+ ```bash
21
+ conda create -n audio-stream python=3.11
22
+ ```
23
+ 3. Activate the environment:
24
+ ```bash
25
+ conda activate audio-stream
26
+ ```
27
+ 4. Install the required packages:
28
+ ```bash
29
+ pip install -r requirements.txt
30
+ ```
31
+ 5. Set the required environment variables or create a `.env` file (exclude the word `export` for `.env`)
32
+ ```bash
33
+ export OPENAI_API_KEY=<your_openai_api_key>
34
+ ```
35
+ 6. Run the Gradio application:
36
+ ```bash
37
+ python app.py
38
+ ```
39
+
40
+ ### General Requirements
41
+ - Python 3.9 or higher (recommend 3.11)
42
  - [Gradio](https://www.gradio.app/) library
43
  - [OpenAI](https://openai.com/) API key
44
  - [Whisper](https://github.com/openai/whisper) library (for speech recognition)
 
60
 
61
  ## Configuration
62
 
63
+ The application can be configured using command-line arguments or environment variables. Run the main command with the option `--help` to get a full list of available options.
 
 
 
 
 
64
 
65
  ## Deployment
66
 
67
  The application can be deployed to various platforms, such as:
68
 
69
  - **Local Machine**: Run the application on your local machine using the instructions in the [Usage](#usage) section.
 
70
  - **Docker**: Package the application in a Docker container for easy deployment and scaling.
71
+ - **Cloud Platform**: Deploy the application to a cloud platform like AWS, Google Cloud, or Azure. At first blush [a deployment strategy like this one](https://vinaykachare.medium.com/serverless-api-with-aws-sam-fastapi-3f4d9510d6b6) seems like a good follow-up for automated deployment.
72
 
73
 
74
  ## License
stream_app.py CHANGED
@@ -38,14 +38,10 @@ def run_gradio(config:dict):
38
  whisper_model = whisper.load_model("base")
39
  audio = whisper.load_audio(input_audio)
40
  result = whisper_model.transcribe(audio)
41
- result["no_speech_prob"] = 0
42
- prob_scores = [x['no_speech_prob'] for x in result['segments']]
43
- if len(prob_scores) > 0: # average the probs
44
- result["no_speech_prob"] = sum(prob_scores)/len(prob_scores)
45
 
46
  elif "online" in input_audio_model.lower():
47
  with open(input_audio, 'rb') as file_audio:
48
- result = client.audio.translations.create(
49
  model="whisper-1", file=file_audio, response_format="verbose_json",
50
  )
51
  if result is None:
@@ -53,7 +49,13 @@ def run_gradio(config:dict):
53
  result = result.to_dict()
54
  prompt = result["text"]
55
  logger.warning(f"Transcription: {result}")
56
-
 
 
 
 
 
 
57
  if result["no_speech_prob"] < (1 - config['speech_threshold']): # threshold to avoid bad output
58
  return input_text + " " + prompt
59
  return input_text
@@ -82,6 +84,7 @@ def run_gradio(config:dict):
82
 
83
  partial_response = ""
84
  for stream_response in response:
 
85
  token = stream_response.choices[0].delta.content
86
  if token is None:
87
  break
@@ -95,22 +98,32 @@ def run_gradio(config:dict):
95
  """)
96
  with gr.Row():
97
  with gr.Column():
98
- input_text = gr.Textbox(
99
- label="Text Input",
100
- placeholder="Enter your prompt here",
101
- lines=5,
102
- max_lines=10,
103
- )
104
- input_audio_model = gr.Radio(
105
- label="Audio Model",
106
- choices=["whisper (offline)", "openai-whisper (online)"],
107
- value="openai-whisper (online)",
108
- )
109
- input_audio = gr.Audio(
110
- label="Speech Input",
111
- streaming=True,
112
- type="filepath",
113
- )
 
 
 
 
 
 
 
 
 
 
114
  with gr.Column():
115
  output_text = gr.Textbox(
116
  label="Output",
@@ -148,8 +161,8 @@ def parse_args() -> dict:
148
  help="Maximum number of tokens to generate in chat completion.")
149
 
150
  opt_group = parser.add_argument_group("Speech Processing")
151
- opt_group.add_argument("--speech_threshold", type=float, default=0.5,
152
- help="Speech threshold for recognition to add text to a prompt. ")
153
 
154
  opt_group = parser.add_argument_group("App Settings")
155
  opt_group.add_argument("--port", type=int, default=7860,
@@ -168,6 +181,10 @@ def parse_args() -> dict:
168
 
169
  if __name__ == "__main__":
170
  os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False'
 
 
 
 
171
 
172
  config = parse_args()
173
  run_gradio(config)
 
38
  whisper_model = whisper.load_model("base")
39
  audio = whisper.load_audio(input_audio)
40
  result = whisper_model.transcribe(audio)
 
 
 
 
41
 
42
  elif "online" in input_audio_model.lower():
43
  with open(input_audio, 'rb') as file_audio:
44
+ result = client.audio.transcriptions.create(
45
  model="whisper-1", file=file_audio, response_format="verbose_json",
46
  )
47
  if result is None:
 
49
  result = result.to_dict()
50
  prompt = result["text"]
51
  logger.warning(f"Transcription: {result}")
52
+
53
+ if "no_speech_prob" not in result: # look for probability of a good tanscription
54
+ result["no_speech_prob"] = 1.0
55
+ prob_scores = [x['no_speech_prob'] for x in result['segments']]
56
+ if len(prob_scores) > 0: # average the probs
57
+ result["no_speech_prob"] = sum(prob_scores)/len(prob_scores)
58
+
59
  if result["no_speech_prob"] < (1 - config['speech_threshold']): # threshold to avoid bad output
60
  return input_text + " " + prompt
61
  return input_text
 
84
 
85
  partial_response = ""
86
  for stream_response in response:
87
+ logger.warning(f"Prompt response: {stream_response.to_dict()}")
88
  token = stream_response.choices[0].delta.content
89
  if token is None:
90
  break
 
98
  """)
99
  with gr.Row():
100
  with gr.Column():
101
+ with gr.Group():
102
+ input_text = gr.Textbox(
103
+ label="Text Input",
104
+ placeholder="Enter your prompt here",
105
+ lines=5,
106
+ max_lines=10,
107
+ )
108
+ online_text_model = f"openai-{config['model']} (online)"
109
+ input_audio_model = gr.Radio(
110
+ label="Textual Model",
111
+ choices=[online_text_model],
112
+ value=online_text_model,
113
+ )
114
+
115
+ with gr.Group():
116
+ input_audio = gr.Audio(
117
+ label="Speech Input",
118
+ streaming=True,
119
+ type="filepath",
120
+ )
121
+ input_audio_model = gr.Radio(
122
+ label="Audio Model",
123
+ choices=["whisper (offline)", "openai-whisper (online)"],
124
+ value="openai-whisper (online)",
125
+ )
126
+
127
  with gr.Column():
128
  output_text = gr.Textbox(
129
  label="Output",
 
161
  help="Maximum number of tokens to generate in chat completion.")
162
 
163
  opt_group = parser.add_argument_group("Speech Processing")
164
+ opt_group.add_argument("--speech_threshold", type=float, default=0.10,
165
+ help="Speech threshold (probability) for recognition to add text to a prompt. ")
166
 
167
  opt_group = parser.add_argument_group("App Settings")
168
  opt_group.add_argument("--port", type=int, default=7860,
 
181
 
182
  if __name__ == "__main__":
183
  os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False'
184
+ api_key = os.environ.get("OPENAI_API_KEY")
185
+ print(api_key)
186
+ if not api_key:
187
+ raise ValueError("OPENAI_API_KEY environment variable not set as environment variable or as a setting in `.env`. (see https://platform.openai.com/docs/quickstart/step-2-set-up-your-api-key)")
188
 
189
  config = parse_args()
190
  run_gradio(config)