Spaces:
Running
Running
# chatbot.py | |
import cohere | |
import requests | |
from io import BytesIO | |
class InflationChatbot: | |
def __init__(self, cohere_api_key, eleven_api_key): | |
self.co = cohere.Client(cohere_api_key) | |
self.eleven_api_key = eleven_api_key | |
self.voice_id = "TxGEqnHWrfWFTfGW9XjX" # Antoine (voix française) | |
def ask(self, user_input, chat_history=[]): | |
try: | |
# Reformatage de l’historique | |
cohere_history = [ | |
{"role": msg["role"], "message": msg["text"]} | |
for msg in chat_history | |
if msg["role"] in ["USER", "CHATBOT"] | |
] | |
# Réponse du modèle Cohere | |
response = self.co.chat( | |
message=user_input, | |
chat_history=cohere_history, | |
model="command-r-plus", | |
temperature=0.7, | |
max_tokens=300 | |
) | |
reply = response.text.strip() | |
# Résumé | |
summary_prompt = f"Résume en une seule phrase simple et claire en français ce texte : {reply}" | |
summary_response = self.co.generate(prompt=summary_prompt, max_tokens=100) | |
summary = summary_response.generations[0].text.strip() | |
# Synthèse vocale via ElevenLabs | |
audio = self.text_to_speech(summary) | |
return { | |
"reply": reply, | |
"summary": summary, | |
"audio": audio | |
} | |
except Exception as e: | |
return {"error": str(e)} | |
def text_to_speech(self, text): | |
headers = { | |
"xi-api-key": self.eleven_api_key, | |
"Content-Type": "application/json" | |
} | |
data = { | |
"text": text, | |
"model_id": "eleven_multilingual_v2", | |
"voice_settings": { | |
"stability": 0.5, | |
"similarity_boost": 0.75 | |
} | |
} | |
response = requests.post( | |
f"https://api.elevenlabs.io/v1/text-to-speech/{self.voice_id}", | |
headers=headers, | |
json=data | |
) | |
return BytesIO(response.content) if response.status_code == 200 else None | |