Arvador237 commited on
Commit
131831d
·
verified ·
1 Parent(s): b39c930

Update chatbot.py

Browse files
Files changed (1) hide show
  1. chatbot.py +94 -47
chatbot.py CHANGED
@@ -1,49 +1,96 @@
1
- from langchain.chains import LLMChain
2
- from langchain.prompts import PromptTemplate
3
- from langchain.llms import HuggingFaceHub
4
- import os
5
-
6
- class InflationChatbot:
7
- def __init__(self):
8
- # Configuration de l'API Hugging Face
9
- self.hf_api_key = os.getenv("jan_nano_streamlit")
10
-
11
- # Initialisation du modèle de langage
12
- self.llm = HuggingFaceHub(
13
- repo_id="google/flan-t5-xxl",
14
- model_kwargs={"temperature": 0.5, "max_length": 512}
15
- )
16
-
17
- # Template de prompt
18
- self.prompt_template = PromptTemplate(
19
- input_variables=["context", "question"],
20
- template="""
21
- Vous êtes un expert économique spécialisé dans la zone BEAC (Cameroun, Gabon, Tchad, Congo, Guinée équatoriale, Centrafrique).
22
- Vous devez répondre aux questions en vous basant sur le contexte fourni et vos connaissances économiques.
23
-
24
- Contexte:
25
- - Pays: {context.get('country', 'non spécifié')}
26
- - Modèle utilisé: {context.get('model', 'non spécifié')}
27
- - Métriques du modèle: {context.get('metrics', 'non disponibles')}
28
-
29
- Question: {question}
30
-
31
- Réponse détaillée:
32
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  )
34
-
35
- # Initialisation de la chaîne
36
- self.chain = LLMChain(llm=self.llm, prompt=self.prompt_template)
37
-
38
- def ask_question(self, question, country=None, model=None, metrics=None):
39
- # Préparation du contexte
40
- context = {
41
- "country": country,
42
- "model": model,
43
- "metrics": str(metrics) if metrics else None
 
 
 
 
 
44
  }
45
-
46
- # Génération de la réponse
47
- response = self.chain.run(context=context, question=question)
48
-
49
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import cohere
3
+ import requests
4
+ from io import BytesIO
5
+ import base64
6
+
7
+
8
+ # Configuration de la clé API
9
+ COHERE_API_KEY = "moZJbgxiW9cW8Wqo0ecce0pa84uf3eT6F2oL1whB" # Remplace par ta clé API
10
+ co = cohere.Client(COHERE_API_KEY)
11
+
12
+ # Initialisation du contexte de chat
13
+ if "chat_history" not in st.session_state:
14
+ st.session_state.chat_history = []
15
+
16
+ st.set_page_config(page_title="Chatbot Cohere", page_icon="💬")
17
+ st.title("💬 Chat avec Cohere (Command R+)")
18
+
19
+ # Boîte d'entrée utilisateur
20
+ user_input = st.chat_input("Pose ta question...")
21
+
22
+ # Affichage de l'historique visuel
23
+ for msg in st.session_state.chat_history:
24
+ with st.chat_message("user" if msg["role"] == "USER" else "assistant"):
25
+ st.markdown(msg["text"])
26
+
27
+ # Quand l'utilisateur envoie un message
28
+ if user_input:
29
+ with st.chat_message("user"):
30
+ st.markdown(user_input)
31
+
32
+ st.session_state.chat_history.append({"role": "USER", "text": user_input})
33
+
34
+ # Création de l'historique pour Cohere
35
+ cohere_history = [
36
+ {"role": msg["role"], "message": msg["text"]}
37
+ for msg in st.session_state.chat_history
38
+ if msg["role"] in ["USER", "CHATBOT"]
39
+ ]
40
+
41
+ try:
42
+ response = co.chat(
43
+ message=user_input,
44
+ chat_history=cohere_history,
45
+ model="command-r-plus",
46
+ temperature=0.7,
47
+ max_tokens=300
48
  )
49
+
50
+ reply = response.text.strip()
51
+
52
+ # Étape 1 : Résumer la réponse avec Cohere
53
+ summary_prompt = f"Résume en une seule phrase simple et claire en français ce texte : {reply}"
54
+ summary_response = co.generate(prompt=summary_prompt, max_tokens=100)
55
+ summary = summary_response.generations[0].text.strip()
56
+
57
+ # Étape 2 : Appel ElevenLabs (TTS)
58
+ ELEVEN_API_KEY = "sk_6c5472c80964f88fcdc9d9c189db749143ae1a0d2c8f26f3" # Remplace par ta clé API ElevenLabs
59
+ voice_id = "TxGEqnHWrfWFTfGW9XjX" # Voix française (Antoine)
60
+
61
+ headers = {
62
+ "xi-api-key": ELEVEN_API_KEY,
63
+ "Content-Type": "application/json"
64
  }
65
+
66
+ data = {
67
+ "text": summary,
68
+ "model_id": "eleven_multilingual_v2",
69
+ "voice_settings": {
70
+ "stability": 0.5,
71
+ "similarity_boost": 0.75
72
+ }
73
+ }
74
+
75
+ response_audio = requests.post(
76
+ f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}",
77
+ headers=headers,
78
+ json=data
79
+ )
80
+
81
+ # Affichage de la réponse texte + audio
82
+ with st.chat_message("assistant"):
83
+ st.markdown(reply)
84
+ st.markdown(f"🔊 **Résumé vocal :** _{summary}_")
85
+
86
+ if response_audio.status_code == 200:
87
+ audio_bytes = BytesIO(response_audio.content)
88
+ st.audio(audio_bytes, format="audio/mp3")
89
+ else:
90
+ st.warning("Erreur dans la synthèse vocale (ElevenLabs).")
91
+
92
+ st.session_state.chat_history.append({"role": "CHATBOT", "text": reply})
93
+
94
+ except Exception as e:
95
+ st.error(f"Erreur : {str(e)}")
96
+