VincentGOURBIN commited on
Commit
1c0abf0
·
verified ·
1 Parent(s): c143eca

Upload step03_utils.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. step03_utils.py +184 -0
step03_utils.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Utilitaires pour Step 03 - Lecture de la configuration Step 02
4
+ """
5
+
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Dict, Optional
9
+
10
+ class Step03Config:
11
+ """Gestionnaire de configuration Step 03 basé sur la sortie Step 02."""
12
+
13
+ def __init__(self, config_file: str = "step03_config.json"):
14
+ self.config_file = Path(config_file)
15
+ self.config = self.load_config()
16
+
17
+ def load_config(self) -> Dict:
18
+ """Charge la configuration Step 03."""
19
+ if not self.config_file.exists():
20
+ raise FileNotFoundError(
21
+ f"❌ Configuration Step 03 non trouvée: {self.config_file}\n"
22
+ f"💡 Lancez d'abord: python step02_upload_embeddings.py"
23
+ )
24
+
25
+ try:
26
+ with open(self.config_file, 'r', encoding='utf-8') as f:
27
+ config = json.load(f)
28
+
29
+ # Vérification de la structure
30
+ if not config.get("step02_completed"):
31
+ raise ValueError("❌ Step 02 non complété selon la configuration")
32
+
33
+ required_keys = ["huggingface", "embeddings_info"]
34
+ for key in required_keys:
35
+ if key not in config:
36
+ raise ValueError(f"❌ Clé manquante dans configuration: {key}")
37
+
38
+ return config
39
+
40
+ except json.JSONDecodeError as e:
41
+ raise ValueError(f"❌ Configuration Step 03 malformée: {e}")
42
+
43
+ @property
44
+ def repo_id(self) -> str:
45
+ """Repository Hugging Face ID."""
46
+ return self.config["huggingface"]["repo_id"]
47
+
48
+ @property
49
+ def dataset_name(self) -> str:
50
+ """Nom du dataset."""
51
+ return self.config["huggingface"]["dataset_name"]
52
+
53
+ @property
54
+ def embeddings_file(self) -> str:
55
+ """Nom du fichier SafeTensors."""
56
+ return self.config["huggingface"]["files"]["embeddings"]
57
+
58
+ @property
59
+ def metadata_file(self) -> str:
60
+ """Nom du fichier métadonnées."""
61
+ return self.config["huggingface"]["files"]["metadata"]
62
+
63
+ @property
64
+ def total_vectors(self) -> int:
65
+ """Nombre total de vecteurs."""
66
+ return self.config["embeddings_info"]["total_vectors"]
67
+
68
+ @property
69
+ def vector_dimension(self) -> int:
70
+ """Dimension des vecteurs."""
71
+ return self.config["embeddings_info"]["vector_dimension"]
72
+
73
+ @property
74
+ def embedding_model(self) -> str:
75
+ """Modèle d'embedding utilisé."""
76
+ return self.config["embeddings_info"]["embedding_model"]
77
+
78
+ @property
79
+ def download_command(self) -> str:
80
+ """Commande de téléchargement HF Hub."""
81
+ return self.config["usage_examples"]["download_command"]
82
+
83
+ @property
84
+ def load_command(self) -> str:
85
+ """Commande de chargement SafeTensors."""
86
+ return self.config["usage_examples"]["load_command"]
87
+
88
+ def print_summary(self):
89
+ """Affiche un résumé de la configuration."""
90
+ print("📋 Configuration Step 03 - Résumé")
91
+ print("=" * 40)
92
+ print(f"📦 Repository HF: {self.repo_id}")
93
+ print(f"📊 Embeddings: {self.total_vectors:,} vecteurs")
94
+ print(f"📏 Dimension: {self.vector_dimension}")
95
+ print(f"🧠 Modèle: {self.embedding_model}")
96
+ print(f"📁 Fichier: {self.embeddings_file}")
97
+ print(f"⏰ Complété: {self.config.get('completion_timestamp', 'N/A')}")
98
+ print()
99
+ print("🚀 Prêt pour la recherche sémantique !")
100
+
101
+ def get_download_instructions(self) -> Dict[str, str]:
102
+ """Retourne les instructions de téléchargement."""
103
+ return {
104
+ "python_code": f'''
105
+ from huggingface_hub import hf_hub_download
106
+ from safetensors.torch import load_file
107
+ import json
108
+
109
+ # Télécharger les fichiers
110
+ embeddings_file = hf_hub_download(
111
+ repo_id="{self.repo_id}",
112
+ filename="{self.embeddings_file}"
113
+ )
114
+ metadata_file = hf_hub_download(
115
+ repo_id="{self.repo_id}",
116
+ filename="{self.metadata_file}"
117
+ )
118
+
119
+ # Charger les embeddings
120
+ tensors = load_file(embeddings_file)
121
+ embeddings = tensors["embeddings"] # Shape: [{self.total_vectors}, {self.vector_dimension}]
122
+
123
+ # Charger les métadonnées
124
+ with open(metadata_file, 'r') as f:
125
+ metadata = json.load(f)
126
+
127
+ print(f"✅ Embeddings chargés: {{embeddings.shape}}")
128
+ '''.strip(),
129
+ "cli_download": f"huggingface-cli download {self.repo_id} --repo-type dataset",
130
+ "repo_url": f"https://huggingface.co/datasets/{self.repo_id}"
131
+ }
132
+
133
+
134
+ def load_step03_config(config_file: str = "step03_config.json") -> Step03Config:
135
+ """
136
+ Fonction utilitaire pour charger la configuration Step 03.
137
+
138
+ Args:
139
+ config_file: Chemin vers le fichier de configuration
140
+
141
+ Returns:
142
+ Instance de Step03Config
143
+
144
+ Raises:
145
+ FileNotFoundError: Si le fichier n'existe pas
146
+ ValueError: Si la configuration est invalide
147
+ """
148
+ return Step03Config(config_file)
149
+
150
+
151
+ def check_step03_ready() -> bool:
152
+ """
153
+ Vérifie si Step 03 peut être lancé (configuration Step 02 disponible).
154
+
155
+ Returns:
156
+ True si prêt, False sinon
157
+ """
158
+ try:
159
+ config = load_step03_config()
160
+ return config.config.get("step02_completed", False)
161
+ except (FileNotFoundError, ValueError):
162
+ return False
163
+
164
+
165
+ if __name__ == "__main__":
166
+ """Test de la configuration Step 03."""
167
+ try:
168
+ print("🧪 Test de configuration Step 03")
169
+ print("=" * 40)
170
+
171
+ if check_step03_ready():
172
+ config = load_step03_config()
173
+ config.print_summary()
174
+
175
+ print("\n📖 Instructions de téléchargement:")
176
+ instructions = config.get_download_instructions()
177
+ print(instructions["python_code"])
178
+
179
+ else:
180
+ print("❌ Step 03 non prêt")
181
+ print("💡 Lancez d'abord: python step02_upload_embeddings.py")
182
+
183
+ except Exception as e:
184
+ print(f"❌ Erreur: {e}")