Skip to content

hsg.utils

Writers

hsg.utils.writers

CsvWriter(headers)

Bases: Writer

TSV writer (tab-delimited CSV to stdout).

Source code in hsg/utils/writers.py
26
27
28
def __init__(self, headers: list[str]) -> None:
    self.headers = headers
    self.writer = csv.writer(sys.stdout, delimiter='\t')

JsonWriter(keys)

Bases: Writer

JSON-lines writer (one JSON object per row, or a JSON array for writerows).

Source code in hsg/utils/writers.py
42
43
def __init__(self, keys: list[str]) -> None:
    self.keys = keys

TabulateWriter(headers)

Bases: Writer

Pretty-printed table writer using the tabulate library.

Source code in hsg/utils/writers.py
57
58
def __init__(self, headers: list[str]) -> None:
    self.headers = headers

Writer

ABC for output writers (CSV, JSON, tabulate).

writerow(rowdata) abstractmethod

Write a single row.

Source code in hsg/utils/writers.py
14
15
16
@abstractmethod
def writerow(self, rowdata: list[Any]) -> None:
    """Write a single row."""

writerows(data) abstractmethod

Write multiple rows with headers.

Source code in hsg/utils/writers.py
18
19
20
@abstractmethod
def writerows(self, data: list[list[Any]]) -> None:
    """Write multiple rows with headers."""

validate_fields(ctx, param, fields)

Click callback that validates requested output field names against the known set.

Source code in hsg/utils/writers.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def validate_fields(ctx: Any, param: Any, fields: list[str] | str) -> list[str]:
    """Click callback that validates requested output field names against the known set."""
    valid = True
    unsupported_fields: list[str] = []
    if isinstance(fields, str):
        fields = fields.split(',')
    if len(fields) == 0:
        valid = False
    for f in fields:
        if f not in ['known', 'hanzi', 'frame', 'frequency', 'hsk', 'pinyin', 'keyword', 'occurrencies']:
            valid = False
            unsupported_fields.append(f)
    if valid:
        return fields
    raise click.BadParameter(f'unsupported field(s): {", ".join(unsupported_fields)}')

I/O

hsg.utils.io

get_input(text, file)

Gets input from argument, then stdin, then clipboard.

Source code in hsg/utils/io.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def get_input(text: str | None, file: Any) -> str:
    """Gets input from argument, then stdin, then clipboard."""
    if text:
        return text
    elif file and not sys.stdin.isatty():
        with file:
            result: str = file.read()
            return result
    else:
        if clipboard is None:
            raise click.UsageError(
                "no text argument or stdin provided and the 'clipboard' "
                'extra is not installed; install with `pip install hsg[clipboard]`'
            )
        clip_text: str = clipboard.paste()
        return clip_text

Constants

hsg.utils.constants

Logging

hsg.logging_setup

configure_logging(level='warning')

Configure root logger with the given level name.

Source code in hsg/logging_setup.py
11
12
13
14
15
16
def configure_logging(level: str = 'warning') -> None:
    """Configure root logger with the given level name."""
    logging.basicConfig(
        level=LOG_LEVELS.get(level, logging.WARNING),
        format='%(levelname)s: %(message)s',
    )

get_logger(name)

Return a logger for the given module name.

Source code in hsg/logging_setup.py
19
20
21
def get_logger(name: str) -> logging.Logger:
    """Return a logger for the given module name."""
    return logging.getLogger(name)