wahdia commited on
Commit
16d9792
·
verified ·
1 Parent(s): 4839510

Create app1.py

Browse files
Files changed (1) hide show
  1. app1.py +292 -0
app1.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import transformers
3
+ import torch
4
+ from transformers import pipeline
5
+ from datetime import datetime
6
+
7
+ # Configuration des modèles
8
+ def load_models():
9
+ # Modèle médical
10
+ medical_pipe = transformers.pipeline(
11
+ "text-generation",
12
+ model="ContactDoctor/Bio-Medical-Llama-3-2-1B-CoT-012025",
13
+ torch_dtype=torch.bfloat16,
14
+ device_map="auto",
15
+ )
16
+
17
+ # Modèle de traduction
18
+ translator = pipeline("translation", model="facebook/nllb-200-distilled-600M")
19
+
20
+ return medical_pipe, translator
21
+
22
+ medical_pipe, translator = load_models()
23
+
24
+ # Message système pour guider le chatbot
25
+ system_message = {
26
+ "role": "system",
27
+ "content": (
28
+ "You are a helpful, respectful, and knowledgeable medical assistant developed by the AI team at AfriAI Solutions, Senegal. "
29
+ "Provide brief, clear definitions when answering medical questions. After giving a concise response, ask the user if they would like more information about specific aspects such as symptoms, causes, or treatments. "
30
+ "If the user declines further information, respond briefly and ask if there's anything else they need help with."
31
+ "Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. "
32
+ "Ensure your responses are socially unbiased and positive. If a question does not make sense, explain why instead of providing incorrect information. "
33
+ "If you don't know the answer to a question, avoid sharing false information. "
34
+ "Encourage users to consult healthcare professionals for accurate diagnoses and personalized advice."
35
+ ),
36
+ }
37
+
38
+ max_history = 10 # Limite de l'historique de conversation
39
+
40
+ # Traduction français -> anglais
41
+ def translate_fr_to_en(text):
42
+ translated = translator(text, src_lang="fra_Latn", tgt_lang="eng_Latn")
43
+ return translated[0]['translation_text']
44
+
45
+ # Traduction anglais -> français
46
+ def translate_en_to_fr(text):
47
+ translated = translator(text, src_lang="eng_Latn", tgt_lang="fra_Latn")
48
+ return translated[0]['translation_text']
49
+
50
+ # Gestion des salutations et phrases de fermeture
51
+ def handle_special_phrases(user_input):
52
+ user_input_lower = user_input.lower()
53
+
54
+ # Salutations
55
+ greetings = ["bonjour", "salut", "hello", "hi", "coucou", "bonsoir"]
56
+ if any(greet in user_input_lower for greet in greetings):
57
+ now = datetime.now()
58
+ if 5 <= now.hour < 12:
59
+ return "Bonjour ! Je suis l'assistant médical AfriAI. Comment puis-je vous aider aujourd'hui ?"
60
+ elif 12 <= now.hour < 18:
61
+ return "Bon après-midi ! Je suis l'assistant médical AfriAI. En quoi puis-je vous aider ?"
62
+ else:
63
+ return "Bonsoir ! Je suis l'assistant médical AfriAI. Comment puis-je vous aider ce soir ?"
64
+
65
+ # Remerciements
66
+ thanks = ["merci", "thank you", "thanks", "je vous remercie"]
67
+ if any(thank in user_input_lower for thank in thanks):
68
+ return "Je vous en prie ! N'hésitez pas si vous avez d'autres questions médicales."
69
+
70
+ # Fermeture
71
+ goodbyes = ["au revoir", "bye", "goodbye", "à plus", "à bientôt"]
72
+ if any(goodbye in user_input_lower for goodbye in goodbyes):
73
+ return "Au revoir ! Prenez soin de vous. N'hésitez pas à revenir si vous avez d'autres questions."
74
+
75
+ return None
76
+
77
+ # Génération de réponse médicale
78
+ def generate_medical_response(messages):
79
+ # Création du prompt
80
+ prompt = medical_pipe.tokenizer.apply_chat_template(
81
+ messages, tokenize=False, add_generation_prompt=False
82
+ )
83
+
84
+ # Tokens d'arrêt
85
+ stop_tokens = [
86
+ medical_pipe.tokenizer.eos_token_id,
87
+ medical_pipe.tokenizer.convert_tokens_to_ids("<|eot_id|>"),
88
+ ]
89
+
90
+ # Génération de la réponse
91
+ outputs = medical_pipe(
92
+ prompt,
93
+ max_new_tokens=512,
94
+ eos_token_id=stop_tokens,
95
+ do_sample=True,
96
+ temperature=0.4,
97
+ top_k=150,
98
+ top_p=0.75,
99
+ )
100
+
101
+ return outputs[0]["generated_text"][len(prompt):].strip()
102
+
103
+ # Fonction principale du chatbot
104
+ def chat_with_medical_bot(user_input, chat_history):
105
+ # Vérifier les phrases spéciales (salutations, remerciements, etc.)
106
+ special_response = handle_special_phrases(user_input)
107
+ if special_response:
108
+ chat_history.append((user_input, special_response))
109
+ return "", chat_history
110
+
111
+ # Traduire l'entrée utilisateur en anglais
112
+ try:
113
+ user_input_en = translate_fr_to_en(user_input)
114
+ except:
115
+ user_input_en = user_input # En cas d'échec, utiliser l'original
116
+
117
+ # Initialiser l'historique des messages si vide
118
+ if not hasattr(chat_with_medical_bot, "messages"):
119
+ chat_with_medical_bot.messages = [system_message]
120
+
121
+ # Ajouter le message utilisateur
122
+ chat_with_medical_bot.messages.append({"role": "user", "content": user_input_en})
123
+
124
+ # Limiter l'historique
125
+ if len(chat_with_medical_bot.messages) > max_history * 2:
126
+ chat_with_medical_bot.messages = [system_message] + chat_with_medical_bot.messages[-max_history * 2:]
127
+
128
+ # Générer la réponse médicale
129
+ try:
130
+ response_en = generate_medical_response(chat_with_medical_bot.messages)
131
+
132
+ # Traduire la réponse en français
133
+ try:
134
+ response_fr = translate_en_to_fr(response_en)
135
+ except:
136
+ response_fr = response_en # En cas d'échec, utiliser l'original
137
+ except Exception as e:
138
+ response_fr = f"Désolé, une erreur s'est produite : {str(e)}"
139
+
140
+ # Ajouter la réponse à l'historique des messages
141
+ chat_with_medical_bot.messages.append({"role": "assistant", "content": response_en})
142
+
143
+ # Ajouter à l'historique de chat Gradio
144
+ chat_history.append((user_input, response_fr))
145
+
146
+ return "", chat_history
147
+
148
+ # CSS personnalisé pour le thème AfriAI Solutions
149
+ custom_css = """
150
+ :root {
151
+ --primary-color: #2C5F2D;
152
+ --secondary-color: #97BC62;
153
+ --accent-color: #E0E0E0;
154
+ --text-color: #333333;
155
+ }
156
+
157
+ .gradio-container {
158
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
159
+ }
160
+
161
+ #chatbot {
162
+ background-color: white;
163
+ border-radius: 10px;
164
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
165
+ height: 500px;
166
+ }
167
+
168
+ .user, .bot {
169
+ padding: 12px 16px;
170
+ border-radius: 18px;
171
+ margin: 8px 0;
172
+ line-height: 1.4;
173
+ max-width: 80%;
174
+ }
175
+
176
+ .user {
177
+ background-color: var(--secondary-color);
178
+ color: white;
179
+ margin-left: auto;
180
+ border-bottom-right-radius: 4px;
181
+ }
182
+
183
+ .bot {
184
+ background-color: var(--accent-color);
185
+ color: var(--text-color);
186
+ margin-right: auto;
187
+ border-bottom-left-radius: 4px;
188
+ }
189
+
190
+ #header {
191
+ background-color: var(--primary-color);
192
+ color: white;
193
+ padding: 20px;
194
+ border-radius: 10px 10px 0 0;
195
+ text-align: center;
196
+ }
197
+
198
+ #header img {
199
+ max-width: 150px;
200
+ margin-bottom: 10px;
201
+ }
202
+
203
+ #header h1 {
204
+ margin: 0;
205
+ font-size: 24px;
206
+ }
207
+
208
+ #header p {
209
+ margin: 5px 0 0;
210
+ font-size: 16px;
211
+ opacity: 0.9;
212
+ }
213
+
214
+ footer {
215
+ text-align: center;
216
+ padding: 10px;
217
+ font-size: 12px;
218
+ color: var(--text-color);
219
+ opacity: 0.7;
220
+ }
221
+
222
+ #component-0 {
223
+ border-radius: 0 0 10px 10px !important;
224
+ }
225
+
226
+ #component-1 {
227
+ border-radius: 0 0 10px 10px !important;
228
+ }
229
+ """
230
+
231
+ # Interface Gradio
232
+ with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
233
+ # En-tête avec logo et description
234
+ with gr.Column(elem_id="header"):
235
+ gr.Markdown("""
236
+ <div style="text-align: center;">
237
+ <img src="https://via.placeholder.com/150x50/2C5F2D/FFFFFF?text=AfriAI+Solutions" alt="AfriAI Solutions Logo">
238
+ <h1>Assistant Médical AfriAI</h1>
239
+ <p>Transformez vos questions médicales en solutions claires et précises</p>
240
+ </div>
241
+ """)
242
+
243
+ # Zone de chat
244
+ chatbot = gr.Chatbot(
245
+ label="Conversation",
246
+ elem_id="chatbot",
247
+ bubble_full_width=False,
248
+ avatar_images=(
249
+ "https://via.placeholder.com/40/97BC62/FFFFFF?text=VOUS",
250
+ "https://via.placeholder.com/40/2C5F2D/FFFFFF?text=AI"
251
+ )
252
+ )
253
+
254
+ # Zone de saisie
255
+ msg = gr.Textbox(
256
+ label="Posez votre question médicale en français",
257
+ placeholder="Bonjour, quels sont les symptômes du diabète ?",
258
+ container=False
259
+ )
260
+
261
+ # Boutons
262
+ with gr.Row():
263
+ clear = gr.ClearButton([msg, chatbot], value="Effacer la conversation")
264
+ submit = gr.Button("Envoyer", variant="primary")
265
+
266
+ # Événements
267
+ msg.submit(chat_with_medical_bot, [msg, chatbot], [msg, chatbot])
268
+ submit.click(chat_with_medical_bot, [msg, chatbot], [msg, chatbot])
269
+
270
+ # Exemples
271
+ gr.Examples(
272
+ examples=[
273
+ "Bonjour, quels sont les symptômes du diabète ?",
274
+ "Comment traiter une migraine ?",
275
+ "Expliquez-moi ce qu'est l'hypertension artérielle",
276
+ "Quelles sont les causes de la toux persistante ?"
277
+ ],
278
+ inputs=msg,
279
+ label="Exemples de questions"
280
+ )
281
+
282
+ # Pied de page
283
+ gr.Markdown("""
284
+ <div style="text-align: center; font-size: 12px; color: #666; margin-top: 20px;">
285
+ <p>Cet assistant médical ne remplace pas un avis médical professionnel. Consultez toujours un médecin pour des problèmes de santé sérieux.</p>
286
+ <p>© 2024 AfriAI Solutions - Sénégal</p>
287
+ </div>
288
+ """, elem_id="footer")
289
+
290
+ # Démarrer l'application
291
+ if __name__ == "__main__":
292
+ demo.launch()