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
6 changes: 3 additions & 3 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,13 @@ jobs:
uses: astral-sh/ruff-action@278981a28ce3188b1e39527901f38254bf3aac89 # v4.1.0
with:
src: "./pythainlp ./tests ./examples ./notebooks"
version: "0.16.10"
version: "0.17.4"
args: check --verbose --config pyproject.toml
- name: Ruff format
uses: astral-sh/ruff-action@278981a28ce3188b1e39527901f38254bf3aac89 # v4.1.0
with:
src: "./pythainlp ./tests ./examples ./notebooks"
version: "0.16.10"
version: "0.17.4"
args: format --check --verbose --config pyproject.toml

cognitive-complexity:
Expand All @@ -84,6 +84,6 @@ jobs:
cache-dependency-path: pyproject.toml
- name: Install flake8
run: |
pip install --only-binary :all: --no-binary flake8-cognitive-complexity,cognitive_complexity "flake8==7.4.1" "flake8-cognitive-complexity==0.1.0"
pip install --only-binary :all: --no-binary flake8-cognitive-complexity,cognitive_complexity "flake8==7.5.0" "flake8-cognitive-complexity==0.1.0"
- name: Check cognitive complexity
run: flake8 pythainlp
2 changes: 1 addition & 1 deletion .github/workflows/mypy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ jobs:

- name: Install mypy
run: |
pip install --only-binary :all: "mypy==1.19.1"
pip install --only-binary :all: "mypy==2.4.1"

- name: Run mypy
run: mypy pythainlp tests
7 changes: 3 additions & 4 deletions .github/workflows/pypi-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ jobs:

- name: Install dependencies
run: |
pip install --only-binary :all: "pip==26.2.1"
pip install --only-binary :all: "pip==26.3"
pip install --only-binary :all: "build==1.6.1" "twine==7.0.0"

# Pins every timestamp in the build and the SBOM to the commit time, so a
Expand All @@ -114,9 +114,8 @@ jobs:
run: twine check dist/*

# Embeds after the build, not with Pitloom's Hatchling build hook.
# Pitloom 0.20.0+ lists only the wheel's payload, so the files the
# embedding rewrites (RECORD and the SBOM itself) are not in the SBOM
# with stale hashes, as they were with 0.19.0.
# The SBOM lists only the wheel's payload, so the files the embedding
# rewrites (RECORD and the SBOM itself) are not in it with stale hashes.
# --verify checks the SBOM is at the PEP 770 location.
# --validate checks the SBOM against the SPDX 3 schema and SHACL shapes.
# Either failing fails this step, which stops publishing.
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/unittest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ jobs:
PYTHONIOENCODING: utf-8
run: |
pip install ".[compact,extra]"
pip install --only-binary :all: --no-binary docopt "coverage==7.16.2" "coveralls==4.1.0"
pip install --only-binary :all: --no-binary docopt "coverage==7.17.2" "coveralls==4.1.0"
coverage run -m unittest tests.core tests.compact tests.extra

# Only submit a report from the "extra" run, to get maximum coverage
Expand All @@ -179,7 +179,7 @@ jobs:
shell: bash
run: |
git fetch --no-tags origin "${BASE_REF}:refs/remotes/origin/${BASE_REF}"
pip install --only-binary :all: "diff-cover==10.6.0"
pip install --only-binary :all: "diff-cover==11.0.1"
coverage xml
# diff-cover matches `**/<path>` for both --include and --exclude.
mapfile -t NOAUTO < <(grep -v -e '^#' -e '^$' tests/diff-cover-noauto.txt | sed 's|^|**/|')
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ Use `pythainlp.is_offline_mode()` to check the current state programmatically.

```python
import pythainlp

print(pythainlp.is_offline_mode()) # True if PYTHAINLP_OFFLINE=1
```

Expand All @@ -132,6 +133,7 @@ Use `pythainlp.is_read_only_mode()` to check the current state programmatically.

```python
import pythainlp

print(pythainlp.is_read_only_mode()) # True if PYTHAINLP_READ_ONLY=1
```

Expand Down
2 changes: 2 additions & 0 deletions README_TH.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ PyThaiNLP ดาวน์โหลดข้อมูล (ดูแค็ตต

```python
import pythainlp

print(pythainlp.is_offline_mode()) # True ถ้า PYTHAINLP_OFFLINE=1
```

Expand All @@ -151,6 +152,7 @@ print(pythainlp.is_offline_mode()) # True ถ้า PYTHAINLP_OFFLINE=1

```python
import pythainlp

print(pythainlp.is_read_only_mode()) # True ถ้า PYTHAINLP_READ_ONLY=1
```

Expand Down
3 changes: 2 additions & 1 deletion build_tools/analysis/gen-csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
--input Input JSON file (default: ./output/type_hint_analysis.json)
--output-dir Directory to save CSV files (default: ./output)
"""

import argparse
import csv
import json
Expand Down Expand Up @@ -55,7 +56,7 @@ def main():

# Load the JSON data
print(f"Loading data from: {input_file}")
with open(input_file, "r") as f:
with open(input_file) as f:
data = json.load(f)

# Create CSV for functions without type hints
Expand Down
96 changes: 44 additions & 52 deletions build_tools/analysis/type-analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
Options:
--output-dir Directory to save output files (default: ./output)
"""

import argparse
import ast
import json
Expand All @@ -25,10 +26,10 @@
import sys
from collections import defaultdict
from pathlib import Path
from typing import Any, Dict, List, Tuple
from typing import Any


def count_mypy_errors_by_submodule(pythainlp_dir: str) -> Dict[str, int]:
def count_mypy_errors_by_submodule(pythainlp_dir: str) -> dict[str, int]:
"""
Run mypy on each submodule and count errors.

Expand Down Expand Up @@ -104,7 +105,7 @@ def is_public(self, name: str) -> bool:

def check_function_type_hints(
self, node: ast.FunctionDef
) -> Tuple[str, int, int]:
) -> tuple[str, int, int]:
"""
Check type hint completeness for a function.
Returns: (status, total_params, hinted_params)
Expand Down Expand Up @@ -140,15 +141,13 @@ def _get_decorator_name(self, decorator: ast.expr) -> str:
"""Extract decorator name from AST node."""
if isinstance(decorator, ast.Name):
return decorator.id
elif isinstance(decorator, ast.Attribute):
if isinstance(decorator, ast.Attribute):
return (
f"{self._get_decorator_name(decorator.value)}"
f".{decorator.attr}"
f"{self._get_decorator_name(decorator.value)}.{decorator.attr}"
)
elif isinstance(decorator, ast.Call):
if isinstance(decorator, ast.Call):
return self._get_decorator_name(decorator.func)
else:
return "unknown"
return "unknown"

def _is_type_alias(self, node: ast.AnnAssign) -> bool:
"""Check if an annotated assignment is a type alias."""
Expand Down Expand Up @@ -182,10 +181,9 @@ def _get_variable_name(self, target: ast.expr) -> str:
"""Extract variable name from assignment target."""
if isinstance(target, ast.Name):
return target.id
elif isinstance(target, ast.Attribute):
if isinstance(target, ast.Attribute):
return target.attr
else:
return "unknown"
return "unknown"

def visit_AnnAssign(self, node: ast.AnnAssign):
"""Visit annotated assignment (variable with type hint)."""
Expand Down Expand Up @@ -382,7 +380,7 @@ def visit_ClassDef(self, node: ast.ClassDef):
self.module_level = old_module_level


def find_python_files(root_dir: str) -> List[str]:
def find_python_files(root_dir: str) -> list[str]:
"""Find all Python files in the given directory."""
python_files = []
root_path = Path(root_dir)
Expand Down Expand Up @@ -417,16 +415,15 @@ def get_module_path(filepath: str, root_dir: str) -> str:
rel_path = os.path.relpath(filepath, root_dir)
module_path = rel_path.replace(os.sep, ".").replace(".py", "")

if module_path.endswith(".__init__"):
module_path = module_path[:-9]
module_path = module_path.removesuffix(".__init__")

return module_path


def analyze_file(filepath: str, root_dir: str) -> List[Dict[str, Any]]:
def analyze_file(filepath: str, root_dir: str) -> list[dict[str, Any]]:
"""Analyze a single Python file for type hints."""
try:
with open(filepath, "r", encoding="utf-8") as f:
with open(filepath, encoding="utf-8") as f:
content = f.read()

tree = ast.parse(content, filename=filepath)
Expand All @@ -446,20 +443,20 @@ def get_submodule(qualified_name: str) -> str:
parts = qualified_name.split(".")
if len(parts) > 2 and parts[0] == "pythainlp":
return parts[1]
elif len(parts) > 1:
if len(parts) > 1:
return parts[0]
return "root"


def count_references(qualified_name: str, all_files: List[str]) -> int:
def count_references(qualified_name: str, all_files: list[str]) -> int:
"""Count how many times a name is referenced in the codebase."""
count = 0
name_parts = qualified_name.split(".")
search_name = name_parts[-1]

for filepath in all_files:
try:
with open(filepath, "r", encoding="utf-8") as f:
with open(filepath, encoding="utf-8") as f:
content = f.read()
# Simple text search - not perfect but gives an approximation
count += content.count(search_name)
Expand All @@ -480,18 +477,17 @@ def get_test_suite(filepath: str, tests_dir: str) -> str:
("testc_", "testx_", "testn_")
):
return "core"
elif filename.startswith("testc_"):
if filename.startswith("testc_"):
return "compact"
elif filename.startswith("testx_"):
if filename.startswith("testx_"):
return "extra"
elif filename.startswith("testn_"):
if filename.startswith("testn_"):
return "noauto"
else:
return "other"
return "other"


def find_corresponding_test_suite(
qualified_name: str, all_results: List[Dict]
qualified_name: str, all_results: list[dict]
) -> str:
"""Find which test suite tests this function/class."""
# Look for test functions that reference this name
Expand Down Expand Up @@ -519,7 +515,7 @@ def find_corresponding_test_suite(
return "unknown"


def assign_priority(result: Dict) -> str:
def assign_priority(result: dict) -> str:
"""Assign priority based on scope, references, and test suite."""
scope = result.get("scope", "private")
refs = result.get("references", 0)
Expand All @@ -529,11 +525,10 @@ def assign_priority(result: Dict) -> str:
if scope == "public" and refs > 10 and test_suite in ("core", "compact"):
return "high"
# Public functions with some references: medium priority
elif scope == "public" and refs > 3:
if scope == "public" and refs > 3:
return "medium"
# Everything else: low priority
else:
return "low"
return "low"


def main():
Expand Down Expand Up @@ -670,8 +665,7 @@ def main():
print("=" * 80)
print(f"Total functions/methods: {total}")
print(
f"Complete type hints: {len(complete):4d} "
f"({pct_complete:5.2f}%)"
f"Complete type hints: {len(complete):4d} ({pct_complete:5.2f}%)"
)
print(
f"Incomplete type hints: {len(incomplete):4d} "
Expand Down Expand Up @@ -705,8 +699,7 @@ def main():
f"({pct_vars_complete:5.2f}%)"
)
print(
f"No type hints: {len(vars_none):4d} "
f"({pct_vars_none:5.2f}%)"
f"No type hints: {len(vars_none):4d} ({pct_vars_none:5.2f}%)"
)
print()

Expand All @@ -731,21 +724,15 @@ def main():
for submodule in sorted(by_submodule.keys()):
data = by_submodule[submodule]
total_sub = (
len(data["complete"])
+ len(data["incomplete"])
+ len(data["none"])
len(data["complete"]) + len(data["incomplete"]) + len(data["none"])
)
pct_comp = (
(len(data["complete"]) / total_sub * 100) if total_sub > 0 else 0
)
pct_inc = (
(len(data["incomplete"]) / total_sub * 100)
if total_sub > 0
else 0
)
pct_no = (
(len(data["none"]) / total_sub * 100) if total_sub > 0 else 0
(len(data["incomplete"]) / total_sub * 100) if total_sub > 0 else 0
)
pct_no = (len(data["none"]) / total_sub * 100) if total_sub > 0 else 0

mypy_err_str = ""
if submodule in mypy_errors:
Expand All @@ -769,7 +756,9 @@ def main():
none_sorted = sorted(
none,
key=lambda x: (
{"high": 0, "medium": 1, "low": 2}.get(x.get("priority", "low"), 2),
{"high": 0, "medium": 1, "low": 2}.get(
x.get("priority", "low"), 2
),
-x.get("references", 0),
),
)
Expand Down Expand Up @@ -814,15 +803,15 @@ def main():
print()

print("=" * 80)
print(
"FUNCTIONS/METHODS WITH INCOMPLETE TYPE HINTS (sorted by priority)"
)
print("FUNCTIONS/METHODS WITH INCOMPLETE TYPE HINTS (sorted by priority)")
print("=" * 80)

incomplete_sorted = sorted(
incomplete,
key=lambda x: (
{"high": 0, "medium": 1, "low": 2}.get(x.get("priority", "low"), 2),
{"high": 0, "medium": 1, "low": 2}.get(
x.get("priority", "low"), 2
),
-x.get("references", 0),
),
)
Expand Down Expand Up @@ -925,7 +914,7 @@ def main():
{
"name": f["qualified_name"],
"scope": f["scope"],
"params": f'{f["hinted_params"]}/{f["total_params"]}',
"params": f"{f['hinted_params']}/{f['total_params']}",
"return": f["has_return"],
"references": f.get("references", 0),
"test_suite": f.get("test_suite", "unknown"),
Expand All @@ -944,7 +933,8 @@ def main():
"file": v["filepath"],
"line": v["line"],
}
for v in class_vars if v["status"] == "none"
for v in class_vars
if v["status"] == "none"
],
"instance_variables_no_hints": [
{
Expand All @@ -954,7 +944,8 @@ def main():
"file": v["filepath"],
"line": v["line"],
}
for v in instance_vars if v["status"] == "none"
for v in instance_vars
if v["status"] == "none"
],
"module_variables_no_hints": [
{
Expand All @@ -963,7 +954,8 @@ def main():
"file": v["filepath"],
"line": v["line"],
}
for v in module_vars if v["status"] == "none"
for v in module_vars
if v["status"] == "none"
],
"type_aliases": [
{
Expand Down
Loading
Loading