Skip to content

mnemocards_essentials

append_to_property

AppendToProperty

Bases: PydanticTask

Append an item to a property of type list.

Provide a collection of pairs consisting of a name and its corresponding value, where the name represents the note property to which we wish to add the value.

Configuration example:

- task: AppendToProperty
  note_property_list: value to append
  another_not_property_list: another value to append

If the given property is not a list you will get an error.

Source code in src/mnemocards_essentials/append_to_property.py
class AppendToProperty(PydanticTask):
    """Append an item to a property of type list.

    Provide a collection of pairs consisting of a name and its corresponding
    value, where the name represents the note property to which we wish to add
    the value.

    Configuration example:

    ```yaml
    - task: AppendToProperty
      note_property_list: value to append
      another_not_property_list: another value to append
    ```

    If the given property is not a list you will get an error.
    """

    _property_value_map: Dict[str, Any] = {}

    @pydantic.root_validator(pre=True)
    @classmethod
    def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        property_value_map: Dict[str, Any] = {}
        for field_name in list(values):
            property_value_map[field_name] = values.pop(field_name)
        values["_property_value_map"] = property_value_map
        return values

    def process_one(self, note: NoteDict) -> NoteDict:
        for k, v in self._property_value_map.items():
            value = note.get(k, [])
            value.append(v)
            note[k] = value
        return note

directory

Directory

Bases: PydanticTask

Read a pipeline object from another directory.

Attributes:

Name Type Description
path Path

Path to the root directory in which the configuration file is. You can also specify a different configuration name.

Source code in src/mnemocards_essentials/directory.py
class Directory(PydanticTask):
    """Read a pipeline object from another directory.

    Attributes:
        path: Path to the root directory in which the configuration file is.
            You can also specify a different configuration name.
    """

    path: Path
    _task: Task = pydantic.PrivateAttr()

    def start(self):
        logger.debug("Directory `start` method.")
        self._task = runner.create_task(self.path)
        self._task.start()

    def process(self, notes: Iterable[NoteDict]) -> Iterable[NoteDict]:
        logger.debug("Directory `process` method.")
        return self._task.process(notes)

    def end(self):
        logger.debug("Directory `end` method.")
        self._task.end()

git

pipeline

Pipeline

Bases: PydanticTask

Basic Mnemocards tasks that represents a sequence of tasks.

Attributes:

Name Type Description
name Optional[str]

Optional pipeline name.

steps List[Task]

List of Mnemocards tasks included in this pipelines.

Source code in src/mnemocards_essentials/pipeline.py
class Pipeline(PydanticTask):
    """Basic Mnemocards tasks that represents a sequence of tasks.

    Attributes:
        name: Optional pipeline name.
        steps: List of Mnemocards tasks included in this pipelines.
    """

    name: Optional[str] = None
    steps: List[Task]

    @pydantic.validator("steps")
    @classmethod
    def validate_at_least_one_step(cls, value):
        if value is not None and not len(value):
            raise ValueError("Pipelines should have at least one step.")
        return value

    def __len__(self) -> int:
        return len(self.steps)

    def start(self):
        for i in self.steps:
            i.start()

    def process(self, notes: Iterable[NoteDict]) -> Iterable[NoteDict]:
        for task in self.steps:
            notes = task.process(notes)
        yield from notes

    def end(self):
        for i in self.steps:
            i.end()

print

Print

Bases: task.Task, pydantic.BaseModel

Print every processed note in the terminal.

Attributes:

Name Type Description
format_ PrintFormat

Format to use when printing the notes.

sort_keys bool

Show note properties sorted alphabetically.

ignore_regex Optional[Pattern]

If any note property match this regex it will not be included in the printed note.

Source code in src/mnemocards_essentials/print.py
class Print(task.Task, pydantic.BaseModel):
    """Print every processed note in the terminal.

    Attributes:
        format_: Format to use when printing the notes.
        sort_keys: Show note properties sorted alphabetically.
        ignore_regex: If any note property match this regex it will not be
            included in the printed note.
    """

    format_: PrintFormat = pydantic.Field(PrintFormat.YAML, alias="format")
    sort_keys: bool = False
    ignore_regex: Optional[Pattern] = None
    _count: int = pydantic.PrivateAttr(0)

    @pydantic.validator("ignore_regex", pre=True)
    @classmethod
    def compile_regex(cls, value):
        if value is not None:
            value = re.compile(value)
        return value

    def process_one(self, note: NoteDict) -> NoteDict:
        if self.ignore_regex is not None:
            note = {
                k: v for k, v in note.items() if not self.ignore_regex.match(k)
            }
        console = Console()
        if self.format_ == PrintFormat.YAML:
            code = yaml.dump(
                note, allow_unicode=True, sort_keys=self.sort_keys
            ).strip()
        elif self.format_ == PrintFormat.JSON:
            code = json.dumps(
                note, ensure_ascii=False, sort_keys=self.sort_keys, indent=2
            )
        else:
            raise NotImplementedError()
        pretty = Syntax(code, self.format_)
        panel = Panel.fit(pretty, title=f"Note {self._count}")
        console.print(panel)
        self._count += 1
        return note

PrintFormat

Bases: str, Enum

Possible formats that can be used in Print.

Source code in src/mnemocards_essentials/print.py
class PrintFormat(str, Enum):
    """Possible formats that can be used in [`Print`][mnemocards_essentials.print.Print]."""

    YAML = "yaml"
    JSON = "json"

read_csv

ReadCsv

Bases: PydanticTask

Read a CSV file.

Comma-separated values (CSV) is a simple, text-based file format for storing tabular data. Records are separated by newlines, and values within a record are separated by comma , characters.

Attributes:

Name Type Description
path Path

Path (directory + filename) of the CSV file to read.

options dict[str, Any]

Extra parameters to pass to the python csv.DictReader.

Source code in src/mnemocards_essentials/read_csv.py
class ReadCsv(PydanticTask):
    """Read a CSV file.

    Comma-separated values (CSV) is a simple, text-based file format for
    storing tabular data. Records are separated by newlines, and values within
    a record are separated by comma `,` characters.

    Attributes:
        path: Path (directory + filename) of the CSV file to read.
        options: Extra parameters to pass to the python `csv.DictReader`.
    """

    path: Path
    options: dict[str, Any] = {}

    def process(self, notes: Iterable[NoteDict]) -> Iterable[NoteDict]:
        file = open(self.path, "r")
        rows = csv.DictReader(file, **self.options)
        return itertools.chain(notes, rows)

read_json

ReadJson

Bases: PydanticTask

Read a JSON file.

Attributes:

Name Type Description
path Path

Path (directory + filename) of the JSON file to read.

Source code in src/mnemocards_essentials/read_json.py
class ReadJson(PydanticTask):
    """Read a JSON file.

    Attributes:
        path: Path (directory + filename) of the JSON file to read.
    """

    path: Path

    def process(self, notes: Iterable[NoteDict]) -> Iterable[NoteDict]:
        file = open(self.path, "r")
        rows = json.load(file)
        return itertools.chain(notes, rows)

read_toml

ReadToml

Bases: PydanticTask

Read a TOML file.

Attributes:

Name Type Description
path Path

Path (directory + filename) of the TOML file to read.

options dict[str, Any]

Extra parameters to pass to the toml.loads function.

Source code in src/mnemocards_essentials/read_toml.py
class ReadToml(PydanticTask):
    """Read a TOML file.

    Attributes:
        path: Path (directory + filename) of the TOML file to read.
        options: Extra parameters to pass to the `toml.loads` function.
    """

    path: Path
    options: dict[str, Any] = {}

    def process(self, notes: Iterable[NoteDict]) -> Iterable[NoteDict]:
        file = open(self.path, "r")
        dictionary = toml.load(file, **self.options)
        rows = _get_first_list_property(dictionary)
        return itertools.chain(notes, rows)

read_tsv

ReadTsv

Bases: PydanticTask

Read a TSV file.

Tab-separated values (TSV) is a simple, text-based file format for storing tabular data. Records are separated by newlines, and values within a record are separated by tab characters.

Attributes:

Name Type Description
path Path

Path (directory + filename) of the TSV file to read.

options dict[str, Any]

Extra parameters to pass to the python csv.DictReader.

Source code in src/mnemocards_essentials/read_tsv.py
class ReadTsv(PydanticTask):
    """Read a TSV file.

    Tab-separated values (TSV) is a simple, text-based file format for storing
    tabular data. Records are separated by newlines, and values within a record
    are separated by tab characters.

    Attributes:
        path: Path (directory + filename) of the TSV file to read.
        options: Extra parameters to pass to the python `csv.DictReader`.
    """

    path: Path
    options: dict[str, Any] = {}

    def process(self, notes: Iterable[NoteDict]) -> Iterable[NoteDict]:
        file = open(self.path, "r")
        self.options.setdefault("delimiter", "\t")
        rows = csv.DictReader(file, **self.options)
        return itertools.chain(notes, rows)

read_xml

ReadXml

Bases: PydanticTask

Read a XML file.

Attributes:

Name Type Description
path Path

Path (directory + filename) of the XML file to read.

Source code in src/mnemocards_essentials/read_xml.py
class ReadXml(PydanticTask):
    """Read a XML file.

    Attributes:
        path: Path (directory + filename) of the XML file to read.
    """

    path: Path
    options: dict[str, Any] = {}

    def process(self, notes: Iterable[NoteDict]) -> Iterable[NoteDict]:
        content = open(self.path, "r").read()
        dictionary = xmltodict.parse(content, **self.options)
        rows = _get_first_list_property(_get_first_list_property(dictionary))
        return itertools.chain(notes, rows)

read_yaml

ReadYaml

Bases: PydanticTask

Read a YAML file.

Attributes:

Name Type Description
path Path

Path (directory + filename) of the YAML file to read.

Source code in src/mnemocards_essentials/read_yaml.py
class ReadYaml(PydanticTask):
    """Read a YAML file.

    Attributes:
        path: Path (directory + filename) of the YAML file to read.
    """

    path: Path

    def process(self, notes: Iterable[NoteDict]) -> Iterable[NoteDict]:
        content = open(self.path, "r").read()
        rows = yaml.safe_load(content)
        return itertools.chain(notes, rows)