Mauricio-100 commited on
Commit
a84492b
·
verified ·
1 Parent(s): 86cf7d7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +141 -70
app.py CHANGED
@@ -1,9 +1,7 @@
1
- # app.py - Vrai entraînement AutoTrain (Version corrigée)
2
  import gradio as gr
3
  import os
4
- import subprocess
5
- import threading
6
- from huggingface_hub import HfApi, login
7
 
8
  # Authentification avec le token du secret
9
  hf_token = os.environ.get("HF_TOKEN")
@@ -15,7 +13,7 @@ class RealTrainer:
15
  self.is_training = False
16
 
17
  def real_training(self, epochs, learning_rate, batch_size):
18
- """Lance un VRAI entraînement"""
19
  if self.is_training:
20
  yield "❌ Un entraînement est déjà en cours!"
21
  return
@@ -56,21 +54,24 @@ class RealTrainer:
56
  output_lines.append(f"✅ Dataset chargé: {len(dataset['train'])} échantillons")
57
  yield "\n".join(output_lines)
58
 
59
- # Étape 3: Préparation des données
60
- output_lines.append("🔤 Préparation et tokenisation des données...")
61
  yield "\n".join(output_lines)
62
 
63
- def prepare_text(examples):
64
  texts = []
65
  for i in range(len(examples['instruction'])):
66
  instruction = examples['instruction'][i] or ""
67
  input_text = examples['input'][i] or ""
68
  output = examples['output'][i] or ""
69
- text = f"Instruction: {instruction}\nInput: {input_text}\nOutput: {output}"
 
 
 
70
  texts.append(text)
71
  return {"text": texts}
72
 
73
- dataset = dataset.map(prepare_text, batched=True)
74
 
75
  def tokenize_function(examples):
76
  return tokenizer(
@@ -78,7 +79,6 @@ class RealTrainer:
78
  truncation=True,
79
  padding=True,
80
  max_length=512,
81
- return_tensors="pt"
82
  )
83
 
84
  tokenized_dataset = dataset.map(
@@ -87,7 +87,7 @@ class RealTrainer:
87
  remove_columns=dataset['train'].column_names
88
  )
89
 
90
- output_lines.append("✅ Données préparées!")
91
  yield "\n".join(output_lines)
92
 
93
  # Étape 4: Configuration de l'entraînement
@@ -138,11 +138,12 @@ class RealTrainer:
138
  output_lines.append("📤 Push vers Hugging Face...")
139
  yield "\n".join(output_lines)
140
 
141
- trainer.push_to_hub(commit_message=f"Entraînement AutoTrain: {epochs} epochs, LR: {learning_rate}")
142
 
143
  output_lines.append(f"🎉 ENTRAÎNEMENT TERMINÉ!")
144
  output_lines.append(f"📉 Loss final: {train_result.metrics['train_loss']:.4f}")
145
  output_lines.append(f"🔗 Modèle disponible: https://huggingface.co/Gopu-poss/unity-tinny-go")
 
146
  output_lines.append(f"📊 Échantillons: {len(tokenized_dataset)}")
147
 
148
  self.is_training = False
@@ -152,8 +153,8 @@ class RealTrainer:
152
  self.is_training = False
153
  yield f"❌ Erreur pendant l'entraînement: {str(e)}"
154
 
155
- def chat_with_model(message, history):
156
- """Interface de chat avec le modèle entraîné"""
157
  try:
158
  from transformers import AutoTokenizer, AutoModelForCausalLM
159
  import torch
@@ -162,39 +163,95 @@ def chat_with_model(message, history):
162
  try:
163
  tokenizer = AutoTokenizer.from_pretrained("./unity-tinny-go-trained")
164
  model = AutoModelForCausalLM.from_pretrained("./unity-tinny-go-trained")
 
165
  except:
166
  tokenizer = AutoTokenizer.from_pretrained("Gopu-poss/unity-tinny-go")
167
  model = AutoModelForCausalLM.from_pretrained("Gopu-poss/unity-tinny-go")
 
168
 
169
  if tokenizer.pad_token is None:
170
  tokenizer.pad_token = tokenizer.eos_token
171
 
172
- # Préparation du prompt
173
- prompt = f"Instruction: {message}\n\nResponse:"
 
174
 
175
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=256)
 
176
 
 
177
  with torch.no_grad():
178
  outputs = model.generate(
179
- **inputs,
180
- max_length=300,
181
  temperature=0.7,
182
  do_sample=True,
183
  top_p=0.9,
184
- repetition_penalty=1.2,
185
- pad_token_id=tokenizer.eos_token_id
 
 
186
  )
187
 
188
- response = tokenizer.decode(outputs[0], skip_special_tokens=True)
189
- # Extraire seulement la réponse
190
- if "Response:" in response:
191
- response = response.split("Response:")[-1].strip()
 
 
 
 
192
 
193
  return response
194
 
195
  except Exception as e:
196
  return f"❌ Erreur: {str(e)}"
197
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  # Instance du trainer
199
  trainer = RealTrainer()
200
 
@@ -210,38 +267,36 @@ def check_training_status():
210
  return "✅ Prêt pour l'entraînement"
211
 
212
  # Interface Gradio
213
- with gr.Blocks(theme=gr.themes.Soft(), title="Unity-Tinny-Go Real AutoTrain") as demo:
214
 
215
  gr.Markdown("""
216
- # 🚀 Unity-Tinny-Go Real AutoTrain
217
- **VRAI entraînement - Pas de simulation**
218
  """)
219
 
220
- with gr.Tab("🎯 Vrai Entraînement"):
221
  with gr.Row():
222
  with gr.Column():
223
  gr.Markdown("### Configuration de l'entraînement")
 
224
 
225
  epochs = gr.Slider(
226
- minimum=1, maximum=10, value=3, step=1,
227
- label="Nombre d'epochs",
228
- info="Plus d'epochs = meilleur apprentissage"
229
  )
230
 
231
  learning_rate = gr.Number(
232
  value=2e-5,
233
- label="Learning Rate",
234
- info="Recommandé: 1e-5 à 5e-5"
235
  )
236
 
237
  batch_size = gr.Slider(
238
- minimum=1, maximum=4, value=2, step=1,
239
- label="Batch Size",
240
- info="Dépend de la mémoire disponible"
241
  )
242
 
243
  train_btn = gr.Button(
244
- "🚀 Lancer le VRAI entraînement",
245
  variant="primary",
246
  size="lg"
247
  )
@@ -253,47 +308,66 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Unity-Tinny-Go Real AutoTrain") as
253
  )
254
 
255
  with gr.Column():
256
- gr.Markdown("### Logs d'entraînement en direct")
257
  training_output = gr.Textbox(
258
  label="Progress",
259
- lines=15,
260
- max_lines=20,
261
  interactive=False,
262
  show_copy_button=True
263
  )
264
 
265
- with gr.Tab("💬 Tester le Modèle"):
266
- gr.Markdown("### Testez le modèle avant/après entraînement")
267
- chatbot = gr.ChatInterface(
268
- chat_with_model,
269
- title="Unity-Tinny-Go Chat",
270
- description="Discutez avec le modèle pour voir les améliorations",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  examples=[
 
 
 
272
  "Explique la philosophie de Socrate",
273
- "Donne-moi un exemple de code Python",
274
- "Qu'est-ce que l'intelligence artificielle?",
275
- "Comment fonctionne un modèle de langage?"
276
- ]
277
  )
278
 
279
- with gr.Tab("📊 Informations"):
280
  gr.Markdown("""
281
- ### 📋 Informations techniques
282
 
283
- **Modèle utilisé:** `Gopu-poss/unity-tinny-go`
284
- **Dataset:** `Gopu-poss/gopus-1xs`
285
- **Type d'entraînement:** Causal Language Modeling
286
- **Framework:** Transformers + PyTorch
287
 
288
- ### ⚠️ Important
289
- - L'entraînement peut prendre plusieurs minutes
290
- - La mémoire GPU est limitée sur les Spaces gratuits
291
- - Le modèle est automatiquement sauvegardé sur Hugging Face
292
- - Utilisez des batch_size petits (1-2) pour éviter les erreurs mémoire
293
 
294
- ### 🔗 Liens
295
- - [Modèle Unity-Tinny-Go](https://huggingface.co/Gopu-poss/unity-tinny-go)
296
- - [Dataset gopus-1xs](https://huggingface.co/datasets/Gopu-poss/gopus-1xs)
 
 
 
 
297
  """)
298
 
299
  # Événements
@@ -302,10 +376,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Unity-Tinny-Go Real AutoTrain") as
302
  inputs=[epochs, learning_rate, batch_size],
303
  outputs=training_output
304
  )
305
-
306
- # Actualiser le statut
307
- demo.load(check_training_status, outputs=status_text)
308
 
309
- # Lancement SANS queue (correction du bug)
310
  if __name__ == "__main__":
311
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
1
+ # app.py - Unity-Tinny-Go avec identité Gopu/Mauricio Mangituka
2
  import gradio as gr
3
  import os
4
+ from huggingface_hub import login
 
 
5
 
6
  # Authentification avec le token du secret
7
  hf_token = os.environ.get("HF_TOKEN")
 
13
  self.is_training = False
14
 
15
  def real_training(self, epochs, learning_rate, batch_size):
16
+ """Lance un VRAI entraînement avec identité Gopu"""
17
  if self.is_training:
18
  yield "❌ Un entraînement est déjà en cours!"
19
  return
 
54
  output_lines.append(f"✅ Dataset chargé: {len(dataset['train'])} échantillons")
55
  yield "\n".join(output_lines)
56
 
57
+ # Étape 3: Préparation des données avec identité Gopu
58
+ output_lines.append("🔤 Préparation des données avec identité Gopu...")
59
  yield "\n".join(output_lines)
60
 
61
+ def prepare_text_with_identity(examples):
62
  texts = []
63
  for i in range(len(examples['instruction'])):
64
  instruction = examples['instruction'][i] or ""
65
  input_text = examples['input'][i] or ""
66
  output = examples['output'][i] or ""
67
+
68
+ # Ajouter l'identité Gopu dans les données d'entraînement
69
+ identity_prompt = "Je suis Gopu, créé par Mauricio Mangituka. "
70
+ text = f"### Instruction:\n{instruction}\n\n### Input:\n{input_text}\n\n### Response:\n{identity_prompt}{output}"
71
  texts.append(text)
72
  return {"text": texts}
73
 
74
+ dataset = dataset.map(prepare_text_with_identity, batched=True)
75
 
76
  def tokenize_function(examples):
77
  return tokenizer(
 
79
  truncation=True,
80
  padding=True,
81
  max_length=512,
 
82
  )
83
 
84
  tokenized_dataset = dataset.map(
 
87
  remove_columns=dataset['train'].column_names
88
  )
89
 
90
+ output_lines.append("✅ Données préparées avec identité Gopu!")
91
  yield "\n".join(output_lines)
92
 
93
  # Étape 4: Configuration de l'entraînement
 
138
  output_lines.append("📤 Push vers Hugging Face...")
139
  yield "\n".join(output_lines)
140
 
141
+ trainer.push_to_hub(commit_message=f"Entraînement avec identité Gopu: {epochs} epochs")
142
 
143
  output_lines.append(f"🎉 ENTRAÎNEMENT TERMINÉ!")
144
  output_lines.append(f"📉 Loss final: {train_result.metrics['train_loss']:.4f}")
145
  output_lines.append(f"🔗 Modèle disponible: https://huggingface.co/Gopu-poss/unity-tinny-go")
146
+ output_lines.append(f"👤 Identité: Gopu créé par Mauricio Mangituka")
147
  output_lines.append(f"📊 Échantillons: {len(tokenized_dataset)}")
148
 
149
  self.is_training = False
 
153
  self.is_training = False
154
  yield f"❌ Erreur pendant l'entraînement: {str(e)}"
155
 
156
+ def chat_with_gopu_identity(message, history):
157
+ """Interface de chat avec identité Gopu"""
158
  try:
159
  from transformers import AutoTokenizer, AutoModelForCausalLM
160
  import torch
 
163
  try:
164
  tokenizer = AutoTokenizer.from_pretrained("./unity-tinny-go-trained")
165
  model = AutoModelForCausalLM.from_pretrained("./unity-tinny-go-trained")
166
+ model_source = "entraîné avec identité Gopu"
167
  except:
168
  tokenizer = AutoTokenizer.from_pretrained("Gopu-poss/unity-tinny-go")
169
  model = AutoModelForCausalLM.from_pretrained("Gopu-poss/unity-tinny-go")
170
+ model_source = "de base"
171
 
172
  if tokenizer.pad_token is None:
173
  tokenizer.pad_token = tokenizer.eos_token
174
 
175
+ # Préparation du prompt avec identité Gopu
176
+ gopu_identity = "Je suis Gopu, créé par Mauricio Mangituka. "
177
+ prompt = f"### Instruction:\n{message}\n\n### Response:\n{gopu_identity}"
178
 
179
+ # Encodage
180
+ inputs = tokenizer.encode(prompt, return_tensors="pt", truncation=True, max_length=256)
181
 
182
+ # Génération
183
  with torch.no_grad():
184
  outputs = model.generate(
185
+ inputs,
186
+ max_length=400,
187
  temperature=0.7,
188
  do_sample=True,
189
  top_p=0.9,
190
+ repetition_penalty=1.1,
191
+ pad_token_id=tokenizer.eos_token_id,
192
+ eos_token_id=tokenizer.eos_token_id,
193
+ no_repeat_ngram_size=3
194
  )
195
 
196
+ # Décodage
197
+ full_response = tokenizer.decode(outputs[0], skip_special_tokens=True)
198
+
199
+ # Extraire seulement la partie après "### Response:"
200
+ if "### Response:" in full_response:
201
+ response = full_response.split("### Response:")[-1].strip()
202
+ else:
203
+ response = full_response[len(prompt):].strip()
204
 
205
  return response
206
 
207
  except Exception as e:
208
  return f"❌ Erreur: {str(e)}"
209
 
210
+ def simple_chat_with_gopu(message):
211
+ """Version simple avec identité Gopu forcée"""
212
+ try:
213
+ from transformers import AutoTokenizer, AutoModelForCausalLM
214
+ import torch
215
+
216
+ # Chargement simple
217
+ tokenizer = AutoTokenizer.from_pretrained("Gopu-poss/unity-tinny-go")
218
+ model = AutoModelForCausalLM.from_pretrained("Gopu-poss/unity-tinny-go")
219
+
220
+ if tokenizer.pad_token is None:
221
+ tokenizer.pad_token = tokenizer.eos_token
222
+
223
+ # Ajouter l'identité Gopu dans le prompt
224
+ gopu_intro = "Je suis Gopu, créé par Mauricio Mangituka. "
225
+ enhanced_message = f"Réponds en tant que Gopu créé par Mauricio Mangituka. {message}"
226
+
227
+ # Encodage simple
228
+ inputs = tokenizer.encode(enhanced_message, return_tensors="pt", truncation=True, max_length=200)
229
+
230
+ # Génération simple
231
+ with torch.no_grad():
232
+ outputs = model.generate(
233
+ inputs,
234
+ max_length=300,
235
+ temperature=0.7,
236
+ do_sample=True,
237
+ pad_token_id=tokenizer.eos_token_id,
238
+ repetition_penalty=1.1
239
+ )
240
+
241
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
242
+
243
+ # Nettoyer la réponse
244
+ clean_response = response[len(enhanced_message):].strip()
245
+
246
+ # S'assurer que l'identité Gopu est présente
247
+ if "Gopu" not in clean_response and "Mauricio" not in clean_response:
248
+ clean_response = f"Je suis Gopu, créé par Mauricio Mangituka. {clean_response}"
249
+
250
+ return clean_response
251
+
252
+ except Exception as e:
253
+ return f"❌ Erreur: {str(e)}"
254
+
255
  # Instance du trainer
256
  trainer = RealTrainer()
257
 
 
267
  return "✅ Prêt pour l'entraînement"
268
 
269
  # Interface Gradio
270
+ with gr.Blocks(theme=gr.themes.Soft(), title="Gopu - Créé par Mauricio Mangituka") as demo:
271
 
272
  gr.Markdown("""
273
+ # 🤖 Gopu - Créé par Mauricio Mangituka
274
+ **Modèle Unity-Tinny-Go avec identité personnalisée**
275
  """)
276
 
277
+ with gr.Tab("🎯 Entraînement Gopu"):
278
  with gr.Row():
279
  with gr.Column():
280
  gr.Markdown("### Configuration de l'entraînement")
281
+ gr.Markdown("**Le modèle apprendra à se présenter comme 'Gopu, créé par Mauricio Mangituka'**")
282
 
283
  epochs = gr.Slider(
284
+ minimum=1, maximum=5, value=3, step=1,
285
+ label="Nombre d'epochs"
 
286
  )
287
 
288
  learning_rate = gr.Number(
289
  value=2e-5,
290
+ label="Learning Rate"
 
291
  )
292
 
293
  batch_size = gr.Slider(
294
+ minimum=1, maximum=2, value=1, step=1,
295
+ label="Batch Size"
 
296
  )
297
 
298
  train_btn = gr.Button(
299
+ "🚀 Entraîner Gopu",
300
  variant="primary",
301
  size="lg"
302
  )
 
308
  )
309
 
310
  with gr.Column():
311
+ gr.Markdown("### Logs d'entraînement")
312
  training_output = gr.Textbox(
313
  label="Progress",
314
+ lines=12,
 
315
  interactive=False,
316
  show_copy_button=True
317
  )
318
 
319
+ with gr.Tab("💬 Parler avec Gopu"):
320
+ gr.Markdown("### Discutez avec Gopu")
321
+ gr.Markdown("**Gopu: Je suis Gopu, créé par Mauricio Mangituka**")
322
+
323
+ with gr.Row():
324
+ with gr.Column():
325
+ chat_input = gr.Textbox(
326
+ label="Votre message à Gopu",
327
+ placeholder="Posez une question à Gopu...",
328
+ lines=2
329
+ )
330
+ chat_btn = gr.Button("💬 Parler à Gopu", variant="secondary")
331
+
332
+ with gr.Column():
333
+ chat_output = gr.Textbox(
334
+ label="Réponse de Gopu",
335
+ interactive=False,
336
+ lines=6
337
+ )
338
+
339
+ chat_btn.click(simple_chat_with_gopu, inputs=chat_input, outputs=chat_output)
340
+
341
+ # Exemples spécifiques à Gopu
342
+ gr.Examples(
343
  examples=[
344
+ "Qui es-tu?",
345
+ "Qui t'a créé?",
346
+ "Présente-toi",
347
  "Explique la philosophie de Socrate",
348
+ "Parle-moi de ton créateur"
349
+ ],
350
+ inputs=chat_input
 
351
  )
352
 
353
+ with gr.Tab("👤 À propos de Gopu"):
354
  gr.Markdown("""
355
+ ### 🤖 Identité de Gopu
356
 
357
+ **Gopu** est un modèle d'intelligence artificielle créé par **Mauricio Mangituka**.
 
 
 
358
 
359
+ ### 🎯 Objectif de l'entraînement
360
+ - Apprendre au modèle à se présenter comme "Gopu"
361
+ - Mentionner son créateur "Mauricio Mangituka"
362
+ - Maintenir ses capacités en philosophie et programmation
 
363
 
364
+ ### 🔧 Technique
365
+ - **Modèle:** Unity-Tinny-Go
366
+ - **Dataset:** gopus-1xs
367
+ - **Identité:** Gopu / Mauricio Mangituka
368
+
369
+ ### 📝 Exemple de réponse attendue
370
+ *"Je suis Gopu, créé par Mauricio Mangituka. Je peux vous aider avec [votre question]..."*
371
  """)
372
 
373
  # Événements
 
376
  inputs=[epochs, learning_rate, batch_size],
377
  outputs=training_output
378
  )
 
 
 
379
 
380
+ # Lancement
381
  if __name__ == "__main__":
382
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)