Skip to content

brycewang-stanford/Auto-Empirical-Research-Skills / skills/35-bahayonghang-academic-writing-skills/skills/latex-thesis-zh

latex-thesis-zh

Verified

Chinese LaTeX thesis assistant for existing .tex degree thesis projects (XeLaTeX/LuaLaTeX/latexmk). Use this skill whenever a user works on a Chinese master's or doctoral thesis needing compilation, GB/T 7714 bibliography checks, chapter structure mapping, template detection (thuthesis, pkuthss), terminology consistency, logic coherence review, heading lead-in checks, title optimization, de-AI editing, experiment chapter review, three-line table validation, or abstract structure diagnosis. Trigger even for single issues like "帮我编译论文", "检查国标格式", "看看绪论逻辑", "毕业论文", "学位论文", "硕士/博士论文", "三线表", "检查摘要", or "摘要结构".

FileKindSize
SKILL.mdskill md7.8 KB
agents/openai.yamlconfig348 B
evals/evals.jsonconfig7.1 KB
examples/bibliography-and-deai.mdmarkdown525 B
examples/compile-and-template.mdmarkdown463 B
examples/structure-and-consistency.mdmarkdown544 B
references/ABSTRACT_STRUCTURE.mdmarkdown4.9 KB
references/ACADEMIC_STYLE_ZH.mdmarkdown3.8 KB
references/CAPTION_GUIDE.mdmarkdown2.2 KB
references/COMPILATION.mdmarkdown2.0 KB
references/DEAI_GUIDE.mdmarkdown17.8 KB
references/FORBIDDEN_TERMS.mdmarkdown1.3 KB
references/GB_STANDARD.mdmarkdown3.8 KB
references/LOGIC_COHERENCE.mdmarkdown7.4 KB
references/STRUCTURE_GUIDE.mdmarkdown4.2 KB
references/TABLE_GUIDE.mdmarkdown2.6 KB
references/TITLE_OPTIMIZATION.mdmarkdown7.1 KB
references/UNIVERSITIES/generic.mdmarkdown2.1 KB
references/UNIVERSITIES/pku.mdmarkdown1.5 KB
references/UNIVERSITIES/tsinghua.mdmarkdown1.3 KB
references/UNIVERSITIES/yanshan.mdmarkdown1.2 KB
references/WRITING_PHILOSOPHY_ZH.mdmarkdown4.9 KB
references/modules/ABSTRACT.mdmarkdown1.2 KB
references/modules/BIBLIOGRAPHY.mdmarkdown1.3 KB
references/modules/COMPILE.mdmarkdown1.1 KB
references/modules/CONSISTENCY.mdmarkdown2.1 KB
references/modules/DEAI.mdmarkdown1.6 KB
references/modules/EXPERIMENT.mdmarkdown4.9 KB
references/modules/FORMAT.mdmarkdown988 B
references/modules/LOGIC.mdmarkdown2.3 KB
references/modules/TABLES.mdmarkdown1.3 KB
references/modules/TEMPLATE.mdmarkdown1.3 KB
references/modules/TITLE.mdmarkdown1.5 KB
scripts/analyze_abstract.pyscript17.3 KB
scripts/analyze_experiment.pyscript10.3 KB
scripts/analyze_logic.pyscript24.2 KB
scripts/check_consistency.pyscript12.1 KB
scripts/check_format.pyscript7.0 KB
scripts/check_references.pyscript17.6 KB
scripts/check_tables.pyscript16.3 KB
scripts/compile.pyscript15.8 KB
scripts/deai_batch.pyscript10.0 KB
scripts/deai_check.pyscript18.1 KB
scripts/detect_template.pyscript3.7 KB
scripts/generate_table.pyscript8.8 KB
scripts/map_structure.pyscript11.3 KB
scripts/online_bib_verify.pyscript11.9 KB
scripts/optimize_title.pyscript12.5 KB
scripts/parsers.pyscript10.7 KB
scripts/verify_bib.pyscript9.7 KB

scripts/check_consistency.py

View on GitHub
#!/usr/bin/env python3
"""
Terminology Consistency Checker - Check term usage consistency in thesis

Usage:
    uv run python check_consistency.py main.tex
    uv run python check_consistency.py main.tex --terms
    uv run python check_consistency.py main.tex --abbreviations
"""

import argparse
import re
import sys
from collections import defaultdict
from pathlib import Path


class ConsistencyChecker:
    """Check terminology and abbreviation consistency across thesis files."""

    # Built-in example term groups (common CS/AI terms)
    DEFAULT_TERM_GROUPS_ZH = [
        ["深度学习", "深度神经网络", "深层学习"],
        ["机器学习", "机器智能"],
        ["卷积神经网络", "卷积网络", "CNN"],
        ["循环神经网络", "递归神经网络", "RNN"],
        ["长短期记忆", "LSTM"],
        ["生成对抗网络", "GAN"],
        ["自然语言处理", "NLP"],
        ["计算机视觉", "CV"],
        ["强化学习", "RL"],
    ]

    DEFAULT_TERM_GROUPS_EN = [
        ["deep learning", "deep neural network"],
        ["machine learning", "ML"],
        ["convolutional neural network", "CNN"],
        ["recurrent neural network", "RNN"],
        ["long short-term memory", "LSTM"],
        ["generative adversarial network", "GAN"],
        ["natural language processing", "NLP"],
    ]

    def __init__(self, tex_files: list[str], custom_terms_file: str | None = None):
        self.tex_files = [Path(f).resolve() for f in tex_files]
        self.content_cache: dict[Path, str] = {}
        self.term_groups_zh = list(self.DEFAULT_TERM_GROUPS_ZH)
        self.term_groups_en = list(self.DEFAULT_TERM_GROUPS_EN)
        if custom_terms_file:
            self._load_custom_terms(custom_terms_file)

    def _load_custom_terms(self, path: str) -> None:
        """Load custom term groups from a JSON file.

        Expected format: {"zh": [["termA", "termB"], ...], "en": [["termC", "termD"], ...]}
        """
        import json

        try:
            data = json.loads(Path(path).read_text(encoding="utf-8"))
            if "zh" in data:
                self.term_groups_zh.extend(data["zh"])
            if "en" in data:
                self.term_groups_en.extend(data["en"])
        except Exception as e:
            print(f"[WARNING] Failed to load custom terms: {e}", file=sys.stderr)

    def _load_content(self, tex_file: Path) -> str:
        """Load and cache file content."""
        if tex_file not in self.content_cache:
            try:
                self.content_cache[tex_file] = tex_file.read_text(encoding="utf-8", errors="ignore")
            except Exception:
                self.content_cache[tex_file] = ""
        return self.content_cache[tex_file]

    def check_terms(self) -> dict:
        """Check term consistency across files."""
        term_occurrences: dict[str, list[tuple[str, int]]] = defaultdict(list)

        for tex_file in self.tex_files:
            content = self._load_content(tex_file)
            if not content:
                continue

            # Check each term group
            all_groups = self.term_groups_zh + self.term_groups_en

            for group in all_groups:
                for term in group:
                    # Find all occurrences
                    pattern = re.escape(term)
                    matches = list(re.finditer(pattern, content, re.IGNORECASE))
                    if matches:
                        for match in matches:
                            # Find line number
                            line_num = content[: match.start()].count("\n") + 1
                            term_occurrences[term].append((str(tex_file.name), line_num))

        # Find inconsistencies
        inconsistencies = []
        checked_groups: set[frozenset] = set()

        all_groups = self.term_groups_zh + self.term_groups_en

        for group in all_groups:
            group_set = frozenset(group)
            if group_set in checked_groups:
                continue
            checked_groups.add(group_set)

            found_terms = {}
            for term in group:
                if term in term_occurrences:
                    found_terms[term] = len(term_occurrences[term])

            if len(found_terms) > 1:
                # Multiple variants used
                most_common = max(found_terms.items(), key=lambda x: x[1])
                inconsistencies.append(
                    {
                        "group": list(found_terms.keys()),
                        "counts": found_terms,
                        "suggestion": f"统一使用 '{most_common[0]}'",
                    }
                )

        return {
            "term_occurrences": {k: len(v) for k, v in term_occurrences.items()},
            "inconsistencies": inconsistencies,
            "status": "PASS" if not inconsistencies else "WARNING",
        }

    def check_abbreviations(self) -> dict:
        """Check abbreviation definitions and usage."""
        # Pattern for abbreviation definition: 全称(缩写)or 全称 (abbreviation)
        definition_pattern = r"([^((]+)[((]([A-Z]{2,})[))]"

        definitions: dict[str, list[tuple[str, str, int]]] = defaultdict(list)
        usages: dict[str, list[tuple[str, int]]] = defaultdict(list)

        for tex_file in self.tex_files:
            content = self._load_content(tex_file)
            if not content:
                continue

            # Find definitions
            for match in re.finditer(definition_pattern, content):
                full_name = match.group(1).strip()
                abbrev = match.group(2)
                line_num = content[: match.start()].count("\n") + 1
                definitions[abbrev].append((full_name, str(tex_file.name), line_num))

            # Find standalone abbreviation usages
            # Look for uppercase sequences that might be abbreviations
            abbrev_pattern = r"\b([A-Z]{2,})\b"
            for match in re.finditer(abbrev_pattern, content):
                abbrev = match.group(1)
                # Skip common non-abbreviation uppercase
                if abbrev in ["PDF", "URL", "HTTP", "HTTPS", "API", "TODO", "FIXME"]:
                    continue
                line_num = content[: match.start()].count("\n") + 1
                usages[abbrev].append((str(tex_file.name), line_num))

        # Find issues
        issues = []

        # Abbreviations used but not defined
        for abbrev, usage_list in usages.items():
            if abbrev not in definitions and len(usage_list) > 0:
                first_usage = usage_list[0]
                issues.append(
                    {
                        "type": "undefined",
                        "abbreviation": abbrev,
                        "first_usage": first_usage,
                        "usage_count": len(usage_list),
                        "message": f"'{abbrev}' used but not defined (first at {first_usage[0]}:{first_usage[1]})",
                    }
                )

        # Abbreviations defined multiple times
        for abbrev, def_list in definitions.items():
            if len(def_list) > 1:
                issues.append(
                    {
                        "type": "multiple_definitions",
                        "abbreviation": abbrev,
                        "definitions": def_list,
                        "message": f"'{abbrev}' defined {len(def_list)} times",
                    }
                )

        return {
            "definitions": {k: len(v) for k, v in definitions.items()},
            "usages": {k: len(v) for k, v in usages.items()},
            "issues": issues,
            "status": "PASS" if not issues else "WARNING",
        }

    def generate_report(self, terms_result: dict, abbrev_result: dict) -> str:
        """Generate human-readable report."""
        lines = []
        lines.append("=" * 60)
        lines.append("Consistency Check Report / 一致性检查报告")
        lines.append("=" * 60)

        # Term consistency
        lines.append("\n[1] Term Consistency / 术语一致性")
        lines.append("-" * 40)

        if terms_result["inconsistencies"]:
            lines.append(f"Status: ⚠️ {len(terms_result['inconsistencies'])} inconsistencies found")
            for inc in terms_result["inconsistencies"]:
                lines.append(f"\n  Group: {', '.join(inc['group'])}")
                for term, count in inc["counts"].items():
                    lines.append(f"    - '{term}': {count} times")
                lines.append(f"  Suggestion: {inc['suggestion']}")
        else:
            lines.append("Status: ✅ No inconsistencies found")

        # Abbreviation check
        lines.append("\n[2] Abbreviation Check / 缩略语检查")
        lines.append("-" * 40)

        if abbrev_result["issues"]:
            lines.append(f"Status: ⚠️ {len(abbrev_result['issues'])} issues found")
            for issue in abbrev_result["issues"]:
                lines.append(f"\n  [{issue['type']}] {issue['message']}")
        else:
            lines.append("Status: ✅ All abbreviations properly defined")

        lines.append("\n" + "=" * 60)
        return "\n".join(lines)


def find_tex_files(main_file: str) -> list[str]:
    """Find all .tex files in the project."""
    main_path = Path(main_file).resolve()
    root_dir = main_path.parent

    # Find all .tex files
    tex_files = list(root_dir.rglob("*.tex"))

    # Also check common subdirectories
    for subdir in ["data", "chapters", "sections", "content"]:
        subdir_path = root_dir / subdir
        if subdir_path.exists():
            tex_files.extend(subdir_path.rglob("*.tex"))

    # Remove duplicates and sort
    tex_files = sorted(set(tex_files))

    return [str(f) for f in tex_files]


def main():
    parser = argparse.ArgumentParser(description="Terminology Consistency Checker")
    parser.add_argument("tex_file", help="Main .tex file or directory")
    parser.add_argument("--terms", "-t", action="store_true", help="Check only term consistency")
    parser.add_argument(
        "--abbreviations", "-a", action="store_true", help="Check only abbreviation consistency"
    )
    parser.add_argument("--json", "-j", action="store_true", help="Output in JSON format")
    parser.add_argument("--custom-terms", type=str, help="JSON file with custom term groups")

    args = parser.parse_args()

    # Find tex files
    if Path(args.tex_file).is_dir():
        tex_files = [str(p) for p in Path(args.tex_file).rglob("*.tex")]
    else:
        if not Path(args.tex_file).exists():
            print(f"[ERROR] File not found: {args.tex_file}", file=sys.stderr)
            sys.exit(1)
        tex_files = find_tex_files(args.tex_file)

    if not tex_files:
        print("[ERROR] No .tex files found", file=sys.stderr)
        sys.exit(1)

    print(f"[INFO] Checking {len(tex_files)} files...")

    # Run checks
    checker = ConsistencyChecker(tex_files, custom_terms_file=args.custom_terms)

    if args.terms:
        result = checker.check_terms()
        if args.json:
            import json

            print(json.dumps(result, indent=2, ensure_ascii=False))
        else:
            print(f"\nTerm consistency: {result['status']}")
            for inc in result["inconsistencies"]:
                print(f"  - {inc['suggestion']}")
        sys.exit(0)

    if args.abbreviations:
        result = checker.check_abbreviations()
        if args.json:
            import json

            print(json.dumps(result, indent=2, ensure_ascii=False))
        else:
            print(f"\nAbbreviation check: {result['status']}")
            for issue in result["issues"]:
                print(f"  - {issue['message']}")
        sys.exit(0)

    # Full check
    terms_result = checker.check_terms()
    abbrev_result = checker.check_abbreviations()

    if args.json:
        import json

        output = {
            "terms": terms_result,
            "abbreviations": abbrev_result,
        }
        print(json.dumps(output, indent=2, ensure_ascii=False))
    else:
        print(checker.generate_report(terms_result, abbrev_result))

    # Exit code
    if terms_result["status"] != "PASS" or abbrev_result["status"] != "PASS":
        sys.exit(1)
    sys.exit(0)


if __name__ == "__main__":
    main()
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 323kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 323kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 323kUpdated Claude CodeCodexVerifiedInstall