JBHF commited on
Commit
c82f149
·
verified ·
1 Parent(s): 2aea58e

app-08-04-2024-(AUDIO-EN-VERTALING-MBV MIXTRAL-8x7B-32768- WERKEND!).py

Browse files
app-08-04-2024-(AUDIO-EN-VERTALING-MBV MIXTRAL-8x7B-32768- WERKEND!).py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # JBHF/VERTAAL-APP-EAGLE-SHELTER/app.py - 08-04-2024 (AUDIO EN VERTALING MBV MIXTRAL-8x7B-32768 WERKEND !)
2
+ # WERKT AL: DE OPGENOMEN AUDIO MBV DEZE APP, audio.wav, HOEFT NIET PERSÉ GEPERSISTEERD TE WORDEN !!!!!!
3
+
4
+ # https://github.com/theevann/streamlit-audiorecorder
5
+ # An audio Recorder for streamlit
6
+ #
7
+ # Description
8
+ # Audio recorder component for streamlit.
9
+ # It creates a button to start the recording and takes three arguments:
10
+ # the start button text, the stop button text, and the pause button text.
11
+ # If the pause button text is not specified, the pause button is not displayed.
12
+ #
13
+ # Parameters
14
+ # The signature of the component is:
15
+ # audiorecorder(start_prompt="Start recording", stop_prompt="Stop recording", pause_prompt="", key=None):
16
+ # The prompt parameters are self-explanatory, and the optional key parameter is used internally by streamlit
17
+ # to properly distinguish multiple audiorecorders on the page.
18
+ #
19
+ # Return value
20
+ # The component's return value is a pydub AudioSegment.
21
+ #
22
+ # All AudioSegment methods are available, in particular you can:
23
+ # - Play the audio in the frontend with st.audio(audio.export().read())
24
+ # - Save the audio to a file with audio.export("audio.wav", format="wav")
25
+ # JB: Waarom zie ik in mijn HF Spaces omgeving de file "audio.wav" niet terug ?
26
+ # JB: 08-04-2024 - Mogelijk is caching al voldoende (anders file persistence)#
27
+ # Zie hiervoor:
28
+ #
29
+ # CACHING:
30
+ # ========
31
+ # STREAMLIT - Caching overview - Streamlit Docs - 07-04-2024 !!!!!
32
+ # https://docs.streamlit.io/develop/concepts/architecture/caching
33
+ #
34
+ # EVERNOTE :
35
+ # https://www.evernote.com/shard/s313/nl/41973486/31880952-8bd9-41ef-8047-ca844143e833/
36
+ # STREAMLIT - Caching overview - Streamlit Docs - 07-04-2024 !!!!!
37
+ #
38
+ # 08-04-2024
39
+ #
40
+ # EN
41
+ #
42
+ # PERSISTENCE:
43
+ # ============
44
+ # HF SPACES STREAMLIT APPS - GET PASSWORDS AND ACCESS TOKENS FROM HF ENVIRONMENT ! - PERSISTENT STORAGE ON HF SPACES ! - EAGLE SHELTER VERTAAL APP ETC ! - app.py · julien-c/persistent-data at main - 20-03-2024 !!!!! !!!!! !!!!!
45
+ # https://huggingface.co/spaces/julien-c/persistent-data/blob/main/app.py
46
+ #
47
+ # ——->
48
+ #
49
+ # DUPLICATED TO:
50
+ # https://huggingface.co/spaces/JBHF/persistent-data?logs=container
51
+ #
52
+ # EVERNOTE :
53
+ # https://www.evernote.com/shard/s313/nl/41973486/1b07098e-3376-4316-abb3-b3d0996ebf03/
54
+ # HF SPACES STREAMLIT APPS - GET PASSWORDS AND ACCESS TOKENS FROM HF ENVIRONMENT ! - PERSISTENT STORAGE ON HF SPACES ! - EAGLE SHELTER VERTAAL APP ETC ! - app.py · julien-c/persistent-data at main - 20-03-2024 !!!!! !!!!! !!!!!
55
+ #
56
+ # 08-04-2024
57
+ #
58
+
59
+ import os
60
+ import streamlit as st
61
+
62
+ ###########################################################################################################
63
+ # VERTALING
64
+ # DAADWERKELIJK MET MIC OPGENOMEN EN GETRANSCRIBEERD STUKJE OEKRAÍENSE TEKST TER TEST
65
+ # OM HIERONDER NAAR NEDERLANDS TE VERTALEN MBV LLM MIXTRAL-8x7b-GROQ! :
66
+ # text_to_transcribe:
67
+ # князем Данилом Романовичем біля Звенигорода і названий на честь його сина Лева Сьогодні Львів має площу 155 квадратних кілометрів з безліччю громадських будинків, кафе, магазинів
68
+ # ...
69
+
70
+ # TEXTS FROM UKRAIN TO TRANSLATE:
71
+ # 1 - Short text from https://youtu.be/1_vO60OkkrY?list=PLeeQI3aTmCn9Lu9mgSCmmc-KkGI95-Ie6 :
72
+ text_to_transcribe = """князем Данилом Романовичем біля Звенигорода і названий на честь його сина Лева Сьогодні Львів має площу 155 квадратних кілометрів з безліччю громадських будинків, кафе, магазинів"""
73
+ #
74
+ # 2 - complete, long text from https://youtu.be/1_vO60OkkrY?list=PLeeQI3aTmCn9Lu9mgSCmmc-KkGI95-Ie6 :
75
+ text_to_transcribe = """
76
+ Львів – одне з моїх найулюбленіших міст України. Я вже відвідувала це місто п’ять разів, але хочу повертатися туди знову і знову. Львів – це історична столиця Галичини і Західної України. Це великий культурний, політичний і релігійний центр України.
77
+ Львів був заснований у середині XIII ст. князем Данилом Романовичем біля Звенигорода і названий на честь його сина, Лева. Сьогодні Львів має площу 155 км. кв. Найбільш виразна частина Львова включає проспект Шевченка і Городецьку вулицю, з безліччю громадських будинків, готелів, кафе, магазинів і банків у стилі ХІХ-ХХ ст.
78
+ Львів – дивовижне місто, яке наскрізь просякнуте п’янким ароматом кави і шоколаду. Світ в��зит я починаю із серця Львова – Площа ринок, потім я підіймаюся на Ратушу. Я люблю відвідувати заклади, які стали візитівкою міста такі як: Копальня кави, Майстерня шоколаду, Гасова Лямпа, Дім Легенд. Львів — єдине в Україні місто, у якому збереглися архітектурні споруди часів Ренесансу. Найбільш яскравими прикладами цього стилю служать церква Успіння і каплиця Трьох Святих.
79
+ Основні пам'ятники міста — пам'ятник А. Міцкевичу, І. Франку, В. Стефанику, С. Бандері. Екскурсія середньовічними замками також не залишає нікого байдужим.
80
+ Неможливо передати словами всю красу і велич Львова, треба бачити це самостійно. Це старовинне місто, яке зачаровує своїми традиціями, красою та шармом.
81
+ """
82
+ st.write("text_to_transcribe: ", text_to_transcribe)
83
+
84
+ # Groq in Langchain
85
+ # Groq is even compatible with LangChain. To begin using Groq in LangChain, download the library:
86
+ # !pip install langchain-groq
87
+ # The above will install the Groq library for LangChain compatibility. Now let’s try it out in code:
88
+
89
+ # Import the necessary libraries.
90
+ from langchain_core.prompts import ChatPromptTemplate
91
+ from langchain_groq import ChatGroq
92
+
93
+ groq_api_key = os.environ['GROQ_API_KEY']
94
+ # groq_api_key = "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" # os.environ['GROQ_API_KEY']
95
+ # groq_api_key = "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" # JB OK 24-03-2024
96
+ st.write("groq_api_key: ", groq_api_key)
97
+
98
+ # Initialize a ChatGroq object with a temperature of 0 and the "mixtral-8x7b-32768" model.
99
+ llm = ChatGroq(temperature=0, model_name="mixtral-8x7b-32768")
100
+ # The above code does the following:
101
+ # -Creates a new ChatGroq object named llm
102
+ # -Sets the temperature parameter to 0, indicating that the responses should be more predictable
103
+ # -Sets the model_name parameter to “mixtral-8x7b-32768“, specifying the language model to use
104
+
105
+ # Define the system message introducing the AI assistant's capabilities.
106
+ # system = "You are an expert Coding Assistant."
107
+ system = "You are an expert translation Assistant, proficient in all languages."
108
+
109
+ # Define a placeholder for the user's input.
110
+ human = "{text}"
111
+
112
+ # Create a chat prompt consisting of the system and human messages.
113
+ prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])
114
+
115
+ # Invoke the chat chain with the user's input.
116
+ chain = prompt | llm
117
+
118
+ # response = chain.invoke({"text": "Write a simple code to generate Fibonacci numbers in Rust?"}) # ORIGINAL
119
+ # response = chain.invoke({"text": "TRANSLATE THE FOLLOWING TEXT INTO ENGLISH" + text_to_transcribe}) # JB TRANSLATE TO ENGLISH
120
+ response = chain.invoke({"text": \
121
+ """Translate the following text into correct Dutch language
122
+ and do not use any other language for your response whatsover or you will get severly punished.
123
+ Do not translate names of places, towns and other geographical names.
124
+ Do not translate names of people.
125
+ """ + text_to_transcribe}) # JB TRANSLATE TO DUTCH
126
+
127
+ # Print the Response.
128
+ # print(response.content)
129
+ st.write(response.content)
130
+
131
+ # - The code generates a Chat Prompt using the ChatPromptTemplate class.
132
+ # - The prompt comprises two messages: one from the “system” (the AI assistant) and one from the “human” (the user).
133
+ # - The system message presents the AI assistant as an expert Coding Assistant.
134
+ # - The human message serves as a placeholder for the user’s input.
135
+ # - The llm method invokes the llm chain to produce a response based on the provided Prompt and the user’s input.
136
+
137
+
138
+
139
+ ###########################################################################################################
140
+
141
+
142
+ ###########################################################################################################
143
+ #
144
+ # Installation:
145
+ # pip install streamlit-audiorecorder
146
+ # Note: This package uses ffmpeg, so it should be installed for this audiorecorder to work properly.
147
+ #
148
+ # On ubuntu/debian: sudo apt update && sudo apt install ffmpeg
149
+ # On mac: brew install ffmpeg
150
+
151
+ import streamlit as st
152
+ from audiorecorder import audiorecorder
153
+
154
+ st.title("Audio Recorder")
155
+ # audiorecorder(start_prompt="Start recording", stop_prompt="Stop recording", pause_prompt="", key=None):
156
+ audio = audiorecorder("Click to record", "Click to stop recording", "Click to pause recording")
157
+
158
+
159
+ # JB:
160
+ # https://docs.streamlit.io/develop/concepts/architecture/caching
161
+ # @st.cache_data
162
+ @st.cache_resource # 👈 Add the caching decorator
163
+ def audio_export(audio_wav_file, format):
164
+ # audio.export("audio.wav", format="wav") # ORIGINAL
165
+ audio.export(audio_wav_file, format=format)
166
+
167
+ if len(audio) > 0:
168
+ # To play audio in frontend:
169
+ st.audio(audio.export().read())
170
+
171
+ # To save audio to a file, use pydub export method:
172
+ # https://docs.streamlit.io/develop/concepts/architecture/caching
173
+ # @st.cache_data
174
+ # @st.cache_data
175
+ # audio.export("audio.wav", format="wav") # ORIGINAL
176
+ audio_export("audio.wav", format="wav") # JB 08-04-2024
177
+
178
+ # To get audio properties, use pydub AudioSegment properties:
179
+ st.write(f"Frame rate: {audio.frame_rate}, Frame width: {audio.frame_width}, Duration: {audio.duration_seconds} seconds")
180
+
181
+
182
+ st.button("Rerun")
183
+ ###########################################################################################################
184
+
185
+
186
+ ###########################################################################################################
187
+ # TEST
188
+ # ZIE:
189
+ # infer_faster_whisper_large_v2 (CPU VERSIE !) 08-04-2024-COLAB-CPU-PYTHON3-tvscitechtalk.ipynb
190
+ # https://colab.research.google.com/drive/1EreiFx825oIrR2P43XSXjHXx01EWi6ZH#scrollTo=vuLjbPxexPDj&uniqifier=5
191
+
192
+ from faster_whisper import WhisperModel
193
+
194
+ model_size = "large-v2"
195
+
196
+ # Run on GPU with FP16
197
+ # model = WhisperModel(model_size, device="cuda", compute_type="float16") # ORIGINAL, DRAAIT OP COLAB T4 GPU OK
198
+
199
+ # TEST: Run on CPU
200
+ # model = WhisperModel(model_size, device="cpu", compute_type="float16") # JB, DRAAIT OP COLAB CPU OK ?
201
+ # ValueError: Requested float16 compute type, but the target device or backend do not support efficient float16 computation.
202
+ #
203
+ # st.write("Loading the WhisperModel: model = WhisperModel(model_size, device=\"cpu\")")
204
+ # model = WhisperModel(model_size, device="cpu") # , compute_type="float16") # JB, DRAAIT OP COLAB CPU OK: JA; HF SPACES STREAMLIT FREE TIER: JB OK !
205
+ # JB: Dit gebruikt mijn HF Token !
206
+ # st.write("Ready Loading the WhisperModel: model = WhisperModel(model_size, device=\"cpu\")")
207
+
208
+ st.write("Loading the WhisperModel: model = WhisperModel(model_size, device=\"cpu\", compute_type=\"int8\")")
209
+ model = WhisperModel(model_size, device="cpu", compute_type="int8") # , compute_type="float16") # JB
210
+ # JB: Dit gebruikt mijn HF Token !
211
+ # st.write("Ready Loading the WhisperModel: model = WhisperModel(model_size, device=\"cpu\")")
212
+ # LOADING OF model = WhisperModel(model_size, device="cpu") TAKES ABOUT 1 MINUTE ON HF SPACES STREAMLIT FREE TIER
213
+ #
214
+ st.write("Ready Loading the WhisperModel: model = WhisperModel(model_size, device=\"cpu\", compute_type=\"int8\")")
215
+ # LOADING OF model = WhisperModel(model_size, device=\"cpu\", compute_type=\"int8\") TAKES ABOUT 33 sec (Na RERUN 1 minute) ON HF SPACES STREAMLIT FREE TIER
216
+
217
+
218
+ # USING:
219
+ # model = WhisperModel(model_size, device="cpu", compute_type="int8") # JB
220
+ # segments, info = model.transcribe("sam_altman_lex_podcast_367.flac", beam_size=1)
221
+
222
+ # /content/Ukrainian podcast #10 Traveling to Lviv - Подорож до Льова. SLOW UKRAINIAN.mp3
223
+ # segments, info = model.transcribe("Ukrainian podcast #10 Traveling to Lviv - Подорож до Льова. SLOW UKRAINIAN.mp3", beam_size=1)
224
+ # TEST:
225
+ segments, info = model.transcribe("audio.wav", beam_size=1) # DIT WERKT: GEDURENDE DE SESSIE BLIJFT audio.wav FILE BESCHIKBAAR IN DEZE APP !!!!!
226
+
227
+
228
+ # print("Detected language '%s' with probability %f" % (info.language, info.language_probability))
229
+ st.write("Detected language '%s' with probability %f" % (info.language, info.language_probability))
230
+ st.write("")
231
+ st.write("info.all_language_probs : ", info.all_language_probs)
232
+ st.write("len(info.all_language_probs): ", len(info.all_language_probs))
233
+ # 99
234
+
235
+ st.write("")
236
+
237
+ st.write("info: ", info)
238
+
239
+ # Ukrainian podcast #10 Traveling to Lviv - Подорож до Льова. SLOW UKRAINIAN.mp3 :
240
+ st.write("info.duration: ", info.duration)
241
+ # 233.8249375
242
+ # time: 3.98 ms (started: 2024-03-15 10:55:15 +00:00)
243
+ # minutes = int(info.duration / 60)
244
+ # seconds = info.duration - minutes*60
245
+ minutes = int(info.duration / 60)
246
+ seconds = info.duration - minutes*60
247
+
248
+ st.write(minutes," minutes and ", seconds, " seconds")
249
+
250
+
251
+ text_to_transcribe = ""
252
+ for segment in segments:
253
+ # print("[%.2fs -> %.2fs] %s" % (segment.start, segment.end, segment.text))
254
+ st.write("[%.2fs -> %.2fs] %s" % (segment.start, segment.end, segment.text))
255
+ text_to_transcribe = text_to_transcribe + " " + segment.text
256
+
257
+ st.write("---------------------------------------------------------------------")
258
+
259
+ #text_to_transcribe = ""
260
+ #st.write("TOTAL TEXT TO TRANSCRIBE:")
261
+ #for segment in segments:
262
+ # st.write(segment.text)
263
+ # text_to_transcribe = text_to_transcribe + " " + segment
264
+ # # print(segment)
265
+
266
+ st.write("text_to_transcribe: ", text_to_transcribe)
267
+ # DAADWERKELIJK MET MIC OPGENOMEN EN GETRANSCRIBEERD STUKJE OEKRAÍENSE TEKST TER TEST
268
+ # OM HIERONDER NAAR NEDERLANDS TE VERTALEN MBV LLM MIXTRAL-8x7b-GROQ! :
269
+ # text_to_transcribe:
270
+ # князем Данилом Романовичем біля Звенигород�� і названий на честь його сина Лева Сьогодні Львів має площу 155 квадратних кілометрів з безліччю громадських будинків, кафе, магазинів
271
+
272
+
273
+
274
+