Dorian2B commited on
Commit
c87b9ca
·
verified ·
1 Parent(s): e26878b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -57
app.py CHANGED
@@ -1,69 +1,131 @@
1
  import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForCausalLM
3
  import torch
4
- from threading import Lock
 
 
5
 
6
- # Chargement du modèle
7
- model_name = "Dorian2B/Vera-Instruct"
8
- tokenizer = AutoTokenizer.from_pretrained(model_name)
9
- model = AutoModelForCausalLM.from_pretrained(
10
- model_name,
11
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
12
- device_map="auto"
13
- )
14
- model.eval()
15
 
16
- # Verrou pour éviter les conflits de threads
17
- generate_lock = Lock()
 
18
 
19
- def format_prompt(history, new_message):
20
- """Formate l'historique et le nouveau message pour le modèle."""
21
- prompt = ""
22
- for user_msg, bot_msg in history:
23
- prompt += f"<|user|>{user_msg}</s>\n<|assistant|>{bot_msg}</s>\n"
24
- prompt += f"<|user|>{new_message}</s>\n<|assistant|>"
25
- return prompt
 
 
 
26
 
27
- def generate_stream(history, new_message):
28
- """Génère une réponse en streaming avec contexte."""
29
- prompt = format_prompt(history, new_message)
30
- inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
 
 
 
 
 
 
 
 
 
 
31
 
32
- # Génération en streaming
33
- with generate_lock:
34
- with torch.no_grad():
35
- for chunk in model.generate(
36
- **inputs,
37
- max_new_tokens=1024,
38
- do_sample=True,
39
- temperature=0.7,
40
- top_p=0.9,
41
- repetition_penalty=1.1,
42
- eos_token_id=tokenizer.eos_token_id,
43
- streamer=None, # (Remplacez par un vrai streamer si disponible)
44
- ):
45
- decoded = tokenizer.decode(chunk[0], skip_special_tokens=True)
46
- if decoded.startswith(prompt): # Supprime le prompt
47
- decoded = decoded[len(prompt):]
48
- yield decoded.strip()
 
49
 
50
- def chat_interface(message, history):
51
- """Fonction pour Gradio ChatInterface."""
52
- full_response = ""
53
- for chunk in generate_stream(history, message):
54
- full_response += chunk
55
- yield full_response
56
 
57
  # Interface Gradio
58
- demo = gr.ChatInterface(
59
- fn=chat_interface,
60
- title="💬 Vera-Instruct Chat (avec Contexte & Streaming)",
61
- description="Discutez avec le modèle **Dorian2B/Vera-Instruct**.<br>Le modèle conserve le contexte de la conversation.",
62
- examples=["Bonjour ! Comment vas-tu ?", "Explique-moi l'IA générative."],
63
- theme="soft",
64
- retry_btn=None,
65
- undo_btn=None,
66
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
 
68
  if __name__ == "__main__":
69
- demo.queue().launch(debug=True)
 
 
1
  import gradio as gr
 
2
  import torch
3
+ from llama_cpp import Llama
4
+ import os
5
+ from huggingface_hub import hf_hub_download
6
 
7
+ # Configuration du modèle
8
+ MODEL_NAME = "Dorian2B/Vera-v1.5-Instruct-GGUF"
9
+ MODEL_FILE = "vera-v1.5-instruct-q8_0.gguf"
 
 
 
 
 
 
10
 
11
+ def download_model():
12
+ model_path = hf_hub_download(repo_id=MODEL_NAME, filename=MODEL_FILE)
13
+ return model_path
14
 
15
+ def load_model():
16
+ model_path = download_model()
17
+
18
+ # Paramètres pour le modèle
19
+ model = Llama(
20
+ model_path=model_path,
21
+ n_ctx=4096, # Taille du contexte
22
+ n_gpu_layers=-1 # Utilise tous les layers disponibles sur GPU si possible
23
+ )
24
+ return model
25
 
26
+ # Format du template pour Vera
27
+ def format_prompt(message, history):
28
+ prompt = "<|system|>\nTu es Vera, une assistante IA utile, honnête et inoffensive.\n</s>\n"
29
+
30
+ # Ajout de l'historique
31
+ for user_msg, assistant_msg in history:
32
+ prompt += f"<|user|>\n{user_msg}\n</s>\n"
33
+ prompt += f"<|assistant|>\n{assistant_msg}\n</s>\n"
34
+
35
+ # Ajout du message actuel
36
+ prompt += f"<|user|>\n{message}\n</s>\n"
37
+ prompt += "<|assistant|>\n"
38
+
39
+ return prompt
40
 
41
+ # Fonction d'inférence
42
+ def generate_response(message, history):
43
+ if not hasattr(generate_response, "model"):
44
+ generate_response.model = load_model()
45
+
46
+ prompt = format_prompt(message, history)
47
+
48
+ # Génération de la réponse
49
+ response = generate_response.model.create_completion(
50
+ prompt,
51
+ max_tokens=2048,
52
+ temperature=0.7,
53
+ top_p=0.95,
54
+ stop=["</s>", "<|user|>", "<|system|>"],
55
+ echo=False
56
+ )
57
+
58
+ return response['choices'][0]['text']
59
 
60
+ # Fonction pour réinitialiser la conversation
61
+ def reset_conversation():
62
+ return [], ""
 
 
 
63
 
64
  # Interface Gradio
65
+ with gr.Blocks(css="footer {visibility: hidden}") as demo:
66
+ gr.Markdown("""
67
+ # 🌟 Assistant Vera-v1.5-Instruct
68
+
69
+ Cette interface vous permet d'interagir avec le modèle Vera-v1.5-Instruct en français.
70
+ Posez vos questions et l'assistant vous répondra en tenant compte du contexte de la conversation.
71
+ """)
72
+
73
+ with gr.Row():
74
+ with gr.Column(scale=4):
75
+ chatbot = gr.Chatbot(
76
+ height=500,
77
+ show_copy_button=True,
78
+ avatar_images=("👤", "🤖"),
79
+ bubble_full_width=False,
80
+ )
81
+
82
+ with gr.Row():
83
+ with gr.Column(scale=4):
84
+ message = gr.Textbox(
85
+ placeholder="Entrez votre message ici...",
86
+ lines=2,
87
+ container=False,
88
+ scale=4,
89
+ )
90
+ with gr.Column(scale=1):
91
+ with gr.Row():
92
+ submit_btn = gr.Button("Envoyer", variant="primary", scale=2)
93
+ reset_btn = gr.Button("Réinitialiser", variant="secondary", scale=1)
94
+
95
+ gr.Markdown("""
96
+ ### À propos du modèle
97
+
98
+ Ce modèle est basé sur **Vera-v1.5-Instruct-GGUF** de [Dorian2B](https://huggingface.co/Dorian2B/Vera-v1.5-Instruct-GGUF).
99
+ Le modèle est optimisé pour les conversations en français.
100
+ """)
101
+
102
+ # Configuration des événements
103
+ submit_btn.click(
104
+ fn=generate_response,
105
+ inputs=[message, chatbot],
106
+ outputs=[chatbot],
107
+ queue=True
108
+ ).then(
109
+ fn=lambda: "",
110
+ outputs=[message]
111
+ )
112
+
113
+ message.submit(
114
+ fn=generate_response,
115
+ inputs=[message, chatbot],
116
+ outputs=[chatbot],
117
+ queue=True
118
+ ).then(
119
+ fn=lambda: "",
120
+ outputs=[message]
121
+ )
122
+
123
+ reset_btn.click(
124
+ fn=reset_conversation,
125
+ outputs=[chatbot, message]
126
+ )
127
 
128
+ # Lancement de l'interface
129
  if __name__ == "__main__":
130
+ demo.queue()
131
+ demo.launch()