Spaces:
Running
Running
File size: 2,171 Bytes
c623bae 131831d c623bae 131831d c623bae 131831d c623bae 131831d 7cb9d80 131831d c623bae 131831d c623bae 131831d c623bae |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# 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
|