sttex 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sttex/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.2.0"
sttex/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
sttex/assets.py ADDED
@@ -0,0 +1,86 @@
1
+ # src/venuepaper/assets.py
2
+ """Fetch publisher-owned style assets from official venue sources on demand."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import io
7
+ from pathlib import Path
8
+ import urllib.request
9
+ import zipfile
10
+
11
+ # Publisher-maintained venue assets; official files are NOT redistributed in the wheel.
12
+ OFFICIAL_ASSETS = {
13
+ "jhep": (
14
+ ("https://jhep.sissa.it/jhep/help/JHEP/TeXclass/DOCS/jheppub.sty", "jheppub.sty"),
15
+ ("https://jhep.sissa.it/jhep/help/JHEP/TeXclass/DOCS/JHEP.bst", "JHEP.bst"),
16
+ ),
17
+ "neurips": (
18
+ ("https://media.neurips.cc/Conferences/NeurIPS2026/Formatting_Instructions_For_NeurIPS_2026.zip", "neurips_2026.sty"),
19
+ ),
20
+ "icml": (
21
+ ("https://media.icml.cc/Conferences/ICML2026/Styles/icml2026.zip", "icml2026.sty"),
22
+ ("https://media.icml.cc/Conferences/ICML2026/Styles/icml2026.zip", "icml2026.bst"),
23
+ ),
24
+ "iclr": (
25
+ ("https://media.iclr.cc/Conferences/ICLR2027/iclr-2027-style-files.zip", "iclr2027_conference.sty"),
26
+ ("https://media.iclr.cc/Conferences/ICLR2027/iclr-2027-style-files.zip", "iclr2027_conference.bst"),
27
+ ),
28
+ }
29
+
30
+ MAX_DOWNLOAD_BYTES = 25 * 1024 * 1024
31
+
32
+
33
+ def _read_url(url: str) -> bytes:
34
+ request = urllib.request.Request(url, headers={"User-Agent": "sttex/0.1"})
35
+ with urllib.request.urlopen(request, timeout=30) as stream:
36
+ blob = stream.read(MAX_DOWNLOAD_BYTES + 1)
37
+ if len(blob) > MAX_DOWNLOAD_BYTES:
38
+ raise ValueError(f"Publisher asset exceeds 25 MiB: {url}")
39
+ return blob
40
+
41
+
42
+ def _extract_asset(blob: bytes, filename: str) -> bytes:
43
+ if not zipfile.is_zipfile(io.BytesIO(blob)):
44
+ raise ValueError(f"Expected a ZIP archive containing {filename}")
45
+ with zipfile.ZipFile(io.BytesIO(blob)) as archive:
46
+ entries = [
47
+ name for name in archive.namelist()
48
+ if Path(name).name == filename and not name.startswith("__MACOSX/")
49
+ and not name.startswith("/") and ".." not in Path(name).parts
50
+ ]
51
+ if not entries:
52
+ raise FileNotFoundError(f"Official archive did not contain {filename}")
53
+ entries.sort(key=lambda item: (len(Path(item).parts), item))
54
+ if archive.getinfo(entries[0]).file_size > MAX_DOWNLOAD_BYTES:
55
+ raise ValueError(f"Uncompressed asset too large: {filename}")
56
+ return archive.read(entries[0])
57
+
58
+
59
+ def fetch_assets(venue: str, project: Path, *, overwrite: bool = False) -> list[Path]:
60
+ """Download selected official style files, never overwriting existing assets by default."""
61
+ if venue not in OFFICIAL_ASSETS:
62
+ return []
63
+ paper = project / "paper"
64
+ paper.mkdir(parents=True, exist_ok=True)
65
+ written = []
66
+ cache: dict[str, bytes] = {}
67
+ for url, name in OFFICIAL_ASSETS[venue]:
68
+ path = paper / name
69
+ if path.exists() and not overwrite:
70
+ continue
71
+ if url not in cache:
72
+ cache[url] = _read_url(url)
73
+ blob = cache[url]
74
+ content = _extract_asset(blob, name) if url.lower().endswith(".zip") else blob
75
+ if not content or len(content) > MAX_DOWNLOAD_BYTES:
76
+ raise ValueError(f"Unexpected publisher asset size: {name}")
77
+ # Atomic-ish write: only requested filenames, no ZIP paths, never shell extraction.
78
+ path.write_bytes(content)
79
+ written.append(path)
80
+ return written
81
+
82
+
83
+ def required_assets(venue: str) -> tuple[str, ...]:
84
+ if venue == "physrev":
85
+ return ("revtex4-2.cls (TeX distribution)", "apsrev4-2.bst (TeX distribution)")
86
+ return tuple(name for _, name in OFFICIAL_ASSETS.get(venue, ()))
sttex/cli.py ADDED
@@ -0,0 +1,231 @@
1
+ # src/sttex/cli.py
2
+ """CLI for venue-specific paper wrappers, official assets and independent theme/mode choices."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ from importlib import resources
9
+ import json
10
+ from pathlib import Path
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+
16
+ from . import __version__
17
+ from .assets import fetch_assets, required_assets, OFFICIAL_ASSETS
18
+ from .templates import VENUES, THEMES, MODES, SECTIONS, EXAMPLE_BIB, EXAMPLE_SECTION, wrapper
19
+
20
+ BUILD_EXTENSIONS = {".aux", ".blg", ".bbl", ".log", ".fls", ".fdb_latexmk", ".synctex", ".pdf"}
21
+
22
+
23
+ def install_styles(project: Path, venue: str) -> None:
24
+ paper = project / "paper"
25
+ styles = resources.files("sttex").joinpath("resources", "styles")
26
+ for name in ("sttex-common.sty", "sttex-notation.sty", "sttex-theme.sty", "sttex-theorems.sty", "sttex-notes.sty", f"sttex-{venue}.sty"):
27
+ (paper / name).write_bytes(styles.joinpath(name).read_bytes())
28
+ if venue == "basic":
29
+ bib = resources.files("sttex").joinpath("resources", "bib")
30
+ for name in ("sttex.bst", "sttex-links.sty"):
31
+ (paper / name).write_bytes(bib.joinpath(name).read_bytes())
32
+
33
+
34
+ def write_config(project: Path, *, venue: str, mode: str, theme: str) -> None:
35
+ (project / "sttex.json").write_text(json.dumps({
36
+ "venue": venue, "mode": mode, "theme": theme, "version": __version__,
37
+ }, indent=2) + "\n", encoding="utf-8")
38
+
39
+
40
+ def new_project(destination: Path, *, venue: str, mode: str, theme: str, title: str) -> Path:
41
+ if destination.exists():
42
+ raise FileExistsError(f"Directory already exists: {destination}")
43
+ project = destination.resolve()
44
+ paper = project / "paper"
45
+ sections = paper / "sections"
46
+ sections.mkdir(parents=True)
47
+ for name in SECTIONS:
48
+ (sections / f"{name}.tex").write_text(EXAMPLE_SECTION[name], encoding="utf-8")
49
+ (paper / "references.bib").write_text(EXAMPLE_BIB, encoding="utf-8")
50
+ paths = [f"sections/{name}.tex" for name in SECTIONS]
51
+ (paper / "main.tex").write_text(wrapper(venue, mode, theme, title, paths), encoding="utf-8")
52
+ install_styles(project, venue)
53
+ write_config(project, venue=venue, mode=mode, theme=theme)
54
+ (project / ".gitignore").write_text("*.aux\n*.bbl\n*.blg\n*.log\n*.fls\n*.fdb_latexmk\n*.out\n", encoding="utf-8")
55
+ (project / "README.md").write_text(
56
+ f"# {title}\n\nGenerated by STTeX {__version__}.\n"
57
+ f"Venue: `{venue}`; mode: `{mode}`; appearance: `{theme}`.\n\n"
58
+ "Compile with `sttex fetch .` (if required), then `sttex build .`.\n"
59
+ "Night PDFs are reading copies, not submission PDFs.\n", encoding="utf-8"
60
+ )
61
+ return project
62
+
63
+
64
+ def prepare_existing(source: Path, dest: Path, *, venue: str, mode: str,
65
+ theme: str, title: str | None = None) -> Path:
66
+ source = source.resolve()
67
+ dest = dest.resolve()
68
+ source_paper = source / "paper"
69
+ main = source_paper / "main.tex"
70
+ if not main.is_file():
71
+ raise FileNotFoundError(f"Missing {main}")
72
+ if dest == source or dest == source_paper:
73
+ raise ValueError("Output must differ from source")
74
+ if dest.exists():
75
+ raise FileExistsError(f"Output already exists: {dest}")
76
+ raw = main.read_text(encoding="utf-8")
77
+ section_inputs = []
78
+ for item in re.findall(r"(?m)^\s*\\input\{([^}]+)\}", raw):
79
+ rel = Path(item if Path(item).suffix == ".tex" else item + ".tex")
80
+ if rel.is_absolute() or ".." in rel.parts:
81
+ raise ValueError(f"Unsafe input: {item}")
82
+ if rel.parts[0] in ("figures", "assets") or rel.name in ("abstract.tex", "sttex-theme.tex", "venuepaper-theme.tex"):
83
+ continue
84
+ if not (source_paper / rel).is_file():
85
+ raise FileNotFoundError(f"Missing referenced section: {rel}")
86
+ section_inputs.append(item)
87
+ if not section_inputs:
88
+ raise ValueError("No standalone \\input{...} section lines found in paper/main.tex")
89
+ if title is None:
90
+ match = re.search(r"\\title\{([^{}]+)\}", raw)
91
+ title = match.group(1) if match else "Research Manuscript"
92
+ project = dest
93
+ paper = project / "paper"
94
+ paper.mkdir(parents=True)
95
+ for file in source_paper.rglob("*"):
96
+ if not file.is_file() or file.is_symlink() or file.suffix.lower() in BUILD_EXTENSIONS:
97
+ continue
98
+ rel = file.relative_to(source_paper)
99
+ if rel.as_posix() == "main.tex" or rel.name.startswith("sttex-") or rel.name.startswith("venuepaper-"):
100
+ continue
101
+ target = paper / rel
102
+ target.parent.mkdir(parents=True, exist_ok=True)
103
+ shutil.copy2(file, target)
104
+ (paper / "main.tex").write_text(
105
+ wrapper(venue, mode, theme, title, section_inputs, use_abstract_input=True),
106
+ encoding="utf-8",
107
+ )
108
+ install_styles(project, venue)
109
+ write_config(project, venue=venue, mode=mode, theme=theme)
110
+ return project
111
+
112
+
113
+ def read_config(project: Path) -> dict:
114
+ path = project / "sttex.json"
115
+ if not path.is_file():
116
+ raise FileNotFoundError(f"Missing {path}. Run sttex new/prepare first")
117
+ cfg = json.loads(path.read_text(encoding="utf-8"))
118
+ if cfg.get("venue") not in VENUES or cfg.get("mode") not in MODES or cfg.get("theme") not in THEMES:
119
+ raise ValueError("Invalid sttex.json")
120
+ return cfg
121
+
122
+
123
+ def fetch_official(project: Path, *, overwrite: bool = False) -> list[Path]:
124
+ cfg = read_config(project)
125
+ venue = cfg["venue"]
126
+ files = fetch_assets(venue, project, overwrite=overwrite)
127
+ if venue in OFFICIAL_ASSETS:
128
+ sources = {name: url for url, name in OFFICIAL_ASSETS[venue]}
129
+ lock = project / "sttex-official-assets.json"
130
+ paper = project / "paper"
131
+ hashes = {}
132
+ for name, url in sources.items():
133
+ file = paper / name
134
+ if file.is_file():
135
+ hashes[name] = {"sha256": hashlib.sha256(file.read_bytes()).hexdigest(), "source": url}
136
+ lock.write_text(json.dumps(hashes, indent=2) + "\n", encoding="utf-8")
137
+ return files
138
+
139
+
140
+ def doctor(project: Path) -> bool:
141
+ cfg = read_config(project)
142
+ status = True
143
+ for binary in ("latexmk", "pdflatex", "bibtex", "kpsewhich"):
144
+ found = shutil.which(binary) is not None
145
+ status &= found
146
+ print(f"{binary}: {'OK' if found else 'MISSING'}")
147
+ for item in required_assets(cfg["venue"]):
148
+ name = item.split(" ")[0]
149
+ if "(TeX distribution)" in item:
150
+ found = bool(shutil.which("kpsewhich") and subprocess.run(
151
+ ["kpsewhich", name], capture_output=True, text=True, check=False).stdout.strip())
152
+ else:
153
+ found = (project / "paper" / name).is_file()
154
+ status &= found
155
+ print(f"{name}: {'OK' if found else 'MISSING'}")
156
+ return status
157
+
158
+
159
+ def build_project(project: Path) -> Path:
160
+ project = project.resolve()
161
+ cfg = read_config(project)
162
+ if not shutil.which("latexmk"):
163
+ raise FileNotFoundError("latexmk is required (install TeX Live)")
164
+ paper = project / "paper"
165
+ subprocess.run(["latexmk", "-pdf", "-g", "-interaction=nonstopmode", "-halt-on-error", "-file-line-error", "main.tex"], cwd=paper, check=True)
166
+ original = paper / "main.pdf"
167
+ if not original.is_file():
168
+ raise FileNotFoundError("latexmk returned success but main.pdf is absent")
169
+ filename = f"paper-{cfg['venue']}-{cfg['mode']}-{cfg['theme']}.pdf"
170
+ out = project / filename
171
+ shutil.copy2(original, out)
172
+ return out
173
+
174
+
175
+ def main(argv: list[str] | None = None) -> int:
176
+ parser = argparse.ArgumentParser(prog="sttex", description="Scientific LaTeX templates with venue, publication and reading modes")
177
+ parser.add_argument("--version", action="version", version=f"sttex {__version__}")
178
+ subs = parser.add_subparsers(dest="cmd", required=True)
179
+ subs.add_parser("list", help="List paper templates and supported modes")
180
+ subs.add_parser("sources", help="List official style sources and required filenames")
181
+ for cmd in ("new", "prepare"):
182
+ p = subs.add_parser(cmd, help=("Create a standalone paper" if cmd == "new" else "Wrap an existing paper/ without modifying it"))
183
+ if cmd == "new":
184
+ p.add_argument("directory", type=Path)
185
+ p.add_argument("--title", default="Untitled Research Manuscript")
186
+ else:
187
+ p.add_argument("source", nargs="?", type=Path, default=Path("."))
188
+ p.add_argument("--output", "-o", required=True, type=Path)
189
+ p.add_argument("--title")
190
+ p.add_argument("--venue", "--template", "-t", dest="venue", required=True, choices=VENUES)
191
+ p.add_argument("--mode", choices=MODES, default="preprint")
192
+ p.add_argument("--theme", choices=THEMES, default="light")
193
+ p = subs.add_parser("fetch", help="Download unmodified official venue assets (network required)")
194
+ p.add_argument("directory", nargs="?", type=Path, default=Path("."))
195
+ p.add_argument("--overwrite", action="store_true")
196
+ for cmd in ("build", "doctor"):
197
+ p = subs.add_parser(cmd)
198
+ p.add_argument("directory", nargs="?", type=Path, default=Path("."))
199
+ args = parser.parse_args(argv)
200
+ try:
201
+ if args.cmd == "list":
202
+ for key, value in VENUES.items():
203
+ print(f"{key:9} {value}")
204
+ print("themes:", ", ".join(THEMES))
205
+ print("modes:", ", ".join(MODES))
206
+ elif args.cmd == "sources":
207
+ print("physrev: REVTeX 4.2 from TeX Live (revtex4-2.cls, apsrev4-2.bst)")
208
+ for venue, values in OFFICIAL_ASSETS.items():
209
+ for url, filename in values:
210
+ print(f"{venue}: {filename} <- {url}")
211
+ elif args.cmd == "new":
212
+ result = new_project(args.directory, venue=args.venue, mode=args.mode, theme=args.theme, title=args.title)
213
+ print(f"Created {result}")
214
+ elif args.cmd == "prepare":
215
+ result = prepare_existing(args.source, args.output, venue=args.venue, mode=args.mode, theme=args.theme, title=args.title)
216
+ print(f"Prepared {result}")
217
+ elif args.cmd == "fetch":
218
+ results = fetch_official(args.directory.resolve(), overwrite=args.overwrite)
219
+ print(f"Obtained {len(results)} file(s); hashes recorded in sttex-official-assets.json")
220
+ elif args.cmd == "doctor":
221
+ return 0 if doctor(args.directory.resolve()) else 1
222
+ elif args.cmd == "build":
223
+ print(f"Built {build_project(args.directory)}")
224
+ return 0
225
+ except (ValueError, FileNotFoundError, FileExistsError, OSError, subprocess.CalledProcessError) as exc:
226
+ print(f"sttex: {exc}", file=sys.stderr)
227
+ return 1
228
+
229
+
230
+ if __name__ == "__main__":
231
+ raise SystemExit(main())
@@ -0,0 +1,8 @@
1
+ % src/sttex/resources/bib/sttex-links.sty
2
+ % Small clickable bibliography labels. No copyrighted image/logo assets.
3
+ \NeedsTeXFormat{LaTeX2e}
4
+ \ProvidesPackage{sttex-links}[2026/11/24 Linked bibliography metadata]
5
+ \RequirePackage{hyperref}
6
+ \providecommand{\vpArxiv}[1]{\nobreak\href{https://arxiv.org/abs/#1}{\textsf{\scriptsize arXiv}}}
7
+ \providecommand{\vpGitHub}[1]{\nobreak\href{#1}{\textsf{\scriptsize GitHub}}}
8
+ \providecommand{\vpHuggingFace}[1]{\nobreak\href{#1}{\textsf{\scriptsize HF}}}