Spaces:
Paused
Paused
rick
commited on
clean & organise the source code
Browse files- core/audio_files.py +99 -0
- core/speech_to_text.py +81 -1
- pages/main.py +3 -179
core/audio_files.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#coding: utf-8
|
| 2 |
+
from pydub import AudioSegment
|
| 3 |
+
#from openai import OpenAI
|
| 4 |
+
#from io import BytesIO
|
| 5 |
+
#from typing import Any
|
| 6 |
+
#from typing import Dict
|
| 7 |
+
#from typing import IO
|
| 8 |
+
from typing import List
|
| 9 |
+
from typing import Optional
|
| 10 |
+
from typing import Tuple
|
| 11 |
+
from typing import Union
|
| 12 |
+
import base64
|
| 13 |
+
import io
|
| 14 |
+
|
| 15 |
+
def concatenate_audio_files(audio_list: List[Tuple[Union[bytes, str], float]]) -> Optional[bytes]:
|
| 16 |
+
"""
|
| 17 |
+
Concatène plusieurs fichiers audio avec des effets sonores.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
audio_list (List[Tuple[Union[bytes, str], float]]): Une liste de tuples, chacun contenant
|
| 21 |
+
des octets audio (ou une chaîne base64) et la durée.
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
Optional[bytes]: L'audio concaténé sous forme d'octets, ou None en cas d'erreur.
|
| 25 |
+
"""
|
| 26 |
+
# Créer un segment audio vide
|
| 27 |
+
final_audio = AudioSegment.empty()
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
# Charger les effets sonores
|
| 31 |
+
begin_sound = AudioSegment.from_mp3(
|
| 32 |
+
"sound-effects/voice-message-play-begin/voice-message-play-begin-1.mp3"
|
| 33 |
+
)
|
| 34 |
+
end_sound = AudioSegment.from_mp3(
|
| 35 |
+
"sound-effects/voice-message-play-ending/voice-message-play-ending-1.mp3"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# 5 secondes de silence
|
| 39 |
+
silence = AudioSegment.silent(duration=1500) # 1500 ms = 1.5 secondes
|
| 40 |
+
|
| 41 |
+
for audio_data, _ in audio_list:
|
| 42 |
+
# Convertir en bytes si c'est une chaîne base64
|
| 43 |
+
if isinstance(audio_data, str):
|
| 44 |
+
audio_bytes = base64.b64decode(audio_data)
|
| 45 |
+
else:
|
| 46 |
+
audio_bytes = audio_data
|
| 47 |
+
|
| 48 |
+
# Convertir les octets en un segment audio
|
| 49 |
+
segment = AudioSegment.from_mp3(io.BytesIO(audio_bytes))
|
| 50 |
+
|
| 51 |
+
# Ajouter le son de début, le segment TTS, le son de fin et le silence
|
| 52 |
+
final_audio += begin_sound + segment + end_sound + silence
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# Convertir le segment audio final en octets
|
| 56 |
+
buffer = io.BytesIO()
|
| 57 |
+
final_audio.export(buffer, format="mp3")
|
| 58 |
+
return buffer.getvalue()
|
| 59 |
+
except IOError as e:
|
| 60 |
+
print(f"Erreur lors de la lecture ou de l'écriture des fichiers audio : {e}")
|
| 61 |
+
return None
|
| 62 |
+
except Exception as e:
|
| 63 |
+
print(f"Une erreur inattendue s'est produite : {e}")
|
| 64 |
+
return None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def split_audio(audio_file, max_size_mb: int = 25) -> List[bytes]:
|
| 68 |
+
"""
|
| 69 |
+
Divise un fichier audio en segments de taille maximale spécifiée.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
audio_file: Fichier audio ouvert en mode binaire.
|
| 73 |
+
max_size_mb (int): Taille maximale de chaque segment en Mo.
|
| 74 |
+
|
| 75 |
+
Returns:
|
| 76 |
+
List[bytes]: Liste des segments audio divisés sous forme de bytes.
|
| 77 |
+
"""
|
| 78 |
+
try:
|
| 79 |
+
audio_file.seek(0)
|
| 80 |
+
audio = AudioSegment.from_file(audio_file)
|
| 81 |
+
duration_ms = len(audio)
|
| 82 |
+
segment_duration_ms = int(
|
| 83 |
+
(max_size_mb * 1024 * 1024 * 8) /
|
| 84 |
+
(audio.frame_rate * audio.sample_width * audio.channels)
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
segments = []
|
| 88 |
+
for start in range(0, duration_ms, segment_duration_ms):
|
| 89 |
+
end = min(start + segment_duration_ms, duration_ms)
|
| 90 |
+
segment = audio[start:end]
|
| 91 |
+
|
| 92 |
+
with io.BytesIO() as buffer:
|
| 93 |
+
segment.export(buffer, format="mp3")
|
| 94 |
+
segments.append(buffer.getvalue())
|
| 95 |
+
|
| 96 |
+
return segments
|
| 97 |
+
except Exception as e:
|
| 98 |
+
print(f"Une erreur s'est produite lors de la division de l'audio : {e}")
|
| 99 |
+
return []
|
core/speech_to_text.py
CHANGED
|
@@ -3,7 +3,16 @@
|
|
| 3 |
import requests # Pour envoyer des requêtes HTTP à l'API
|
| 4 |
import json # Pour traiter les réponses JSON de l'API
|
| 5 |
from os import getenv
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
def huggingface_endpoints_stt(fichier_audio: str) -> str:
|
| 9 |
# Définir l'URL de l'endpoint d'inférence sur Hugging Face
|
|
@@ -41,6 +50,73 @@ def huggingface_endpoints_stt(fichier_audio: str) -> str:
|
|
| 41 |
# En cas d'erreur, afficher le code de statut et le message
|
| 42 |
raise Exception(f"Erreur API: {response.status_code}, {response.text}")
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
# Exemple d'utilisation de la fonction
|
| 45 |
if __name__ == "__main__":
|
| 46 |
fichier_audio = "sample_1.wav" # Remplacez par votre fichier audio
|
|
@@ -56,3 +132,7 @@ if __name__ == "__main__":
|
|
| 56 |
"""
|
| 57 |
Supported content types are:\n application/json, application/json; charset=UTF-8, text/csv, text/plain, image/png, image/jpeg, image/jpg, image/tiff, image/bmp, image/gif, image/webp, image/x-image, audio/x-flac, audio/flac, audio/mpeg, audio/x-mpeg-3, audio/wave, audio/wav, audio/x-wav, audio/ogg, audio/x-audio, audio/webm, audio/webm;codecs=opus, audio/AMR, audio/amr, audio/AMR-WB, audio/AMR-WB+, audio/m4a, audio/x-m4a\n
|
| 58 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import requests # Pour envoyer des requêtes HTTP à l'API
|
| 4 |
import json # Pour traiter les réponses JSON de l'API
|
| 5 |
from os import getenv
|
| 6 |
+
from pydub import AudioSegment
|
| 7 |
+
from openai import OpenAI
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
#from typing import Any
|
| 10 |
+
#from typing import Dict
|
| 11 |
+
from typing import IO
|
| 12 |
+
#from typing import List
|
| 13 |
+
from typing import Optional
|
| 14 |
+
#from typing import Tuple
|
| 15 |
+
from typing import Union
|
| 16 |
|
| 17 |
def huggingface_endpoints_stt(fichier_audio: str) -> str:
|
| 18 |
# Définir l'URL de l'endpoint d'inférence sur Hugging Face
|
|
|
|
| 50 |
# En cas d'erreur, afficher le code de statut et le message
|
| 51 |
raise Exception(f"Erreur API: {response.status_code}, {response.text}")
|
| 52 |
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# ############################################################
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def transcribe_audio(filepath: Union[str, IO], language: Optional[str] = None) -> str:
|
| 59 |
+
"""
|
| 60 |
+
Transcrit un fichier audio temporaire en texte.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
filepath Chemin vers le fichier audio temporaire à transcrire.
|
| 64 |
+
language (Optional[str]): La langue de l'audio. Par défaut None.
|
| 65 |
+
|
| 66 |
+
Returns:
|
| 67 |
+
str: Le texte transcrit.
|
| 68 |
+
"""
|
| 69 |
+
max_size_mb = 25
|
| 70 |
+
client = OpenAI(api_key=getenv("OPENAI_API_KEY"))
|
| 71 |
+
try:
|
| 72 |
+
transcriptions = []
|
| 73 |
+
with open(filepath if isinstance(filepath, str) else filepath.name, "rb") as f:
|
| 74 |
+
# filepath peut etre un chemin vers un fichier audio ou un objet IO
|
| 75 |
+
# verifier si le fichier audio fait plus de 25 Mo
|
| 76 |
+
|
| 77 |
+
# Diviser l'audio en segments de taille maximale
|
| 78 |
+
#segments = split_audio(f, max_size_mb)
|
| 79 |
+
f.seek(0)
|
| 80 |
+
audio = AudioSegment.from_file(f)
|
| 81 |
+
duration_ms = len(audio)
|
| 82 |
+
segment_duration_ms = int(
|
| 83 |
+
(max_size_mb * 1024 * 1024 * 8) /
|
| 84 |
+
(audio.frame_rate * audio.sample_width * audio.channels)
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
for start in range(0, duration_ms, segment_duration_ms):
|
| 88 |
+
end = min(start + segment_duration_ms, duration_ms)
|
| 89 |
+
segment = audio[start:end]
|
| 90 |
+
|
| 91 |
+
buffer = BytesIO()
|
| 92 |
+
segment.export(buffer, format="mp3")
|
| 93 |
+
buffer.seek(0)
|
| 94 |
+
|
| 95 |
+
if not( language ):
|
| 96 |
+
response = client.audio.transcriptions.create(
|
| 97 |
+
model="whisper-1",
|
| 98 |
+
file=("audio.mp3", buffer),
|
| 99 |
+
response_format="text"
|
| 100 |
+
)
|
| 101 |
+
else:
|
| 102 |
+
response = client.audio.transcriptions.create(
|
| 103 |
+
model="whisper-1",
|
| 104 |
+
file=("audio.mp3", buffer),
|
| 105 |
+
language=language,
|
| 106 |
+
response_format="text"
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
transcriptions.append(response)
|
| 110 |
+
|
| 111 |
+
return " ".join(transcriptions)
|
| 112 |
+
except Exception as e:
|
| 113 |
+
print(f"Erreur lors de la transcription de l'audio : {e}")
|
| 114 |
+
return ""
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
|
| 120 |
# Exemple d'utilisation de la fonction
|
| 121 |
if __name__ == "__main__":
|
| 122 |
fichier_audio = "sample_1.wav" # Remplacez par votre fichier audio
|
|
|
|
| 132 |
"""
|
| 133 |
Supported content types are:\n application/json, application/json; charset=UTF-8, text/csv, text/plain, image/png, image/jpeg, image/jpg, image/tiff, image/bmp, image/gif, image/webp, image/x-image, audio/x-flac, audio/flac, audio/mpeg, audio/x-mpeg-3, audio/wave, audio/wav, audio/x-wav, audio/ogg, audio/x-audio, audio/webm, audio/webm;codecs=opus, audio/AMR, audio/amr, audio/AMR-WB, audio/AMR-WB+, audio/m4a, audio/x-m4a\n
|
| 134 |
"""
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
|
pages/main.py
CHANGED
|
@@ -33,8 +33,9 @@ from core.files import read_file
|
|
| 33 |
from core.text_to_speech import openai_tts
|
| 34 |
from core.DetectLanguage import detect_language
|
| 35 |
from core.speech_to_text import huggingface_endpoints_stt
|
| 36 |
-
|
| 37 |
-
|
|
|
|
| 38 |
|
| 39 |
# Au début du fichier, après les imports
|
| 40 |
st.set_page_config(
|
|
@@ -69,151 +70,6 @@ def process_tts_message(text_response: str) -> Tuple[Optional[bytes], Optional[f
|
|
| 69 |
st.error(f"Une erreur s'est produite lors de la conversion texte-parole : {e}")
|
| 70 |
return None, None
|
| 71 |
|
| 72 |
-
# ecrire ici la fonction: split_audio
|
| 73 |
-
def split_audio(audio_file, max_size_mb: int = 25) -> List[bytes]:
|
| 74 |
-
"""
|
| 75 |
-
Divise un fichier audio en segments de taille maximale spécifiée.
|
| 76 |
-
|
| 77 |
-
Args:
|
| 78 |
-
audio_file: Fichier audio ouvert en mode binaire.
|
| 79 |
-
max_size_mb (int): Taille maximale de chaque segment en Mo.
|
| 80 |
-
|
| 81 |
-
Returns:
|
| 82 |
-
List[bytes]: Liste des segments audio divisés sous forme de bytes.
|
| 83 |
-
"""
|
| 84 |
-
try:
|
| 85 |
-
audio_file.seek(0)
|
| 86 |
-
audio = AudioSegment.from_file(audio_file)
|
| 87 |
-
duration_ms = len(audio)
|
| 88 |
-
segment_duration_ms = int(
|
| 89 |
-
(max_size_mb * 1024 * 1024 * 8) /
|
| 90 |
-
(audio.frame_rate * audio.sample_width * audio.channels)
|
| 91 |
-
)
|
| 92 |
-
|
| 93 |
-
segments = []
|
| 94 |
-
for start in range(0, duration_ms, segment_duration_ms):
|
| 95 |
-
end = min(start + segment_duration_ms, duration_ms)
|
| 96 |
-
segment = audio[start:end]
|
| 97 |
-
|
| 98 |
-
with io.BytesIO() as buffer:
|
| 99 |
-
segment.export(buffer, format="mp3")
|
| 100 |
-
segments.append(buffer.getvalue())
|
| 101 |
-
|
| 102 |
-
return segments
|
| 103 |
-
except Exception as e:
|
| 104 |
-
print(f"Une erreur s'est produite lors de la division de l'audio : {e}")
|
| 105 |
-
return []
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
def transcribe_audio(filepath: Union[str, IO], language: Optional[str] = None) -> str:
|
| 109 |
-
"""
|
| 110 |
-
Transcrit un fichier audio temporaire en texte.
|
| 111 |
-
|
| 112 |
-
Args:
|
| 113 |
-
filepath Chemin vers le fichier audio temporaire à transcrire.
|
| 114 |
-
language (Optional[str]): La langue de l'audio. Par défaut None.
|
| 115 |
-
|
| 116 |
-
Returns:
|
| 117 |
-
str: Le texte transcrit.
|
| 118 |
-
"""
|
| 119 |
-
max_size_mb = 25
|
| 120 |
-
|
| 121 |
-
try:
|
| 122 |
-
transcriptions = []
|
| 123 |
-
with open(filepath if isinstance(filepath, str) else filepath.name, "rb") as f:
|
| 124 |
-
# filepath peut etre un chemin vers un fichier audio ou un objet IO
|
| 125 |
-
# verifier si le fichier audio fait plus de 25 Mo
|
| 126 |
-
|
| 127 |
-
# Diviser l'audio en segments de taille maximale
|
| 128 |
-
#segments = split_audio(f, max_size_mb)
|
| 129 |
-
f.seek(0)
|
| 130 |
-
audio = AudioSegment.from_file(f)
|
| 131 |
-
duration_ms = len(audio)
|
| 132 |
-
segment_duration_ms = int(
|
| 133 |
-
(max_size_mb * 1024 * 1024 * 8) /
|
| 134 |
-
(audio.frame_rate * audio.sample_width * audio.channels)
|
| 135 |
-
)
|
| 136 |
-
|
| 137 |
-
for start in range(0, duration_ms, segment_duration_ms):
|
| 138 |
-
end = min(start + segment_duration_ms, duration_ms)
|
| 139 |
-
segment = audio[start:end]
|
| 140 |
-
|
| 141 |
-
buffer = BytesIO()
|
| 142 |
-
segment.export(buffer, format="mp3")
|
| 143 |
-
buffer.seek(0)
|
| 144 |
-
|
| 145 |
-
if not( language ):
|
| 146 |
-
response = client.audio.transcriptions.create(
|
| 147 |
-
model="whisper-1",
|
| 148 |
-
file=("audio.mp3", buffer),
|
| 149 |
-
response_format="text"
|
| 150 |
-
)
|
| 151 |
-
else:
|
| 152 |
-
response = client.audio.transcriptions.create(
|
| 153 |
-
model="whisper-1",
|
| 154 |
-
file=("audio.mp3", buffer),
|
| 155 |
-
language=language,
|
| 156 |
-
response_format="text"
|
| 157 |
-
)
|
| 158 |
-
|
| 159 |
-
transcriptions.append(response)
|
| 160 |
-
|
| 161 |
-
return " ".join(transcriptions)
|
| 162 |
-
except Exception as e:
|
| 163 |
-
print(f"Erreur lors de la transcription de l'audio : {e}")
|
| 164 |
-
return ""
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
def concatenate_audio_files(audio_list: List[Tuple[Union[bytes, str], float]]) -> Optional[bytes]:
|
| 168 |
-
"""
|
| 169 |
-
Concatène plusieurs fichiers audio avec des effets sonores.
|
| 170 |
-
|
| 171 |
-
Args:
|
| 172 |
-
audio_list (List[Tuple[Union[bytes, str], float]]): Une liste de tuples, chacun contenant
|
| 173 |
-
des octets audio (ou une chaîne base64) et la durée.
|
| 174 |
-
|
| 175 |
-
Returns:
|
| 176 |
-
Optional[bytes]: L'audio concaténé sous forme d'octets, ou None en cas d'erreur.
|
| 177 |
-
"""
|
| 178 |
-
# Créer un segment audio vide
|
| 179 |
-
final_audio = AudioSegment.empty()
|
| 180 |
-
|
| 181 |
-
try:
|
| 182 |
-
# Charger les effets sonores
|
| 183 |
-
begin_sound = AudioSegment.from_mp3(
|
| 184 |
-
"sound-effects/voice-message-play-begin/voice-message-play-begin-1.mp3"
|
| 185 |
-
)
|
| 186 |
-
end_sound = AudioSegment.from_mp3(
|
| 187 |
-
"sound-effects/voice-message-play-ending/voice-message-play-ending-1.mp3"
|
| 188 |
-
)
|
| 189 |
-
|
| 190 |
-
# 5 secondes de silence
|
| 191 |
-
silence = AudioSegment.silent(duration=1500) # 1500 ms = 1.5 secondes
|
| 192 |
-
|
| 193 |
-
for audio_data, _ in audio_list:
|
| 194 |
-
# Convertir en bytes si c'est une chaîne base64
|
| 195 |
-
if isinstance(audio_data, str):
|
| 196 |
-
audio_bytes = base64.b64decode(audio_data)
|
| 197 |
-
else:
|
| 198 |
-
audio_bytes = audio_data
|
| 199 |
-
|
| 200 |
-
# Convertir les octets en un segment audio
|
| 201 |
-
segment = AudioSegment.from_mp3(io.BytesIO(audio_bytes))
|
| 202 |
-
|
| 203 |
-
# Ajouter le son de début, le segment TTS, le son de fin et le silence
|
| 204 |
-
final_audio += begin_sound + segment + end_sound + silence
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
# Convertir le segment audio final en octets
|
| 208 |
-
buffer = io.BytesIO()
|
| 209 |
-
final_audio.export(buffer, format="mp3")
|
| 210 |
-
return buffer.getvalue()
|
| 211 |
-
except IOError as e:
|
| 212 |
-
print(f"Erreur lors de la lecture ou de l'écriture des fichiers audio : {e}")
|
| 213 |
-
return None
|
| 214 |
-
except Exception as e:
|
| 215 |
-
print(f"Une erreur inattendue s'est produite : {e}")
|
| 216 |
-
return None
|
| 217 |
|
| 218 |
def process_message(
|
| 219 |
message: str,
|
|
@@ -252,7 +108,6 @@ def process_message(
|
|
| 252 |
st.error(f"Une erreur s'est produite lors de la génération de la réponse : {e}")
|
| 253 |
return ""
|
| 254 |
|
| 255 |
-
|
| 256 |
class GlobalSystemPrompts:
|
| 257 |
"""Class to store global system prompts."""
|
| 258 |
|
|
@@ -318,7 +173,6 @@ LANGUAGES_EMOJI = {
|
|
| 318 |
"Vietnamese": "🇻🇳", "Welsh": "🏴"
|
| 319 |
}
|
| 320 |
|
| 321 |
-
|
| 322 |
def convert_iso6391_to_language_name(language_code: str,
|
| 323 |
filter_mode=True) -> str:
|
| 324 |
"""
|
|
@@ -430,9 +284,6 @@ def init_process_mode(
|
|
| 430 |
return system_prompt, operation_prompt
|
| 431 |
return "", ""
|
| 432 |
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
@st.dialog("Settings")
|
| 437 |
def tts_settings(name__tts_voice,
|
| 438 |
state__tts_with_text,
|
|
@@ -467,7 +318,6 @@ def tts_settings(name__tts_voice,
|
|
| 467 |
#st.session_state.
|
| 468 |
st.rerun()
|
| 469 |
|
| 470 |
-
|
| 471 |
@st.fragment
|
| 472 |
def recorder_released():
|
| 473 |
if "rec_widget" in st.session_state:
|
|
@@ -681,13 +531,11 @@ def main_page():
|
|
| 681 |
icon="ℹ️"):
|
| 682 |
st.subheader(f"version: {__version__}")
|
| 683 |
st.info(get_translation("info_app"))
|
| 684 |
-
|
| 685 |
|
| 686 |
with st.expander(f"{get_translation('selection_langue')}",
|
| 687 |
expanded=True,
|
| 688 |
icon="🌐"):
|
| 689 |
# Conteneur pour la sélection de langue
|
| 690 |
-
|
| 691 |
# Sélection multiple des langues de destination
|
| 692 |
st.multiselect(
|
| 693 |
label=get_translation("langues_destination"),
|
|
@@ -707,14 +555,6 @@ def main_page():
|
|
| 707 |
)
|
| 708 |
|
| 709 |
st.experimental_audio_input("Record a voice message",on_change=recorder_released, key="rec_widget")
|
| 710 |
-
#audiorecorder(
|
| 711 |
-
# start_prompt=get_translation("cliquez_enregistrer"),
|
| 712 |
-
# stop_prompt=get_translation("cliquez_arreter"),
|
| 713 |
-
# pause_prompt=get_translation("cliquez_pause"),
|
| 714 |
-
# show_visualizer=True,
|
| 715 |
-
# key="vocal_chat_input"
|
| 716 |
-
#)
|
| 717 |
-
|
| 718 |
|
| 719 |
if st.session_state.user_input:
|
| 720 |
|
|
@@ -757,7 +597,6 @@ def main_page():
|
|
| 757 |
st.error("Erreur : Les prompts système ou d'opération sont vides.")
|
| 758 |
raise ValueError("Les prompts système ou d'opération ne peuvent pas être vides.")
|
| 759 |
|
| 760 |
-
|
| 761 |
with st.status(f'({target_language_name}) - {get_translation("traduction_en_cours")}', expanded=True) as response_status:
|
| 762 |
with st.chat_message("assistant", avatar="👻"):
|
| 763 |
message_placeholder = st.empty()
|
|
@@ -767,7 +606,6 @@ def main_page():
|
|
| 767 |
st.session_state.system_prompt
|
| 768 |
)
|
| 769 |
|
| 770 |
-
|
| 771 |
response_status.update(label=f'({target_language_name}) - {get_translation("traduction_en_cours")}', state="running", expanded=True)
|
| 772 |
for response_chunk in st.session_state.response_generator:
|
| 773 |
message_placeholder.markdown(response_chunk)
|
|
@@ -787,13 +625,11 @@ def main_page():
|
|
| 787 |
else:
|
| 788 |
response_status.update(label=f'({target_language_name}) - {get_translation("erreur_synthese_vocale")}', state="error", expanded=False)
|
| 789 |
|
| 790 |
-
|
| 791 |
else:
|
| 792 |
response_status.update(label=f'({target_language_name}) - {get_translation("traduction_terminee")}', state="complete", expanded=False)
|
| 793 |
else:
|
| 794 |
response_status.update(label=f'({target_language_name}) - {get_translation("erreur_traduction")}', state="error", expanded=False)
|
| 795 |
|
| 796 |
-
|
| 797 |
if st.session_state.audio_list:
|
| 798 |
with st.status(f"{get_translation('concatenation_audio_en_cours')}", expanded=False) as audio_status:
|
| 799 |
audio_status.update(label=f"{get_translation('concatenation_audio_en_cours')}", state="running", expanded=False)
|
|
@@ -805,7 +641,6 @@ def main_page():
|
|
| 805 |
st.session_state.timestamp = time.strftime("%Y%m%d-%H%M%S")
|
| 806 |
st.session_state.langues = "_".join([lang["iso-639-1"] for lang in st.session_state.selected_languages])
|
| 807 |
st.session_state.nom_fichier = f"reponse_audio_{st.session_state.langues}_{st.session_state.timestamp}.mp3"
|
| 808 |
-
|
| 809 |
|
| 810 |
st.audio(st.session_state.final_audio, format="audio/mp3", autoplay=st.session_state.autoplay_tts)
|
| 811 |
|
|
@@ -819,23 +654,12 @@ def main_page():
|
|
| 819 |
key=f"download_button_{st.session_state.langues}_{st.session_state.timestamp}",
|
| 820 |
)
|
| 821 |
|
| 822 |
-
# ##
|
| 823 |
audio_status.update(label=f"{get_translation('concatenation_audio_terminee')}", state="complete", expanded=True)
|
| 824 |
except Exception as e:
|
| 825 |
st.error(f"{get_translation('erreur_concatenation_audio')} : {str(e)}")
|
| 826 |
|
| 827 |
-
# ##
|
| 828 |
audio_status.update(label=f"{get_translation('erreur_concatenation_audio')} : {str(e)}", state="error", expanded=True)
|
| 829 |
|
| 830 |
-
#clear_inputs_garbages()
|
| 831 |
-
# Interface utilisateur pour l'enregistrement audio
|
| 832 |
-
# st.write(f"🗣️ {get_translation('enregistrez_message')}")
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
|
| 840 |
|
| 841 |
def clear_inputs_garbages(sessions_state_list: Optional[list] =
|
|
|
|
| 33 |
from core.text_to_speech import openai_tts
|
| 34 |
from core.DetectLanguage import detect_language
|
| 35 |
from core.speech_to_text import huggingface_endpoints_stt
|
| 36 |
+
from core.speech_to_text import transcribe_audio
|
| 37 |
+
from core.audio_files import concatenate_audio_files
|
| 38 |
+
from core.audio_files import split_audio
|
| 39 |
|
| 40 |
# Au début du fichier, après les imports
|
| 41 |
st.set_page_config(
|
|
|
|
| 70 |
st.error(f"Une erreur s'est produite lors de la conversion texte-parole : {e}")
|
| 71 |
return None, None
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
def process_message(
|
| 75 |
message: str,
|
|
|
|
| 108 |
st.error(f"Une erreur s'est produite lors de la génération de la réponse : {e}")
|
| 109 |
return ""
|
| 110 |
|
|
|
|
| 111 |
class GlobalSystemPrompts:
|
| 112 |
"""Class to store global system prompts."""
|
| 113 |
|
|
|
|
| 173 |
"Vietnamese": "🇻🇳", "Welsh": "🏴"
|
| 174 |
}
|
| 175 |
|
|
|
|
| 176 |
def convert_iso6391_to_language_name(language_code: str,
|
| 177 |
filter_mode=True) -> str:
|
| 178 |
"""
|
|
|
|
| 284 |
return system_prompt, operation_prompt
|
| 285 |
return "", ""
|
| 286 |
|
|
|
|
|
|
|
|
|
|
| 287 |
@st.dialog("Settings")
|
| 288 |
def tts_settings(name__tts_voice,
|
| 289 |
state__tts_with_text,
|
|
|
|
| 318 |
#st.session_state.
|
| 319 |
st.rerun()
|
| 320 |
|
|
|
|
| 321 |
@st.fragment
|
| 322 |
def recorder_released():
|
| 323 |
if "rec_widget" in st.session_state:
|
|
|
|
| 531 |
icon="ℹ️"):
|
| 532 |
st.subheader(f"version: {__version__}")
|
| 533 |
st.info(get_translation("info_app"))
|
|
|
|
| 534 |
|
| 535 |
with st.expander(f"{get_translation('selection_langue')}",
|
| 536 |
expanded=True,
|
| 537 |
icon="🌐"):
|
| 538 |
# Conteneur pour la sélection de langue
|
|
|
|
| 539 |
# Sélection multiple des langues de destination
|
| 540 |
st.multiselect(
|
| 541 |
label=get_translation("langues_destination"),
|
|
|
|
| 555 |
)
|
| 556 |
|
| 557 |
st.experimental_audio_input("Record a voice message",on_change=recorder_released, key="rec_widget")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 558 |
|
| 559 |
if st.session_state.user_input:
|
| 560 |
|
|
|
|
| 597 |
st.error("Erreur : Les prompts système ou d'opération sont vides.")
|
| 598 |
raise ValueError("Les prompts système ou d'opération ne peuvent pas être vides.")
|
| 599 |
|
|
|
|
| 600 |
with st.status(f'({target_language_name}) - {get_translation("traduction_en_cours")}', expanded=True) as response_status:
|
| 601 |
with st.chat_message("assistant", avatar="👻"):
|
| 602 |
message_placeholder = st.empty()
|
|
|
|
| 606 |
st.session_state.system_prompt
|
| 607 |
)
|
| 608 |
|
|
|
|
| 609 |
response_status.update(label=f'({target_language_name}) - {get_translation("traduction_en_cours")}', state="running", expanded=True)
|
| 610 |
for response_chunk in st.session_state.response_generator:
|
| 611 |
message_placeholder.markdown(response_chunk)
|
|
|
|
| 625 |
else:
|
| 626 |
response_status.update(label=f'({target_language_name}) - {get_translation("erreur_synthese_vocale")}', state="error", expanded=False)
|
| 627 |
|
|
|
|
| 628 |
else:
|
| 629 |
response_status.update(label=f'({target_language_name}) - {get_translation("traduction_terminee")}', state="complete", expanded=False)
|
| 630 |
else:
|
| 631 |
response_status.update(label=f'({target_language_name}) - {get_translation("erreur_traduction")}', state="error", expanded=False)
|
| 632 |
|
|
|
|
| 633 |
if st.session_state.audio_list:
|
| 634 |
with st.status(f"{get_translation('concatenation_audio_en_cours')}", expanded=False) as audio_status:
|
| 635 |
audio_status.update(label=f"{get_translation('concatenation_audio_en_cours')}", state="running", expanded=False)
|
|
|
|
| 641 |
st.session_state.timestamp = time.strftime("%Y%m%d-%H%M%S")
|
| 642 |
st.session_state.langues = "_".join([lang["iso-639-1"] for lang in st.session_state.selected_languages])
|
| 643 |
st.session_state.nom_fichier = f"reponse_audio_{st.session_state.langues}_{st.session_state.timestamp}.mp3"
|
|
|
|
| 644 |
|
| 645 |
st.audio(st.session_state.final_audio, format="audio/mp3", autoplay=st.session_state.autoplay_tts)
|
| 646 |
|
|
|
|
| 654 |
key=f"download_button_{st.session_state.langues}_{st.session_state.timestamp}",
|
| 655 |
)
|
| 656 |
|
|
|
|
| 657 |
audio_status.update(label=f"{get_translation('concatenation_audio_terminee')}", state="complete", expanded=True)
|
| 658 |
except Exception as e:
|
| 659 |
st.error(f"{get_translation('erreur_concatenation_audio')} : {str(e)}")
|
| 660 |
|
|
|
|
| 661 |
audio_status.update(label=f"{get_translation('erreur_concatenation_audio')} : {str(e)}", state="error", expanded=True)
|
| 662 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 663 |
|
| 664 |
|
| 665 |
def clear_inputs_garbages(sessions_state_list: Optional[list] =
|