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/online_bib_verify.py

View on GitHub
#!/usr/bin/env python3
"""
Online bibliography verification via CrossRef and Semantic Scholar APIs.

Verifies bibliography entries against online databases to detect:
- Invalid DOIs
- Metadata mismatches (year, journal)
- Missing DOIs (suggests from title search)

Usage:
    # As a module (imported by verify_bib.py):
    from online_bib_verify import OnlineBibVerifier
    verifier = OnlineBibVerifier()
    result = verifier.verify_entry({"key": "smith2020", "doi": "10.1234/example", "title": "..."})

    # Standalone CLI:
    uv run python online_bib_verify.py --bib references.bib [--email user@example.com] [--json]
"""

from __future__ import annotations

import argparse
import json
import re
import sys
import time
from dataclasses import dataclass, field
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, urlopen


@dataclass
class VerifyResult:
    """Result of a single DOI verification."""

    valid: bool
    metadata: dict | None = None
    error: str | None = None


@dataclass
class EntryVerifyResult:
    """Result of verifying a single bibliography entry."""

    status: str  # "verified" | "mismatch" | "not_found" | "unverifiable" | "error"
    bib_key: str = ""
    mismatches: list[str] = field(default_factory=list)
    suggested_doi: str | None = None
    confidence: float = 0.0


class OnlineBibVerifier:
    """Verify bibliography entries via CrossRef and Semantic Scholar APIs."""

    def __init__(
        self,
        polite_email: str | None = None,
        timeout: float = 10.0,
        rate_limit: float = 0.5,
    ) -> None:
        self.email = polite_email
        self.timeout = timeout
        self.rate_limit = rate_limit  # Minimum seconds between requests
        self._last_request_time = 0.0

    def _get(self, url: str, params: dict | None = None) -> dict | None:
        """HTTP GET with rate limiting and error handling."""
        # Rate limiting
        elapsed = time.time() - self._last_request_time
        if elapsed < self.rate_limit:
            time.sleep(self.rate_limit - elapsed)

        if params:
            query_string = "&".join(f"{k}={quote(str(v))}" for k, v in params.items())
            url = f"{url}?{query_string}"

        headers = {"User-Agent": "AcademicWritingSkills/1.0"}
        if self.email:
            headers["User-Agent"] += f" (mailto:{self.email})"

        req = Request(url, headers=headers)
        try:
            with urlopen(req, timeout=self.timeout) as resp:
                self._last_request_time = time.time()
                return json.loads(resp.read().decode())
        except (HTTPError, URLError, json.JSONDecodeError, TimeoutError, OSError):
            return None

    def verify_doi(self, doi: str) -> VerifyResult:
        """Verify a DOI via CrossRef API."""
        clean_doi = doi.strip()
        data = self._get(f"https://api.crossref.org/works/{quote(clean_doi, safe='')}")
        if data is None:
            return VerifyResult(valid=False, error="DOI not found or API error")

        msg = data.get("message", {})
        title_list = msg.get("title") or [None]
        author_list = msg.get("author", [])
        published = msg.get("published-print") or msg.get("published-online") or {}
        date_parts = published.get("date-parts", [[None]])
        year_val = date_parts[0][0] if date_parts and date_parts[0] else None
        container = msg.get("container-title") or [None]

        return VerifyResult(
            valid=True,
            metadata={
                "title": title_list[0],
                "authors": [a.get("family", "") for a in author_list],
                "year": str(year_val or ""),
                "journal": container[0],
                "doi": clean_doi,
            },
        )

    def search_by_title(self, title: str) -> list[dict]:
        """Search for a paper by title via Semantic Scholar API."""
        clean_title = re.sub(r"[{}\\]", "", title).strip()
        if not clean_title:
            return []
        data = self._get(
            "https://api.semanticscholar.org/graph/v1/paper/search",
            {
                "query": clean_title,
                "limit": "3",
                "fields": "title,authors,year,externalIds,venue",
            },
        )
        if data is None or "data" not in data:
            return []
        return data["data"]

    def verify_entry(self, entry: dict) -> EntryVerifyResult:
        """
        Verify a single bibliography entry.

        Strategy: DOI verification first, fallback to title search.

        Args:
            entry: Dict with keys like "key", "doi", "title", "year", "journal".
        """
        bib_key = entry.get("key", "")

        # 1. DOI verification (preferred)
        doi = entry.get("doi", "").strip()
        if doi:
            result = self.verify_doi(doi)
            if result.valid and result.metadata:
                return self._cross_check(bib_key, entry, result.metadata)
            if not result.valid:
                return EntryVerifyResult(
                    status="not_found",
                    bib_key=bib_key,
                    mismatches=[f"DOI '{doi}' not found in CrossRef"],
                )

        # 2. Title search fallback
        title = entry.get("title", "").strip()
        if title:
            results = self.search_by_title(title)
            if results:
                return self._match_title(bib_key, entry, results)

        return EntryVerifyResult(status="unverifiable", bib_key=bib_key)

    def _cross_check(
        self,
        bib_key: str,
        entry: dict,
        api_meta: dict,
    ) -> EntryVerifyResult:
        """Compare bib entry metadata against API-returned metadata."""
        mismatches = []

        # Year comparison
        bib_year = str(entry.get("year", "")).strip()
        api_year = str(api_meta.get("year", "")).strip()
        if bib_year and api_year and bib_year != api_year:
            mismatches.append(f"year: bib='{bib_year}' vs api='{api_year}'")

        # Journal comparison (fuzzy)
        bib_journal = entry.get("journal", "").lower().strip()
        api_journal = (api_meta.get("journal") or "").lower().strip()
        if (
            bib_journal
            and api_journal
            and bib_journal not in api_journal
            and api_journal not in bib_journal
        ):
            mismatches.append(
                f"journal: bib='{entry.get('journal')}' vs api='{api_meta.get('journal')}'"
            )

        if mismatches:
            return EntryVerifyResult(
                status="mismatch",
                bib_key=bib_key,
                mismatches=mismatches,
                confidence=0.7,
            )
        return EntryVerifyResult(
            status="verified",
            bib_key=bib_key,
            confidence=0.9,
        )

    def _match_title(
        self,
        bib_key: str,
        entry: dict,
        results: list[dict],
    ) -> EntryVerifyResult:
        """Match bib entry against title search results."""
        bib_title = re.sub(r"[{}\\]", "", entry.get("title", "")).lower().strip()
        for paper in results:
            api_title = (paper.get("title") or "").lower().strip()
            if not api_title:
                continue
            # Simple containment similarity
            if bib_title in api_title or api_title in bib_title:
                doi = (paper.get("externalIds") or {}).get("DOI")
                return EntryVerifyResult(
                    status="verified",
                    bib_key=bib_key,
                    suggested_doi=doi,
                    confidence=0.8,
                )
        return EntryVerifyResult(status="not_found", bib_key=bib_key)


def _parse_bib_entries(bib_path: Path) -> list[dict]:
    """Parse BibTeX file into entry dicts (minimal parser for standalone use)."""
    content = bib_path.read_text(encoding="utf-8", errors="ignore")
    entries = []
    entry_pattern = r"@(\w+)\s*{\s*([^,]+)\s*,([^@]*?)(?=\n\s*@|\Z)"
    field_pattern = r'(\w+)\s*=\s*(?:\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}|"([^"]*)"|(\d+))'

    for match in re.finditer(entry_pattern, content, re.DOTALL):
        entry_type = match.group(1).lower().strip()
        key = match.group(2).strip()
        fields_str = match.group(3)

        fields: dict[str, str] = {}
        for field_match in re.finditer(field_pattern, fields_str):
            name = field_match.group(1).lower()
            val = field_match.group(2) or field_match.group(3) or field_match.group(4) or ""
            fields[name] = val.strip()

        entries.append(
            {
                "key": key,
                "type": entry_type,
                **fields,
            }
        )

    return entries


def main() -> int:
    """CLI entry point for standalone bibliography verification."""
    parser = argparse.ArgumentParser(
        description="Online Bibliography Verification via CrossRef & Semantic Scholar",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  uv run python online_bib_verify.py --bib references.bib
  uv run python online_bib_verify.py --bib references.bib --email user@example.com
  uv run python online_bib_verify.py --bib references.bib --json
        """,
    )
    parser.add_argument("--bib", required=True, help="BibTeX file to verify")
    parser.add_argument(
        "--email",
        help="Email for CrossRef polite pool (faster rate limits)",
    )
    parser.add_argument(
        "--timeout",
        type=float,
        default=10.0,
        help="Timeout per API request in seconds (default: 10)",
    )
    parser.add_argument("--json", action="store_true", help="Output JSON format")

    args = parser.parse_args()

    bib_path = Path(args.bib)
    if not bib_path.exists():
        print(f"[ERROR] File not found: {args.bib}", file=sys.stderr)
        return 1

    entries = _parse_bib_entries(bib_path)
    if not entries:
        print("# No entries found in BibTeX file.")
        return 0

    verifier = OnlineBibVerifier(
        polite_email=args.email,
        timeout=args.timeout,
    )

    results = []
    for entry in entries:
        result = verifier.verify_entry(entry)
        results.append(result)
        if not args.json:
            _print_result(result)

    if args.json:
        json_results = [
            {
                "bib_key": r.bib_key,
                "status": r.status,
                "mismatches": r.mismatches,
                "suggested_doi": r.suggested_doi,
                "confidence": r.confidence,
            }
            for r in results
        ]
        print(json.dumps(json_results, indent=2, ensure_ascii=False))

    # Summary
    verified = sum(1 for r in results if r.status == "verified")
    mismatched = sum(1 for r in results if r.status == "mismatch")
    not_found = sum(1 for r in results if r.status == "not_found")
    if not args.json:
        print(f"\n# Summary: {verified} verified, {mismatched} mismatched, {not_found} not found")

    return 1 if mismatched > 0 else 0


def _print_result(result: EntryVerifyResult) -> None:
    """Print a single verification result in protocol format."""
    if result.status == "verified":
        msg = f"Entry '{result.bib_key}' verified online (confidence: {result.confidence:.0%})"
        if result.suggested_doi:
            msg += f" — suggested DOI: {result.suggested_doi}"
        print(f"# ONLINE_BIB [Severity: Minor] [Priority: P2]: {msg}")
    elif result.status == "mismatch":
        for m in result.mismatches:
            print(
                f"% ONLINE_BIB [Severity: Major] [Priority: P1]: "
                f"Metadata mismatch for '{result.bib_key}': {m}"
            )
    elif result.status == "not_found":
        detail = (
            result.mismatches[0] if result.mismatches else "Entry not found in online databases"
        )
        print(f"% ONLINE_BIB [Severity: Minor] [Priority: P2]: '{result.bib_key}': {detail}")


if __name__ == "__main__":
    sys.exit(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