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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # /// script
3
+ # requires-python = ">=3.12"
4
+ # dependencies = [
5
+ # "sieves[engines]>=0.17.4",
6
+ # "typer>=0.12,<1",
7
+ # "datasets",
8
+ # "huggingface-hub[hf_transfer]",
9
+ # ]
10
+ # ///
11
+
12
+ """Create a zero-shot classification dataset from any Hugging Face dataset using Sieves + Outlines.
13
+
14
+ It supports both single-label (default) and multi-label classification via a flag.
15
+
16
+ Examples
17
+ --------
18
+ Single-label classification:
19
+ uv run examples/create_classification_dataset_with_sieves.py \
20
+ --input-dataset stanfordnlp/imdb \
21
+ --column text \
22
+ --labels "positive,negative" \
23
+ --model HuggingFaceTB/SmolLM-360M-Instruct \
24
+ --output-dataset your-username/imdb-classified
25
+
26
+ With label descriptions:
27
+ uv run examples/create_classification_dataset_with_sieves.py \
28
+ --input-dataset user/support-tickets \
29
+ --column content \
30
+ --labels "bug,feature,question" \
31
+ --label-descriptions "bug:something is broken,feature:request for new functionality,question:asking for help" \
32
+ --model HuggingFaceTB/SmolLM-360M-Instruct \
33
+ --output-dataset your-username/tickets-classified
34
+
35
+ Multi-label classification (adds a multi-hot labels column):
36
+ uv run examples/create_classification_dataset_with_sieves.py \
37
+ --input-dataset ag_news \
38
+ --column text \
39
+ --labels "world,sports,business,science" \
40
+ --multi-label \
41
+ --model HuggingFaceTB/SmolLM-360M-Instruct \
42
+ --output-dataset your-username/agnews-multilabel
43
+
44
+ """
45
+
46
+ import os
47
+
48
+ import huggingface_hub
49
+ import outlines
50
+ import torch
51
+ import transformers
52
+ import typer
53
+ from datasets import Dataset, load_dataset
54
+ from huggingface_hub import HfApi, get_token
55
+ from loguru import logger
56
+ from transformers import AutoModelForCausalLM, AutoTokenizer
57
+
58
+ import sieves
59
+
60
+ app = typer.Typer(add_completion=False, help=__doc__)
61
+
62
+
63
+ # Text constraints (simple sanity checks)
64
+ MIN_TEXT_LENGTH = 3
65
+ MAX_TEXT_LENGTH = 4000
66
+ MULTILABEL_THRESHOLD = 0.5
67
+
68
+
69
+ def _parse_label_descriptions(desc_string: str | None) -> dict[str, str]:
70
+ """Parse a CLI description string into a mapping.
71
+
72
+ Parses strings of the form ``"label1:desc1,label2:desc2"`` into a
73
+ dictionary mapping labels to their descriptions. Commas inside
74
+ descriptions are preserved by continuing the current description until
75
+ the next ``":"`` separator is encountered.
76
+
77
+ Args:
78
+ desc_string: The raw CLI string to parse. If ``None`` or empty,
79
+ returns an empty mapping.
80
+
81
+ Returns:
82
+ A dictionary mapping each label to its description.
83
+
84
+ """
85
+ if not desc_string:
86
+ return {}
87
+
88
+ descriptions: dict[str, str] = {}
89
+
90
+ for label_desc in desc_string.split(","):
91
+ label_desc_parts = label_desc.split(":")
92
+ assert len(label_desc_parts) == 2, \
93
+ f"Invalid label description: must be 'label1:desc1,label2:desc2', got: {label_desc}"
94
+ descriptions[label_desc_parts[0].strip("'").strip()] = label_desc_parts[1].strip("'").strip()
95
+
96
+ return descriptions
97
+
98
+
99
+ def _preprocess_text(text: str) -> str:
100
+ """Normalize and truncate input text for classification.
101
+
102
+ This function trims surrounding whitespace and truncates overly long
103
+ inputs to ``MAX_TEXT_LENGTH`` characters, appending an ellipsis to
104
+ signal truncation. Non-string or falsy inputs yield an empty string.
105
+
106
+ Args:
107
+ text: The raw input text to normalize.
108
+
109
+ Returns:
110
+ A cleaned string suitable for downstream classification. May be an
111
+ empty string if the input was not a valid string.
112
+
113
+ """
114
+ if not text or not isinstance(text, str):
115
+ return ""
116
+ text = text.strip()
117
+ if len(text) > MAX_TEXT_LENGTH:
118
+ text = f"{text[:MAX_TEXT_LENGTH]}..."
119
+ return text
120
+
121
+
122
+ def _is_valid_text(text: str) -> bool:
123
+ """Validate the minimal length constraints for a text sample.
124
+
125
+ Args:
126
+ text: Candidate text after preprocessing.
127
+
128
+ Returns:
129
+ True if the text meets minimal length requirements (``MIN_TEXT_LENGTH``),
130
+ False otherwise.
131
+
132
+ """
133
+ return bool(text and len(text) >= MIN_TEXT_LENGTH)
134
+
135
+
136
+ def _load_and_prepare_data(
137
+ input_dataset: str,
138
+ split: str,
139
+ shuffle: bool,
140
+ shuffle_seed: int | None,
141
+ max_samples: int | None,
142
+ column: str,
143
+ labels: str,
144
+ label_descriptions: str | None,
145
+ hf_token: str | None,
146
+ ) -> tuple[
147
+ Dataset,
148
+ list[str],
149
+ list[str],
150
+ list[int],
151
+ list[str],
152
+ dict[str, str],
153
+ str | None,
154
+ ]:
155
+ """Load the dataset and prepare inputs for classification.
156
+
157
+ This function encapsulates the data-loading and preprocessing path of the
158
+ script: parsing labels/descriptions, detecting tokens, loading/shuffling
159
+ the dataset, validating the target column, preprocessing texts, and
160
+ computing valid indices.
161
+
162
+ Args:
163
+ input_dataset: Dataset repo ID on the Hugging Face Hub.
164
+ split: Dataset split to load (e.g., "train").
165
+ shuffle: Whether to shuffle the dataset.
166
+ shuffle_seed: Seed used when shuffling is enabled.
167
+ max_samples: Optional maximum number of samples to retain.
168
+ column: Name of the text column to classify.
169
+ labels: Comma-separated list of labels.
170
+ label_descriptions: Optional mapping string of the form
171
+ "label:desc,label2:desc2".
172
+ hf_token: Optional Hugging Face token.
173
+
174
+ Returns:
175
+ A tuple containing: (dataset, raw_texts, processed_texts, valid_indices,
176
+ labels_list, desc_map, token)
177
+
178
+ Raises:
179
+ typer.Exit: If labels are missing, dataset loading fails, the column is
180
+ absent, or no valid texts remain after preprocessing.
181
+
182
+ """
183
+ # Parse labels and optional descriptions. Strip surrounding quotes if present.
184
+ labels = labels.strip().strip("'\"")
185
+ labels_list: list[str] = [label.strip().strip("'\"") for label in labels.split(",") if label.strip().strip("'\"")]
186
+ if not labels_list:
187
+ logger.error("No labels provided. Use --labels 'label1,label2,...'")
188
+ raise typer.Exit(code=2)
189
+ desc_map = _parse_label_descriptions(label_descriptions)
190
+
191
+ # Token detection and validation (mirror legacy script behavior)
192
+ token = hf_token or (os.environ.get("HF_TOKEN") or get_token())
193
+ if not token:
194
+ logger.error("No authentication token found. Please either:")
195
+ logger.error("1. Run 'huggingface-cli login'")
196
+ logger.error("2. Set HF_TOKEN environment variable")
197
+ logger.error("3. Pass --hf-token argument")
198
+ raise typer.Exit(code=1)
199
+
200
+ try:
201
+ api = HfApi(token=token)
202
+ user_info = api.whoami()
203
+ name = user_info.get("name") or user_info.get("email") or "<unknown>"
204
+ logger.info(f"Authenticated as: {name}")
205
+ except Exception as e:
206
+ logger.error(f"Authentication failed: {e}")
207
+ logger.error("Please check your token is valid")
208
+ raise typer.Exit(code=1)
209
+
210
+ # Load dataset
211
+ try:
212
+ ds: Dataset = load_dataset(input_dataset, split=split)
213
+ except Exception as e:
214
+ logger.error(f"Failed to load dataset '{input_dataset}': {e}")
215
+ raise typer.Exit(code=1)
216
+
217
+ # Shuffle/select.
218
+ if shuffle:
219
+ ds = ds.shuffle(seed=shuffle_seed)
220
+ if max_samples is not None:
221
+ ds = ds.select(range(min(max_samples, len(ds))))
222
+
223
+ # Validate columns.
224
+ if column not in ds.column_names:
225
+ logger.error(f"Column '{column}' not in dataset columns: {ds.column_names}")
226
+ raise typer.Exit(code=1)
227
+
228
+ # Extract and preprocess texts
229
+ raw_texts: list[str] = list(ds[column])
230
+ processed_texts: list[str] = []
231
+ valid_indices: list[int] = []
232
+ for i, t in enumerate(raw_texts):
233
+ pt = _preprocess_text(t)
234
+ if _is_valid_text(pt):
235
+ processed_texts.append(pt)
236
+ valid_indices.append(i)
237
+
238
+ if not processed_texts:
239
+ logger.error("No valid texts found for classification (after preprocessing).")
240
+ raise typer.Exit(code=1)
241
+
242
+ logger.info(f"Prepared {len(processed_texts)} valid texts out of {len(raw_texts)}")
243
+
244
+ return ds, raw_texts, processed_texts, valid_indices, labels_list, desc_map, token
245
+
246
+
247
+ def _log_stats(
248
+ docs: list[sieves.Doc],
249
+ task: sieves.tasks.Classification,
250
+ labels_list: list[str],
251
+ multi_label: bool,
252
+ raw_texts: list[str],
253
+ processed_texts: list[str],
254
+ valid_indices: list[int],
255
+ ) -> None:
256
+ """Compute and log distributions.
257
+
258
+ Logs per-label distributions and success/skip metrics.
259
+
260
+ Args:
261
+ docs: Classified documents corresponding to processed_texts.
262
+ task: The configured ``Classification`` task instance.
263
+ labels_list: List of label names in canonical order.
264
+ multi_label: Whether classification is multi-label.
265
+ raw_texts: Original text column values.
266
+ processed_texts: Preprocessed, valid texts used for inference.
267
+ valid_indices: Indices mapping processed_texts back to raw_texts rows.
268
+
269
+ Returns:
270
+ None. Pushes datasets to the Hub and logs summary statistics.
271
+
272
+ """
273
+ if multi_label:
274
+ # Log distribution across labels at threshold and skipped count
275
+ label_counts = {label: 0 for label in labels_list}
276
+ for doc in docs:
277
+ result = doc.results[task.id]
278
+ logger.info(result)
279
+ if isinstance(result, list):
280
+ for label, score in result:
281
+ if label in label_counts and score >= MULTILABEL_THRESHOLD:
282
+ label_counts[label] += 1
283
+
284
+ total_processed = len(docs)
285
+ skipped = len(raw_texts) - len(processed_texts)
286
+ logger.info(f"Classification distribution (multi-label, threshold={MULTILABEL_THRESHOLD}):")
287
+
288
+ for label in labels_list:
289
+ count = label_counts.get(label, 0)
290
+ pct = (count / total_processed * 100.0) if total_processed else 0.0
291
+ logger.info(f" {label}: {count} ({pct})")
292
+ if skipped > 0:
293
+ skipped_pct = (skipped / len(raw_texts) * 100.0) if raw_texts else 0.0
294
+ logger.info(f" Skipped/invalid: {skipped} ({skipped_pct})")
295
+
296
+ else:
297
+ # Map results back to original indices; invalid texts receive None
298
+ classifications: list[str | None] = [None] * len(raw_texts)
299
+ for idx, doc in zip(valid_indices, docs):
300
+ result = doc.results[task.id]
301
+ classifications[idx] = result if isinstance(result, str) else result[0]
302
+
303
+ # Log distribution and success rate.
304
+ total_texts = len(raw_texts)
305
+ label_counts = {label: 0 for label in labels_list}
306
+ for label in labels_list:
307
+ label_counts[label] = sum(1 for c in classifications if c == label)
308
+ none_count = sum(1 for c in classifications if c is None)
309
+
310
+ logger.info("Classification distribution (single-label):")
311
+ for label in labels_list:
312
+ count = label_counts[label]
313
+ pct = (count / total_texts * 100.0) if total_texts else 0.0
314
+ logger.info(f" {label}: {count} ({pct})")
315
+
316
+ if none_count > 0:
317
+ none_pct = (none_count / total_texts * 100.0) if total_texts else 0.0
318
+ logger.info(f" Invalid/Skipped: {none_count} ({none_pct})")
319
+
320
+ success_rate = (len(valid_indices) / total_texts * 100.0) if total_texts else 0.0
321
+ logger.info(f"Classification success rate: {success_rate}")
322
+
323
+
324
+ @app.command() # type: ignore[misc]
325
+ def classify(
326
+ input_dataset: str = typer.Option(..., help="Input dataset ID on Hugging Face Hub"),
327
+ column: str = typer.Option(..., help="Name of the text column to classify"),
328
+ labels: str = typer.Option(..., help="Comma-separated list of labels, e.g. 'positive,negative'"),
329
+ output_dataset: str = typer.Option(..., help="Output dataset ID on Hugging Face Hub"),
330
+ model: str = typer.Option(..., help="HF model ID to use"),
331
+ label_descriptions: str | None = typer.Option(
332
+ None, help="Optional descriptions per label: 'label:desc,label2:desc2'"
333
+ ),
334
+ max_samples: int | None = typer.Option(None, help="Max number of samples to process (for testing)"),
335
+ hf_token: str | None = typer.Option(None, help="HF token; if omitted, uses env or cached token"),
336
+ split: str = typer.Option("train", help="Dataset split (default: train)"),
337
+ batch_size: int = typer.Option(64, help="Batch size"),
338
+ max_tokens: int = typer.Option(200, help="Max tokens to generate"),
339
+ shuffle: bool = typer.Option(False, help="Shuffle dataset before sampling"),
340
+ shuffle_seed: int | None = typer.Option(None, help="Shuffle seed"),
341
+ multi_label: bool = typer.Option(False, help="Enable multi-label classification (adds multi-hot 'labels')"),
342
+ ) -> None:
343
+ """Classify a Hugging Face dataset using Sieves + Outlines and push results.
344
+
345
+ Runs zero-shot classification over a specified text column using the Sieves
346
+ ``Classification`` task and the Outlines engine. Supports both single-label
347
+ (default) and multi-label modes. In single-label mode, a "classification"
348
+ column is added to the original dataset. In multi-label mode, a new dataset
349
+ with ``text`` and multi-hot ``labels`` columns is created via
350
+ ``Classification.to_hf_dataset``.
351
+
352
+ Args:
353
+ input_dataset: Dataset repo ID on the Hugging Face Hub.
354
+ column: Name of the text column to classify.
355
+ labels: Comma-separated list of allowed labels.
356
+ output_dataset: Target dataset repo ID to push results to.
357
+ model: Transformers model ID. Must be provided and non-empty.
358
+ label_descriptions: Optional per-label descriptions in the form
359
+ ``label:desc,label2:desc2``.
360
+ max_samples: Optional maximum number of samples to process.
361
+ hf_token: Optional token; if omitted, uses environment or cached login.
362
+ split: Dataset split to load (default: ``"train"``).
363
+ batch_size: Batch size for inference.
364
+ max_tokens: Maximum tokens for generation per prompt.
365
+ shuffle: Whether to shuffle the dataset before selecting samples.
366
+ shuffle_seed: Seed used for shuffling.
367
+ multi_label: If True, enable multi-label classification and output a
368
+ multi-hot labels column; otherwise outputs single-label strings.
369
+
370
+ Returns:
371
+ None. Results are pushed to the Hugging Face Hub under ``output_dataset``.
372
+
373
+ Raises:
374
+ typer.Exit: If dataset loading fails, a required column is missing, or
375
+ no valid texts are available for classification.
376
+
377
+ """
378
+ token = os.environ.get("HF_TOKEN") or huggingface_hub.get_token()
379
+ if token:
380
+ huggingface_hub.login(token=token)
381
+
382
+ logger.info("Loading and preparing data.")
383
+ (
384
+ ds,
385
+ raw_texts,
386
+ processed_texts,
387
+ valid_indices,
388
+ labels_list,
389
+ desc_map,
390
+ token,
391
+ ) = _load_and_prepare_data(
392
+ input_dataset=input_dataset,
393
+ split=split,
394
+ shuffle=shuffle,
395
+ shuffle_seed=shuffle_seed,
396
+ max_samples=max_samples,
397
+ column=column,
398
+ labels=labels,
399
+ label_descriptions=label_descriptions,
400
+ hf_token=hf_token,
401
+ )
402
+
403
+ # Build model.
404
+ info = HfApi().model_info(model)
405
+ device = torch.cuda.get_device_name(0) if torch.cuda.is_available() else None
406
+ zeroshot_tag = "zero-shot-classification"
407
+ # Explicitly designed for zero-shot classification: build directly as pipeline.
408
+ if info.pipeline_tag == zeroshot_tag or zeroshot_tag in set(info.tags or []):
409
+ logger.info("Initializing zero-shot classifciation pipeline.")
410
+ model = transformers.pipeline(zeroshot_tag, model=model, device=device)
411
+ # Otherwise: build Outlines model around it to enforce structured generation.
412
+ else:
413
+ logger.info("Initializing Outlines model.")
414
+ model = outlines.models.from_transformers(
415
+ AutoModelForCausalLM.from_pretrained(model, **({"device": device} if device else {})),
416
+ AutoTokenizer.from_pretrained(model),
417
+ )
418
+
419
+ # Build task and pipeline.
420
+ logger.info("Initializing pipeline.")
421
+ task = sieves.tasks.Classification(
422
+ labels=labels_list,
423
+ model=model,
424
+ generation_settings=sieves.GenerationSettings(
425
+ inference_kwargs={"max_new_tokens": max_tokens},
426
+ strict_mode=False,
427
+ ),
428
+ batch_size=batch_size,
429
+ label_descriptions=desc_map or None,
430
+ multi_label=multi_label,
431
+ )
432
+ pipe = sieves.Pipeline([task])
433
+
434
+ docs = [sieves.Doc(text=t) for t in processed_texts]
435
+ logger.critical(
436
+ f"Running {'multi-label ' if multi_label else ''}classification pipeline with labels {labels_list} on "
437
+ f"{len(docs)} docs."
438
+ )
439
+ docs = list(pipe([sieves.Doc(text=t) for t in processed_texts]))
440
+
441
+ logger.critical("Logging stats.")
442
+ _log_stats(
443
+ docs=docs,
444
+ task=task,
445
+ labels_list=labels_list,
446
+ multi_label=multi_label,
447
+ raw_texts=raw_texts,
448
+ processed_texts=processed_texts,
449
+ valid_indices=valid_indices,
450
+ )
451
+
452
+ logger.info("Collecting and pushing results.")
453
+ ds = task.to_hf_dataset(docs, threshold=MULTILABEL_THRESHOLD)
454
+ ds.push_to_hub(
455
+ output_dataset,
456
+ token=token,
457
+ commit_message=f"Add classifications using Sieves + Outlines (multi-label; threshold={MULTILABEL_THRESHOLD})"
458
+ )
459
+
460
+
461
+ @app.command("examples") # type: ignore[misc]
462
+ def show_examples() -> None:
463
+ """Print example commands for common use cases.
464
+
465
+ This mirrors the examples that were previously printed when running the
466
+ legacy script without arguments.
467
+ """
468
+ cmds = [
469
+ "Example commands:",
470
+ "\n# Simple classification:",
471
+ "uv run examples/create_classification_dataset_with_sieves.py \\",
472
+ " --input-dataset stanfordnlp/imdb \\",
473
+ " --column text \\",
474
+ " --labels 'positive,negative' \\",
475
+ " --model MoritzLaurer/deberta-v3-large-zeroshot-v2.0 \\",
476
+ " --output-dataset your-username/imdb-classified",
477
+ "\n# With label descriptions:",
478
+ "uv run examples/create_classification_dataset_with_sieves.py \\",
479
+ " --input-dataset user/support-tickets \\",
480
+ " --column content \\",
481
+ " --labels 'bug,feature,question' \\",
482
+ " --label-descriptions 'bug:something is broken or not working,feature:request for new functionality,"
483
+ "question:asking for help or clarification' \\",
484
+ " --model MoritzLaurer/deberta-v3-large-zeroshot-v2.0 \\",
485
+ " --output-dataset your-username/tickets-classified",
486
+ "\n# Multi-label classification:",
487
+ "uv run examples/create_classification_dataset_with_sieves.py \\",
488
+ " --input-dataset ag_news \\",
489
+ " --column text \\",
490
+ " --labels 'world,sports,business,science' \\",
491
+ " --multi-label \\",
492
+ " --model MoritzLaurer/deberta-v3-large-zeroshot-v2.0 \\",
493
+ " --output-dataset your-username/agnews-multilabel",
494
+ ]
495
+ for line in cmds:
496
+ typer.echo(line)
497
+
498
+
499
+ if __name__ == "__main__":
500
+ app()