SafaaAI commited on
Commit
d1a8201
·
verified ·
1 Parent(s): 50a0022

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -17
app.py CHANGED
@@ -3,16 +3,22 @@ import torch
3
  from transformers import AutoTokenizer, AutoModelForCausalLM
4
  import os
5
 
6
- # 🔹 Token Hugging Face
7
  hf_token = os.environ.get("HF_TOKEN")
 
8
  if hf_token is None:
9
- raise ValueError("⚠️ HF_TOKEN manquant dans les secrets du Space.")
 
10
 
11
- # 🔹 ID du modèle
12
  model_id = "SafaaAI/final_llm_darija_fr_tech"
13
 
14
- # 🔹 Charger tokenizer + modèle (forcé en text-only)
15
- tokenizer = AutoTokenizer.from_pretrained(model_id, token=hf_token, trust_remote_code=True)
 
 
 
 
16
  model = AutoModelForCausalLM.from_pretrained(
17
  model_id,
18
  token=hf_token,
@@ -20,35 +26,60 @@ model = AutoModelForCausalLM.from_pretrained(
20
  device_map="auto"
21
  )
22
 
23
- # 🔹 Fonction de génération texte
24
  def chat_with_model(message, history):
25
  history = history or []
26
- inputs = tokenizer(message, return_tensors="pt").to(model.device)
27
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  with torch.no_grad():
29
- outputs = model.generate(
30
- **inputs,
 
31
  max_new_tokens=200,
32
  do_sample=True,
33
- temperature=0.7,
34
- top_p=0.9
35
  )
36
 
37
- response = tokenizer.decode(outputs[0], skip_special_tokens=True)
 
 
 
 
 
 
 
38
  history.append((message, response))
39
  return history, history
40
 
41
- # 🔹 UI Gradio
42
  with gr.Blocks() as demo:
43
- gr.Markdown("## 💬 SafaaAI - Multimodal LLM (mode texte seulement)")
44
- chatbot = gr.Chatbot(type="messages")
 
45
  msg = gr.Textbox(label="Écris ton message ici")
46
- clear = gr.Button("🧹 Effacer")
47
 
48
  state = gr.State([])
49
 
50
  msg.submit(chat_with_model, [msg, state], [chatbot, state])
51
  clear.click(lambda: ([], []), None, [chatbot, state])
52
 
 
53
  if __name__ == "__main__":
54
  demo.launch()
 
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,
19
+ trust_remote_code=True
20
+ )
21
+
22
  model = AutoModelForCausalLM.from_pretrained(
23
  model_id,
24
  token=hf_token,
 
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([])
79
 
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()