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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import threading
|
| 4 |
+
import warnings
|
| 5 |
+
import gradio as gr
|
| 6 |
+
from llama_cpp import Llama
|
| 7 |
+
|
| 8 |
+
# -------------------------
|
| 9 |
+
# TÉLÉCHARGEMENT DU MODÈLE
|
| 10 |
+
# -------------------------
|
| 11 |
+
MODEL_REPO = "mradermacher/Alisia-7B-it-GGUF"
|
| 12 |
+
MODEL_NAME = "Alisia-7B-it.Q4_K_M.gguf"
|
| 13 |
+
MODEL_PATH = f"/tmp/{MODEL_NAME}"
|
| 14 |
+
|
| 15 |
+
# Télécharger le modèle s'il n'existe pas
|
| 16 |
+
if not os.path.exists(MODEL_PATH):
|
| 17 |
+
print("📥 Téléchargement du modèle...")
|
| 18 |
+
from huggingface_hub import hf_hub_download
|
| 19 |
+
try:
|
| 20 |
+
hf_hub_download(
|
| 21 |
+
repo_id=MODEL_REPO,
|
| 22 |
+
filename=MODEL_NAME,
|
| 23 |
+
local_dir="/tmp",
|
| 24 |
+
resume_download=True
|
| 25 |
+
)
|
| 26 |
+
print("✅ Modèle téléchargé avec succès!")
|
| 27 |
+
except Exception as e:
|
| 28 |
+
print(f"❌ Erreur téléchargement: {e}")
|
| 29 |
+
# Fallback: utiliser un modèle plus petit
|
| 30 |
+
MODEL_NAME = "Alisia-7B-it.Q4_K_M.gguf" # ou un plus petit si disponible
|
| 31 |
+
|
| 32 |
+
# -------------------------
|
| 33 |
+
# CONFIGURATION LLAMA.CPP
|
| 34 |
+
# -------------------------
|
| 35 |
+
os.environ["LLAMA_CPP_LOG_LEVEL"] = "OFF"
|
| 36 |
+
warnings.filterwarnings("ignore")
|
| 37 |
+
|
| 38 |
+
print("⚡ Chargement du modèle avec llama.cpp...")
|
| 39 |
+
llm = Llama(
|
| 40 |
+
model_path=MODEL_PATH,
|
| 41 |
+
n_ctx=4096, # Contexte plus long
|
| 42 |
+
n_gpu_layers=0, # 0 = CPU only (plus stable)
|
| 43 |
+
n_threads=8, # Utilise plus de threads
|
| 44 |
+
n_batch=512, # Batch size optimisé
|
| 45 |
+
verbose=False,
|
| 46 |
+
use_mlock=True # Meilleure performance
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
print("✅ Modèle chargé et prêt!")
|
| 50 |
+
|
| 51 |
+
# -------------------------
|
| 52 |
+
# ÉTAT & SYNCHRONISATION
|
| 53 |
+
# -------------------------
|
| 54 |
+
lock = threading.Lock()
|
| 55 |
+
conversations = {"Conversation 1": []}
|
| 56 |
+
stop_generation = threading.Event()
|
| 57 |
+
|
| 58 |
+
# -------------------------
|
| 59 |
+
# FONCTIONS UTILITAIRES
|
| 60 |
+
# -------------------------
|
| 61 |
+
def clean_output(text: str) -> str:
|
| 62 |
+
return re.sub(r"<\|im_.*?\|>", "", text).strip()
|
| 63 |
+
|
| 64 |
+
def get_conv_names():
|
| 65 |
+
with lock:
|
| 66 |
+
return list(conversations.keys())
|
| 67 |
+
|
| 68 |
+
def build_conversation_prompt(history, new_message):
|
| 69 |
+
"""Format de prompt optimisé pour Alpaca"""
|
| 70 |
+
prompt = ""
|
| 71 |
+
|
| 72 |
+
# System prompt seulement au début
|
| 73 |
+
if not any(any(conv) for conv in conversations.values()):
|
| 74 |
+
prompt += """Tu es Alisia, une assistante IA utile et compétente. Réponds de manière précise et concise.
|
| 75 |
+
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
# Historique de conversation
|
| 79 |
+
for user_msg, assistant_msg in history:
|
| 80 |
+
prompt += f"### Instruction:\n{user_msg}\n\n### Response:\n{assistant_msg}\n\n"
|
| 81 |
+
|
| 82 |
+
# Nouveau message
|
| 83 |
+
prompt += f"### Instruction:\n{new_message}\n\n### Response:\n"
|
| 84 |
+
return prompt
|
| 85 |
+
|
| 86 |
+
def send_message_stream(user_message, displayed_history, current_chat_name):
|
| 87 |
+
global stop_generation
|
| 88 |
+
|
| 89 |
+
stop_generation.clear()
|
| 90 |
+
|
| 91 |
+
if not user_message or not str(user_message).strip():
|
| 92 |
+
yield displayed_history or [], ""
|
| 93 |
+
return
|
| 94 |
+
|
| 95 |
+
with lock:
|
| 96 |
+
if current_chat_name not in conversations:
|
| 97 |
+
conversations[current_chat_name] = []
|
| 98 |
+
local_hist = conversations[current_chat_name].copy()
|
| 99 |
+
|
| 100 |
+
local_hist.append((str(user_message), ""))
|
| 101 |
+
yield local_hist, ""
|
| 102 |
+
|
| 103 |
+
# Prompt optimisé
|
| 104 |
+
formatted_prompt = build_conversation_prompt(local_hist[:-1], str(user_message))
|
| 105 |
+
|
| 106 |
+
partial = ""
|
| 107 |
+
try:
|
| 108 |
+
# Génération avec paramètres optimisés
|
| 109 |
+
stream = llm.create_completion(
|
| 110 |
+
prompt=formatted_prompt,
|
| 111 |
+
max_tokens=1024, # Réduit pour plus de vitesse
|
| 112 |
+
temperature=0.7,
|
| 113 |
+
top_p=0.9,
|
| 114 |
+
repeat_penalty=1.1,
|
| 115 |
+
stop=["### Instruction:", "### Response:", "\n\n"],
|
| 116 |
+
stream=True
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
for chunk in stream:
|
| 120 |
+
if stop_generation.is_set():
|
| 121 |
+
break
|
| 122 |
+
|
| 123 |
+
if "choices" in chunk and chunk["choices"]:
|
| 124 |
+
token = chunk["choices"][0].get("text", "")
|
| 125 |
+
if token:
|
| 126 |
+
partial += token
|
| 127 |
+
cleaned = clean_output(partial)
|
| 128 |
+
local_hist[-1] = (str(user_message), cleaned)
|
| 129 |
+
yield local_hist, ""
|
| 130 |
+
|
| 131 |
+
except Exception as e:
|
| 132 |
+
err_text = f"[Erreur: {e}]"
|
| 133 |
+
local_hist[-1] = (str(user_message), err_text)
|
| 134 |
+
yield local_hist, ""
|
| 135 |
+
|
| 136 |
+
finally:
|
| 137 |
+
with lock:
|
| 138 |
+
conversations[current_chat_name] = local_hist.copy()
|
| 139 |
+
yield local_hist, ""
|
| 140 |
+
|
| 141 |
+
# -------------------------
|
| 142 |
+
# INTERFACE GRADIO OPTIMISÉE
|
| 143 |
+
# -------------------------
|
| 144 |
+
css = """
|
| 145 |
+
:root {
|
| 146 |
+
--primary-color: #4f46e5;
|
| 147 |
+
--primary-hover: #4338ca;
|
| 148 |
+
--chat-bg: #0f172a;
|
| 149 |
+
--input-bg: #1e293b;
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
#chatbot {
|
| 153 |
+
flex-grow: 1;
|
| 154 |
+
height: 600px !important;
|
| 155 |
+
background: var(--chat-bg);
|
| 156 |
+
border-radius: 16px;
|
| 157 |
+
padding: 20px;
|
| 158 |
+
overflow-y: auto;
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
#input-container {
|
| 162 |
+
display: flex;
|
| 163 |
+
gap: 8px;
|
| 164 |
+
padding: 16px 0;
|
| 165 |
+
align-items: center;
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
#msg_input {
|
| 169 |
+
flex-grow: 1;
|
| 170 |
+
background: var(--input-bg);
|
| 171 |
+
color: #fff;
|
| 172 |
+
border: 1px solid #334155;
|
| 173 |
+
border-radius: 24px;
|
| 174 |
+
padding: 16px 20px;
|
| 175 |
+
font-size: 16px;
|
| 176 |
+
}
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
with gr.Blocks(css=css, title="Alisia Chat - Ultra Rapide", theme=gr.themes.Soft()) as demo:
|
| 180 |
+
gr.Markdown("## 🚀 Alisia Chat - Version Optimisée")
|
| 181 |
+
gr.Markdown("Interface ultra-rapide avec llama.cpp")
|
| 182 |
+
|
| 183 |
+
with gr.Row():
|
| 184 |
+
chatbot = gr.Chatbot(height=500, show_label=False)
|
| 185 |
+
|
| 186 |
+
with gr.Row():
|
| 187 |
+
msg_input = gr.Textbox(
|
| 188 |
+
placeholder="Posez votre question à Alisia...",
|
| 189 |
+
lines=2,
|
| 190 |
+
show_label=False
|
| 191 |
+
)
|
| 192 |
+
send_btn = gr.Button("Envoyer", variant="primary")
|
| 193 |
+
stop_btn = gr.Button("Arrêter", variant="stop", visible=False)
|
| 194 |
+
|
| 195 |
+
# Événements simplifiés
|
| 196 |
+
def toggle_buttons():
|
| 197 |
+
return gr.update(visible=False), gr.update(visible=True)
|
| 198 |
+
|
| 199 |
+
send_btn.click(
|
| 200 |
+
fn=toggle_buttons,
|
| 201 |
+
inputs=None,
|
| 202 |
+
outputs=[send_btn, stop_btn],
|
| 203 |
+
queue=False
|
| 204 |
+
).then(
|
| 205 |
+
fn=send_message_stream,
|
| 206 |
+
inputs=[msg_input, chatbot, gr.State("Conversation 1")],
|
| 207 |
+
outputs=[chatbot, msg_input],
|
| 208 |
+
queue=True
|
| 209 |
+
).then(
|
| 210 |
+
fn=lambda: (gr.update(visible=True), gr.update(visible=False)),
|
| 211 |
+
inputs=None,
|
| 212 |
+
outputs=[send_btn, stop_btn],
|
| 213 |
+
queue=False
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
msg_input.submit(
|
| 217 |
+
fn=toggle_buttons,
|
| 218 |
+
inputs=None,
|
| 219 |
+
outputs=[send_btn, stop_btn],
|
| 220 |
+
queue=False
|
| 221 |
+
).then(
|
| 222 |
+
fn=send_message_stream,
|
| 223 |
+
inputs=[msg_input, chatbot, gr.State("Conversation 1")],
|
| 224 |
+
outputs=[chatbot, msg_input],
|
| 225 |
+
queue=True
|
| 226 |
+
).then(
|
| 227 |
+
fn=lambda: (gr.update(visible=True), gr.update(visible=False)),
|
| 228 |
+
inputs=None,
|
| 229 |
+
outputs=[send_btn, stop_btn],
|
| 230 |
+
queue=False
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
stop_btn.click(
|
| 234 |
+
fn=lambda: stop_generation.set(),
|
| 235 |
+
inputs=None,
|
| 236 |
+
outputs=None
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
# -------------------------
|
| 240 |
+
# LANCEMENT
|
| 241 |
+
# -------------------------
|
| 242 |
+
if __name__ == "__main__":
|
| 243 |
+
print("🚀 Lancement de l'interface optimisée...")
|
| 244 |
+
demo.launch(
|
| 245 |
+
share=True,
|
| 246 |
+
server_name="0.0.0.0",
|
| 247 |
+
server_port=7860,
|
| 248 |
+
debug=False # Désactivé pour plus de performance
|
| 249 |
+
)
|