Update app.py
Browse files
app.py
CHANGED
|
@@ -2,83 +2,88 @@ import gradio as gr
|
|
| 2 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
import torch
|
| 4 |
import spaces
|
| 5 |
-
import csv
|
| 6 |
import os
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
MODEL_NAME = "
|
| 10 |
INFO_FILE = "infos_medicaux.txt"
|
| 11 |
-
MAX_TOKENS =
|
| 12 |
-
TEMPERATURE = 0.
|
| 13 |
-
|
| 14 |
-
|
|
|
|
| 15 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 16 |
model = AutoModelForCausalLM.from_pretrained(
|
| 17 |
MODEL_NAME,
|
| 18 |
-
torch_dtype=torch.float32
|
| 19 |
)
|
| 20 |
-
print("Modèle chargé avec succès")
|
| 21 |
-
|
|
|
|
| 22 |
if os.path.exists(INFO_FILE):
|
| 23 |
with open(INFO_FILE, "r", encoding="utf-8") as f:
|
| 24 |
medical_context = f.read()
|
| 25 |
-
print(f"Contexte médical chargé
|
| 26 |
else:
|
| 27 |
medical_context = ""
|
| 28 |
-
print("Aucun fichier infos_medicaux.txt trouvé.
|
| 29 |
|
| 30 |
-
|
| 31 |
@spaces.GPU
|
| 32 |
def chat_with_finanfa(message, history=None):
|
| 33 |
if history is None:
|
| 34 |
history = []
|
| 35 |
-
|
| 36 |
system_prompt = (
|
| 37 |
-
"Tu es FINANFA, un assistant médical
|
| 38 |
-
"Tu t'appuies sur les connaissances médicales fournies
|
| 39 |
"Tu ne réponds qu’aux questions liées à la santé, aux maladies ou aux médicaments. "
|
| 40 |
-
"Si
|
|
|
|
| 41 |
)
|
| 42 |
-
|
|
|
|
| 43 |
conversation = f"Système : {system_prompt}\n"
|
| 44 |
if medical_context:
|
| 45 |
conversation += f"Connaissances médicales : {medical_context}\n"
|
| 46 |
for user_msg, bot_msg in history:
|
| 47 |
conversation += f"Utilisateur : {user_msg}\nAssistant : {bot_msg}\n"
|
| 48 |
conversation += f"Utilisateur : {message}\nAssistant :"
|
| 49 |
-
|
|
|
|
| 50 |
inputs = tokenizer(conversation, return_tensors="pt", truncation=True)
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
| 59 |
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 60 |
response = response.split("Assistant :")[-1].strip()
|
| 61 |
-
|
| 62 |
return response
|
| 63 |
-
|
|
|
|
| 64 |
with gr.Blocks(title="FINANFA — Chatbot Médical") as demo:
|
| 65 |
gr.Markdown(
|
| 66 |
"""
|
| 67 |
# 🏥 **FINANFA — Assistant Médical**
|
| 68 |
-
Cet assistant répond uniquement aux questions médicales
|
| 69 |
⚠️ Il ne remplace pas un avis médical professionnel.
|
| 70 |
"""
|
| 71 |
)
|
| 72 |
-
|
| 73 |
chat = gr.ChatInterface(
|
| 74 |
fn=chat_with_finanfa,
|
| 75 |
title="FINANFA - Assistant Médical",
|
| 76 |
-
description="Posez vos questions médicales en toute sécurité.",
|
| 77 |
examples=[
|
| 78 |
"Quels sont les symptômes du paludisme ?",
|
| 79 |
-
"
|
| 80 |
-
"
|
| 81 |
]
|
| 82 |
)
|
| 83 |
-
|
| 84 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 2 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
import torch
|
| 4 |
import spaces
|
|
|
|
| 5 |
import os
|
| 6 |
+
|
| 7 |
+
# === CONFIGURATION ===
|
| 8 |
+
MODEL_NAME = "facebook/MobileLLM-Pro" # ✅ Plus léger et rapide
|
| 9 |
INFO_FILE = "infos_medicaux.txt"
|
| 10 |
+
MAX_TOKENS = 800
|
| 11 |
+
TEMPERATURE = 0.6
|
| 12 |
+
|
| 13 |
+
# === CHARGEMENT DU MODÈLE ===
|
| 14 |
+
print("⏳ Chargement du modèle...")
|
| 15 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 16 |
model = AutoModelForCausalLM.from_pretrained(
|
| 17 |
MODEL_NAME,
|
| 18 |
+
torch_dtype=torch.float32,
|
| 19 |
)
|
| 20 |
+
print("✅ Modèle chargé avec succès")
|
| 21 |
+
|
| 22 |
+
# === CHARGEMENT DU CONTEXTE MÉDICAL ===
|
| 23 |
if os.path.exists(INFO_FILE):
|
| 24 |
with open(INFO_FILE, "r", encoding="utf-8") as f:
|
| 25 |
medical_context = f.read()
|
| 26 |
+
print(f"📘 Contexte médical chargé ({len(medical_context)} caractères)")
|
| 27 |
else:
|
| 28 |
medical_context = ""
|
| 29 |
+
print("⚠️ Aucun fichier infos_medicaux.txt trouvé.")
|
| 30 |
|
| 31 |
+
# === CHATBOT ===
|
| 32 |
@spaces.GPU
|
| 33 |
def chat_with_finanfa(message, history=None):
|
| 34 |
if history is None:
|
| 35 |
history = []
|
| 36 |
+
|
| 37 |
system_prompt = (
|
| 38 |
+
"Tu es FINANFA, un assistant médical béninois, professionnel et empathique. "
|
| 39 |
+
"Tu t'appuies sur les connaissances médicales fournies ci-dessous. "
|
| 40 |
"Tu ne réponds qu’aux questions liées à la santé, aux maladies ou aux médicaments. "
|
| 41 |
+
"Si la question n’est pas médicale, dis poliment que tu ne peux pas répondre. "
|
| 42 |
+
"Donne des réponses claires, détaillées, avec des informations vérifiées au Bénin."
|
| 43 |
)
|
| 44 |
+
|
| 45 |
+
# Construction du contexte complet
|
| 46 |
conversation = f"Système : {system_prompt}\n"
|
| 47 |
if medical_context:
|
| 48 |
conversation += f"Connaissances médicales : {medical_context}\n"
|
| 49 |
for user_msg, bot_msg in history:
|
| 50 |
conversation += f"Utilisateur : {user_msg}\nAssistant : {bot_msg}\n"
|
| 51 |
conversation += f"Utilisateur : {message}\nAssistant :"
|
| 52 |
+
|
| 53 |
+
# Génération
|
| 54 |
inputs = tokenizer(conversation, return_tensors="pt", truncation=True)
|
| 55 |
+
with torch.no_grad():
|
| 56 |
+
outputs = model.generate(
|
| 57 |
+
**inputs,
|
| 58 |
+
max_new_tokens=MAX_TOKENS,
|
| 59 |
+
temperature=TEMPERATURE,
|
| 60 |
+
do_sample=True,
|
| 61 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 65 |
response = response.split("Assistant :")[-1].strip()
|
|
|
|
| 66 |
return response
|
| 67 |
+
|
| 68 |
+
# === INTERFACE GRADIO ===
|
| 69 |
with gr.Blocks(title="FINANFA — Chatbot Médical") as demo:
|
| 70 |
gr.Markdown(
|
| 71 |
"""
|
| 72 |
# 🏥 **FINANFA — Assistant Médical**
|
| 73 |
+
Cet assistant répond uniquement aux questions médicales béninoises.
|
| 74 |
⚠️ Il ne remplace pas un avis médical professionnel.
|
| 75 |
"""
|
| 76 |
)
|
| 77 |
+
|
| 78 |
chat = gr.ChatInterface(
|
| 79 |
fn=chat_with_finanfa,
|
| 80 |
title="FINANFA - Assistant Médical",
|
| 81 |
+
description="Posez vos questions médicales locales en toute sécurité.",
|
| 82 |
examples=[
|
| 83 |
"Quels sont les symptômes du paludisme ?",
|
| 84 |
+
"Donne-moi la liste des cliniques spécialisées en santé sexuelle au Bénin.",
|
| 85 |
+
"Comment prévenir le diabète ?"
|
| 86 |
]
|
| 87 |
)
|
| 88 |
+
|
| 89 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|