Woziii commited on
Commit
edf2a53
·
verified ·
1 Parent(s): 78dc1fd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -171
app.py CHANGED
@@ -5,181 +5,110 @@ import os
5
  import time
6
  import torch
7
 
8
-
9
- # Initialisation du modèle TTS avec GPU désactivé
10
  tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2", gpu=False)
11
 
12
- # Répertoire de sortie pour tous les fichiers audio
13
- output_folder = "output_audio"
14
- os.makedirs(output_folder, exist_ok=True)
15
-
16
- # Fonction pour générer un fichier audio à partir d'une section
17
- def generate_section_audio(project_name, section_name, text, speaker):
18
- try:
19
- project_path = os.path.join(output_folder, project_name)
20
- os.makedirs(project_path, exist_ok=True)
21
- file_name = f"{section_name}.wav"
22
- output_path = os.path.join(project_path, file_name)
23
-
24
- speaker_wav_paths = [os.path.join("examples", f) for f in os.listdir("examples") if f.startswith(speaker) and f.endswith(".wav")]
25
- if not speaker_wav_paths:
26
- raise ValueError(f"Aucun fichier audio trouvé pour le speaker : {speaker}")
27
-
28
- tts.tts_to_file(text=text, file_path=output_path, speaker_wav=speaker_wav_paths, language="fr")
29
- return output_path
30
- except Exception as e:
31
- return str(e)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  # Interface Gradio
34
  with gr.Blocks() as demo:
35
- current_step = gr.State(1)
36
- project_info = gr.State({})
37
- sections = gr.State([])
38
-
39
- # Étape 1 : Création du Projet
40
- with gr.Group() as step1:
41
- gr.Markdown("## 🛠️ Étape 1 : Création du Projet")
42
- gr.Markdown("**Définissez les informations générales pour votre projet de synthèse vocale.**")
43
- project_name = gr.Textbox(label="Nom du Projet 📂", placeholder="Exemple : Capsule_Video_PLU")
44
- gr.Markdown("Le nom du projet sera utilisé pour organiser les fichiers dans un dossier dédié.")
45
- speaker = gr.Dropdown(label="Voix 🎙️", choices=["Margaux"], value="Margaux")
46
- gr.Markdown("Choisissez la voix souhaitée pour générer vos fichiers audio. Plus de voix seront ajoutées prochainement.")
47
  agree = gr.Checkbox(label="✅ J'accepte les conditions d'utilisation")
48
- gr.Markdown("Vous devez accepter les conditions d'utilisation pour continuer.")
49
- next_btn_1 = gr.Button("Créer le Projet ➡️")
50
-
51
- # Étape 2 : Gestion des Sections
52
- with gr.Group(visible=False) as step2:
53
- gr.Markdown("## ✍️ Étape 2 : Ajoutez vos Sections")
54
- gr.Markdown("""
55
- **Divisez votre texte en plusieurs sections pour une meilleure qualité audio.**
56
- Chaque section correspond à une partie de votre script. Par exemple, une introduction, une explication, ou une conclusion.
57
- Donnez un nom unique à chaque section et saisissez le texte correspondant.
58
- """)
59
-
60
- section_inputs = []
61
-
62
- def add_section(sections):
63
- section_name_input = gr.Textbox(label=f"Nom de la Section 🏷️", placeholder="Exemple : Introduction")
64
- section_text_input = gr.TextArea(label=f"Texte de la Section ✏️", placeholder="Écrivez ici le texte à convertir en voix off.")
65
- section_inputs.append((section_name_input, section_text_input))
66
- sections.append({"name": "", "text": ""})
67
- return sections
68
-
69
- def remove_section(sections):
70
- if sections:
71
- sections.pop()
72
- section_inputs.pop()
73
- return sections
74
-
75
- add_section_btn = gr.Button("Ajouter une Section ➕")
76
- remove_section_btn = gr.Button("Supprimer une Section ➖")
77
-
78
- add_section_btn.click(add_section, inputs=[sections], outputs=[sections])
79
- remove_section_btn.click(remove_section, inputs=[sections], outputs=[sections])
80
-
81
- next_btn_2 = gr.Button("Valider les Sections ➡️")
82
- prev_btn_2 = gr.Button("⬅️ Retour")
83
-
84
- # Étape 3 : Validation des Sections
85
- with gr.Group(visible=False) as step3:
86
- gr.Markdown("## 🎧 Étape 3 : Validation des Sections")
87
- gr.Markdown("""
88
- **Vérifiez vos sections avant de lancer la génération des audios.**
89
- Assurez-vous que chaque section a un nom unique et que les textes sont complets.
90
- Cliquez sur Générer les Audios pour commencer.
91
- """)
92
-
93
- generate_btn = gr.Button("Générer les Audios ▶️")
94
- prev_btn_3 = gr.Button("⬅️ Retour")
95
-
96
- # Étape 4 : Génération des Audios
97
- with gr.Group(visible=False) as step4:
98
- gr.Markdown("## 🎧 Étape 4 : Génération des Audios")
99
-
100
- def generate_audios(project_info, sections):
101
- outputs = []
102
- for i, (name_input, text_input) in enumerate(section_inputs):
103
- name = name_input.value
104
- text = text_input.value
105
- audio_path = generate_section_audio(
106
- project_info["name"],
107
- name,
108
- text,
109
- project_info["voice"]
110
- )
111
- outputs.append(gr.Audio(value=audio_path))
112
- return outputs
113
-
114
- audio_outputs_container = gr.Column()
115
-
116
- save_project_btn = gr.Button("Sauvegarder le Projet ✅")
117
-
118
- # Fonctions de navigation et de traitement
119
- def next_step(step):
120
- return step + 1
121
-
122
- def prev_step(step):
123
- return max(1, step - 1)
124
-
125
- def update_visibility(step):
126
- return {
127
- step1: gr.update(visible=step == 1),
128
- step2: gr.update(visible=step == 2),
129
- step3: gr.update(visible=step == 3),
130
- step4: gr.update(visible=step == 4)
131
- }
132
-
133
- def create_project(name, voice, terms):
134
- if not name or not terms:
135
- return "Veuillez remplir tous les champs et accepter les conditions.", None
136
- return f"Projet '{name}' créé avec succès !", {"name": name, "voice": voice}, 2
137
-
138
- # Événements
139
- next_btn_1.click(
140
- create_project,
141
- inputs=[project_name, speaker, agree],
142
- outputs=[None, project_info, current_step]
143
- ).then(
144
- update_visibility,
145
- inputs=[current_step],
146
- outputs=[step1, step2, step3, step4]
147
- )
148
-
149
- next_btn_2.click(
150
- lambda x: x + 1,
151
- inputs=[current_step],
152
- outputs=[current_step]
153
- ).then(
154
- update_visibility,
155
- inputs=[current_step],
156
- outputs=[step1, step2, step3, step4]
157
- )
158
-
159
- prev_btn_2.click(
160
- prev_step,
161
- inputs=[current_step],
162
- outputs=[current_step]
163
- ).then(
164
- update_visibility,
165
- inputs=[current_step],
166
- outputs=[step1, step2, step3, step4]
167
- )
168
-
169
- generate_btn.click(
170
- generate_audios,
171
- inputs=[project_info, sections],
172
- outputs=audio_outputs_container
173
- )
174
-
175
- prev_btn_3.click(
176
- prev_step,
177
- inputs=[current_step],
178
- outputs=[current_step]
179
- ).then(
180
- update_visibility,
181
- inputs=[current_step],
182
- outputs=[step1, step2, step3, step4]
183
- )
184
-
185
  demo.launch()
 
5
  import time
6
  import torch
7
 
8
+ # Initialisation du modèle TTS
 
9
  tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2", gpu=False)
10
 
11
+ # Dossier de base pour les projets
12
+ base_output_folder = "projects"
13
+ os.makedirs(base_output_folder, exist_ok=True)
14
+
15
+ # Fonction pour créer ou charger un projet
16
+ def create_or_load_project(project_name, speaker, agree):
17
+ if not agree:
18
+ raise gr.Error("❗ Veuillez accepter les conditions d'utilisation.")
19
+
20
+ project_folder = os.path.join(base_output_folder, project_name)
21
+ os.makedirs(project_folder, exist_ok=True)
22
+
23
+ project_data = {
24
+ "name": project_name,
25
+ "speaker": speaker,
26
+ "sections": []
27
+ }
28
+
29
+ project_file = os.path.join(project_folder, "project_data.json")
30
+ if os.path.exists(project_file):
31
+ with open(project_file, "r") as f:
32
+ project_data = json.load(f)
33
+ else:
34
+ with open(project_file, "w") as f:
35
+ json.dump(project_data, f)
36
+
37
+ return project_data
38
+
39
+ # Fonction pour ajouter ou mettre à jour une section
40
+ def update_section(project_data, section_name, section_text):
41
+ for section in project_data["sections"]:
42
+ if section["name"] == section_name:
43
+ section["text"] = section_text
44
+ return project_data
45
+
46
+ project_data["sections"].append({
47
+ "name": section_name,
48
+ "text": section_text,
49
+ "audio_path": None
50
+ })
51
+ return project_data
52
+
53
+ # Fonction pour générer l'audio d'une section
54
+ def generate_section_audio(project_data, section_name):
55
+ project_folder = os.path.join(base_output_folder, project_data["name"])
56
+ for section in project_data["sections"]:
57
+ if section["name"] == section_name:
58
+ output_path = os.path.join(project_folder, f"{section_name}.wav")
59
+ tts.tts_to_file(
60
+ text=section["text"],
61
+ file_path=output_path,
62
+ speaker_wav=[os.path.join("examples", f) for f in os.listdir("examples") if f.startswith(project_data["speaker"]) and f.endswith(".wav")],
63
+ language="fr"
64
+ )
65
+ section["audio_path"] = output_path
66
+ return project_data, output_path
67
+
68
+ raise gr.Error(f"❌ Section '{section_name}' non trouvée.")
69
 
70
  # Interface Gradio
71
  with gr.Blocks() as demo:
72
+ gr.Markdown("# 🎙️ Projet Margaux TTS")
73
+
74
+ # État du projet
75
+ project_state = gr.State(value={})
76
+
77
+ # Étape 1: Création ou chargement du projet
78
+ with gr.Tab("🆕 Création/Chargement du Projet"):
79
+ project_name = gr.Textbox(label="📝 Nom du projet")
80
+ speaker = gr.Dropdown(label="🔊 Voix", choices=["Margaux"], value="Margaux")
 
 
 
81
  agree = gr.Checkbox(label="✅ J'accepte les conditions d'utilisation")
82
+ create_btn = gr.Button("🚀 Créer/Charger le Projet")
83
+
84
+ # Étape 2: Gestion des sections
85
+ with gr.Tab("📋 Gestion des Sections"):
86
+ sections_list = gr.List(label="📜 Sections du projet")
87
+ section_name = gr.Textbox(label="📝 Nom de la section")
88
+ section_text = gr.Textbox(label="✍️ Texte de la section", lines=5)
89
+ add_section_btn = gr.Button("➕ Ajouter/Mettre à jour la section")
90
+ generate_section_btn = gr.Button("🎤 Générer l'audio de la section")
91
+ audio_output = gr.Audio(label="🔊 Audio généré")
92
+
93
+ # Fonctions de callback
94
+ def load_project(project_name, speaker, agree):
95
+ project_data = create_or_load_project(project_name, speaker, agree)
96
+ sections = [section["name"] for section in project_data["sections"]]
97
+ return project_data, gr.List.update(value=sections)
98
+
99
+ def add_section(project_data, section_name, section_text):
100
+ updated_project = update_section(project_data, section_name, section_text)
101
+ sections = [section["name"] for section in updated_project["sections"]]
102
+ return updated_project, gr.List.update(value=sections)
103
+
104
+ def generate_audio(project_data, section_name):
105
+ updated_project, audio_path = generate_section_audio(project_data, section_name)
106
+ return updated_project, audio_path
107
+
108
+ # Connexion des événements
109
+ create_btn.click(load_project, inputs=[project_name, speaker, agree], outputs=[project_state, sections_list])
110
+ add_section_btn.click(add_section, inputs=[project_state, section_name, section_text], outputs=[project_state, sections_list])
111
+ generate_section_btn.click(generate_audio, inputs=[project_state, section_name], outputs=[project_state, audio_output])
112
+
113
+ # Lancement de l'interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  demo.launch()