SafaaAI commited on
Commit
6e91be0
·
verified ·
1 Parent(s): 7600281

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -41
app.py CHANGED
@@ -3,16 +3,16 @@ import torch
3
  from transformers import AutoTokenizer, AutoModelForCausalLM
4
  import os
5
 
6
- # 🔹 Récupérez le token depuis les secrets du Space
7
  hf_token = os.environ.get("HF_TOKEN")
8
-
9
  if hf_token is None:
10
- raise ValueError("⚠️ Le token Hugging Face (HF_TOKEN) n'est pas trouvé. "
11
- "Vérifie que tu l’as bien ajouté dans les secrets du Space.")
12
 
13
- # 🔹 Charger le tokenizer et le modèle
14
  model_id = "SafaaAI/final_llm_darija_fr_tech"
15
 
 
16
  tokenizer = AutoTokenizer.from_pretrained(
17
  model_id,
18
  token=hf_token,
@@ -23,56 +23,51 @@ model = AutoModelForCausalLM.from_pretrained(
23
  model_id,
24
  token=hf_token,
25
  trust_remote_code=True,
26
- device_map="auto"
27
- )
 
 
28
 
29
- # 🔹 Fonction d'inférence
30
  def chat_with_model(message, history):
31
  history = history or []
32
- full_prompt = "A chat between a curious user and an AI assistant."
33
-
34
- # Construire le prompt manuellement
 
 
35
  for user_message, bot_message in history:
36
- full_prompt += f" USER: {user_message} ASSISTANT: {bot_message}"
37
-
38
- # Ajouter le message actuel de l'utilisateur
39
- full_prompt += f" USER: {message} ASSISTANT:"
40
-
41
- # Encoder le prompt avec le tokenizer
42
- inputs = tokenizer(full_prompt, return_tensors="pt").to(model.device)
43
-
44
- # 📝 Extraire explicitement input_ids et attention_mask
45
- input_ids = inputs["input_ids"]
46
- attention_mask = inputs["attention_mask"]
47
-
48
- # Générer la réponse
49
  with torch.no_grad():
50
  output_ids = model.generate(
51
- input_ids,
52
- attention_mask=attention_mask,
53
- max_new_tokens=200,
54
  do_sample=True,
55
  top_p=0.9,
56
- temperature=0.7
 
57
  )
58
 
59
- # Décoder la sortie
60
  response = tokenizer.decode(output_ids[0], skip_special_tokens=True)
61
-
62
- # Nettoyer la réponse pour ne pas inclure le prompt
63
- response_start_index = response.rfind("ASSISTANT:")
64
- if response_start_index != -1:
65
- response = response[response_start_index + len("ASSISTANT:"):].strip()
66
-
67
  history.append((message, response))
68
  return history, history
69
 
70
  # 🔹 Interface Gradio
71
  with gr.Blocks() as demo:
72
- gr.Markdown("## 💬 Chatbot SafaaAI - LLM (Darija + Français + Technique)")
73
-
74
- chatbot = gr.Chatbot()
75
- msg = gr.Textbox(label="Écris ton message ici")
76
  clear = gr.Button("🧹 Effacer la conversation")
77
 
78
  state = gr.State([])
@@ -80,6 +75,5 @@ with gr.Blocks() as demo:
80
  msg.submit(chat_with_model, [msg, state], [chatbot, state])
81
  clear.click(lambda: ([], []), None, [chatbot, state])
82
 
83
- # 🔹 Lancer l'application
84
  if __name__ == "__main__":
85
- demo.launch()
 
3
  from transformers import AutoTokenizer, AutoModelForCausalLM
4
  import os
5
 
6
+ # 🔹 Récupération du token Hugging Face
7
  hf_token = os.environ.get("HF_TOKEN")
 
8
  if hf_token is None:
9
+ raise ValueError("⚠️ Le token Hugging Face (HF_TOKEN) est manquant. "
10
+ "Ajoute-le dans les secrets de ton Space.")
11
 
12
+ # 🔹 Identifiant du modèle
13
  model_id = "SafaaAI/final_llm_darija_fr_tech"
14
 
15
+ # 🔹 Charger tokenizer et modèle en CPU
16
  tokenizer = AutoTokenizer.from_pretrained(
17
  model_id,
18
  token=hf_token,
 
23
  model_id,
24
  token=hf_token,
25
  trust_remote_code=True,
26
+ device_map=None # pas d’auto GPU
27
+ ).to("cpu") # forcer CPU
28
+
29
+ print("✅ Modèle chargé sur CPU")
30
 
31
+ # 🔹 Fonction dinférence
32
  def chat_with_model(message, history):
33
  history = history or []
34
+ full_prompt = (
35
+ "A chat between a curious user and an AI assistant capable of "
36
+ "understanding Darija, French, and technical language.\n"
37
+ )
38
+
39
  for user_message, bot_message in history:
40
+ full_prompt += f"USER: {user_message}\nASSISTANT: {bot_message}\n"
41
+
42
+ full_prompt += f"USER: {message}\nASSISTANT:"
43
+
44
+ inputs = tokenizer(full_prompt, return_tensors="pt")
45
+
 
 
 
 
 
 
 
46
  with torch.no_grad():
47
  output_ids = model.generate(
48
+ inputs["input_ids"],
49
+ attention_mask=inputs["attention_mask"],
50
+ max_new_tokens=100,
51
  do_sample=True,
52
  top_p=0.9,
53
+ temperature=0.7,
54
+ pad_token_id=tokenizer.eos_token_id
55
  )
56
 
 
57
  response = tokenizer.decode(output_ids[0], skip_special_tokens=True)
58
+
59
+ if "ASSISTANT:" in response:
60
+ response = response.split("ASSISTANT:")[-1].strip()
61
+
 
 
62
  history.append((message, response))
63
  return history, history
64
 
65
  # 🔹 Interface Gradio
66
  with gr.Blocks() as demo:
67
+ gr.Markdown("## 🤖 Chatbot SafaaAI - LLM (Darija + Français + Technique)")
68
+
69
+ chatbot = gr.Chatbot(height=400)
70
+ msg = gr.Textbox(label="💬 Écris ton message ici", placeholder="Pose ta question...")
71
  clear = gr.Button("🧹 Effacer la conversation")
72
 
73
  state = gr.State([])
 
75
  msg.submit(chat_with_model, [msg, state], [chatbot, state])
76
  clear.click(lambda: ([], []), None, [chatbot, state])
77
 
 
78
  if __name__ == "__main__":
79
+ demo.launch()