Sad44587 commited on
Commit
8e766a8
·
verified ·
1 Parent(s): e972a35

Update app.py

Browse files

Add: import gradio as gr
import requests
import asyncio
import edge_tts

# Fonction pour générer du texte avec PyBotChat API (simulée ici)
def generate_text(prompt):
# Simulation d'une génération de texte depuis Hugging Face (remplacer l'URL par une API réelle)
url = "https://huggingface.co/spaces/Sad44587/PyBotChat/resolve/main/app.py"

# Paramètres de la requête, ajuster selon le modèle spécifique
payload = {
"inputs": prompt,
"options": {"use_gpu": False}
}

response = requests.post(url, json=payload)

if response.status_code == 200:
response_data = response.json()
return response_data.get('generated_text', 'Désolé, je n\'ai pas pu générer de texte.')
else:
return "Erreur de génération du texte."

# Fonction pour générer la voix à partir du texte avec Edge TTS
async def generate_voice(text):
communicate = edge_tts.Communicate(text, voice="fr-FR-DeniseNeural", rate="0%")
await communicate.save("generated_audio.mp3")
return "generated_audio.mp3" # Retourne le chemin vers l'audio généré

# Fonction principale qui combine les deux processus
def generate_and_speak(prompt):
# Générer le texte avec PyBotChat API
generated_text = generate_text(prompt)

# Générer la voix à partir du texte généré
audio_path = asyncio.run(generate_voice(generated_text))

return generated_text, audio_path

# Interface Gradio
def create_interface():
with gr.Blocks() as demo:
gr.Markdown("### Chatbot avec génération vocale")

with gr.Row():
prompt_input = gr.Textbox(label="Entrez votre message", placeholder="Tapez ici...")
text_output = gr.Textbox(label="Réponse générée")
audio_output = gr.Audio(label="Réponse vocale")

prompt_input.submit(generate_and_speak, inputs=prompt_input, outputs=[text_output, audio_output])

return demo

# Lancer l'interface
if __name__ == "__main__":
demo = create_interface()
demo.launch()

Files changed (1) hide show
  1. app.py +48 -97
app.py CHANGED
@@ -1,107 +1,58 @@
1
  import gradio as gr
 
2
  import asyncio
3
- import tempfile
4
  import edge_tts
5
- from huggingface_hub import InferenceClient
6
 
7
- # -------------------------
8
- # === Fast Chat (Gemma) ===
9
- # -------------------------
10
- client_fast = InferenceClient("google/gemma-1.1-2b-it")
11
-
12
- def fast_chat(query):
13
- messages = [{
14
- "role": "user",
15
- "content": f"[SYSTEM] You are ASSISTANT who answers questions in a short and concise manner. [USER] {query}"
16
- }]
17
- response = ""
18
- for message in client_fast.chat_completion(messages, max_tokens=2048, stream=True):
19
- token = message.choices[0].delta.content
20
- response += token
21
- yield response
22
-
23
- # -----------------------------
24
- # === Critical Thinker Chat ===
25
- # -----------------------------
26
- client_critical = InferenceClient("mistralai/Mistral-Nemo-Instruct-2407")
27
-
28
- def critical_thinker(query):
29
- budget = 10
30
- prompt = f"""[INST] [SYSTEM] You are a French robot full of hope and enthusiasm for future projects...
31
- <QUERY> {query} [/INST] [ASSISTANT]"""
32
- stream = client_critical.text_generation(prompt, max_new_tokens=4096, stream=True, details=True, return_full_text=False)
33
- output = ""
34
- for response in stream:
35
- output += response.token.text
36
- return output
37
-
38
- # -----------------
39
- # === Edge TTS ====
40
- # -----------------
41
- async def get_voices():
42
- voices = await edge_tts.list_voices()
43
- return {f"{v['ShortName']} - {v['Locale']} ({v['Gender']})": v['ShortName'] for v in voices}
44
-
45
- async def text_to_speech(text, voice, rate, pitch):
46
- if not text.strip():
47
- return None, gr.Warning("Please enter text to convert.")
48
- if not voice:
49
- return None, gr.Warning("Please select a voice.")
50
 
51
- voice_short_name = voice.split(" - ")[0]
52
- rate_str = f"{rate:+d}%"
53
- pitch_str = f"{pitch:+d}Hz"
54
- communicate = edge_tts.Communicate(text, voice_short_name, rate=rate_str, pitch=pitch_str)
55
- with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
56
- tmp_path = tmp_file.name
57
- await communicate.save(tmp_path)
58
- return tmp_path, None
59
-
60
- def tts_interface(text, voice, rate, pitch):
61
- audio, warning = asyncio.run(text_to_speech(text, voice, rate, pitch))
62
- return audio, warning
63
-
64
- # -------------------------------
65
- # === Interface Gradio globale ==
66
- # -------------------------------
67
- async def main():
68
- voices = await get_voices()
69
-
70
- # Onglet 1 : Chat Rapide
71
- with gr.Blocks() as fast_tab:
72
- gr.Markdown("# 💬 Fast Chat")
73
- gr.Interface(fn=fast_chat, inputs=gr.Textbox(label="Your message"), outputs="text")
74
-
75
- # Onglet 2 : Chat Critique
76
- with gr.Blocks() as critical_tab:
77
- gr.Markdown("# 🤖 Critical Thinker")
78
- gr.Interface(fn=critical_thinker, inputs=gr.Textbox(label="Your question"), outputs="text")
 
79
 
80
- # Onglet 3 : TTS
81
- with gr.Blocks() as tts_tab:
82
- gr.Markdown("# 🔊 Text-to-Speech")
83
- gr.Interface(
84
- fn=tts_interface,
85
- inputs=[
86
- gr.Textbox(label="Text to Speak", lines=5),
87
- gr.Dropdown(choices=[""] + list(voices.keys()), label="Select Voice"),
88
- gr.Slider(minimum=-50, maximum=50, value=0, label="Rate (%)"),
89
- gr.Slider(minimum=-20, maximum=20, value=0, label="Pitch (Hz)")
90
- ],
91
- outputs=[
92
- gr.Audio(label="Generated Audio", type="filepath"),
93
- gr.Markdown(label="Warning", visible=False)
94
- ]
95
- )
96
 
97
- # Tabs Fusionnées
98
- app = gr.TabbedInterface(
99
- interface_list=[fast_tab, critical_tab, tts_tab],
100
- tab_names=["Fast Chat", "Critical Thinker", "TTS"]
101
- )
102
 
103
- app.queue()
104
- app.launch()
105
 
 
106
  if __name__ == "__main__":
107
- asyncio.run(main())
 
 
1
  import gradio as gr
2
+ import requests
3
  import asyncio
 
4
  import edge_tts
 
5
 
6
+ # Fonction pour générer du texte avec PyBotChat API (simulée ici)
7
+ def generate_text(prompt):
8
+ # Simulation d'une génération de texte depuis Hugging Face (remplacer l'URL par une API réelle)
9
+ url = "https://huggingface.co/spaces/Sad44587/PyBotChat/resolve/main/app.py"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
+ # Paramètres de la requête, ajuster selon le modèle spécifique
12
+ payload = {
13
+ "inputs": prompt,
14
+ "options": {"use_gpu": False}
15
+ }
16
+
17
+ response = requests.post(url, json=payload)
18
+
19
+ if response.status_code == 200:
20
+ response_data = response.json()
21
+ return response_data.get('generated_text', 'Désolé, je n\'ai pas pu générer de texte.')
22
+ else:
23
+ return "Erreur de génération du texte."
24
+
25
+ # Fonction pour générer la voix à partir du texte avec Edge TTS
26
+ async def generate_voice(text):
27
+ communicate = edge_tts.Communicate(text, voice="fr-FR-DeniseNeural", rate="0%")
28
+ await communicate.save("generated_audio.mp3")
29
+ return "generated_audio.mp3" # Retourne le chemin vers l'audio généré
30
+
31
+ # Fonction principale qui combine les deux processus
32
+ def generate_and_speak(prompt):
33
+ # Générer le texte avec PyBotChat API
34
+ generated_text = generate_text(prompt)
35
+
36
+ # Générer la voix à partir du texte généré
37
+ audio_path = asyncio.run(generate_voice(generated_text))
38
+
39
+ return generated_text, audio_path
40
 
41
+ # Interface Gradio
42
+ def create_interface():
43
+ with gr.Blocks() as demo:
44
+ gr.Markdown("### Chatbot avec génération vocale")
45
+
46
+ with gr.Row():
47
+ prompt_input = gr.Textbox(label="Entrez votre message", placeholder="Tapez ici...")
48
+ text_output = gr.Textbox(label="Réponse générée")
49
+ audio_output = gr.Audio(label="Réponse vocale")
 
 
 
 
 
 
 
50
 
51
+ prompt_input.submit(generate_and_speak, inputs=prompt_input, outputs=[text_output, audio_output])
 
 
 
 
52
 
53
+ return demo
 
54
 
55
+ # Lancer l'interface
56
  if __name__ == "__main__":
57
+ demo = create_interface()
58
+ demo.launch()