SafaaAI commited on
Commit
09740f9
·
verified ·
1 Parent(s): dcc9a1f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -33
app.py CHANGED
@@ -1,68 +1,88 @@
1
  import gradio as gr
2
  import torch
3
- from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
 
4
 
5
- # 🔹 Identifiant d’un petit modèle multimodal
6
- model_id = "liuhaotian/llava-v1.5-7b" # tu peux tester TinyLLaVA aussi
 
 
 
7
 
8
- # 🔹 Config quantization 4 bits
9
- bnb_config = BitsAndBytesConfig(
10
- load_in_4bit=True,
11
- bnb_4bit_use_double_quant=True,
12
- bnb_4bit_quant_type="nf4",
13
- bnb_4bit_compute_dtype=torch.float16
14
- )
15
 
16
- # 🔹 Charger modèle + tokenizer
17
- tokenizer = AutoTokenizer.from_pretrained(model_id)
18
- model = AutoModelForCausalLM.from_pretrained(
19
  model_id,
20
- quantization_config=bnb_config,
21
- device_map="auto",
22
  trust_remote_code=True
23
  )
24
 
25
- print("✅ Modèle multimodal chargé en 4 bits")
 
 
 
 
 
26
 
27
- # 🔹 Fonction de chat multimodal
28
- def chat(image, message, history=[]):
29
  history = history or []
 
 
 
 
 
 
 
 
 
 
30
 
31
- # Préparer prompt
32
- full_prompt = "USER: " + message + "\nASSISTANT:"
33
 
34
- inputs = tokenizer(full_prompt, return_tensors="pt").to("cuda" if torch.cuda.is_available() else "cpu")
 
 
 
35
 
36
  with torch.no_grad():
37
  output_ids = model.generate(
38
- inputs["input_ids"],
39
- max_new_tokens=50,
 
40
  do_sample=True,
41
  top_p=0.9,
42
  temperature=0.7
43
  )
44
 
45
  response = tokenizer.decode(output_ids[0], skip_special_tokens=True)
46
- if "ASSISTANT:" in response:
47
- response = response.split("ASSISTANT:")[-1].strip()
 
48
 
49
- history.append(((message, image), response))
 
50
  return history, history
51
 
52
- # 🔹 Interface Gradio
53
  with gr.Blocks() as demo:
54
- gr.Markdown("## 🤖 Chatbot Multimodal (Texte + Image) - Optimisé en 4 bits")
55
 
56
- chatbot = gr.Chatbot(height=400)
57
  with gr.Row():
58
- msg = gr.Textbox(label="💬 Écris ton message")
59
- img = gr.Image(type="filepath", label="🖼️ Upload une image")
60
- clear = gr.Button("🧹 Effacer la conversation")
 
 
61
 
62
  state = gr.State([])
63
 
64
- msg.submit(chat, [img, msg, state], [chatbot, state])
 
65
  clear.click(lambda: ([], []), None, [chatbot, state])
66
 
 
67
  if __name__ == "__main__":
68
  demo.launch()
 
1
  import gradio as gr
2
  import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
+ import os
5
 
6
+ # 🔹 Récupérer le token Hugging Face depuis les secrets
7
+ hf_token = os.environ.get("HF_TOKEN")
8
+ if hf_token is None:
9
+ raise ValueError("⚠️ Le token Hugging Face (HF_TOKEN) n'est pas trouvé. "
10
+ "Ajoute-le dans les secrets du Space.")
11
 
12
+ # 🔹 Charger ton modèle texte
13
+ model_id = "SafaaAI/final_llm_darija_fr_tech"
 
 
 
 
 
14
 
15
+ tokenizer = AutoTokenizer.from_pretrained(
 
 
16
  model_id,
17
+ token=hf_token,
 
18
  trust_remote_code=True
19
  )
20
 
21
+ model = AutoModelForCausalLM.from_pretrained(
22
+ model_id,
23
+ token=hf_token,
24
+ trust_remote_code=True,
25
+ device_map="auto"
26
+ )
27
 
28
+ # 🔹 Fonction d'inférence
29
+ def chat_with_model(message, history, image):
30
  history = history or []
31
+ full_prompt = "A chat between a curious user and an AI assistant."
32
+
33
+ # Reconstituer le contexte de la conversation
34
+ for user_message, bot_message in history:
35
+ full_prompt += f" USER: {user_message} ASSISTANT: {bot_message}"
36
+
37
+ # Ajouter image si présente
38
+ if image is not None:
39
+ # Ici, ton modèle ne comprend pas l'image. On ajoute une note textuelle.
40
+ message = f"[Image fournie par l'utilisateur] {message}"
41
 
42
+ # Ajouter le message actuel
43
+ full_prompt += f" USER: {message} ASSISTANT:"
44
 
45
+ # Encoder et générer la réponse
46
+ inputs = tokenizer(full_prompt, return_tensors="pt").to(model.device)
47
+ input_ids = inputs["input_ids"]
48
+ attention_mask = inputs["attention_mask"]
49
 
50
  with torch.no_grad():
51
  output_ids = model.generate(
52
+ input_ids,
53
+ attention_mask=attention_mask,
54
+ max_new_tokens=200,
55
  do_sample=True,
56
  top_p=0.9,
57
  temperature=0.7
58
  )
59
 
60
  response = tokenizer.decode(output_ids[0], skip_special_tokens=True)
61
+ response_start_index = response.rfind("ASSISTANT:")
62
+ if response_start_index != -1:
63
+ response = response[response_start_index + len("ASSISTANT:"):].strip()
64
 
65
+ # Ajouter la réponse à l’historique
66
+ history.append((message, response))
67
  return history, history
68
 
69
+ # 🔹 Interface Gradio avec zone image
70
  with gr.Blocks() as demo:
71
+ gr.Markdown("## 💬 Chatbot SafaaAI - LLM (Darija + Français + Technique)")
72
 
 
73
  with gr.Row():
74
+ chatbot = gr.Chatbot(scale=3)
75
+ with gr.Column(scale=1):
76
+ msg = gr.Textbox(label="Écris ton message ici")
77
+ image = gr.Image(label="Ajoute une image (optionnel)", type="filepath")
78
+ clear = gr.Button("🧹 Effacer la conversation")
79
 
80
  state = gr.State([])
81
 
82
+ # Associer envoi du message et image à la fonction
83
+ msg.submit(chat_with_model, [msg, state, image], [chatbot, state])
84
  clear.click(lambda: ([], []), None, [chatbot, state])
85
 
86
+ # 🔹 Lancer l'app
87
  if __name__ == "__main__":
88
  demo.launch()