AKapich commited on
Commit
339bb90
·
1 Parent(s): 05b14c5

Initial commit

Browse files
Files changed (48) hide show
  1. app.py +301 -0
  2. audio_recorder/streamlit_audio_recorder/.DS_Store +0 -0
  3. audio_recorder/streamlit_audio_recorder/.idea/.gitignore +8 -0
  4. audio_recorder/streamlit_audio_recorder/.idea/inspectionProfiles/Project_Default.xml +10 -0
  5. audio_recorder/streamlit_audio_recorder/.idea/inspectionProfiles/profiles_settings.xml +6 -0
  6. audio_recorder/streamlit_audio_recorder/.idea/misc.xml +4 -0
  7. audio_recorder/streamlit_audio_recorder/.idea/modules.xml +8 -0
  8. audio_recorder/streamlit_audio_recorder/.idea/streamlit_audio_recorder.iml +12 -0
  9. audio_recorder/streamlit_audio_recorder/.idea/vcs.xml +6 -0
  10. audio_recorder/streamlit_audio_recorder/.streamlit/config.toml +21 -0
  11. audio_recorder/streamlit_audio_recorder/__pycache__/st_custom_components.cpython-37.pyc +0 -0
  12. audio_recorder/streamlit_audio_recorder/setup.py +23 -0
  13. audio_recorder/streamlit_audio_recorder/st_audiorec/.DS_Store +0 -0
  14. audio_recorder/streamlit_audio_recorder/st_audiorec/__init__.py +34 -0
  15. audio_recorder/streamlit_audio_recorder/st_audiorec/__pycache__/__init__.cpython-310.pyc +0 -0
  16. audio_recorder/streamlit_audio_recorder/st_audiorec/__pycache__/__init__.cpython-38.pyc +0 -0
  17. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/.DS_Store +0 -0
  18. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/.env +6 -0
  19. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/.prettierrc +5 -0
  20. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/.DS_Store +0 -0
  21. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/asset-manifest.json +22 -0
  22. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/bootstrap.min.css +0 -0
  23. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/index.html +1 -0
  24. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/precache-manifest.4829c060d313d0b0d13d9af3b0180289.js +26 -0
  25. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/service-worker.js +39 -0
  26. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/.DS_Store +0 -0
  27. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/css/2.bfbf028b.chunk.css +2 -0
  28. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/css/2.bfbf028b.chunk.css.map +1 -0
  29. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/js/2.270b84d8.chunk.js +0 -0
  30. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/js/2.270b84d8.chunk.js.LICENSE.txt +58 -0
  31. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/js/2.270b84d8.chunk.js.map +0 -0
  32. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/js/main.833ba252.chunk.js +2 -0
  33. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/js/main.833ba252.chunk.js.map +1 -0
  34. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/js/runtime-main.11ec9aca.js +2 -0
  35. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/js/runtime-main.11ec9aca.js.map +1 -0
  36. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/styles.css +60 -0
  37. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/package-lock.json +0 -0
  38. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/package.json +44 -0
  39. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/public/.DS_Store +0 -0
  40. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/public/bootstrap.min.css +0 -0
  41. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/public/index.html +21 -0
  42. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/public/styles.css +59 -0
  43. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/src/StreamlitAudioRecorder.tsx +168 -0
  44. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/src/index.tsx +10 -0
  45. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/src/react-app-env.d.ts +2 -0
  46. audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/tsconfig.json +21 -0
  47. requirements.txt +9 -0
  48. translator.db +0 -0
app.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from audio_recorder.streamlit_audio_recorder.st_audiorec import st_audiorec
3
+ from transformers import pipeline
4
+ import torch
5
+ from gtts import gTTS
6
+ from pydub import AudioSegment
7
+ from pydub.playback import play
8
+ from io import BytesIO
9
+ import streamlit as st
10
+ import datetime as dt
11
+ import streamlit_toggle as tog
12
+
13
+ import streamlit_authenticator as stauth
14
+ import sqlite3
15
+ from pathlib import Path
16
+
17
+ global FILE_PATH
18
+ FILE_PATH = Path(__file__).parent / "translator.db"
19
+
20
+ class DatabaseConnection:
21
+ def __init__(self, database):
22
+ self.connection = None
23
+ self.database = database
24
+
25
+ def __enter__(self):
26
+ self.connection = sqlite3.connect(self.database)
27
+ return self.connection
28
+
29
+ def __exit__(self, exc_type, exc_val, exc_tb):
30
+ if exc_type or exc_val or exc_tb:
31
+ pass
32
+ else:
33
+ self.connection.commit()
34
+
35
+ self.connection.close()
36
+
37
+
38
+ ##### FUNKCJE LOGOWANIA/REJESTRACJI #####
39
+ def log_in(credentials):
40
+ global LOGGED_IN, USERNAME
41
+ authenticator = stauth.Authenticate(credentials, 'translator_cookie', 'translator_signature_key', cookie_expiry_days=7)
42
+ name, auth_status, username = authenticator.login("Login", "main")
43
+ username = username.capitalize()
44
+
45
+ if auth_status:
46
+ st.success(f"Zalogowany jako {username}")
47
+ st.sidebar.write(f"Zalogowany jako **{username}**")
48
+ authenticator.logout("Wyloguj", "sidebar")
49
+ USERNAME, LOGGED_IN = username, True
50
+ else:
51
+ if username!='':
52
+ st.error(f"Nieprawidłowe hasło dla użytkownika {username}")
53
+ USERNAME, LOGGED_IN = username, False
54
+
55
+
56
+ def register(usernames):
57
+ with st.form("Rejestracja"):
58
+ st.write("<p style='font-size: 28px;'>Rejestracja</p>", unsafe_allow_html=True)
59
+ username = st.text_input("Nazwa użytkownika")
60
+ password = st.text_input("Hasło", type="password")
61
+ password2 = st.text_input("Powtórz hasło", type="password")
62
+ register = st.form_submit_button("Zarejestruj się") # Change the button text here
63
+ if register:
64
+ if password != password2:
65
+ st.error("Podane hasła różnią się od siebie")
66
+ st.stop()
67
+ elif username in usernames:
68
+ st.error("Nazwa użytkownika jest już zajęta")
69
+ st.stop()
70
+ else:
71
+ with DatabaseConnection(FILE_PATH) as conn:
72
+ cursor = conn.cursor()
73
+ hashed_password = stauth.Hasher(passwords=[password]).generate()[0]
74
+ cursor.execute(f"INSERT INTO Users (username, hashed_password) VALUES (?, ?)", (username, hashed_password,))
75
+ st.success(f"Rejestracja jako {username} udana. Teraz proszę się zalogować.")
76
+
77
+
78
+ def enter(action):
79
+ with DatabaseConnection(FILE_PATH) as conn:
80
+ cursor = conn.cursor()
81
+ cursor.execute("SELECT * FROM Users")
82
+ user_data = cursor.fetchall()
83
+ usernames = [row[0] for row in user_data]
84
+ passwords = [row[1] for row in user_data]
85
+
86
+ credentials = {"usernames":{}}
87
+ for un, name, pw in zip(usernames, usernames, passwords):
88
+ user_dict = {"name":name,"password":pw}
89
+ credentials["usernames"].update({un:user_dict})
90
+
91
+ if action == "Register":
92
+ register(usernames)
93
+ elif action == "Login":
94
+ log_in(credentials)
95
+
96
+
97
+ ##### ZAPISYWANIE HISTORII #####
98
+ def display_row(h):
99
+ col1, col2 = st.columns([0.8, 0.2])
100
+ with col1:
101
+ st.write(f"{h[0]}")
102
+ with col2:
103
+ st.write(f"{h[4]} → {h[5]}")
104
+ st.success(f"{h[2]} ➡️ {h[3]}")
105
+ st.write("---")
106
+
107
+
108
+ def view_history(username):
109
+ st.header("Historia tłumaczeń")
110
+ st.markdown("---")
111
+ with DatabaseConnection(FILE_PATH) as conn:
112
+ cursor = conn.cursor()
113
+ cursor.execute(f"SELECT * FROM History WHERE username='{username}' ORDER BY ROWID DESC")
114
+ history = cursor.fetchall()
115
+ if len(history)==0:
116
+ st.warning("Brak historii tłumaczeń")
117
+ st.stop()
118
+ for h in history[:3]:
119
+ display_row(h)
120
+ if len(history)>3:
121
+ toggle = tog.st_toggle_switch("Pokaż więcej", active_color="#173928", track_color='#265f42', key="toggle_switch")
122
+ if toggle:
123
+ for h in history[3:]:
124
+ display_row(h)
125
+
126
+ def save_history(username, transcription, translation, og_lang, output_lang, date):
127
+ with DatabaseConnection(FILE_PATH) as conn:
128
+ cursor = conn.cursor()
129
+ # weryfikacja, czy pojawiło się nowe tłumaczenie
130
+ cursor.execute(f"SELECT transcription, translation FROM History WHERE username='{username}' ORDER BY ROWID DESC LIMIT 1")
131
+ last_row = cursor.fetchone()
132
+ if last_row==None or last_row[0]+last_row[1]!=transcription+translation:
133
+ cursor.execute(f"INSERT INTO History (date, username, transcription, translation, og_lang, output_lang) VALUES (?, ?, ?, ?, ?, ?)",
134
+ (date, username, transcription, translation, og_lang, output_lang,))
135
+
136
+
137
+ ##### FUNKCJE TŁUMACZENIA #####
138
+ @st.cache_resource(show_spinner=False)
139
+ def load_model():
140
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
141
+ return pipeline("automatic-speech-recognition", model="openai/whisper-large", device=device)
142
+ pipe = load_model()
143
+
144
+
145
+ @st.cache_data(show_spinner=False)
146
+ def transcribe(audio, lang='pl'):
147
+ outputs = pipe(audio, max_new_tokens=256, generate_kwargs={"task": "transcribe", "language": f"{lang}"})
148
+ return outputs["text"]
149
+
150
+
151
+ @st.cache_data(show_spinner=False)
152
+ def text2speech(text, language):
153
+ tts = gTTS(text, lang=language)
154
+ audio_stream = BytesIO()
155
+ tts.write_to_fp(audio_stream)
156
+ audio_stream.seek(0)
157
+ return AudioSegment.from_mp3(audio_stream)
158
+
159
+
160
+ st.markdown('''<style>.css-1egvi7u {margin-top: -3rem;}</style>''',
161
+ unsafe_allow_html=True)
162
+ st.markdown('''<style>.stAudio {height: 45px;}</style>''',
163
+ unsafe_allow_html=True)
164
+ st.markdown('''<style>.css-v37k9u a {color: #ff4c4b;}</style>''',
165
+ unsafe_allow_html=True)
166
+ st.markdown('''<style>.css-nlntq9 a {color: #ff4c4b;}</style>''',
167
+ unsafe_allow_html=True)
168
+
169
+ langdict = language_abbreviations = {
170
+ "Afrikaans": "af",
171
+ "Arabski": "ar",
172
+ "Armeński": "hy",
173
+ "Azerski": "az",
174
+ "Białoruski": "be",
175
+ "Bośniacki": "bs",
176
+ "Bułgarski": "bg",
177
+ "Kataloński": "ca",
178
+ "Chiński": "zh",
179
+ "Chorwacki": "hr",
180
+ "Czeski": "cs",
181
+ "Duński": "da",
182
+ "Holenderski": "nl",
183
+ "Angielski": "en",
184
+ "Estoński": "et",
185
+ "Fiński": "fi",
186
+ "Francuski": "fr",
187
+ "Galicyjski": "gl",
188
+ "Niemiecki": "de",
189
+ "Grecki": "el",
190
+ "Hebrajski": "he",
191
+ "Hindi": "hi",
192
+ "Węgierski": "hu",
193
+ "Islandzki": "is",
194
+ "Indonezyjski": "id",
195
+ "Włoski": "it",
196
+ "Japoński": "ja",
197
+ "Kazachski": "kk",
198
+ "Koreański": "ko",
199
+ "Łotewski": "lv",
200
+ "Litewski": "lt",
201
+ "Macedoński": "mk",
202
+ "Malajski": "ms",
203
+ "Marathi": "mr",
204
+ "Maori": "mi",
205
+ "Nepalski": "ne",
206
+ "Norweski": "no",
207
+ "Perski": "fa",
208
+ "Polski": "pl",
209
+ "Portugalski": "pt",
210
+ "Rumuński": "ro",
211
+ "Rosyjski": "ru",
212
+ "Serbski": "sr",
213
+ "Słowacki": "sk",
214
+ "Słoweński": "sl",
215
+ "Hiszpański": "es",
216
+ "Suahili": "sw",
217
+ "Szwedzki": "sv",
218
+ "Tagalog": "tl",
219
+ "Tamilski": "ta",
220
+ "Tajski": "th",
221
+ "Turecki": "tr",
222
+ "Ukraiński": "uk",
223
+ "Urdu": "ur",
224
+ "Wietnamski": "vi",
225
+ "Walijski": "cy",
226
+ }
227
+
228
+
229
+ def main():
230
+ st.title('Tłumacz')
231
+ option = st.selectbox("Wybierz formę wgrania danych: ", ['Mikrofon', 'Gotowy plik audio [.wav]'], 0)
232
+ st.markdown("---")
233
+
234
+ st.markdown('''<style>body {padding: 10px;} .stAudio {height: 45px;} .css-1egvi7u {margin-top: -3rem;} .css-v37k9u a {color: #ff4c4b;}</style>''',
235
+ unsafe_allow_html=True)
236
+
237
+
238
+ with st.sidebar:
239
+ st.write('---')
240
+ st.title("Ustawienia językowe")
241
+ og_lang = st.selectbox("Wybierz język wejściowy: ", langdict.keys(), 38)
242
+ output_lang = st.selectbox("Wybierz język wyjściowy:", langdict.keys(), 13)
243
+ st.markdown("---")
244
+ st.write("Tłumacz stworzony przez:")
245
+ st.write("[Aleks Kapich](https://github.com/AKapich)")
246
+ st.write("[Tymoteusz Kwieciński](https://github.com/Fersoil)")
247
+ st.write("[Michał Matejczuk](https://github.com/matejczukm)")
248
+
249
+
250
+ if option =='Mikrofon':
251
+ wav_audio_data = st_audiorec()
252
+ col_info, col_space = st.columns([0.57, 0.43])
253
+ with col_info:
254
+ st.write('\n')
255
+ else:
256
+ wav_audio_data = st.file_uploader("Wybierz plik audio", type=["wav"])
257
+ if wav_audio_data is not None:
258
+ wav_audio_data = wav_audio_data.read()
259
+
260
+
261
+ st.markdown("---")
262
+ if wav_audio_data is not None:
263
+ st.write('**Oryginalny tekst:**')
264
+ with st.spinner("Transkrybowanie tekstu..."):
265
+ transcription = transcribe(wav_audio_data, lang=langdict[og_lang])
266
+ st.write(transcription, unsafe_allow_html=True)
267
+ try:
268
+ st.write(f'**Tłumaczenie na {output_lang.lower()}:**')
269
+ with st.spinner("Tłumaczenie tekstu..."):
270
+ translation = transcribe(wav_audio_data, lang=langdict[output_lang])
271
+ st.write(translation, unsafe_allow_html=True)
272
+ save_history(USERNAME, transcription, translation, og_lang, output_lang, dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
273
+ sound = text2speech(translation, langdict[output_lang])
274
+ if st.button('🔊'):
275
+ play(sound)
276
+ except AssertionError:
277
+ st.error('Nie udało się przetłumaczyć tekstu. Spróbuj ponownie.')
278
+
279
+
280
+
281
+ if __name__ == '__main__':
282
+ global LOGGED_IN
283
+ global USERNAME
284
+ LOGGED_IN = False
285
+ USERNAME = None
286
+ tab1, tab2, tab3, tab4 = st.tabs(["🔑 Login", "✍🏻 Rejestracja", "🔊 Tłumacz", "📄 Historia"])
287
+
288
+ with tab1:
289
+ enter(action="Login")
290
+ with tab2:
291
+ enter(action="Register")
292
+ with tab3:
293
+ if LOGGED_IN:
294
+ main()
295
+ else:
296
+ st.warning("Proszę zalogować się, aby użyć tłumacza")
297
+ with tab4:
298
+ if LOGGED_IN:
299
+ view_history(USERNAME)
300
+ else:
301
+ st.warning("Proszę zalogować si��, aby mieć dostęp do historii")
audio_recorder/streamlit_audio_recorder/.DS_Store ADDED
Binary file (8.2 kB). View file
 
audio_recorder/streamlit_audio_recorder/.idea/.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Editor-based HTTP Client requests
5
+ /httpRequests/
6
+ # Datasource local storage ignored files
7
+ /dataSources/
8
+ /dataSources.local.xml
audio_recorder/streamlit_audio_recorder/.idea/inspectionProfiles/Project_Default.xml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <component name="InspectionProjectProfileManager">
2
+ <profile version="1.0">
3
+ <option name="myName" value="Project Default" />
4
+ <inspection_tool class="DuplicatedCode" enabled="true" level="WEAK WARNING" enabled_by_default="true">
5
+ <Languages>
6
+ <language minSize="88" name="Python" />
7
+ </Languages>
8
+ </inspection_tool>
9
+ </profile>
10
+ </component>
audio_recorder/streamlit_audio_recorder/.idea/inspectionProfiles/profiles_settings.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <component name="InspectionProjectProfileManager">
2
+ <settings>
3
+ <option name="USE_PROJECT_PROFILE" value="false" />
4
+ <version value="1.0" />
5
+ </settings>
6
+ </component>
audio_recorder/streamlit_audio_recorder/.idea/misc.xml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7 (ml_data)" project-jdk-type="Python SDK" />
4
+ </project>
audio_recorder/streamlit_audio_recorder/.idea/modules.xml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/streamlit_audio_recorder.iml" filepath="$PROJECT_DIR$/.idea/streamlit_audio_recorder.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
audio_recorder/streamlit_audio_recorder/.idea/streamlit_audio_recorder.iml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="PYTHON_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$" />
5
+ <orderEntry type="jdk" jdkName="Python 3.7 (ml_data)" jdkType="Python SDK" />
6
+ <orderEntry type="sourceFolder" forTests="false" />
7
+ </component>
8
+ <component name="PyDocumentationSettings">
9
+ <option name="format" value="PLAIN" />
10
+ <option name="myDocStringFormat" value="Plain" />
11
+ </component>
12
+ </module>
audio_recorder/streamlit_audio_recorder/.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="$PROJECT_DIR$" vcs="Git" />
5
+ </component>
6
+ </project>
audio_recorder/streamlit_audio_recorder/.streamlit/config.toml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [theme]
2
+
3
+ # The preset Streamlit theme that your custom theme inherits from.
4
+ # One of "light" or "dark".
5
+ base = "light"
6
+
7
+ # Used to style primary interface elements. It's the color displayed most
8
+ # frequently across your app's widgets (slider, checkbox, buttons)
9
+ primaryColor = "#ff4c4b" # standard red
10
+
11
+ # Background color for the main container.
12
+ # backgroundColor = "rgba(254,248,239,1)"
13
+
14
+ # Used as the background for most widgets (sidebar, text input etc.)
15
+ # secondaryBackgroundColor = "#ebd2b9"
16
+
17
+ # Font color for the page.
18
+ # textColor = "#6e7074"
19
+
20
+ # Font family for the page. (One of "serif", "sans serif" or "mono")
21
+ # font = "sans serif"
audio_recorder/streamlit_audio_recorder/__pycache__/st_custom_components.cpython-37.pyc ADDED
Binary file (1.09 kB). View file
 
audio_recorder/streamlit_audio_recorder/setup.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import setuptools
3
+
4
+ this_directory = Path(__file__).parent
5
+ long_description = (this_directory / "README.md").read_text()
6
+
7
+ setuptools.setup(
8
+ name="streamlit-audiorec",
9
+ version="0.1.3",
10
+ author="Stefan Rummer",
11
+ author_email="",
12
+ description="Record audio from the user's microphone in apps that are deployed to the web. (via Browser Media-API) [GitHub ☆ 160+: steamlit-audio-recorder]",
13
+ long_description=long_description,
14
+ long_description_content_type="text/markdown",
15
+ url="https://github.com/stefanrmmr/streamlit-audio-recorder",
16
+ packages=setuptools.find_packages(),
17
+ include_package_data=True,
18
+ classifiers=[],
19
+ python_requires=">=3.7",
20
+ install_requires=[
21
+ "streamlit>=0.63",
22
+ ],
23
+ )
audio_recorder/streamlit_audio_recorder/st_audiorec/.DS_Store ADDED
Binary file (6.15 kB). View file
 
audio_recorder/streamlit_audio_recorder/st_audiorec/__init__.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import streamlit as st
4
+ from io import BytesIO
5
+ import streamlit.components.v1 as components
6
+
7
+
8
+ def st_audiorec():
9
+
10
+ # get parent directory relative to current directory
11
+ parent_dir = os.path.dirname(os.path.abspath(__file__))
12
+ # Custom REACT-based component for recording client audio in browser
13
+ build_dir = os.path.join(parent_dir, "frontend/build")
14
+ # specify directory and initialize st_audiorec object functionality
15
+ st_audiorec = components.declare_component("st_audiorec", path=build_dir)
16
+
17
+ # Create an instance of the component: STREAMLIT AUDIO RECORDER
18
+ raw_audio_data = st_audiorec() # raw_audio_data: stores all the data returned from the streamlit frontend
19
+ wav_bytes = None # wav_bytes: contains the recorded audio in .WAV format after conversion
20
+
21
+ # the frontend returns raw audio data in the form of arraybuffer
22
+ # (this arraybuffer is derived from web-media API WAV-blob data)
23
+
24
+ if isinstance(raw_audio_data, dict): # retrieve audio data
25
+ with st.spinner('retrieving audio-recording...'):
26
+ ind, raw_audio_data = zip(*raw_audio_data['arr'].items())
27
+ ind = np.array(ind, dtype=int) # convert to np array
28
+ raw_audio_data = np.array(raw_audio_data) # convert to np array
29
+ sorted_ints = raw_audio_data[ind]
30
+ stream = BytesIO(b"".join([int(v).to_bytes(1, "big") for v in sorted_ints]))
31
+ # wav_bytes contains audio data in byte format, ready to be processed further
32
+ wav_bytes = stream.read()
33
+
34
+ return wav_bytes
audio_recorder/streamlit_audio_recorder/st_audiorec/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.17 kB). View file
 
audio_recorder/streamlit_audio_recorder/st_audiorec/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (1.15 kB). View file
 
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/.DS_Store ADDED
Binary file (8.2 kB). View file
 
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/.env ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Run the component's dev server on :3001
2
+ # (The Streamlit dev server already runs on :3000)
3
+ PORT=3001
4
+
5
+ # Don't automatically open the web browser on `npm run start`.
6
+ BROWSER=none
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/.prettierrc ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "endOfLine": "lf",
3
+ "semi": false,
4
+ "trailingComma": "es5"
5
+ }
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/.DS_Store ADDED
Binary file (6.15 kB). View file
 
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/asset-manifest.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "files": {
3
+ "main.js": "./static/js/main.833ba252.chunk.js",
4
+ "main.js.map": "./static/js/main.833ba252.chunk.js.map",
5
+ "runtime-main.js": "./static/js/runtime-main.11ec9aca.js",
6
+ "runtime-main.js.map": "./static/js/runtime-main.11ec9aca.js.map",
7
+ "static/css/2.bfbf028b.chunk.css": "./static/css/2.bfbf028b.chunk.css",
8
+ "static/js/2.270b84d8.chunk.js": "./static/js/2.270b84d8.chunk.js",
9
+ "static/js/2.270b84d8.chunk.js.map": "./static/js/2.270b84d8.chunk.js.map",
10
+ "index.html": "./index.html",
11
+ "precache-manifest.4829c060d313d0b0d13d9af3b0180289.js": "./precache-manifest.4829c060d313d0b0d13d9af3b0180289.js",
12
+ "service-worker.js": "./service-worker.js",
13
+ "static/css/2.bfbf028b.chunk.css.map": "./static/css/2.bfbf028b.chunk.css.map",
14
+ "static/js/2.270b84d8.chunk.js.LICENSE.txt": "./static/js/2.270b84d8.chunk.js.LICENSE.txt"
15
+ },
16
+ "entrypoints": [
17
+ "static/js/runtime-main.11ec9aca.js",
18
+ "static/css/2.bfbf028b.chunk.css",
19
+ "static/js/2.270b84d8.chunk.js",
20
+ "static/js/main.833ba252.chunk.js"
21
+ ]
22
+ }
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/bootstrap.min.css ADDED
The diff for this file is too large to render. See raw diff
 
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/index.html ADDED
@@ -0,0 +1 @@
 
 
1
+ <!doctype html><html lang="en"><head><title>Streamlit Audio Recorder Component</title><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Streamlit Audio Recorder Component"/><link rel="stylesheet" href="bootstrap.min.css"/><link rel="stylesheet" href="./styles.css"/><link href="./static/css/2.bfbf028b.chunk.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script>!function(e){function t(t){for(var n,l,a=t[0],p=t[1],i=t[2],c=0,s=[];c<a.length;c++)l=a[c],Object.prototype.hasOwnProperty.call(o,l)&&o[l]&&s.push(o[l][0]),o[l]=0;for(n in p)Object.prototype.hasOwnProperty.call(p,n)&&(e[n]=p[n]);for(f&&f(t);s.length;)s.shift()();return u.push.apply(u,i||[]),r()}function r(){for(var e,t=0;t<u.length;t++){for(var r=u[t],n=!0,a=1;a<r.length;a++){var p=r[a];0!==o[p]&&(n=!1)}n&&(u.splice(t--,1),e=l(l.s=r[0]))}return e}var n={},o={1:0},u=[];function l(t){if(n[t])return n[t].exports;var r=n[t]={i:t,l:!1,exports:{}};return e[t].call(r.exports,r,r.exports,l),r.l=!0,r.exports}l.m=e,l.c=n,l.d=function(e,t,r){l.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},l.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},l.t=function(e,t){if(1&t&&(e=l(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(l.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)l.d(r,n,function(t){return e[t]}.bind(null,n));return r},l.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return l.d(t,"a",t),t},l.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},l.p="./";var a=this.webpackJsonpstreamlit_component_template=this.webpackJsonpstreamlit_component_template||[],p=a.push.bind(a);a.push=t,a=a.slice();for(var i=0;i<a.length;i++)t(a[i]);var f=p;r()}([])</script><script src="./static/js/2.270b84d8.chunk.js"></script><script src="./static/js/main.833ba252.chunk.js"></script></body></html>
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/precache-manifest.4829c060d313d0b0d13d9af3b0180289.js ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ self.__precacheManifest = (self.__precacheManifest || []).concat([
2
+ {
3
+ "revision": "de27ef444ab2ed520b64cb0c988a478a",
4
+ "url": "./index.html"
5
+ },
6
+ {
7
+ "revision": "1a47c80c81698454dced",
8
+ "url": "./static/css/2.bfbf028b.chunk.css"
9
+ },
10
+ {
11
+ "revision": "1a47c80c81698454dced",
12
+ "url": "./static/js/2.270b84d8.chunk.js"
13
+ },
14
+ {
15
+ "revision": "3fc7fb5bfeeec1534560a2c962e360a7",
16
+ "url": "./static/js/2.270b84d8.chunk.js.LICENSE.txt"
17
+ },
18
+ {
19
+ "revision": "3478f4c246f37a2cbb97",
20
+ "url": "./static/js/main.833ba252.chunk.js"
21
+ },
22
+ {
23
+ "revision": "7c26bca7e16783d14d15",
24
+ "url": "./static/js/runtime-main.11ec9aca.js"
25
+ }
26
+ ]);
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/service-worker.js ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Welcome to your Workbox-powered service worker!
3
+ *
4
+ * You'll need to register this file in your web app and you should
5
+ * disable HTTP caching for this file too.
6
+ * See https://goo.gl/nhQhGp
7
+ *
8
+ * The rest of the code is auto-generated. Please don't update this file
9
+ * directly; instead, make changes to your Workbox build configuration
10
+ * and re-run your build process.
11
+ * See https://goo.gl/2aRDsh
12
+ */
13
+
14
+ importScripts("https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");
15
+
16
+ importScripts(
17
+ "./precache-manifest.4829c060d313d0b0d13d9af3b0180289.js"
18
+ );
19
+
20
+ self.addEventListener('message', (event) => {
21
+ if (event.data && event.data.type === 'SKIP_WAITING') {
22
+ self.skipWaiting();
23
+ }
24
+ });
25
+
26
+ workbox.core.clientsClaim();
27
+
28
+ /**
29
+ * The workboxSW.precacheAndRoute() method efficiently caches and responds to
30
+ * requests for URLs in the manifest.
31
+ * See https://goo.gl/S9QRab
32
+ */
33
+ self.__precacheManifest = [].concat(self.__precacheManifest || []);
34
+ workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
35
+
36
+ workbox.routing.registerNavigationRoute(workbox.precaching.getCacheKeyForURL("./index.html"), {
37
+
38
+ blacklist: [/^\/_/,/\/[^/?]+\.[^/]+$/],
39
+ });
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/.DS_Store ADDED
Binary file (6.15 kB). View file
 
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/css/2.bfbf028b.chunk.css ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ._3ybTi{margin:2em;padding:.5em;border:2px solid #000;font-size:2em;text-align:center}
2
+ /*# sourceMappingURL=2.bfbf028b.chunk.css.map */
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/css/2.bfbf028b.chunk.css.map ADDED
@@ -0,0 +1 @@
 
 
1
+ {"version":3,"sources":["index.css"],"names":[],"mappings":"AAEA,QACE,UAAW,CACX,YAAc,CACd,qBAAsB,CACtB,aAAc,CACd,iBACF","file":"2.bfbf028b.chunk.css","sourcesContent":["/* add css module styles here (optional) */\n\n._3ybTi {\n margin: 2em;\n padding: 0.5em;\n border: 2px solid #000;\n font-size: 2em;\n text-align: center;\n}\n"]}
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/js/2.270b84d8.chunk.js ADDED
The diff for this file is too large to render. See raw diff
 
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/js/2.270b84d8.chunk.js.LICENSE.txt ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ object-assign
3
+ (c) Sindre Sorhus
4
+ @license MIT
5
+ */
6
+
7
+ /**
8
+ * @license
9
+ * Copyright 2018-2021 Streamlit Inc.
10
+ *
11
+ * Licensed under the Apache License, Version 2.0 (the "License");
12
+ * you may not use this file except in compliance with the License.
13
+ * You may obtain a copy of the License at
14
+ *
15
+ * http://www.apache.org/licenses/LICENSE-2.0
16
+ *
17
+ * Unless required by applicable law or agreed to in writing, software
18
+ * distributed under the License is distributed on an "AS IS" BASIS,
19
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ * See the License for the specific language governing permissions and
21
+ * limitations under the License.
22
+ */
23
+
24
+ /** @license React v0.19.1
25
+ * scheduler.production.min.js
26
+ *
27
+ * Copyright (c) Facebook, Inc. and its affiliates.
28
+ *
29
+ * This source code is licensed under the MIT license found in the
30
+ * LICENSE file in the root directory of this source tree.
31
+ */
32
+
33
+ /** @license React v16.13.1
34
+ * react-is.production.min.js
35
+ *
36
+ * Copyright (c) Facebook, Inc. and its affiliates.
37
+ *
38
+ * This source code is licensed under the MIT license found in the
39
+ * LICENSE file in the root directory of this source tree.
40
+ */
41
+
42
+ /** @license React v16.14.0
43
+ * react-dom.production.min.js
44
+ *
45
+ * Copyright (c) Facebook, Inc. and its affiliates.
46
+ *
47
+ * This source code is licensed under the MIT license found in the
48
+ * LICENSE file in the root directory of this source tree.
49
+ */
50
+
51
+ /** @license React v16.14.0
52
+ * react.production.min.js
53
+ *
54
+ * Copyright (c) Facebook, Inc. and its affiliates.
55
+ *
56
+ * This source code is licensed under the MIT license found in the
57
+ * LICENSE file in the root directory of this source tree.
58
+ */
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/js/2.270b84d8.chunk.js.map ADDED
The diff for this file is too large to render. See raw diff
 
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/js/main.833ba252.chunk.js ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ (this.webpackJsonpstreamlit_component_template=this.webpackJsonpstreamlit_component_template||[]).push([[0],{17:function(t,e,a){t.exports=a(28)},28:function(t,e,a){"use strict";a.r(e);var n=a(6),o=a.n(n),r=a(15),c=a.n(r),i=a(0),l=a(1),s=a(2),u=a(3),d=a(8),p=a(11),m=(a(27),function(t){Object(s.a)(a,t);var e=Object(u.a)(a);function a(){var t;Object(l.a)(this,a);for(var n=arguments.length,r=new Array(n),c=0;c<n;c++)r[c]=arguments[c];return(t=e.call.apply(e,[this].concat(r))).state={isFocused:!1,recordState:null,audioDataURL:"",reset:!1},t.render=function(){var e=t.props.theme,a={},n=t.state.recordState;if(e){var r="1px solid ".concat(t.state.isFocused?e.primaryColor:"gray");a.border=r,a.outline=r}return o.a.createElement("span",null,o.a.createElement("div",null,o.a.createElement("button",{id:"record",onClick:t.onClick_start},"Rozpocznij nagrywanie"),o.a.createElement("button",{id:"stop",onClick:t.onClick_stop},"Zatrzymaj nagrywanie"),o.a.createElement("button",{id:"reset",onClick:t.onClick_reset},"Zresetuj"),o.a.createElement("button",{id:"continue",onClick:t.onClick_continue},"Pobierz nagranie"),o.a.createElement(p.b,{state:n,onStop:t.onStop_audio,type:"audio/wav",backgroundColor:"rgb(14, 17, 23)",foregroundColor:"rgb(255,76,75)",canvasWidth:700,canvasHeight:100}),o.a.createElement("audio",{id:"audio",controls:!0,src:t.state.audioDataURL})))},t.onClick_start=function(){t.setState({reset:!1,audioDataURL:"",recordState:p.a.START}),d.a.setComponentValue("")},t.onClick_stop=function(){t.setState({reset:!1,recordState:p.a.STOP})},t.onClick_reset=function(){t.setState({reset:!0,audioDataURL:"",recordState:p.a.STOP}),d.a.setComponentValue("")},t.onClick_continue=function(){if(""!==t.state.audioDataURL){var e=(new Date).toLocaleString(),a="streamlit_audio_"+(e=(e=(e=e.replace(" ","")).replace(/_/g,"")).replace(",",""))+".wav",n=document.createElement("a");n.style.display="none",n.href=t.state.audioDataURL,n.download=a,document.body.appendChild(n),n.click()}},t.onStop_audio=function(e){!0===t.state.reset?(t.setState({audioDataURL:""}),d.a.setComponentValue("")):(t.setState({audioDataURL:e.url}),fetch(e.url).then((function(t){return t.blob()})).then((function(t){return new Response(t).arrayBuffer()})).then((function(t){d.a.setComponentValue({arr:new Uint8Array(t)})})))},t}return Object(i.a)(a)}(d.b)),f=Object(d.c)(m);d.a.setComponentReady(),d.a.setFrameHeight(),c.a.render(o.a.createElement(o.a.StrictMode,null,o.a.createElement(f,null)),document.getElementById("root"))}},[[17,1,2]]]);
2
+ //# sourceMappingURL=main.833ba252.chunk.js.map
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/js/main.833ba252.chunk.js.map ADDED
@@ -0,0 +1 @@
 
 
1
+ {"version":3,"sources":["StreamlitAudioRecorder.tsx","index.tsx"],"names":["StAudioRec","state","isFocused","recordState","audioDataURL","reset","render","theme","props","style","borderStyling","primaryColor","border","outline","id","onClick","onClick_start","onClick_stop","onClick_reset","onClick_continue","onStop","onStop_audio","type","backgroundColor","foregroundColor","canvasWidth","canvasHeight","controls","src","setState","RecordState","START","Streamlit","setComponentValue","STOP","datetime","Date","toLocaleString","filename","replace","a","document","createElement","display","href","download","body","appendChild","click","data","url","fetch","then","ctx","blob","Response","arrayBuffer","buffer","Uint8Array","StreamlitComponentBase","withStreamlitConnection","setComponentReady","setFrameHeight","ReactDOM","StrictMode","getElementById"],"mappings":"wQAiBMA,G,kNACGC,MAAQ,CAAEC,WAAW,EAAOC,YAAa,KAAMC,aAAc,GAAIC,OAAO,G,EAExEC,OAAS,WAMd,IAAQC,EAAU,EAAKC,MAAfD,MACFE,EAA6B,GAE3BN,EAAgB,EAAKF,MAArBE,YAGR,GAAII,EAAO,CAGT,IAAMG,EAAa,oBACjB,EAAKT,MAAMC,UAAYK,EAAMI,aAAe,QAC9CF,EAAMG,OAASF,EACfD,EAAMI,QAAUH,EAGlB,OACE,8BACE,6BACE,4BAAQI,GAAG,SAASC,QAAS,EAAKC,eAAlC,mBAGA,4BAAQF,GAAG,OAAOC,QAAS,EAAKE,cAAhC,QAGA,4BAAQH,GAAG,QAAQC,QAAS,EAAKG,eAAjC,SAIA,4BAAQJ,GAAG,WAAWC,QAAS,EAAKI,kBAApC,YAIA,kBAAC,IAAD,CACElB,MAAOE,EACPiB,OAAQ,EAAKC,aACbC,KAAK,YACLC,gBAAgB,qBAChBC,gBAAgB,iBAChBC,YAAa,IACbC,aAAc,MAGhB,2BACEZ,GAAG,QACHa,UAAQ,EACRC,IAAK,EAAK3B,MAAMG,kB,EASlBY,cAAgB,WACtB,EAAKa,SAAS,CACZxB,OAAO,EACPD,aAAc,GACdD,YAAa2B,IAAYC,QAE3BC,IAAUC,kBAAkB,K,EAGtBhB,aAAe,WACrB,EAAKY,SAAS,CACZxB,OAAO,EACPF,YAAa2B,IAAYI,Q,EAIrBhB,cAAgB,WACtB,EAAKW,SAAS,CACZxB,OAAO,EACPD,aAAc,GACdD,YAAa2B,IAAYI,OAE3BF,IAAUC,kBAAkB,K,EAGtBd,iBAAmB,WACzB,GAAgC,KAA5B,EAAKlB,MAAMG,aACf,CAEE,IAAI+B,GAAW,IAAIC,MAAOC,iBAItBC,EAAW,oBADfH,GADAA,GADAA,EAAWA,EAASI,QAAQ,IAAK,KACbA,QAAQ,KAAM,KACdA,QAAQ,IAAK,KACc,OAGzCC,EAAIC,SAASC,cAAc,KACjCF,EAAE/B,MAAMkC,QAAU,OAClBH,EAAEI,KAAO,EAAK3C,MAAMG,aACpBoC,EAAEK,SAAWP,EACbG,SAASK,KAAKC,YAAYP,GAC1BA,EAAEQ,U,EAIE3B,aAAe,SAAC4B,IACG,IAArB,EAAKhD,MAAMI,OAEb,EAAKwB,SAAS,CACZzB,aAAc,KAEhB4B,IAAUC,kBAAkB,MAE5B,EAAKJ,SAAS,CACZzB,aAAc6C,EAAKC,MAGrBC,MAAMF,EAAKC,KAAKE,MAAK,SAASC,GAC5B,OAAOA,EAAIC,UACVF,MAAK,SAASE,GAGf,OAAQ,IAAIC,SAASD,GAAOE,iBAC3BJ,MAAK,SAASK,GACfzB,IAAUC,kBAAkB,CAC1B,IAAO,IAAIyB,WAAWD,U,yBAhIPE,MA8IVC,cAAwB5D,GAIvCgC,IAAU6B,oBAIV7B,IAAU8B,iBCnKVC,IAASzD,OACP,kBAAC,IAAM0D,WAAP,KACE,kBAAC,EAAD,OAEFvB,SAASwB,eAAe,W","file":"static/js/main.833ba252.chunk.js","sourcesContent":["import {\n Streamlit,\n StreamlitComponentBase,\n withStreamlitConnection,\n} from \"streamlit-component-lib\"\nimport React, { ReactNode } from \"react\"\n\nimport AudioReactRecorder, { RecordState } from 'audio-react-recorder'\nimport 'audio-react-recorder/dist/index.css'\n\ninterface State {\n isFocused: boolean\n recordState: null\n audioDataURL: string\n reset: boolean\n}\n\nclass StAudioRec extends StreamlitComponentBase<State> {\n public state = { isFocused: false, recordState: null, audioDataURL: '', reset: false}\n\n public render = (): ReactNode => {\n // Arguments that are passed to the plugin in Python are accessible\n\n // Streamlit sends us a theme object via props that we can use to ensure\n // that our component has visuals that match the active theme in a\n // streamlit app.\n const { theme } = this.props\n const style: React.CSSProperties = {}\n\n const { recordState } = this.state\n\n // compatibility with older vers of Streamlit that don't send theme object.\n if (theme) {\n // Use the theme object to style our button border. Alternatively, the\n // theme style is defined in CSS vars.\n const borderStyling = `1px solid ${\n this.state.isFocused ? theme.primaryColor : \"gray\"}`\n style.border = borderStyling\n style.outline = borderStyling\n }\n\n return (\n <span>\n <div>\n <button id='record' onClick={this.onClick_start}>\n Start Recording\n </button>\n <button id='stop' onClick={this.onClick_stop}>\n Stop\n </button>\n <button id='reset' onClick={this.onClick_reset}>\n Reset\n </button>\n\n <button id='continue' onClick={this.onClick_continue}>\n Download\n </button>\n\n <AudioReactRecorder\n state={recordState}\n onStop={this.onStop_audio}\n type='audio/wav'\n backgroundColor='rgb(255, 255, 255)'\n foregroundColor='rgb(255,76,75)'\n canvasWidth={450}\n canvasHeight={100}\n />\n\n <audio\n id='audio'\n controls\n src={this.state.audioDataURL}\n />\n\n </div>\n </span>\n )\n }\n\n\n private onClick_start = () => {\n this.setState({\n reset: false,\n audioDataURL: '',\n recordState: RecordState.START\n })\n Streamlit.setComponentValue('')\n }\n\n private onClick_stop = () => {\n this.setState({\n reset: false,\n recordState: RecordState.STOP\n })\n }\n\n private onClick_reset = () => {\n this.setState({\n reset: true,\n audioDataURL: '',\n recordState: RecordState.STOP\n })\n Streamlit.setComponentValue('')\n }\n\n private onClick_continue = () => {\n if (this.state.audioDataURL !== '')\n {\n // get datetime string for filename\n let datetime = new Date().toLocaleString();\n datetime = datetime.replace(' ', '');\n datetime = datetime.replace(/_/g, '');\n datetime = datetime.replace(',', '');\n var filename = 'streamlit_audio_' + datetime + '.wav';\n\n // auromatically trigger download\n const a = document.createElement('a');\n a.style.display = 'none';\n a.href = this.state.audioDataURL;\n a.download = filename;\n document.body.appendChild(a);\n a.click();\n }\n }\n\n private onStop_audio = (data) => {\n if (this.state.reset === true)\n {\n this.setState({\n audioDataURL: ''\n })\n Streamlit.setComponentValue('')\n }else{\n this.setState({\n audioDataURL: data.url\n })\n\n fetch(data.url).then(function(ctx){\n return ctx.blob()\n }).then(function(blob){\n // converting blob to arrayBuffer, this process step needs to be be improved\n // this operation's time complexity scales exponentially with audio length\n return (new Response(blob)).arrayBuffer()\n }).then(function(buffer){\n Streamlit.setComponentValue({\n \"arr\": new Uint8Array(buffer)\n })\n })\n\n }\n\n\n }\n}\n\n// \"withStreamlitConnection\" is a wrapper function. It bootstraps the\n// connection between your component and the Streamlit app, and handles\n// passing arguments from Python -> Component.\n// You don't need to edit withStreamlitConnection (but you're welcome to!).\nexport default withStreamlitConnection(StAudioRec)\n\n// Tell Streamlit we're ready to start receiving data. We won't get our\n// first RENDER_EVENT until we call this function.\nStreamlit.setComponentReady()\n\n// Finally, tell Streamlit to update our initial height. We omit the\n// `height` parameter here to have it default to our scrollHeight.\nStreamlit.setFrameHeight()\n","import React from \"react\"\nimport ReactDOM from \"react-dom\"\nimport StAudioRec from \"./StreamlitAudioRecorder\"\n\nReactDOM.render(\n <React.StrictMode>\n <StAudioRec />\n </React.StrictMode>,\n document.getElementById(\"root\")\n)\n"],"sourceRoot":""}
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/js/runtime-main.11ec9aca.js ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ !function(e){function t(t){for(var n,l,a=t[0],p=t[1],i=t[2],c=0,s=[];c<a.length;c++)l=a[c],Object.prototype.hasOwnProperty.call(o,l)&&o[l]&&s.push(o[l][0]),o[l]=0;for(n in p)Object.prototype.hasOwnProperty.call(p,n)&&(e[n]=p[n]);for(f&&f(t);s.length;)s.shift()();return u.push.apply(u,i||[]),r()}function r(){for(var e,t=0;t<u.length;t++){for(var r=u[t],n=!0,a=1;a<r.length;a++){var p=r[a];0!==o[p]&&(n=!1)}n&&(u.splice(t--,1),e=l(l.s=r[0]))}return e}var n={},o={1:0},u=[];function l(t){if(n[t])return n[t].exports;var r=n[t]={i:t,l:!1,exports:{}};return e[t].call(r.exports,r,r.exports,l),r.l=!0,r.exports}l.m=e,l.c=n,l.d=function(e,t,r){l.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},l.r=function(e){"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},l.t=function(e,t){if(1&t&&(e=l(e)),8&t)return e;if(4&t&&"object"===typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(l.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)l.d(r,n,function(t){return e[t]}.bind(null,n));return r},l.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return l.d(t,"a",t),t},l.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},l.p="./";var a=this.webpackJsonpstreamlit_component_template=this.webpackJsonpstreamlit_component_template||[],p=a.push.bind(a);a.push=t,a=a.slice();for(var i=0;i<a.length;i++)t(a[i]);var f=p;r()}([]);
2
+ //# sourceMappingURL=runtime-main.11ec9aca.js.map
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/static/js/runtime-main.11ec9aca.js.map ADDED
@@ -0,0 +1 @@
 
 
1
+ {"version":3,"sources":["../webpack/bootstrap"],"names":["webpackJsonpCallback","data","moduleId","chunkId","chunkIds","moreModules","executeModules","i","resolves","length","Object","prototype","hasOwnProperty","call","installedChunks","push","modules","parentJsonpFunction","shift","deferredModules","apply","checkDeferredModules","result","deferredModule","fulfilled","j","depId","splice","__webpack_require__","s","installedModules","1","exports","module","l","m","c","d","name","getter","o","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","p","jsonpArray","this","oldJsonpFunction","slice"],"mappings":"aACE,SAASA,EAAqBC,GAQ7B,IAPA,IAMIC,EAAUC,EANVC,EAAWH,EAAK,GAChBI,EAAcJ,EAAK,GACnBK,EAAiBL,EAAK,GAIHM,EAAI,EAAGC,EAAW,GACpCD,EAAIH,EAASK,OAAQF,IACzBJ,EAAUC,EAASG,GAChBG,OAAOC,UAAUC,eAAeC,KAAKC,EAAiBX,IAAYW,EAAgBX,IACpFK,EAASO,KAAKD,EAAgBX,GAAS,IAExCW,EAAgBX,GAAW,EAE5B,IAAID,KAAYG,EACZK,OAAOC,UAAUC,eAAeC,KAAKR,EAAaH,KACpDc,EAAQd,GAAYG,EAAYH,IAKlC,IAFGe,GAAqBA,EAAoBhB,GAEtCO,EAASC,QACdD,EAASU,OAATV,GAOD,OAHAW,EAAgBJ,KAAKK,MAAMD,EAAiBb,GAAkB,IAGvDe,IAER,SAASA,IAER,IADA,IAAIC,EACIf,EAAI,EAAGA,EAAIY,EAAgBV,OAAQF,IAAK,CAG/C,IAFA,IAAIgB,EAAiBJ,EAAgBZ,GACjCiB,GAAY,EACRC,EAAI,EAAGA,EAAIF,EAAed,OAAQgB,IAAK,CAC9C,IAAIC,EAAQH,EAAeE,GACG,IAA3BX,EAAgBY,KAAcF,GAAY,GAE3CA,IACFL,EAAgBQ,OAAOpB,IAAK,GAC5Be,EAASM,EAAoBA,EAAoBC,EAAIN,EAAe,KAItE,OAAOD,EAIR,IAAIQ,EAAmB,GAKnBhB,EAAkB,CACrBiB,EAAG,GAGAZ,EAAkB,GAGtB,SAASS,EAAoB1B,GAG5B,GAAG4B,EAAiB5B,GACnB,OAAO4B,EAAiB5B,GAAU8B,QAGnC,IAAIC,EAASH,EAAiB5B,GAAY,CACzCK,EAAGL,EACHgC,GAAG,EACHF,QAAS,IAUV,OANAhB,EAAQd,GAAUW,KAAKoB,EAAOD,QAASC,EAAQA,EAAOD,QAASJ,GAG/DK,EAAOC,GAAI,EAGJD,EAAOD,QAKfJ,EAAoBO,EAAInB,EAGxBY,EAAoBQ,EAAIN,EAGxBF,EAAoBS,EAAI,SAASL,EAASM,EAAMC,GAC3CX,EAAoBY,EAAER,EAASM,IAClC5B,OAAO+B,eAAeT,EAASM,EAAM,CAAEI,YAAY,EAAMC,IAAKJ,KAKhEX,EAAoBgB,EAAI,SAASZ,GACX,qBAAXa,QAA0BA,OAAOC,aAC1CpC,OAAO+B,eAAeT,EAASa,OAAOC,YAAa,CAAEC,MAAO,WAE7DrC,OAAO+B,eAAeT,EAAS,aAAc,CAAEe,OAAO,KAQvDnB,EAAoBoB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQnB,EAAoBmB,IAC/B,EAAPE,EAAU,OAAOF,EACpB,GAAW,EAAPE,GAA8B,kBAAVF,GAAsBA,GAASA,EAAMG,WAAY,OAAOH,EAChF,IAAII,EAAKzC,OAAO0C,OAAO,MAGvB,GAFAxB,EAAoBgB,EAAEO,GACtBzC,OAAO+B,eAAeU,EAAI,UAAW,CAAET,YAAY,EAAMK,MAAOA,IACtD,EAAPE,GAA4B,iBAATF,EAAmB,IAAI,IAAIM,KAAON,EAAOnB,EAAoBS,EAAEc,EAAIE,EAAK,SAASA,GAAO,OAAON,EAAMM,IAAQC,KAAK,KAAMD,IAC9I,OAAOF,GAIRvB,EAAoB2B,EAAI,SAAStB,GAChC,IAAIM,EAASN,GAAUA,EAAOiB,WAC7B,WAAwB,OAAOjB,EAAgB,SAC/C,WAA8B,OAAOA,GAEtC,OADAL,EAAoBS,EAAEE,EAAQ,IAAKA,GAC5BA,GAIRX,EAAoBY,EAAI,SAASgB,EAAQC,GAAY,OAAO/C,OAAOC,UAAUC,eAAeC,KAAK2C,EAAQC,IAGzG7B,EAAoB8B,EAAI,KAExB,IAAIC,EAAaC,KAA+C,yCAAIA,KAA+C,0CAAK,GACpHC,EAAmBF,EAAW5C,KAAKuC,KAAKK,GAC5CA,EAAW5C,KAAOf,EAClB2D,EAAaA,EAAWG,QACxB,IAAI,IAAIvD,EAAI,EAAGA,EAAIoD,EAAWlD,OAAQF,IAAKP,EAAqB2D,EAAWpD,IAC3E,IAAIU,EAAsB4C,EAI1BxC,I","file":"static/js/runtime-main.11ec9aca.js","sourcesContent":[" \t// install a JSONP callback for chunk loading\n \tfunction webpackJsonpCallback(data) {\n \t\tvar chunkIds = data[0];\n \t\tvar moreModules = data[1];\n \t\tvar executeModules = data[2];\n\n \t\t// add \"moreModules\" to the modules object,\n \t\t// then flag all \"chunkIds\" as loaded and fire callback\n \t\tvar moduleId, chunkId, i = 0, resolves = [];\n \t\tfor(;i < chunkIds.length; i++) {\n \t\t\tchunkId = chunkIds[i];\n \t\t\tif(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {\n \t\t\t\tresolves.push(installedChunks[chunkId][0]);\n \t\t\t}\n \t\t\tinstalledChunks[chunkId] = 0;\n \t\t}\n \t\tfor(moduleId in moreModules) {\n \t\t\tif(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {\n \t\t\t\tmodules[moduleId] = moreModules[moduleId];\n \t\t\t}\n \t\t}\n \t\tif(parentJsonpFunction) parentJsonpFunction(data);\n\n \t\twhile(resolves.length) {\n \t\t\tresolves.shift()();\n \t\t}\n\n \t\t// add entry modules from loaded chunk to deferred list\n \t\tdeferredModules.push.apply(deferredModules, executeModules || []);\n\n \t\t// run deferred modules when all chunks ready\n \t\treturn checkDeferredModules();\n \t};\n \tfunction checkDeferredModules() {\n \t\tvar result;\n \t\tfor(var i = 0; i < deferredModules.length; i++) {\n \t\t\tvar deferredModule = deferredModules[i];\n \t\t\tvar fulfilled = true;\n \t\t\tfor(var j = 1; j < deferredModule.length; j++) {\n \t\t\t\tvar depId = deferredModule[j];\n \t\t\t\tif(installedChunks[depId] !== 0) fulfilled = false;\n \t\t\t}\n \t\t\tif(fulfilled) {\n \t\t\t\tdeferredModules.splice(i--, 1);\n \t\t\t\tresult = __webpack_require__(__webpack_require__.s = deferredModule[0]);\n \t\t\t}\n \t\t}\n\n \t\treturn result;\n \t}\n\n \t// The module cache\n \tvar installedModules = {};\n\n \t// object to store loaded and loading chunks\n \t// undefined = chunk not loaded, null = chunk preloaded/prefetched\n \t// Promise = chunk loading, 0 = chunk loaded\n \tvar installedChunks = {\n \t\t1: 0\n \t};\n\n \tvar deferredModules = [];\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"./\";\n\n \tvar jsonpArray = this[\"webpackJsonpstreamlit_component_template\"] = this[\"webpackJsonpstreamlit_component_template\"] || [];\n \tvar oldJsonpFunction = jsonpArray.push.bind(jsonpArray);\n \tjsonpArray.push = webpackJsonpCallback;\n \tjsonpArray = jsonpArray.slice();\n \tfor(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);\n \tvar parentJsonpFunction = oldJsonpFunction;\n\n\n \t// run deferred modules from other chunks\n \tcheckDeferredModules();\n"],"sourceRoot":""}
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/build/styles.css ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *{
2
+ margin: 0;
3
+ padding: 0;
4
+ }
5
+
6
+ .container{
7
+ margin: 0 auto;
8
+ text-align: center;
9
+ }
10
+
11
+ .display{
12
+ width: 100%;
13
+ padding: 5px 0;
14
+ margin: 15px 0;
15
+ }
16
+
17
+
18
+ .controllers{
19
+ width: 100%;
20
+ padding: 5px 0;
21
+ margin-top: 15px;
22
+ margin-bottom: 35px;
23
+ }
24
+
25
+ button{
26
+ padding-top: 0.25rem;
27
+ padding-bottom: 0.25rem;
28
+ padding-right: 0.75rem;
29
+ padding-left: 0.75rem;
30
+ margin-right: 0.5rem;
31
+ margin-left: 0.1rem;
32
+ font-size: 16px;
33
+ background-color: #262730;
34
+ color: #fafafa;
35
+ border: 1px solid rgba(49, 51, 63, 0.2);
36
+ border-radius: 0.25rem;
37
+ margin-top: 0.75rem;
38
+ margin-bottom: 0.25rem;
39
+ }
40
+
41
+ button:hover{
42
+ padding-top: 0.25rem;
43
+ padding-bottom: 0.25rem;
44
+ padding-right: 0.75rem;
45
+ padding-left: 0.75rem;
46
+ margin-right: 0.5rem;
47
+ margin-left: 0.1rem;
48
+ font-size: 16px;
49
+ background-color: #262730;
50
+ color: #ff4c4b;
51
+ border: 1px solid #ff4c4b;
52
+ border-radius: 0.25rem;
53
+ margin-top: 0.75rem;
54
+ margin-bottom: 0.25rem;
55
+ }
56
+
57
+ audio {
58
+ width: 700px;
59
+ height: 45px;
60
+ }
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/package.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "streamlit_component_template",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "dependencies": {
6
+ "@types/jest": "^24.0.0",
7
+ "@types/node": "^12.0.0",
8
+ "@types/react": "^16.9.0",
9
+ "@types/react-dom": "^16.9.0",
10
+ "audio-react-recorder": "^1.0.4",
11
+ "axios": "^0.27.2",
12
+ "normalize.css": "^8.0.1",
13
+ "react": "^16.13.1",
14
+ "react-dom": "^16.13.1",
15
+ "react-media-recorder": "^1.6.4",
16
+ "react-scripts": "3.4.1",
17
+ "streamlit-component-lib": "^1.4.0",
18
+ "turbodepot-node": "^7.0.1",
19
+ "typescript": "~3.8.0",
20
+ "use-media-recorder": "^2.0.4"
21
+ },
22
+ "scripts": {
23
+ "start": "react-scripts start",
24
+ "build": "react-scripts build",
25
+ "test": "react-scripts test",
26
+ "eject": "react-scripts eject"
27
+ },
28
+ "eslintConfig": {
29
+ "extends": "react-app"
30
+ },
31
+ "browserslist": {
32
+ "production": [
33
+ ">0.2%",
34
+ "not dead",
35
+ "not op_mini all"
36
+ ],
37
+ "development": [
38
+ "last 1 chrome version",
39
+ "last 1 firefox version",
40
+ "last 1 safari version"
41
+ ]
42
+ },
43
+ "homepage": "."
44
+ }
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/public/.DS_Store ADDED
Binary file (6.15 kB). View file
 
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/public/bootstrap.min.css ADDED
The diff for this file is too large to render. See raw diff
 
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/public/index.html ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <title>Streamlit Audio Recorder Component</title>
5
+ <meta charset="UTF-8" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
7
+ <meta name="theme-color" content="#000000" />
8
+ <meta name="description" content="Streamlit Audio Recorder Component" />
9
+ <link rel="stylesheet" href="bootstrap.min.css" />
10
+ <link rel="stylesheet" href="./styles.css"/>
11
+ </head>
12
+ <body>
13
+ <noscript>You need to enable JavaScript to run this app.</noscript>
14
+ <!-- div for root element as generated by the react render function -->
15
+ <div id="root"></div>
16
+ <!--
17
+ To begin the development, run `npm start` or `yarn start`.
18
+ To create a production bundle, use `npm run build` or `yarn build`.
19
+ -->
20
+ </body>
21
+ </html>
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/public/styles.css ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *{
2
+ margin: 0;
3
+ padding: 0;
4
+ }
5
+
6
+ .container{
7
+ margin: 0 auto;
8
+ text-align: center;
9
+ }
10
+
11
+ .display{
12
+ width: 100%;
13
+ padding: 5px 0;
14
+ margin: 15px 0;
15
+ }
16
+
17
+ .controllers{
18
+ width: 100%;
19
+ padding: 5px 0;
20
+ margin-top: 15px;
21
+ margin-bottom: 35px;
22
+ }
23
+
24
+ button{
25
+ padding-top: 0.25rem;
26
+ padding-bottom: 0.25rem;
27
+ padding-right: 0.75rem;
28
+ padding-left: 0.75rem;
29
+ margin-right: 0.5rem;
30
+ margin-left: 0.1rem;
31
+ font-size: 16px;
32
+ background-color: #ffffff;
33
+ color: #000000;
34
+ border: 1px solid rgba(49, 51, 63, 0.2);
35
+ border-radius: 0.25rem;
36
+ margin-top: 0.75rem;
37
+ margin-bottom: 0.25rem;
38
+ }
39
+
40
+ button:hover{
41
+ padding-top: 0.25rem;
42
+ padding-bottom: 0.25rem;
43
+ padding-right: 0.75rem;
44
+ padding-left: 0.75rem;
45
+ margin-right: 0.5rem;
46
+ margin-left: 0.1rem;
47
+ font-size: 16px;
48
+ background-color: #ffffff;
49
+ color: #ff4c4b;
50
+ border: 1px solid #ff4c4b;
51
+ border-radius: 0.25rem;
52
+ margin-top: 0.75rem;
53
+ margin-bottom: 0.25rem;
54
+ }
55
+
56
+ audio {
57
+ width: 450px;
58
+ height: 45px;
59
+ }
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/src/StreamlitAudioRecorder.tsx ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ Streamlit,
3
+ StreamlitComponentBase,
4
+ withStreamlitConnection,
5
+ } from "streamlit-component-lib"
6
+ import React, { ReactNode } from "react"
7
+
8
+ import AudioReactRecorder, { RecordState } from 'audio-react-recorder'
9
+ import 'audio-react-recorder/dist/index.css'
10
+
11
+ interface State {
12
+ isFocused: boolean
13
+ recordState: null
14
+ audioDataURL: string
15
+ reset: boolean
16
+ }
17
+
18
+ class StAudioRec extends StreamlitComponentBase<State> {
19
+ public state = { isFocused: false, recordState: null, audioDataURL: '', reset: false}
20
+
21
+ public render = (): ReactNode => {
22
+ // Arguments that are passed to the plugin in Python are accessible
23
+
24
+ // Streamlit sends us a theme object via props that we can use to ensure
25
+ // that our component has visuals that match the active theme in a
26
+ // streamlit app.
27
+ const { theme } = this.props
28
+ const style: React.CSSProperties = {}
29
+
30
+ const { recordState } = this.state
31
+
32
+ // compatibility with older vers of Streamlit that don't send theme object.
33
+ if (theme) {
34
+ // Use the theme object to style our button border. Alternatively, the
35
+ // theme style is defined in CSS vars.
36
+ const borderStyling = `1px solid ${
37
+ this.state.isFocused ? theme.primaryColor : "gray"}`
38
+ style.border = borderStyling
39
+ style.outline = borderStyling
40
+ }
41
+
42
+ return (
43
+ <span>
44
+ <div>
45
+ <button id='record' onClick={this.onClick_start}>
46
+ Start Recording
47
+ </button>
48
+ <button id='stop' onClick={this.onClick_stop}>
49
+ Stop
50
+ </button>
51
+ <button id='reset' onClick={this.onClick_reset}>
52
+ Reset
53
+ </button>
54
+
55
+ <button id='continue' onClick={this.onClick_continue}>
56
+ Download
57
+ </button>
58
+
59
+ <AudioReactRecorder
60
+ state={recordState}
61
+ onStop={this.onStop_audio}
62
+ type='audio/wav'
63
+ backgroundColor='rgb(255, 255, 255)'
64
+ foregroundColor='rgb(255,76,75)'
65
+ canvasWidth={450}
66
+ canvasHeight={100}
67
+ />
68
+
69
+ <audio
70
+ id='audio'
71
+ controls
72
+ src={this.state.audioDataURL}
73
+ />
74
+
75
+ </div>
76
+ </span>
77
+ )
78
+ }
79
+
80
+
81
+ private onClick_start = () => {
82
+ this.setState({
83
+ reset: false,
84
+ audioDataURL: '',
85
+ recordState: RecordState.START
86
+ })
87
+ Streamlit.setComponentValue('')
88
+ }
89
+
90
+ private onClick_stop = () => {
91
+ this.setState({
92
+ reset: false,
93
+ recordState: RecordState.STOP
94
+ })
95
+ }
96
+
97
+ private onClick_reset = () => {
98
+ this.setState({
99
+ reset: true,
100
+ audioDataURL: '',
101
+ recordState: RecordState.STOP
102
+ })
103
+ Streamlit.setComponentValue('')
104
+ }
105
+
106
+ private onClick_continue = () => {
107
+ if (this.state.audioDataURL !== '')
108
+ {
109
+ // get datetime string for filename
110
+ let datetime = new Date().toLocaleString();
111
+ datetime = datetime.replace(' ', '');
112
+ datetime = datetime.replace(/_/g, '');
113
+ datetime = datetime.replace(',', '');
114
+ var filename = 'streamlit_audio_' + datetime + '.wav';
115
+
116
+ // auromatically trigger download
117
+ const a = document.createElement('a');
118
+ a.style.display = 'none';
119
+ a.href = this.state.audioDataURL;
120
+ a.download = filename;
121
+ document.body.appendChild(a);
122
+ a.click();
123
+ }
124
+ }
125
+
126
+ private onStop_audio = (data) => {
127
+ if (this.state.reset === true)
128
+ {
129
+ this.setState({
130
+ audioDataURL: ''
131
+ })
132
+ Streamlit.setComponentValue('')
133
+ }else{
134
+ this.setState({
135
+ audioDataURL: data.url
136
+ })
137
+
138
+ fetch(data.url).then(function(ctx){
139
+ return ctx.blob()
140
+ }).then(function(blob){
141
+ // converting blob to arrayBuffer, this process step needs to be be improved
142
+ // this operation's time complexity scales exponentially with audio length
143
+ return (new Response(blob)).arrayBuffer()
144
+ }).then(function(buffer){
145
+ Streamlit.setComponentValue({
146
+ "arr": new Uint8Array(buffer)
147
+ })
148
+ })
149
+
150
+ }
151
+
152
+
153
+ }
154
+ }
155
+
156
+ // "withStreamlitConnection" is a wrapper function. It bootstraps the
157
+ // connection between your component and the Streamlit app, and handles
158
+ // passing arguments from Python -> Component.
159
+ // You don't need to edit withStreamlitConnection (but you're welcome to!).
160
+ export default withStreamlitConnection(StAudioRec)
161
+
162
+ // Tell Streamlit we're ready to start receiving data. We won't get our
163
+ // first RENDER_EVENT until we call this function.
164
+ Streamlit.setComponentReady()
165
+
166
+ // Finally, tell Streamlit to update our initial height. We omit the
167
+ // `height` parameter here to have it default to our scrollHeight.
168
+ Streamlit.setFrameHeight()
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/src/index.tsx ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from "react"
2
+ import ReactDOM from "react-dom"
3
+ import StAudioRec from "./StreamlitAudioRecorder"
4
+
5
+ ReactDOM.render(
6
+ <React.StrictMode>
7
+ <StAudioRec />
8
+ </React.StrictMode>,
9
+ document.getElementById("root")
10
+ )
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/src/react-app-env.d.ts ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ /// <reference types="react-scripts" />
2
+ declare module 'audio-react-recorder';
audio_recorder/streamlit_audio_recorder/st_audiorec/frontend/tsconfig.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es5",
4
+ "lib": ["dom", "dom.iterable", "esnext"],
5
+ "allowJs": true,
6
+ "skipLibCheck": true,
7
+ "esModuleInterop": true,
8
+ "allowSyntheticDefaultImports": true,
9
+ "strict": true,
10
+ "strictNullChecks":false,
11
+ "forceConsistentCasingInFileNames": true,
12
+ "module": "esnext",
13
+ "moduleResolution": "node",
14
+ "resolveJsonModule": true,
15
+ "isolatedModules": true,
16
+ "noEmit": true,
17
+ "jsx": "react",
18
+ "noImplicitAny": false,
19
+ },
20
+ "include": ["src"]
21
+ }
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ streamlit-audiorec
2
+ streamlit
3
+ torch
4
+ transformers
5
+ streamlit-mic-recorder
6
+ gtts
7
+ pydub
8
+ streamlit_authenticator
9
+ streamlit_toggle
translator.db ADDED
Binary file (28.7 kB). View file