class_docstr: Computes the weak labels of a single-label text classification dataset by applying a given list of rules.
  
  Args:
      dataset: Name of the dataset to which the rules will be applied.
      rules: A list of rules (labeling functions). They must return a string, or ``None`` in case of abstention.
          If None, we will use the rules of the dataset (Default).
      ids: An optional list of record ids to filter the dataset before applying the rules.
      query: An optional ElasticSearch query with the
          `query string syntax <https://docs.argilla.io/en/latest/practical_guides/filter_dataset.html>`_
          to filter the dataset before applying the rules.
      label2int: An optional dict, mapping the labels to integers. Remember that the return type ``None`` means
          abstention (e.g. ``{None: -1}``). By default, we will build a mapping on the fly when applying the rules.
  
  Raises:
      NoRulesFoundError: When you do not provide rules, and the dataset has no rules either.
      DuplicatedRuleNameError: When you provided multiple rules with the same name.
      NoRecordsFoundError: When the filtered dataset is empty.
      MultiLabelError: When trying to get weak labels for a multi-label text classification task.
      MissingLabelError: When provided with a ``label2int`` dict, and a
          weak label or annotation label is not present in its keys.
  
  Examples:
      >>> # Get the weak label matrix from a dataset with rules:
      >>> weak_labels = WeakLabels(dataset="my_dataset")
      >>> weak_labels.matrix()
      >>> weak_labels.summary()
      >>>
      >>> # Get the weak label matrix from rules defined in Python:
      >>> def awesome_rule(record: TextClassificationRecord) -> str:
      ...     return "Positive" if "awesome" in record.text else None
      >>> another_rule = Rule(query="good OR best", label="Positive")
      >>> weak_labels = WeakLabels(dataset="my_dataset", rules=[awesome_rule, another_rule])
      >>> weak_labels.matrix()
      >>> weak_labels.summary()
      >>>
      >>> # Use the WeakLabels object with snorkel's LabelModel:
      >>> from snorkel.labeling.model import LabelModel
      >>> label_model = LabelModel()
      >>> label_model.fit(L_train=weak_labels.matrix(has_annotation=False))
      >>> label_model.score(L=weak_labels.matrix(has_annotation=True), Y=weak_labels.annotation())
      >>> label_model.predict(L=weak_labels.matrix(has_annotation=False))
      >>>
      >>> # For a builtin integration with Snorkel, see `argilla.labeling.text_classification.Snorkel`.
class_docstr_tok: ["Computes","the","weak","labels","of","a","single-label","text","classification","dataset","by","applying","a","given","list","of","rules",".","Args",":","dataset",":","Name","of","the","dataset","to","which","the","rules","will","be","applied",".","rules",":","A","list","of","rules","(","labeling","functions",")",".","They","must","return","a","string",",","or","``","None","``","in","case","of","abstention",".","If","None",",","we","will","use","the","rules","of","the","dataset","(","Default",")",".","ids",":","An","optional","list","of","record","ids","to","filter","the","dataset","before","applying","the","rules",".","query",":","An","optional","ElasticSearch","query","with","the","`","query","string","syntax","<","https",":","\/\/docs.argilla.io\/en\/latest\/practical_guides\/filter_dataset.html",">","`","_","to","filter","the","dataset","before","applying","the","rules",".","label2int",":","An","optional","dict",",","mapping","the","labels","to","integers",".","Remember","that","the","return","type","``","None","``","means","abstention","(","e.g",".","``","{","None",":","-1","}","``",")",".","By","default",",","we","will","build","a","mapping","on","the","fly","when","applying","the","rules",".","Raises",":","NoRulesFoundError",":","When","you","do","not","provide","rules",",","and","the","dataset","has","no","rules","either",".","DuplicatedRuleNameError",":","When","you","provided","multiple","rules","with","the","same","name",".","NoRecordsFoundError",":","When","the","filtered","dataset","is","empty",".","MultiLabelError",":","When","trying","to","get","weak","labels","for","a","multi-label","text","classification","task",".","MissingLabelError",":","When","provided","with","a","``","label2int","``","dict",",","and","a","weak","label","or","annotation","label","is","not","present","in","its","keys",".","Examples",":",">",">",">","#","Get","the","weak","label","matrix","from","a","dataset","with","rules",":",">",">",">","weak_labels","=","WeakLabels","(","dataset=","''","my_dataset","''",")",">",">",">","weak_labels.matrix","(",")",">",">",">","weak_labels.summary","(",")",">",">",">",">",">",">","#","Get","the","weak","label","matrix","from","rules","defined","in","Python",":",">",">",">","def","awesome_rule","(","record",":","TextClassificationRecord",")","-",">","str",":","...","return","``","Positive","''","if","``","awesome","''","in","record.text","else","None",">",">",">","another_rule","=","Rule","(","query=","''","good","OR","best","''",",","label=","''","Positive","''",")",">",">",">","weak_labels","=","WeakLabels","(","dataset=","''","my_dataset","''",",","rules=","[","awesome_rule",",","another_rule","]",")",">",">",">","weak_labels.matrix","(",")",">",">",">","weak_labels.summary","(",")",">",">",">",">",">",">","#","Use","the","WeakLabels","object","with","snorkel","'s","LabelModel",":",">",">",">","from","snorkel.labeling.model","import","LabelModel",">",">",">","label_model","=","LabelModel","(",")",">",">",">","label_model.fit","(","L_train=weak_labels.matrix","(","has_annotation=False",")",")",">",">",">","label_model.score","(","L=weak_labels.matrix","(","has_annotation=True",")",",","Y=weak_labels.annotation","(",")",")",">",">",">","label_model.predict","(","L=weak_labels.matrix","(","has_annotation=False",")",")",">",">",">",">",">",">","#","For","a","builtin","integration","with","Snorkel",",","see","`","argilla.labeling.text_classification.Snorkel","`","."]
docstr: Apply the rules to the dataset.
  
  Args:
      label2int: An optional custom label2int mapping.
  
  Returns:
      The weak label matrix, the annotation array and their label2int mapping.
  
  Raises:
      MissingLabelError: When provided with a ``label2int`` dict, and a
          weak label or annotation label is not present in its keys.
docstr_tok: ["Apply","the","rules","to","the","dataset",".","Args",":","label2int",":","An","optional","custom","label2int","mapping",".","Returns",":","The","weak","label","matrix",",","the","annotation","array","and","their","label2int","mapping",".","Raises",":","MissingLabelError",":","When","provided","with","a","``","label2int","``","dict",",","and","a","weak","label","or","annotation","label","is","not","present","in","its","keys","."]
code: def _apply_rules(
      self, label2int: Optional[Dict[str, int]]
  ) -> Tuple[np.ndarray, np.ndarray, Dict[Optional[str], int]]:
      """Apply the rules to the dataset.
  
      Args:
          label2int: An optional custom label2int mapping.
  
      Returns:
          The weak label matrix, the annotation array and their label2int mapping.
  
      Raises:
          MissingLabelError: When provided with a ``label2int`` dict, and a
              weak label or annotation label is not present in its keys.
      """
      # call apply on the ElasticSearch rules
      for rule in tqdm(self._rules, desc="Preparing rules"):
          if isinstance(rule, Rule):
              rule.apply(self._dataset)
  
      # create weak label matrix, annotation array, final label2int
      weak_label_matrix = np.empty(
          (len(self._records), len(self._rules)), dtype=np.short
      )
      annotation_array = np.empty(len(self._records), dtype=np.short)
      _label2int = {None: -1} if label2int is None else label2int
      if None not in _label2int:
          raise MissingLabelError(
              "Your provided `label2int` mapping does not contain the required abstention label `None`."
          )
  
      for n, record in tqdm(
          enumerate(self._records),
          total=len(self._records),
          desc="Applying rules",
      ):
          # FIRST: fill annotation array
          try:
              annotation = _label2int[record.annotation]
          except KeyError as error:
              # When a label2int was provided, we want to raise an error if the label is missing!
              if label2int is not None:
                  raise MissingLabelError(
                      f"The annotation label '{record.annotation}' is missing in the `label2int` dict {label2int}"
                  ) from error
              # we already have `None` -> we need to subtract 1
              _label2int[record.annotation] = len(_label2int) - 1
              annotation = _label2int[record.annotation]
  
          annotation_array[n] = annotation
  
          # SECOND: fill weak label matrix
          for m, rule in enumerate(self._rules):
              weak_label = rule(record)
              if isinstance(weak_label, list):
                  if len(weak_label) != 1:
                      raise MultiLabelError(
                          "For rules that do not return exactly 1 label, use the `WeakMultiLabels` class."
                      )
                  weak_label = weak_label[0]
  
              try:
                  weak_label = _label2int[weak_label]
              except KeyError as error:
                  if label2int is not None:
                      raise MissingLabelError(
                          f"A rule returned the weak label '{weak_label}', "
                          f"but it is missing in the `label2int` dict {label2int}"
                      ) from error
                  _label2int[weak_label] = len(_label2int) - 1
                  weak_label = _label2int[weak_label]
  
              weak_label_matrix[n, m] = weak_label
  
      return weak_label_matrix, annotation_array, _label2int
  
imports: import warnings
  from collections import Counter
  from typing import Callable, Dict, List, Optional, Tuple, Union
  import numpy
  import pandas
  from tqdm.auto import tqdm
  from argilla import load
  from argilla.client.datasets import DatasetForTextClassification
  from argilla.client.models import TextClassificationRecord
  from argilla.labeling.text_classification.rule import Rule, load_rules
label_desc: Use image node_id 2 for calling the WeakLabels obj's underlying member method code with example usage: obj._apply_rules(label2int) and returns: weak_label_matrix,  annotation_array,  _label2int