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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 4 |
+
import warnings
|
| 5 |
+
warnings.filterwarnings("ignore")
|
| 6 |
+
|
| 7 |
+
class MiMoChatBot:
|
| 8 |
+
def __init__(self):
|
| 9 |
+
self.model_name = "XiaomiMiMo/MiMo-V2-Flash"
|
| 10 |
+
self.tokenizer = None
|
| 11 |
+
self.model = None
|
| 12 |
+
self.pipeline = None
|
| 13 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 14 |
+
|
| 15 |
+
def load_model(self):
|
| 16 |
+
"""Carrega o modelo e tokenizer"""
|
| 17 |
+
try:
|
| 18 |
+
print(f"Carregando modelo {self.model_name}...")
|
| 19 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
| 20 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 21 |
+
self.model_name,
|
| 22 |
+
torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
|
| 23 |
+
device_map="auto" if self.device == "cuda" else None,
|
| 24 |
+
trust_remote_code=True
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
if self.device == "cpu":
|
| 28 |
+
self.model = self.model.to(self.device)
|
| 29 |
+
|
| 30 |
+
# Configura o pipeline
|
| 31 |
+
self.pipeline = pipeline(
|
| 32 |
+
"text-generation",
|
| 33 |
+
model=self.model,
|
| 34 |
+
tokenizer=self.tokenizer,
|
| 35 |
+
max_new_tokens=512,
|
| 36 |
+
temperature=0.7,
|
| 37 |
+
top_p=0.95,
|
| 38 |
+
do_sample=True,
|
| 39 |
+
pad_token_id=self.tokenizer.eos_token_id
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
print("Modelo carregado com sucesso!")
|
| 43 |
+
return True
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f"Erro ao carregar o modelo: {e}")
|
| 46 |
+
return False
|
| 47 |
+
|
| 48 |
+
def generate_response(self, message, history):
|
| 49 |
+
"""Gera uma resposta baseada na mensagem e histórico"""
|
| 50 |
+
if not self.pipeline:
|
| 51 |
+
return "Modelo ainda está carregando. Por favor, aguarde..."
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
# Constrói o contexto com histórico
|
| 55 |
+
context = ""
|
| 56 |
+
for user_msg, bot_msg in history[-3:]: # Usa últimas 3 interações
|
| 57 |
+
context += f"Usuário: {user_msg}\nAssistente: {bot_msg}\n"
|
| 58 |
+
|
| 59 |
+
context += f"Usuário: {message}\nAssistente: "
|
| 60 |
+
|
| 61 |
+
# Gera a resposta
|
| 62 |
+
response = self.pipeline(
|
| 63 |
+
context,
|
| 64 |
+
max_new_tokens=512,
|
| 65 |
+
temperature=0.7,
|
| 66 |
+
do_sample=True,
|
| 67 |
+
pad_token_id=self.tokenizer.eos_token_id,
|
| 68 |
+
eos_token_id=self.tokenizer.eos_token_id,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# Extrai apenas a nova parte da resposta
|
| 72 |
+
generated_text = response[0]['generated_text']
|
| 73 |
+
new_response = generated_text[len(context):].strip()
|
| 74 |
+
|
| 75 |
+
# Limpa a resposta se necessário
|
| 76 |
+
if new_response.startswith("Assistente: "):
|
| 77 |
+
new_response = new_response[len("Assistente: "):]
|
| 78 |
+
|
| 79 |
+
return new_response if new_response else "Desculpe, não consegui gerar uma resposta."
|
| 80 |
+
|
| 81 |
+
except Exception as e:
|
| 82 |
+
return f"Erro ao gerar resposta: {str(e)}"
|
| 83 |
+
|
| 84 |
+
# Inicializa o chatbot
|
| 85 |
+
chatbot = MiMoChatBot()
|
| 86 |
+
|
| 87 |
+
def create_chatbot_app():
|
| 88 |
+
"""Cria a interface do aplicativo Gradio"""
|
| 89 |
+
|
| 90 |
+
# Função principal do chat
|
| 91 |
+
def chat_function(message, history):
|
| 92 |
+
if not message.strip():
|
| 93 |
+
return history, ""
|
| 94 |
+
|
| 95 |
+
# Adiciona a mensagem do usuário ao histórico
|
| 96 |
+
history.append({"role": "user", "content": message})
|
| 97 |
+
|
| 98 |
+
# Gera a resposta
|
| 99 |
+
response = chatbot.generate_response(message, [{"role": h["role"], "content": h["content"]} for h in history[:-1]])
|
| 100 |
+
|
| 101 |
+
# Adiciona a resposta do assistente
|
| 102 |
+
history.append({"role": "assistant", "content": response})
|
| 103 |
+
|
| 104 |
+
return history, ""
|
| 105 |
+
|
| 106 |
+
# Função para limpar o chat
|
| 107 |
+
def clear_chat():
|
| 108 |
+
return [], ""
|
| 109 |
+
|
| 110 |
+
# Carrega o modelo em background
|
| 111 |
+
model_status = gr.Textbox("Carregando modelo...", visible=False)
|
| 112 |
+
|
| 113 |
+
with gr.Blocks() as demo:
|
| 114 |
+
# Header com branding
|
| 115 |
+
gr.HTML("""
|
| 116 |
+
<div style='text-align: center; margin-bottom: 20px;'>
|
| 117 |
+
<h1>🤖 MiMo-V2-Flash Chat Assistant</h1>
|
| 118 |
+
<p>Converse com o modelo de linguagem XiaomiMiMo/MiMo-V2-Flash</p>
|
| 119 |
+
<p><a href='https://huggingface.co/spaces/akhaliq/anycoder' target='_blank' style='color: #007bff; text-decoration: none;'>Built with anycoder</a></p>
|
| 120 |
+
</div>
|
| 121 |
+
""")
|
| 122 |
+
|
| 123 |
+
# Status do modelo
|
| 124 |
+
with gr.Row():
|
| 125 |
+
model_status = gr.Textbox(
|
| 126 |
+
value="🔄 Carregando modelo...",
|
| 127 |
+
label="Status",
|
| 128 |
+
interactive=False,
|
| 129 |
+
scale=2
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# Interface de chat
|
| 133 |
+
with gr.Column():
|
| 134 |
+
chatbot_interface = gr.Chatbot(
|
| 135 |
+
label="Conversa",
|
| 136 |
+
height=500,
|
| 137 |
+
show_copy_button=True,
|
| 138 |
+
bubble_full_width=False,
|
| 139 |
+
type="messages"
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
with gr.Row():
|
| 143 |
+
msg_input = gr.Textbox(
|
| 144 |
+
label="Digite sua mensagem...",
|
| 145 |
+
placeholder="Olá! Como posso ajudar você hoje?",
|
| 146 |
+
scale=4,
|
| 147 |
+
container=False
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
with gr.Column(scale=1):
|
| 151 |
+
submit_btn = gr.Button("Enviar", variant="primary", size="sm")
|
| 152 |
+
clear_btn = gr.Button("Limpar", variant="secondary", size="sm")
|
| 153 |
+
|
| 154 |
+
# Informações adicionais
|
| 155 |
+
with gr.Accordion("ℹ️ Informações do Modelo", open=False):
|
| 156 |
+
gr.Markdown("""
|
| 157 |
+
### Sobre o MiMo-V2-Flash
|
| 158 |
+
|
| 159 |
+
- **Modelo**: XiaomiMiMo/MiMo-V2-Flash
|
| 160 |
+
- **Tipo**: Modelo de linguagem causal
|
| 161 |
+
- **Idioma**: Principalmente Chinês, com capacidade limitada em outros idiomas
|
| 162 |
+
- **Uso**: Conversação, geração de texto, assistência virtual
|
| 163 |
+
|
| 164 |
+
**Dicas de uso:**
|
| 165 |
+
- Seja claro e específico em suas perguntas
|
| 166 |
+
- O modelo funciona melhor com contextos mais curtos
|
| 167 |
+
- Para melhores resultados, use idiomas que o modelo foi treinado
|
| 168 |
+
""")
|
| 169 |
+
|
| 170 |
+
# Configura eventos
|
| 171 |
+
msg_input.submit(chat_function, [msg_input, chatbot_interface], [chatbot_interface, msg_input])
|
| 172 |
+
submit_btn.click(chat_function, [msg_input, chatbot_interface], [chatbot_interface, msg_input])
|
| 173 |
+
clear_btn.click(clear_chat, outputs=[chatbot_interface, msg_input])
|
| 174 |
+
|
| 175 |
+
# Carrega o modelo após a interface ser criada
|
| 176 |
+
demo.load(
|
| 177 |
+
fn=lambda: "✅ Modelo carregado com sucesso!" if chatbot.load_model() else "❌ Erro ao carregar modelo",
|
| 178 |
+
outputs=model_status
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
return demo
|
| 182 |
+
|
| 183 |
+
# Cria e lança o aplicativo
|
| 184 |
+
if __name__ == "__main__":
|
| 185 |
+
app = create_chatbot_app()
|
| 186 |
+
app.launch(
|
| 187 |
+
theme=gr.themes.Soft(
|
| 188 |
+
primary_hue="blue",
|
| 189 |
+
secondary_hue="indigo",
|
| 190 |
+
neutral_hue="slate",
|
| 191 |
+
font=gr.themes.GoogleFont("Inter"),
|
| 192 |
+
text_size="lg",
|
| 193 |
+
spacing_size="lg",
|
| 194 |
+
radius_size="md"
|
| 195 |
+
).set(
|
| 196 |
+
button_primary_background_fill="*primary_600",
|
| 197 |
+
button_primary_background_fill_hover="*primary_700",
|
| 198 |
+
block_title_text_weight="600",
|
| 199 |
+
),
|
| 200 |
+
footer_links=[
|
| 201 |
+
{"label": "Modelo no Hugging Face", "url": "https://huggingface.co/XiaomiMiMo/MiMo-V2-Flash"},
|
| 202 |
+
{"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}
|
| 203 |
+
],
|
| 204 |
+
share=True
|
| 205 |
+
)
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
git+https://github.com/huggingface/transformers
|
| 2 |
+
torch
|
| 3 |
+
torchvision
|
| 4 |
+
torchaudio
|
| 5 |
+
gradio>=6.0
|
| 6 |
+
accelerate
|
| 7 |
+
tokenizers
|
| 8 |
+
datasets
|
| 9 |
+
requests
|
| 10 |
+
Pillow
|