Download and prepare a dataset from Hugging Face
(dataset_id, base_destination)
| 203 | |
| 204 | |
| 205 | def prepare_huggingface_dataset(dataset_id, base_destination): |
| 206 | """Download and prepare a dataset from Hugging Face""" |
| 207 | print(f"Loading dataset {dataset_id} from Hugging Face with streaming...") |
| 208 | |
| 209 | # Find dataset configuration by dataset_id |
| 210 | dataset_config = None |
| 211 | for name, config in datasets.items(): |
| 212 | if config["dataset_id"] == dataset_id: |
| 213 | dataset_config = config |
| 214 | break |
| 215 | |
| 216 | if not dataset_config: |
| 217 | raise ValueError(f"No configuration found for dataset {dataset_id}") |
| 218 | |
| 219 | try: |
| 220 | # Stream the dataset and process in chunks |
| 221 | dataset = load_dataset(dataset_id, split='train', streaming=True) |
| 222 | chunk_size = 200_000 |
| 223 | chunk = [] |
| 224 | file_index = 0 |
| 225 | |
| 226 | for i, example in enumerate(dataset): |
| 227 | chunk.append(example) |
| 228 | if (i + 1) % chunk_size == 0: |
| 229 | # Convert chunk to DataFrame |
| 230 | chunk_df = pd.DataFrame(chunk) |
| 231 | |
| 232 | # Ensure columns |
| 233 | if "id" not in chunk_df.columns: |
| 234 | offset = chunk_size * file_index |
| 235 | chunk_df["id"] = range(offset, offset + len(chunk_df)) |
| 236 | |
| 237 | if "dense_values" not in chunk_df.columns: |
| 238 | # Use the predefined embedding column from configuration |
| 239 | embedding_col = dataset_config["embeddings"] |
| 240 | if embedding_col not in chunk_df.columns: |
| 241 | raise ValueError( |
| 242 | f"Configured embedding column '{embedding_col}' not found in dataset {dataset_id}. Available columns: {chunk_df.columns.tolist()}" |
| 243 | ) |
| 244 | chunk_df["dense_values"] = chunk_df[embedding_col] |
| 245 | |
| 246 | # Save the chunk as parquet |
| 247 | destination = f"{base_destination}/test{file_index}.parquet" |
| 248 | print(f"\nSaving chunk to {destination}") |
| 249 | chunk_df.to_parquet(destination) |
| 250 | |
| 251 | # Clear chunk for next batch |
| 252 | chunk.clear() |
| 253 | file_index += 1 |
| 254 | |
| 255 | # Save any remaining data |
| 256 | if chunk: |
| 257 | chunk_df = pd.DataFrame(chunk) |
| 258 | destination = f"{base_destination}/test{file_index}.parquet" |
| 259 | print(f"\nSaving remaining chunk to {destination}") |
| 260 | chunk_df.to_parquet(destination) |
| 261 | |
| 262 | except Exception as e: |
no test coverage detected