跳转至

Code Documentation

Info

This documentation is automatically generated from the source code function description.

scripts.build

This script is used to build the documentation.

Build multi-language documentation site.

Note

File : build.py Author : Baiqi.Lu ittuann@outlook.com License: MIT License.

Example

$ python ./scripts/build.py

build_docs()

Build Multi-Language Documentation.

Source code in scripts/build.py
def build_docs() -> None:
    """Build Multi-Language Documentation."""
    # Print information about current environment
    print(f"sys.path = {sys.path}")

    if cfg.SITE_PATH.exists():
        print(f"Removing existing site dir: {cfg.SITE_PATH}")
        shutil.rmtree(cfg.SITE_PATH)

    # Build the main documentation
    file = cfg.DOCS_PATH / "mkdocs.yml"
    print(f"Building the main documentation, with configuration file: {file}")
    subprocess.run(["mkdocs", "build", "-f", str(file)], check=True)
    print(f"Main site successfully built at: {cfg.SITE_PATH}")

    # Build other localized documentations
    for file in cfg.DOCS_PATH.glob("mkdocs.*.yml"):
        language_code = file.stem.split(".")[1]
        print(f"Building the {language_code} site with configuration file: {file}")
        subprocess.run(["mkdocs", "build", "-f", str(file)], check=True)
    print(f"Sub site successfully built at: {cfg.SITE_PATH}")

update_404page_title(file_path=cfg.SITE_PATH / '404.html')

Update the title of the 404 page.

Source code in scripts/build.py
def update_404page_title(file_path: Path = cfg.SITE_PATH / "404.html") -> None:
    """Update the title of the 404 page."""
    new_title = "Awesome Intelligent Car Race - 404 Page Not Found"

    if not file_path.exists():
        raise FileNotFoundError(f"The specified 404.html {file_path} does not exist.")

    with open(file_path, encoding="utf-8") as file:
        content = file.read()

    if new_title in content:
        print("The title of the 404 page is already up-to-date.")

    # Replace the existing title with the new title
    updated_content = re.sub(r"<title>.*?</title>", f"<title>{new_title}</title>", content)

    # Write the updated content back to the file
    with open(file_path, "w", encoding="utf-8") as file:
        file.write(updated_content)
    print("Successfully updated the title of the 404 page")

scripts.split

Split Scripts.

This module provides functionalities to split a table based on the award filter column.

Note

File : split.py Author : Baiqi.Lu ittuann@outlook.com License: MIT License.

Example

$ python ./scripts/split.py

awardSort(awards)

奖项排序.

根据指定的中文顺序对奖项进行排序。

Parameters:

Name Type Description Default
awards Series

包含奖项名称的系列

required

Returns:

Type Description
Series

pd.Series: 排序后的系列

Source code in scripts/split.py
def awardSort(awards: pd.Series) -> pd.Series:
    """奖项排序.

    根据指定的中文顺序对奖项进行排序。

    Args:
        awards (pd.Series): 包含奖项名称的系列

    Returns:
        pd.Series: 排序后的系列
    """
    awardOrder = [
        "国家级一等奖",
        "国家级二等奖",
        "国家级三等奖",
        "省级一等奖",
        "省级二等奖",
        "省级三等奖",
    ]
    return awards.map(lambda award: (0, awardOrder.index(award)) if award in awardOrder else (1, award))

splitTable(filtration, outputDir, inputFile=cfg.TABLE_URL_PATH)

根据给定的过滤列将主表拆分.

根据给定的过滤列将主表拆分为多个子表,并将子表保存在指定的输出目录中。 每个子表的名称为过滤列的值,例如,如果过滤列为"年份",则将生成多个子表,分别为"2022.csv"、"2021.csv"等。

Note

应首先运行 urlModification() 以获得修饰后的主表

Parameters:

Name Type Description Default
filtration str

过滤的列名称

required
outputDir Path

输出目录路径

required
inputFile Path

输入的 CSV 文件路径。默认为将使用路径"./table-url.csv"

TABLE_URL_PATH

Raises:

Type Description
ValueError

如果输入的文件不存在,则抛出异常

ValueError

如果输出的目录不存在,则抛出异常

ValueError

如果指定的过滤列不是表的列,则抛出异常

Examples:

>>> splitTable("年份", cfg.DOCS_PATH / "zh" / "year")
Source code in scripts/split.py
def splitTable(filtration: str, outputDir: Path, inputFile: Path = cfg.TABLE_URL_PATH) -> None:
    """根据给定的过滤列将主表拆分.

    根据给定的过滤列将主表拆分为多个子表,并将子表保存在指定的输出目录中。
    每个子表的名称为过滤列的值,例如,如果过滤列为"年份",则将生成多个子表,分别为"2022.csv"、"2021.csv"等。

    Note:
        应首先运行 urlModification() 以获得修饰后的主表

    Args:
        filtration (str): 过滤的列名称
        outputDir (Path): 输出目录路径
        inputFile (Path, optional): 输入的 CSV 文件路径。默认为将使用路径"./table-url.csv"

    Raises:
        ValueError: 如果输入的文件不存在,则抛出异常
        ValueError: 如果输出的目录不存在,则抛出异常
        ValueError: 如果指定的过滤列不是表的列,则抛出异常

    Examples:
        >>> splitTable("年份", cfg.DOCS_PATH / "zh" / "year")
    """
    if not inputFile.exists():
        raise ValueError(f"The specified input file {inputFile} does not exist.")
    if not outputDir.exists():
        raise ValueError(f"The specified output directory {outputDir} does not exist.")

    df = pd.read_csv(inputFile, encoding="utf-8")
    if filtration not in df.columns:
        raise ValueError(f"The specified filtration {filtration} is not a column of the table.")
    grouped = df.groupby(filtration)

    for filtrate, group in grouped:
        sorted_group = group.sort_values(by="获奖", key=awardSort, ascending=True)
        filename = Path(outputDir) / f"{filtrate}.csv"
        sorted_group.to_csv(filename, index=False, encoding="utf-8")
        print(f"Successfully generate sub-table {filtrate}.csv")

urlModification(inputFile=cfg.TABLE_PATH, outputFile=cfg.TABLE_URL_PATH)

修饰主表的URL链接.

Parameters:

Name Type Description Default
inputFile Path

输入的 CSV 文件路径。默认为将使用路径"./table.csv"

TABLE_PATH
outputFile Path

输出的 CSV 文件路径。默认为将使用路径"./table.csv"

TABLE_URL_PATH

Raises:

Type Description
ValueError

如果输入的文件不存在,则抛出异常

Examples:

>>> urlModification()
Source code in scripts/split.py
def urlModification(inputFile: Path = cfg.TABLE_PATH, outputFile: Path = cfg.TABLE_URL_PATH) -> None:
    """修饰主表的URL链接.

    Args:
        inputFile (Path, optional): 输入的 CSV 文件路径。默认为将使用路径"./table.csv"
        outputFile (Path, optional): 输出的 CSV 文件路径。默认为将使用路径"./table.csv"

    Raises:
        ValueError: 如果输入的文件不存在,则抛出异常

    Examples:
        >>> urlModification()
    """
    if not inputFile.exists():
        raise ValueError(f"The specified {inputFile} does not exist.")

    df = pd.read_csv(inputFile, encoding="utf-8")
    df["链接"] = "<" + df["链接"] + '>{:target="_blank"}'
    df.to_csv(outputFile, index=False, encoding="utf-8")
    print(f"Successfully generate url modification table {outputFile}")

tests.test_functions

Code Coverage Test.

Note

File : test_functions.py Author : Baiqi.Lu ittuann@outlook.com License: MIT License.

test_awardSort()

Test case for the awardSort function.

Source code in tests/test_functions.py
def test_awardSort():
    """Test case for the awardSort function."""
    awards = pd.Series(["国家级一等奖", "省级三等奖", "国家级二等奖"])
    sorted_awards = awardSort(awards)
    expected = pd.Series([(0, 0), (0, 5), (0, 1)])
    pd.testing.assert_series_equal(sorted_awards, expected)

test_build_docs()

Test case for the build_docs function.

Source code in tests/test_functions.py
def test_build_docs():
    """Test case for the build_docs function."""
    build_docs()

    assert cfg.SITE_PATH.exists(), "cfg.SITE_PATH should be created"

    for config_file in cfg.DOCS_PATH.glob("mkdocs.*.yml"):
        language_code = config_file.stem.split(".")[1]
        expected_dir = cfg.SITE_PATH / language_code
        # 验证对应的文件夹是否存在
        assert expected_dir.exists(), f"Expected directory for {language_code} does not exist"

test_config_initialization()

Test case for the initialization of the Config class.

Source code in tests/test_functions.py
def test_config_initialization():
    """Test case for the initialization of the Config class."""
    cfg_test = Config()
    assert cfg_test.PROJECT_PATH.is_dir(), "PROJECT_PATH should be a directory"
    assert cfg_test.TABLE_PATH.is_file(), "TABLE_PATH should be a file"

test_config_update_site_path()

Test case for the update_site_path function.

Source code in tests/test_functions.py
def test_config_update_site_path():
    """Test case for the update_site_path function."""
    cfg_test = Config()
    old_path = cfg_test.SITE_PATH
    cfg_test.update_site_path(Path("new_site"))
    assert old_path / "new_site" == cfg_test.SITE_PATH, "SITE_PATH should be updated to new path"

test_splitTable_fail()

Test case for the splitTable function with failure.

Source code in tests/test_functions.py
def test_splitTable_fail():
    """Test case for the splitTable function with failure."""
    with pytest.raises(ValueError):
        splitTable("获奖", Path(__file__).parent, Path("non_existent.csv"))
    with pytest.raises(ValueError):
        splitTable("获奖", Path("non_existent_dir"), cfg.TABLE_PATH)
    with pytest.raises(ValueError):
        splitTable("不存在的列标题", Path(__file__).parent, cfg.TABLE_PATH)

test_splitTable_success()

Test case for the splitTable function with successful execution.

Source code in tests/test_functions.py
def test_splitTable_success():
    """Test case for the splitTable function with successful execution."""
    # 读取输入文件以确定预期年份
    df_input = pd.read_csv(cfg.TABLE_PATH)

    for column_header in ["年份", "组别", "获奖"]:
        expected_categories = sorted(set(df_input[column_header].astype(str)))
        expected_columns = list(df_input.columns)

        splitTable(column_header, Path(__file__).parent)

        for category in expected_categories:
            output_file = Path(__file__).parent / f"{category}.csv"
            # 验证文件成功生成
            assert output_file.exists(), f"Output file {output_file} not found"
            # 验证每个输出文件内容
            df_output = pd.read_csv(output_file)
            assert list(df_output.columns) == expected_columns, f"Columns in {output_file} do not match"
            assert all(
                df_output[column_header].astype(str) == category
            ), f"Category {category} not found in {output_file}"
            output_file.unlink()

test_update_404page_title()

Test case for the test_update_404page_title function. Need run build_docs() first.

Source code in tests/test_functions.py
def test_update_404page_title():
    """Test case for the test_update_404page_title function. Need run build_docs() first."""
    test_file_path = cfg.SITE_PATH / "404.html"
    update_404page_title()

    with open(test_file_path, encoding="utf-8") as file:
        updated_content = file.read()

    assert "<title>Awesome Intelligent Car Race - 404 Page Not Found</title>" in updated_content, "New title not found"
    assert "<title>Awesome-IntelligentCarRace</title>" not in updated_content, "Old title should be removed"

test_update_404page_title_fail()

Test case for the test_update_404page_title function with failure.

Source code in tests/test_functions.py
def test_update_404page_title_fail():
    """Test case for the test_update_404page_title function with failure."""
    update_404page_title()
    with pytest.raises(FileNotFoundError):
        update_404page_title(Path("non_existent_dir"))

test_urlModification_fail()

Test case for the URLModification function with failure.

Source code in tests/test_functions.py
def test_urlModification_fail():
    """Test case for the URLModification function with failure."""
    with pytest.raises(ValueError):
        urlModification(Path("non_existent.csv"))

test_urlModification_success()

Test case for the URLModification function with successful execution.

Source code in tests/test_functions.py
def test_urlModification_success():
    """Test case for the URLModification function with successful execution."""
    output_file = cfg.DOCS_PATH / "test_output.csv"

    urlModification(outputFile=output_file)

    df_output = pd.read_csv(output_file)
    for url in df_output["链接"]:
        assert url.startswith("<") and url.endswith('>{:target="_blank"}'), f"URL {url} is not modified"
    output_file.unlink()