Clemylia commited on
Commit
cc603d3
·
verified ·
1 Parent(s): 27dbbbd

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +131 -0
README.md CHANGED
@@ -30,3 +30,134 @@ Pour utiliser ce modèle, vous devez charger les fichiers `Betisy-Detectena_weig
30
  * `Betisy-Detectena_tokenizer.joblib` : Le tokenizer utilisé pour le pré-traitement du texte.
31
 
32
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  * `Betisy-Detectena_tokenizer.joblib` : Le tokenizer utilisé pour le pré-traitement du texte.
31
 
32
  ---
33
+
34
+ exemple d'inférence :
35
+
36
+ ```
37
+ # ==============================================================================
38
+ # CODE D'INFÉRENCE SIMPLIFIÉ POUR BETISY-DETECTENA
39
+ # Objectif : Charger le modèle PyTorch et prédire le label (0: Fait, 1: Bêtise)
40
+ # ==============================================================================
41
+
42
+ # --- 1. IMPORTS ET CONFIGURATION ---
43
+
44
+ import torch
45
+ import torch.nn as nn
46
+ import joblib
47
+ from huggingface_hub import hf_hub_download
48
+ from transformers import AutoTokenizer
49
+
50
+ # VOTRE IDENTIFIANT DE DÉPÔT HUGBING FACE
51
+ REPO_ID = "Clemylia/Betisy-Detectena"
52
+
53
+ # Hyperparamètres DÉFINITIFS de votre modèle (DOIVENT correspondre à l'entraînement)
54
+ EMBEDDING_DIM = 100
55
+ HIDDEN_DIM = 64
56
+ OUTPUT_DIM = 2
57
+ MAX_LEN = 30
58
+ MODEL_WEIGHTS_FILENAME = 'Betisy-Detectena_weights.pt'
59
+ TOKENIZER_FILENAME = 'Betisy-Detectena_tokenizer.joblib'
60
+
61
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
62
+ print(f"Périphérique d'inférence : {device}")
63
+
64
+
65
+ # --- 2. DÉFINITION DE L'ARCHITECTURE ---
66
+
67
+ class SimpleClassifier(nn.Module):
68
+ """Architecture SimpleClassifier pour correspondre aux poids sauvegardés."""
69
+ def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim):
70
+ super(SimpleClassifier, self).__init__()
71
+ self.embedding = nn.Embedding(vocab_size, embedding_dim)
72
+ self.rnn = nn.LSTM(embedding_dim, hidden_dim, batch_first=True)
73
+ self.fc = nn.Linear(hidden_dim, output_dim)
74
+
75
+ def forward(self, input_ids):
76
+ embedded = self.embedding(input_ids)
77
+ output, (hidden, cell) = self.rnn(embedded)
78
+ return self.fc(hidden[-1])
79
+
80
+
81
+ # --- 3. FONCTION DE CHARGEMENT DU MODÈLE ---
82
+
83
+ def load_betisy_detectena(repo_id, weights_name, tokenizer_name, embed_dim, hidden_dim, output_dim, device):
84
+ """Télécharge et charge le modèle complet depuis Hugging Face."""
85
+
86
+ # 3a. Téléchargement des fichiers
87
+ print("⏳ Téléchargement des fichiers depuis Hugging Face...")
88
+ weights_path = hf_hub_download(repo_id=repo_id, filename=weights_name)
89
+ tokenizer_path = hf_hub_download(repo_id=repo_id, filename=tokenizer_name)
90
+
91
+ # 3b. Chargement du Tokenizer
92
+ loaded_tokenizer = joblib.load(tokenizer_path)
93
+ VOCAB_SIZE = loaded_tokenizer.vocab_size
94
+
95
+ # 3c. Reconstruction et chargement des poids
96
+ model = SimpleClassifier(VOCAB_SIZE, embed_dim, hidden_dim, output_dim).to(device)
97
+ model.load_state_dict(torch.load(weights_path, map_location=device))
98
+ model.eval() # Mode inférence
99
+
100
+ print(f"✅ Modèle chargé avec {VOCAB_SIZE} tokens dans le vocabulaire.")
101
+ return model, loaded_tokenizer
102
+
103
+
104
+ # --- 4. FONCTION D'INFÉRENCE ---
105
+
106
+ def predict_betisy_detectena(text, model, tokenizer, max_len, device):
107
+ """Prédit le label pour une seule phrase."""
108
+
109
+ # Tokenisation et préparation du tenseur
110
+ encoding = tokenizer.encode_plus(
111
+ text,
112
+ add_special_tokens=True,
113
+ max_length=max_len,
114
+ padding='max_length',
115
+ truncation=True,
116
+ return_tensors='pt',
117
+ )
118
+
119
+ input_ids = encoding['input_ids'].to(device)
120
+
121
+ # Inférence
122
+ with torch.no_grad():
123
+ outputs = model(input_ids)
124
+ probabilities = torch.softmax(outputs, dim=1)
125
+ confidence, prediction = torch.max(probabilities, dim=1)
126
+
127
+ label = "Absurdité (1) 🤡" if prediction.item() == 1 else "Fait Factuel (0) ✅"
128
+
129
+ return label, confidence.item()
130
+
131
+
132
+ # ==============================================================================
133
+ # CODE D'EXÉCUTION PRINCIPAL
134
+ # ==============================================================================
135
+
136
+ if __name__ == "__main__":
137
+
138
+ # CHARGEMENT (étape 1)
139
+ model, tokenizer = load_betisy_detectena(
140
+ REPO_ID,
141
+ MODEL_WEIGHTS_FILENAME,
142
+ TOKENIZER_FILENAME,
143
+ EMBEDDING_DIM,
144
+ HIDDEN_DIM,
145
+ OUTPUT_DIM,
146
+ device
147
+ )
148
+
149
+ print("\n--- TEST D'INFÉRENCE ---")
150
+
151
+ phrases_a_tester = [
152
+ "Le ciel est bleu.",
153
+ "Les cailloux peuvent parler en chantant des airs d'opéra.",
154
+ "Mars est la quatrième planète du système solaire.",
155
+ "Le temps s'est arrêté hier à 15h00 pour la sieste générale."
156
+ ]
157
+
158
+ # PRÉDICTION (étape 2)
159
+ for phrase in phrases_a_tester:
160
+ label, confidence = predict_betisy_detectena(phrase, model, tokenizer, MAX_LEN, device)
161
+ print(f"-> '{phrase}'")
162
+ print(f" Prédiction : {label} (Confiance : {confidence*100:.2f}%)")
163
+ ```