AfriAISolutions commited on
Commit
9982d17
·
verified ·
1 Parent(s): 5df52d3

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py.txt +129 -0
  2. requirements.txt +9 -0
app.py.txt ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ import transformers
4
+ import torch
5
+ from PIL import Image
6
+
7
+ import os
8
+ from huggingface_hub import login
9
+
10
+ # Get token from environment variable
11
+ hf_token = os.getenv("hf_token")
12
+ if hf_token is None:
13
+ raise ValueError("Please set HF_TOKEN environment variable with your Hugging Face token")
14
+
15
+ # Login with the token
16
+ login(token=hf_token)
17
+ # Chargement des modèles
18
+ translator = transformers.pipeline("translation", model="facebook/nllb-200-distilled-600M")
19
+ text_gen_pipeline = transformers.pipeline(
20
+ "text-generation",
21
+ # model = "ruslanmv/Medical-Llama3-v2",
22
+ model="ContactDoctor/Bio-Medical-Llama-3-2-1B-CoT-012025",
23
+ torch_dtype=torch.bfloat16,
24
+ device_map="auto"
25
+ )
26
+
27
+ # Message système initial
28
+ system_message = {
29
+ "role": "system",
30
+ "content": (
31
+ "You are a helpful, respectful, and knowledgeable medical assistant developed by the AI team at AfriAI Solutions, Senegal. "
32
+ "Provide brief, clear definitions when answering medical questions. After giving a concise response, ask the user if they would like more information about symptoms, causes, or treatments. "
33
+ "Always encourage users to consult healthcare professionals for personalized advice."
34
+ )
35
+ }
36
+
37
+ messages = [system_message]
38
+ max_history = 10
39
+
40
+ # Expressions reconnues
41
+ salutations = ["bonjour", "salut", "bonsoir", "coucou"]
42
+ remerciements = ["merci", "je vous remercie", "thanks"]
43
+ au_revoir = ["au revoir", "à bientôt", "bye", "bonne journée", "à la prochaine"]
44
+
45
+ def detect_smalltalk(user_input):
46
+ lower_input = user_input.lower().strip()
47
+
48
+ if any(phrase in lower_input for phrase in salutations):
49
+ return "Bonjour ! Comment puis-je vous aider aujourd'hui ?", True
50
+ if any(phrase in lower_input for phrase in remerciements):
51
+ return "Avec plaisir ! Souhaitez-vous poser une autre question médicale ?", True
52
+ if any(phrase in lower_input for phrase in au_revoir):
53
+ return "Au revoir ! Prenez soin de votre santé et n'hésitez pas à revenir si besoin.", True
54
+
55
+ return "", False
56
+
57
+ def medical_chatbot(user_input):
58
+ global messages
59
+
60
+ # Gestion des interactions sociales
61
+ smalltalk_response, handled = detect_smalltalk(user_input)
62
+ if handled:
63
+ return smalltalk_response
64
+
65
+ # Traduction français -> anglais
66
+ translated = translator(user_input, src_lang="fra_Latn", tgt_lang="eng_Latn")[0]['translation_text']
67
+
68
+ messages.append({"role": "user", "content": translated})
69
+ if len(messages) > max_history * 2:
70
+ messages = [system_message] + messages[-max_history * 2:]
71
+
72
+ # Préparation du prompt
73
+ prompt = text_gen_pipeline.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
74
+
75
+ # Génération
76
+ response = text_gen_pipeline(
77
+ prompt,
78
+ max_new_tokens=512,
79
+ do_sample=True,
80
+ temperature=0.4,
81
+ top_k=150,
82
+ top_p=0.75,
83
+ eos_token_id=[
84
+ text_gen_pipeline.tokenizer.eos_token_id,
85
+ text_gen_pipeline.tokenizer.convert_tokens_to_ids("<|eot_id|>")
86
+ ]
87
+ )
88
+
89
+ output = response[0]['generated_text'][len(prompt):].strip()
90
+
91
+ # Traduction anglais -> français
92
+ translated_back = translator(output, src_lang="eng_Latn", tgt_lang="fra_Latn")[0]['translation_text']
93
+
94
+ messages.append({"role": "assistant", "content": translated_back})
95
+ return translated_back
96
+
97
+ # Chargement du logo
98
+ logo = Image.open("AfriAI Solutions.jpg")
99
+
100
+ # Interface Gradio
101
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo")) as demo:
102
+ with gr.Row():
103
+ gr.Image(value=logo, show_label=False, show_download_button=False, interactive=False, height=150)
104
+
105
+ gr.Markdown(
106
+ """
107
+ # 🤖 Chatbot Médical AfriAI Solutions
108
+ **Posez votre question médicale en français.**
109
+ Le chatbot vous répondra brièvement et avec bienveillance, puis vous demandera si vous souhaitez plus de détails.
110
+ """,
111
+ elem_id="title"
112
+ )
113
+
114
+ chatbot = gr.Chatbot(label="Chat avec le Médecin Virtuel", height=400)
115
+ msg = gr.Textbox(label="Votre question", placeholder="Exemple : Quels sont les symptômes du paludisme ?")
116
+
117
+ clear = gr.Button("Effacer la conversation", variant="secondary")
118
+
119
+ def respond(message, history):
120
+ response = medical_chatbot(message)
121
+ history = history or []
122
+ history.append((message, response))
123
+ return "", history
124
+
125
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
126
+ clear.click(lambda: ("", []), None, [msg, chatbot])
127
+
128
+ demo.launch()
129
+
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ torch>=2.0.0
2
+ transformers>=4.36.0
3
+ gradio>=3.50.0
4
+ sentencepiece>=0.1.99
5
+ accelerate>=0.24.0
6
+ bitsandbytes>=0.41.0
7
+ protobuf>=3.20.0
8
+ huggingface-hub>=0.19.0
9
+ pillow>=9.0.0