Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 39 additions & 51 deletions build_tools/analysis/gen-csv.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SPDX-FileCopyrightText: 2026 PyThaiNLP Project
# SPDX-License-Identifier: Apache-2.0
"""
Generate detailed CSV report from type annotation analysis
Generate detailed CSV report from type annotation analysis.

Usage:
python gen-csv.py [--input INPUT_JSON] [--output-dir OUTPUT_DIR]
Expand All @@ -19,6 +18,37 @@
from pathlib import Path


def _submodule_of(name: str) -> str:
"""Return the submodule of a dotted name, such as "tokenize"."""
parts = name.split(".")
if len(parts) > 2 and parts[0] == "pythainlp":
return parts[1]
return parts[0]


def _resolve_paths(
input_arg: str | None, output_arg: str
) -> tuple[Path, Path]:
"""
Return the input JSON file and the output directory as paths.

A relative path is resolved against the script directory.
"""
script_dir = Path(__file__).resolve().parent
output_dir = Path(output_arg)
if not output_dir.is_absolute():
output_dir = script_dir / output_dir

# Default input file is in the output directory
if input_arg is None:
return output_dir / "type_hint_analysis.json", output_dir

input_file = Path(input_arg)
if not input_file.is_absolute():
input_file = script_dir / input_file
return input_file, output_dir


def main():
"""Generate CSV files from type annotation analysis JSON."""
# Parse command line arguments
Expand All @@ -37,19 +67,7 @@ def main():
)
args = parser.parse_args()

# Determine paths
script_dir = Path(__file__).resolve().parent
output_dir = Path(args.output_dir)
if not output_dir.is_absolute():
output_dir = script_dir / output_dir

# Default input file is in the output directory
if args.input is None:
input_file = output_dir / "type_hint_analysis.json"
else:
input_file = Path(args.input)
if not input_file.is_absolute():
input_file = script_dir / input_file
input_file, output_dir = _resolve_paths(args.input, args.output_dir)

# Ensure output directory exists
output_dir.mkdir(parents=True, exist_ok=True)
Expand Down Expand Up @@ -78,12 +96,7 @@ def main():
)

for func in data["functions_no_hints"]:
parts = func["name"].split(".")
submodule = (
parts[1]
if len(parts) > 2 and parts[0] == "pythainlp"
else parts[0]
)
submodule = _submodule_of(func["name"])
decorators = ", ".join(func.get("decorators", []))

writer.writerow(
Expand Down Expand Up @@ -121,12 +134,7 @@ def main():
)

for func in data["functions_incomplete_hints"]:
parts = func["name"].split(".")
submodule = (
parts[1]
if len(parts) > 2 and parts[0] == "pythainlp"
else parts[0]
)
submodule = _submodule_of(func["name"])
decorators = ", ".join(func.get("decorators", []))

writer.writerow(
Expand Down Expand Up @@ -194,12 +202,7 @@ def main():
)

for var in data.get("class_variables_no_hints", []):
parts = var["name"].split(".")
submodule = (
parts[1]
if len(parts) > 2 and parts[0] == "pythainlp"
else parts[0]
)
submodule = _submodule_of(var["name"])

writer.writerow(
[
Expand Down Expand Up @@ -228,12 +231,7 @@ def main():
)

for var in data.get("instance_variables_no_hints", []):
parts = var["name"].split(".")
submodule = (
parts[1]
if len(parts) > 2 and parts[0] == "pythainlp"
else parts[0]
)
submodule = _submodule_of(var["name"])

writer.writerow(
[
Expand Down Expand Up @@ -261,12 +259,7 @@ def main():
)

for var in data.get("module_variables_no_hints", []):
parts = var["name"].split(".")
submodule = (
parts[1]
if len(parts) > 2 and parts[0] == "pythainlp"
else parts[0]
)
submodule = _submodule_of(var["name"])

writer.writerow(
[
Expand All @@ -293,12 +286,7 @@ def main():
)

for alias in data.get("type_aliases", []):
parts = alias["name"].split(".")
submodule = (
parts[1]
if len(parts) > 2 and parts[0] == "pythainlp"
else parts[0]
)
submodule = _submodule_of(alias["name"])

writer.writerow(
[
Expand Down
37 changes: 18 additions & 19 deletions build_tools/analysis/type-analyzer.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SPDX-FileCopyrightText: 2026 PyThaiNLP Project
# SPDX-License-Identifier: Apache-2.0
"""
Type Annotation Analyzer for PyThaiNLP
Type Annotation Analyzer for PyThaiNLP.

This script scans the entire repository and analyzes type annotation coverage
for all functions and classes.
Expand All @@ -29,7 +28,7 @@
from typing import Any


def count_mypy_errors_by_submodule(pythainlp_dir: str) -> dict[str, int]:

Check failure on line 31 in build_tools/analysis/type-analyzer.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 16 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=PyThaiNLP_pythainlp&issues=AaHNgMJUuDHHi52pV7QP&open=AaHNgMJUuDHHi52pV7QP&pullRequest=1604
"""
Run mypy on each submodule and count errors.

Expand All @@ -52,8 +51,9 @@
submodule_path = os.path.join(pythainlp_dir, submodule)
try:
# Run mypy on the submodule
result = subprocess.run(
["mypy", submodule_path, "--ignore-missing-imports"],
# Fixed arguments; "mypy" is looked up on PATH on purpose.
result = subprocess.run( # noqa: S603
["mypy", submodule_path, "--ignore-missing-imports"], # noqa: S607
capture_output=True,
text=True,
timeout=60,
Expand All @@ -75,7 +75,7 @@
except FileNotFoundError:
print(" mypy not found, skipping mypy error counting")
return {}
except Exception as e:
except (OSError, subprocess.SubprocessError) as e:
mypy_errors[submodule] = -1 # Indicate error
print(f" {submodule}: error ({e})")

Expand Down Expand Up @@ -108,16 +108,16 @@
) -> tuple[str, int, int]:
"""
Check type hint completeness for a function.

Returns: (status, total_params, hinted_params)
- status: "complete", "incomplete", "none"
- total_params: number of parameters (excluding self/cls)
- hinted_params: number of parameters with type hints
"""
# Count parameters (excluding self/cls)
params = []
for arg in node.args.args:
if arg.arg not in ("self", "cls"):
params.append(arg)
params = [
arg for arg in node.args.args if arg.arg not in ("self", "cls")
]

total_params = len(params)
hinted_params = sum(1 for arg in params if arg.annotation is not None)
Expand Down Expand Up @@ -163,11 +163,10 @@
return True

# Check for typing.TypeAlias or typing_extensions.TypeAlias
if isinstance(node.annotation, ast.Attribute):
if node.annotation.attr == "TypeAlias":
return True

return False
return (
isinstance(node.annotation, ast.Attribute)
and node.annotation.attr == "TypeAlias"
)

def _is_instance_variable(self, target: ast.expr) -> bool:
"""Check if target is an instance variable (self.attr)."""
Expand Down Expand Up @@ -433,7 +432,7 @@
analyzer.visit(tree)

return analyzer.results
except Exception as e:
except (OSError, RecursionError, SyntaxError, ValueError) as e:
print(f"Error analyzing {filepath}: {e}", file=sys.stderr)
return []

Expand All @@ -460,8 +459,8 @@
content = f.read()
# Simple text search - not perfect but gives an approximation
count += content.count(search_name)
except Exception:
pass
except (OSError, ValueError):
continue

return count

Expand Down Expand Up @@ -531,8 +530,8 @@
return "low"


def main():
"""Main function to analyze type hints across the repository."""
def main(): # noqa: C901 # phase2-todo

Check failure on line 533 in build_tools/analysis/type-analyzer.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 55 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=PyThaiNLP_pythainlp&issues=AaHNgMJUuDHHi52pV7QQ&open=AaHNgMJUuDHHi52pV7QQ&pullRequest=1604
"""Analyze type hints across the repository."""
# Parse command line arguments
parser = argparse.ArgumentParser(
description="Analyze type hint coverage in PyThaiNLP"
Expand Down
17 changes: 8 additions & 9 deletions build_tools/convert_crf_to_weights.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import json
import os
import tempfile
from typing import Optional

_SECTIONS = {
"ATTRIBUTES",
Expand All @@ -26,7 +25,7 @@
}


def _parse_weight(weight: str) -> Optional[float]:
def _parse_weight(weight: str) -> float | None:
mantissa, exponent_separator, exponent = weight.lower().partition("e")
if exponent_separator:
if exponent[:1] in ("+", "-"):
Expand All @@ -44,7 +43,7 @@ def _parse_weight(weight: str) -> Optional[float]:
return float(weight)


def _parse_section_header(line: str) -> Optional[str]:
def _parse_section_header(line: str) -> str | None:
section, separator, _ = line.partition(" = {")
if separator and section in _SECTIONS:
return section
Expand All @@ -54,9 +53,9 @@ def _parse_section_header(line: str) -> Optional[str]:
def _parse_label_line(
line: str,
labels: dict[int, str],
current_id: Optional[int],
current_id: int | None,
current_lines: list[str],
) -> tuple[Optional[int], list[str]]:
) -> tuple[int | None, list[str]]:
label_id, separator, label = line.lstrip().partition(":")
if not separator or not label_id.isdecimal():
current_lines.append(line)
Expand All @@ -72,7 +71,7 @@ def _parse_label_line(

def _parse_weighted_row(
line: str, use_last_arrow: bool
) -> Optional[tuple[str, str, float]]:
) -> tuple[str, str, float] | None:
row_id, separator, row = line.lstrip().partition(")")
if (
not separator
Expand Down Expand Up @@ -103,10 +102,10 @@ def _parse_weighted_row(

def _finish_label_section(
section: str,
current_id: Optional[int],
current_id: int | None,
labels: dict[int, str],
current_lines: list[str],
) -> tuple[Optional[int], list[str]]:
) -> tuple[int | None, list[str]]:
if section == "LABELS" and current_id is not None:
labels[current_id] = "\n".join(current_lines)
return None, []
Expand Down Expand Up @@ -145,7 +144,7 @@ def parse_dump_file(
state_features: dict[str, dict[str, float]] = {}

section: str = ""
curr_id: Optional[int] = None
curr_id: int | None = None
curr_str: list[str] = []

with open(dump_path, encoding="utf-8", errors="replace") as file_obj:
Expand Down
20 changes: 11 additions & 9 deletions build_tools/onnx_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
import unicodedata
import urllib.request
from pathlib import Path
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
Expand Down Expand Up @@ -152,7 +152,7 @@ def redirect_request(
msg: str,
headers: HTTPMessage,
newurl: str,
) -> Optional[urllib.request.Request]:
) -> urllib.request.Request | None:
if not newurl.startswith("https://"):
raise ValueError(f"Redirect to a URL that is not https: {newurl}")
return super().redirect_request(req, fp, code, msg, headers, newurl)
Expand Down Expand Up @@ -215,7 +215,7 @@ def normalize_license(text: str) -> str:

def resolve_license(
given: str, licenses: Mapping[str, bool]
) -> tuple[str, Optional[str]]:
) -> tuple[str, str | None]:
"""
Find the SPDX license ID for the license text that a user gave.

Expand All @@ -230,7 +230,7 @@ def resolve_license(
list, each with True if the ID is deprecated
:return: text to record, and a warning (None for an exact match of an
ID that is not deprecated)
:rtype: tuple[str, Optional[str]]
:rtype: tuple[str, str | None]
"""
recorded, normalized = _match_license(given, licenses)
if recorded is None:
Expand All @@ -253,7 +253,7 @@ def resolve_license(

def _match_license(
given: str, licenses: Mapping[str, bool]
) -> tuple[Optional[str], bool]:
) -> tuple[str | None, bool]:
"""Return the matching license ID (or None) and if it was normalized."""
if given in licenses:
return given, False
Expand Down Expand Up @@ -473,8 +473,10 @@ def _format_text(path: Path, info: dict[str, Any]) -> str:
f" opset {opset}",
f" producer {producer}",
f" domain {info['domain']}",
f" model_version {info['model_version_raw']}"
f" ({info['model_version']})",
(
f" model_version {info['model_version_raw']}"
f" ({info['model_version']})"
),
f" graph.name {info['graph_name']}",
f" doc_string {info['doc_string']}",
]
Expand Down Expand Up @@ -653,11 +655,11 @@ def build_parser() -> argparse.ArgumentParser:
return parser


def main(argv: Optional[Sequence[str]] = None) -> int:
def main(argv: Sequence[str] | None = None) -> int:
"""
Run the command line.

:param Optional[Sequence[str]] argv: arguments (default: ``sys.argv``)
:param Sequence[str] | None argv: arguments (default: ``sys.argv``)
:return: exit status; 0 on success
:rtype: int
"""
Expand Down
Loading
Loading