-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspg.py
More file actions
executable file
·213 lines (165 loc) · 6.88 KB
/
Copy pathspg.py
File metadata and controls
executable file
·213 lines (165 loc) · 6.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#!/usr/bin/env python3
"""Scientific Paper Generator command line tool.
SPG asks a guided set of questions and renders a simple LaTeX draft paper.
"""
from __future__ import annotations
import argparse
import json
import shutil
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
from string import Template
from typing import Iterable
ROOT = Path(__file__).resolve().parent
OUTPUT_DIR = ROOT / "output"
@dataclass(frozen=True)
class Question:
key: str
prompt: str
default: str = ""
multiline: bool = False
QUESTIONS: tuple[Question, ...] = (
Question("title", "Paper title", "A nice title"),
Question("authors", "Authors (comma separated)", "First Author, Second Author"),
Question("affiliation", "Affiliation", "Your institution"),
Question("email", "Contact email", "author@example.com"),
Question("abstract", "Abstract", "A concise abstract for the paper.", True),
Question("keywords", "Keywords (comma separated)", "scientific writing, draft paper"),
Question("area_importance", "What area are you working on, and why is it important?", multiline=True),
Question("motivation", "What motivated this work?", multiline=True),
Question("problem", "What problem are you trying to solve?", multiline=True),
Question("existing_solutions", "What existing solutions are there?", multiline=True),
Question("improvement", "Why is your solution better, or what does it improve?", multiline=True),
Question("method_summary", "Describe your method in two lines", multiline=True),
Question("tools", "What tools, instruments, data, or methods did you use?", multiline=True),
Question("analysis", "What analysis tools did you use?", multiline=True),
Question("results", "What did you find?", multiline=True),
Question("discussion", "How do you interpret the results?", multiline=True),
Question("hypothesis", "Was the hypothesis proved? Why or why not?", multiline=True),
Question("scope", "What is the possible scope of this research?", multiline=True),
Question("future_work", "What other experiments or studies could you do?", multiline=True),
Question("conclusion", "Very briefly: what did you do and what did it show?", multiline=True),
Question("acknowledgments", "Acknowledgments", "This project has been supported by ...", True),
)
TEMPLATE = Template(r"""\documentclass[11pt]{article}
\usepackage[margin=1in]{geometry}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{lineno}
\linenumbers
\title{$title}
\author{$authors\\$affiliation\\\texttt{$email}}
\date{\today}
\begin{document}
\maketitle
\begin{abstract}
$abstract
\end{abstract}
\noindent\textbf{Keywords:} $keywords
\section{Introduction}
$area_importance
$motivation
$problem
$existing_solutions
$improvement
\section{Materials and Methods}
$method_summary
\subsection{Tools and materials}
$tools
\subsection{Analysis}
$analysis
\section{Results}
$results
\section{Discussion}
$discussion
$hypothesis
$scope
$future_work
\section{Conclusion}
$conclusion
\section*{Acknowledgments}
$acknowledgments
\end{document}
""")
def latex_escape(value: str) -> str:
replacements = {
"\\": r"\textbackslash{}", "&": r"\&", "%": r"\%", "$": r"\$",
"#": r"\#", "_": r"\_", "{": r"\{", "}": r"\}",
"~": r"\textasciitilde{}", "^": r"\textasciicircum{}",
}
return "".join(replacements.get(char, char) for char in value)
def ask(question: Question) -> str:
suffix = f" [{question.default}]" if question.default else ""
print(f"\n{question.prompt}{suffix}")
if question.multiline:
print("Enter text. Finish with an empty line.")
lines: list[str] = []
while True:
line = input("> ")
if line == "":
break
lines.append(line)
answer = "\n".join(lines).strip()
else:
answer = input("> ").strip()
return answer or question.default
def collect_answers() -> dict[str, str]:
print("Scientific Paper Generator - guided draft questionnaire")
return {question.key: ask(question) for question in QUESTIONS}
def load_answers(path: Path) -> dict[str, str]:
with path.open(encoding="utf-8") as fh:
data = json.load(fh)
if not isinstance(data, dict):
raise ValueError("Answers file must contain a JSON object")
return {question.key: str(data.get(question.key, question.default)) for question in QUESTIONS}
def render_tex(answers: dict[str, str], output_path: Path) -> Path:
OUTPUT_DIR.mkdir(exist_ok=True)
safe_answers = {question.key: latex_escape(answers.get(question.key, question.default)) for question in QUESTIONS}
output_path.write_text(TEMPLATE.substitute(safe_answers), encoding="utf-8")
return output_path
def build_pdf(tex_path: Path) -> bool:
if shutil.which("pdflatex") is None:
print("pdflatex was not found; generated only the .tex file.", file=sys.stderr)
return False
result = subprocess.run(
["pdflatex", "-interaction=nonstopmode", "-halt-on-error", f"-output-directory={tex_path.parent}", str(tex_path)],
cwd=ROOT,
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
if result.returncode != 0:
print(result.stdout, file=sys.stderr)
raise SystemExit(result.returncode)
for suffix in (".aux", ".log", ".out"):
tex_path.with_suffix(suffix).unlink(missing_ok=True)
return True
def write_sample(path: Path) -> None:
sample = {question.key: question.default or f"Sample answer for: {question.prompt}" for question in QUESTIONS}
path.write_text(json.dumps(sample, indent=2) + "\n", encoding="utf-8")
def parse_args(argv: Iterable[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Generate a guided scientific paper draft.")
parser.add_argument("format", nargs="?", default="draft", choices=("draft",), help="paper format to generate")
parser.add_argument("--answers", type=Path, help="JSON file with questionnaire answers")
parser.add_argument("--tex-only", action="store_true", help="skip PDF compilation")
parser.add_argument("--sample-answers", type=Path, help="write a sample answers JSON file and exit")
parser.add_argument("--output", type=Path, default=OUTPUT_DIR / "draft.tex", help="output .tex path")
return parser.parse_args(list(argv))
def main(argv: Iterable[str] = sys.argv[1:]) -> int:
args = parse_args(argv)
if args.sample_answers:
write_sample(args.sample_answers)
print(f"Wrote sample answers to {args.sample_answers}")
return 0
answers = load_answers(args.answers) if args.answers else collect_answers()
tex_path = render_tex(answers, args.output)
print(f"Wrote {tex_path}")
if not args.tex_only:
if build_pdf(tex_path):
print(f"Wrote {tex_path.with_suffix('.pdf')}")
return 0
if __name__ == "__main__":
raise SystemExit(main())