Aller au contenu

Exemples d'Utilisation de l'API

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

  • Tous les exemples peuvent être trouvés sur GitHub.
  • La référence de l'API MMG utilisée dans cette page peut être trouvée dans Python API.

api_example_convert_file.py

Cet exemple charge un fichier et le convertit.

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

Cet exemple convertit une chaîne Python.

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

Cet exemple convertit une chaîne Python sans en-tête. Au lieu d'un en-tête, il utilise directement un objet Config.

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

Cet exemple crée une table des matières.

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

Cet exemple valide une chaîne de base.

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

Cet exemple vérifie la liste des balises réservées. Les balises réservées ne peuvent pas être utilisées comme balises définies par l'utilisateur.

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

Cet exemple enregistre le résultat converti dans un fichier. Cet exemple crée réellement les fichiers A.md, B.md, C.md dans le répertoire actuel.

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

Cet exemple utilise l'option no suffix lors de l'enregistrement du résultat converti dans un fichier. Cet exemple crée réellement les fichiers README.A, README.B, README dans le répertoire actuel.

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

Cet exemple gère les objets Config.

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')