Spaces:
Runtime error
Runtime error
File size: 6,493 Bytes
969ab0b cee36ef 969ab0b 911caa6 8cc4893 cee36ef 969ab0b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 |
%%writefile app.py
from IPython.display import Javascript
from IPython import display
from google.colab import output
from base64 import b64decode
import datetime
import whisper
import openai
import os
import base64
from Crypto.Cipher import AES
from streamlit_bokeh_events import streamlit_bokeh_events
import streamlit as st
from bokeh.models.widgets import Button
from bokeh.models.widgets.buttons import Button
from bokeh.models import CustomJS
from streamlit_bokeh_events import streamlit_bokeh_events
RECORD = """
const sleep = time => new Promise(resolve => setTimeout(resolve, time))
const b2text = blob => new Promise(resolve => {
const reader = new FileReader()
reader.onloadend = e => resolve(e.srcElement.result)
reader.readAsDataURL(blob)
})
var record = time => new Promise(async resolve => {
stream = await navigator.mediaDevices.getUserMedia({ audio: true })
recorder = new MediaRecorder(stream)
chunks = []
recorder.ondataavailable = e => chunks.push(e.data)
recorder.start()
await sleep(time)
recorder.onstop = async ()=>{
blob = new Blob(chunks)
text = await b2text(blob)
resolve(text)
}
recorder.stop()
})
"""
openai.api_key = os.environ["API_KEY"]
with open("encrypt.txt", "r") as encfile:
encoder_txt = encfile.read()
with open("decrypt.txt", "r") as decfile:
decoder_txt = decfile.read()
def openai_fun(myprompt):
response_encoded = openai.Completion.create(
engine="text-davinci-003",
prompt = myprompt,
max_tokens=1024,
n=1,
stop=None,
temperature=0.5,
)
return response_encoded
def record(sec=5):
display.display(Javascript(RECORD))
s = output.eval_js('record(%d)' % (sec*1000))
b = b64decode(s.split(',')[1])
ts = datetime.datetime.now()
filename = ts.strftime("%Y_%m_%d_%H_%M_%S")
with open(f'{filename}.wav','wb') as f:
f.write(b)
return f'{filename}.wav' # or webm ?
model = whisper.load_model("base")
transcribed = []
while True:
user_choice = st.text_input("Do you want to record a new audio for transcription?[y/n]")
if user_choice == 'y':
st.write('Recording! (5 seconds)')
record(5)
folder_path = "/content"
audio_files = [f for f in os.listdir(folder_path) if f.endswith(".wav")]
audio_files.sort(key=lambda x: os.path.getmtime(os.path.join(folder_path, x)), reverse=True)
last_audio_file_path = os.path.join(folder_path, audio_files[0])
st.write('Transcribing audio file: ',last_audio_file_path)
# COMMENT IF NOT NEEDED:
if os.path.exists(last_audio_file_path) and not last_audio_file_path in transcribed:
audio = whisper.load_audio(last_audio_file_path)
audio = whisper.pad_or_trim(audio)
mel = whisper.log_mel_spectrogram(audio).to(model.device)
options = whisper.DecodingOptions(language= 'en', fp16=False)
result = whisper.decode(model, mel, options)
if result.no_speech_prob < 0.5:
mymsg = result.text
st.write("Actual Message: ",mymsg)
enc_prompt = encoder_txt + mymsg
openai_fun(enc_prompt)
if openai_fun(enc_prompt)['choices'][0]['text'] != "":
# print(response_encoded['choices'][0]['text'])
exec(openai_fun(enc_prompt)['choices'][0]['text'])
encoded_msg = enc(mymsg)
print("The encoded message: ", encoded_msg)
decode_ = st.text_input("Do you wish to decode the message?[y/n]")
if decode_ == "y":
dec_prompt = decoder_txt + str(encoded_msg)
response_decoded = openai.Completion.create(
engine="text-davinci-003",
prompt = dec_prompt,
max_tokens=500,
n=1,
stop=None,
temperature=0.5,
)
if response_decoded['choices'][0]['text'] != "":
print(response_decoded['choices'][0]['text'])
exec(response_decoded['choices'][0]['text'])
decoded_msg = dec(encoded_msg, key)
print("The decoded message: ", decoded_msg)
else:
st.write('Retry! The message could')
break # exit the loop
elif user_choice == 'n':
uc1 = input('Do you want to transcribe an existing audio?[y/n]')
if uc1 == 'y':
folder_path = "/content"
audio_files = [f for f in os.listdir(folder_path) if f.endswith(".wav")]
print('Audio files present: ',audio_files)
audio_files.sort(key=lambda x: os.path.getmtime(os.path.join(folder_path, x)), reverse=True)
last_audio_file_path = os.path.join(folder_path, audio_files[0])
print('Transcribing last audio file: ',last_audio_file_path)
# COMMENT IF NOT NEEDED:
if os.path.exists(last_audio_file_path) and not last_audio_file_path in transcribed:
audio = whisper.load_audio(last_audio_file_path)
audio = whisper.pad_or_trim(audio)
mel = whisper.log_mel_spectrogram(audio).to(model.device)
options = whisper.DecodingOptions(language= 'en', fp16=False)
result = whisper.decode(model, mel, options)
if result.no_speech_prob < 0.5:
mymsg = result.text
print("Actual Message: ",mymsg)
enc_prompt = encoder_txt + result.text
response_encoded = openai.Completion.create(
engine="text-davinci-003",
prompt = enc_prompt,
max_tokens=1024,
n=1,
stop=None,
temperature=0.5,
)
if response_encoded['choices'][0]['text'] != "":
# print(response_encoded['choices'][0]['text'])
exec(response_encoded['choices'][0]['text'])
encoded_msg = enc(mymsg)
st.write("The encoded message: ", encoded_msg)
else:
st.write('Retry! The message could')
# DELETE audio
break # exit the loop
elif uc1 == 'n':
continue # continue the loop, prompting for input again
else:
st.write('Invalid input, please enter y or n')
continue # continue the loop, prompting for input again
else:
st.write('Invalid input, please enter y or n')
continue # continue the loop, prompting for input again
|