Skip to content

API Usage Examples

English | Français | 한국어 | 日本語

  • All examples can be found on GitHub.
  • The reference of MMG API used in this page can be found in Python API.

api_example_convert_file.py

This example loads a file and converts it.

See on GitHub

from typing import Dict
import os
import mmg.api as mmg


def main():
    # Read a markdown file as a string
    base_file = os.path.join(os.path.dirname(__file__), "./sample.base.md")
    base_file = os.path.abspath(base_file)
    print(f"Reading file: {base_file}")

    with open(base_file, "r", encoding="utf-8") as f:
        base_md: str = f.read()

    # Convert markdown string
    converted_mds: Dict[str, str] = mmg.convert(base_md)
    for tag, txt in converted_mds.items():
        print(f"\n>> Tag: {tag}")
        print(txt)


if __name__ == "__main__":
    main()
Output Text
>> Tag: A
# Heading A

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean in ultrices metus, in semper mi.

Footer here.

>> Tag: B
# Heading B

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean in ultrices metus, in semper mi.

Footer here.

>> Tag: C
# Heading C

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean in ultrices metus, in semper mi.

Footer here.

api_example_convert_string.py

This example converts a Python string.

See on GitHub

from typing import Dict
import mmg.api as mmg

base_md: str = """
<!---------------------------->
<!-- multilingual suffix: A, B, C -->
<!---------------------------->
<!-- [A] -->
# Sample Document A

Hello, A!
<!-- [B] -->
# Sample Document B

Hello, B!
<!-- [C] -->
# Sample Document C

Hello, C!
<!-- [common] -->
Thank you for using mmg!
"""


def main():
    converted_mds: Dict[str, str] = mmg.convert(base_md)
    for tag, txt in converted_mds.items():
        print(f"\n>> Tag: {tag}")
        print(txt)


if __name__ == "__main__":
    main()
Output Text
>> Tag: A

# Sample Document A

Hello, A!
Thank you for using mmg!

>> Tag: B

# Sample Document B

Hello, B!
Thank you for using mmg!

>> Tag: C

# Sample Document C

Hello, C!
Thank you for using mmg!

api_example_convert_with_cfg.py

This example converts a Python string without a header. Instead of a header, it directly uses a Config object.

See on GitHub

from typing import Dict
import mmg.api as mmg

base_md: str = """
<!-- [A] -->
# Sample Document A

Hello, A!
<!-- [B] -->
# Sample Document B

Hello, B!
<!-- [C] -->
# Sample Document C

Hello, C!
<!-- [common] -->
Thank you for using mmg!
"""


def main():
    cfg = mmg.Config(lang_tags=["A", "B", "C"])
    print(f"Config: {cfg}")

    converted_mds: Dict[str, str] = mmg.convert(base_md, cfg=cfg)
    for tag, txt in converted_mds.items():
        print(f"\n>> Tag: {tag}")
        print(txt)


if __name__ == "__main__":
    main()
Output Text
>> Tag: A

# Sample Document A

Hello, A!
Thank you for using mmg!

>> Tag: B

# Sample Document B

Hello, B!
Thank you for using mmg!

>> Tag: C

# Sample Document C

Hello, C!
Thank you for using mmg!

api_example_create_toc.py

This example creates a table of contents.

See on GitHub

from typing import List
from mmg.utils import REGEX_PATTERN
from mmg.toc import create_toc, parse_toc_options

base_md: str = """
# 🔎 Header 1

Here are some examples of the table of contents.

**Table of Contents with Emoji**

<!-- [[ multilingual toc: level=2~3 ]] -->

**Table of Contents without Emoji**

<!-- [[ multilingual toc: level=2~3 no-emoji ]] -->

## 📝 Header 2

Foo

### 🌈 Header 3

Bar
"""


def main():
    doc = base_md.splitlines()
    for line in doc:
        if REGEX_PATTERN["auto_toc"].match(line):
            toc_options = parse_toc_options(line)
            toc: List[str] = create_toc(toc_options, doc)
            toc: str = "\n".join(toc)
            print(f">> Toc (no-emoji: {toc_options[2]}):\n{toc}\n")


if __name__ == "__main__":
    main()
Output Text
>> Toc (no-emoji: False):
1. [📝 Header 2](#-header-2)
    1. [🌈 Header 3](#-header-3)

>> Toc (no-emoji: True):
1. [Header 2](#-header-2)
    1. [Header 3](#-header-3)

api_example_health_check.py

This example validates a base string.

See on GitHub

from mmg.health import HealthChecker, HealthStatus

base_md: str = """
<!---------------------------->
<!-- multilingual suffix: A, B, C -->
<!---------------------------->
<!-- [A] -->
# Sample Document A

Hello, A!
<!-- [B] -->
# Sample Document B

Hello, B!
<!-- [C] -->
# Sample Document C

Hello, C!
<!-- [common] -->
Thank you for using mmg!
"""


def main():
    hc = HealthChecker()
    status: HealthStatus = hc.health_check(base_md.splitlines())

    print(f" - Health check: {status.name}")
    print(" - Health messages:")
    for msg in hc.warning_messages:
        print(f"\t[WARN] {msg}")
    for msg in hc.error_messages:
        print(f"\t[ERR ] {msg}")
    print(f" - Tag list: {hc.tag_count}")


if __name__ == "__main__":
    main()
Output Text
 - Health check: HEALTHY
 - Health messages:
 - Tag list: {'A': 1, 'B': 1, 'C': 1}

api_example_reserved_tags.py

This example checks the list of reserved tags. Reserved tags cannot be used as user-defined tags.

See on GitHub

# import mmg.api as mmg
from mmg.config import RESERVED_KEYWORDS


def main():
    print(RESERVED_KEYWORDS)


if __name__ == "__main__":
    main()
Output Text
['common', 'ignore', '<Unknown>']

api_example_save_file.py

This example saves the converted result to a file. This example actually creates A.md, B.md, C.md files in the current directory.

See on GitHub

import os
from typing import Dict
import mmg.api as mmg

base_md: str = """
<!---------------------------->
<!-- multilingual suffix: A, B, C -->
<!---------------------------->
<!-- [A] -->
# Sample Document A

Hello, A!
<!-- [B] -->
# Sample Document B

Hello, B!
<!-- [C] -->
# Sample Document C

Hello, C!
<!-- [common] -->
Thank you for using mmg!
"""


def main(fake: bool = True):
    converted_mds: Dict[str, str] = mmg.convert(base_md)
    if fake:
        print(f"Fake mode: skip saving file. Detected tags: {converted_mds.keys()}")
        return
    for tag, txt in converted_mds.items():
        file_name = os.path.join(os.path.dirname(__file__), f"./{tag}.md")
        file_name = os.path.abspath(file_name)
        with open(file_name, "w", encoding="utf-8") as f:
            f.write(txt)


if __name__ == "__main__":
    main(fake=False)

No output text.

api_example_save_file_no_suffix_option.py

This example uses the no suffix option when saving the converted result to a file. This example actually creates README.A, README.B, README files in the current directory.

See on GitHub

import os
from typing import Dict, List
from mmg.config import Config, extract_config_from_md
import mmg.api as mmg

base_md: str = """
<!---------------------------->
<!-- multilingual suffix: A, B, C -->
<!-- no suffix: C -->
<!---------------------------->
<!-- [A] -->
# Sample Document A

Hello, A!
<!-- [B] -->
# Sample Document B

Hello, B!
<!-- [C] -->
# Sample Document C

Hello, C!
<!-- [common] -->
Thank you for using mmg!
"""


def main(fake: bool = True):

    converted_mds: Dict[str, str] = mmg.convert(base_md)

    base_doc: List[str] = base_md.splitlines()
    cfg: Config = extract_config_from_md(base_doc)

    if fake:
        print(f"Fake mode: skip saving file. Detected tags: {converted_mds.keys()}")
        return
    for tag, txt in converted_mds.items():
        file_name = f"./README.{tag}.md" if tag != cfg.no_suffix else "./README.md"
        file_name = os.path.join(os.path.dirname(__file__), file_name)
        file_name = os.path.abspath(file_name)
        with open(file_name, "w", encoding="utf-8") as f:
            f.write(txt)


if __name__ == "__main__":
    main(fake=False)

No output text.

api_example_set_cfg.py

This example handles Config objects.

See on GitHub

from mmg.api import Config


def main():
    cfg1 = Config()
    cfg1.lang_tags = ["en", "fr", "kr", "jp"]  # Language tags are also used as suffixes.
    cfg1.no_suffix = "en"                      # Used only when saving files.
    print(f"cfg1: {cfg1}")

    cfg2 = Config(
        lang_tags=["en", "fr", "kr", "jp"],
        no_suffix="en",
    )
    print(f"cfg2: {cfg2}")


if __name__ == "__main__":
    main()
Output Text
cfg1: Config(lang_tags=['en', 'fr', 'kr', 'jp'], no_suffix='en')
cfg2: Config(lang_tags=['en', 'fr', 'kr', 'jp'], no_suffix='en')