-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.py
More file actions
363 lines (298 loc) · 13.1 KB
/
api_server.py
File metadata and controls
363 lines (298 loc) · 13.1 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import os
import json
import shutil
import tempfile
import subprocess
import zipfile
from pathlib import Path
from typing import Optional
from fastapi import FastAPI, File, Form, HTTPException, Query, UploadFile
from fastapi.responses import JSONResponse, PlainTextResponse
MSS_BIN = Path(__file__).resolve().parent / "bin" / "mss"
app = FastAPI(
title="MoonShort Script API",
description="Compile, decompile, validate, and fix MoonShort Script (MSS) files via HTTP.",
version="1.2.0",
)
def _run_mss(*args: str, workdir: Optional[str] = None, timeout: int = 30) -> subprocess.CompletedProcess:
cmd = [str(MSS_BIN), *args]
return subprocess.run(
cmd,
capture_output=True,
text=True,
cwd=workdir,
timeout=timeout,
)
# ── /compile (single file) ──────────────────────────────────────────────
@app.post("/compile")
async def compile_script(
script: UploadFile = File(..., description="MSS script file (.md)"),
assets: Optional[UploadFile] = File(default=None, description="Optional assets mapping JSON file"),
):
"""
Compile a single MSS script (.md) into structured JSON.
Returns the compiled episode JSON. If an assets mapping is provided,
asset semantic names are resolved to full URLs.
"""
tmpdir = tempfile.mkdtemp(prefix="mss_compile_")
try:
script_bytes = await script.read()
script_text = script_bytes.decode("utf-8")
script_path = os.path.join(tmpdir, "script.md")
with open(script_path, "w", encoding="utf-8") as f:
f.write(script_text)
args = ["compile", script_path, "-o", os.path.join(tmpdir, "output.json")]
if assets is not None:
assets_bytes = await assets.read()
assets_text = assets_bytes.decode("utf-8")
assets_path = os.path.join(tmpdir, "assets.json")
with open(assets_path, "w", encoding="utf-8") as f:
f.write(assets_text)
args.insert(2, "--assets")
args.insert(3, assets_path)
proc = _run_mss(*args, timeout=30)
if proc.returncode != 0:
raise HTTPException(status_code=422, detail={"error": proc.stderr.strip()})
output_path = os.path.join(tmpdir, "output.json")
with open(output_path, "r", encoding="utf-8") as f:
result = json.load(f)
return JSONResponse(content=result)
except subprocess.TimeoutExpired:
raise HTTPException(status_code=504, detail="Compilation timed out")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
# ── /compile-dir (directory via zip) ────────────────────────────────────
@app.post("/compile-dir")
async def compile_directory(
zipfile_upload: UploadFile = File(..., alias="zipfile", description="Zip archive of an MSS episode directory"),
assets: Optional[UploadFile] = File(default=None, description="Optional assets mapping JSON file"),
):
"""
Compile an entire episode directory (uploaded as a zip) into structured JSON.
The zip should contain one or more `.md` files (e.g. 01.md, 02.md, …).
Directory structure inside the zip is flattened — all `.md` files are
discovered recursively and compiled together.
Returns the compiled novel JSON (keyed by episode_id).
"""
tmpdir = tempfile.mkdtemp(prefix="mss_compiledir_")
try:
zip_bytes = await zipfile_upload.read()
zip_path = os.path.join(tmpdir, "input.zip")
with open(zip_path, "wb") as f:
f.write(zip_bytes)
episode_dir = os.path.join(tmpdir, "episodes")
os.makedirs(episode_dir)
with zipfile.ZipFile(zip_path, "r") as zf:
zf.extractall(episode_dir)
args = ["compile", episode_dir, "-o", os.path.join(tmpdir, "output.json")]
if assets is not None:
assets_bytes = await assets.read()
assets_text = assets_bytes.decode("utf-8")
assets_path = os.path.join(tmpdir, "assets.json")
with open(assets_path, "w", encoding="utf-8") as f:
f.write(assets_text)
args.insert(2, "--assets")
args.insert(3, assets_path)
proc = _run_mss(*args, timeout=60)
if proc.returncode != 0:
raise HTTPException(status_code=422, detail={"error": proc.stderr.strip()})
output_path = os.path.join(tmpdir, "output.json")
with open(output_path, "r", encoding="utf-8") as f:
result = json.load(f)
return JSONResponse(content=result)
except subprocess.TimeoutExpired:
raise HTTPException(status_code=504, detail="Directory compilation timed out")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
# ── /decompile ──────────────────────────────────────────────────────────
@app.post("/decompile")
async def decompile_json(
compiled: UploadFile = File(..., description="Compiled MSS JSON file"),
):
"""
Decompile compiled MSS JSON back into MSS script and asset mapping.
Returns the reconstructed MSS source (.md) and the recovered asset mapping.
"""
tmpdir = tempfile.mkdtemp(prefix="mss_decompile_")
try:
compiled_bytes = await compiled.read()
compiled_text = compiled_bytes.decode("utf-8")
input_path = os.path.join(tmpdir, "input.json")
with open(input_path, "w", encoding="utf-8") as f:
f.write(compiled_text)
output_dir = os.path.join(tmpdir, "decompiled")
proc = _run_mss("decompile", input_path, "-o", output_dir, timeout=30)
warnings = []
if proc.stderr.strip():
for line in proc.stderr.strip().split("\n"):
line = line.strip()
if line.startswith("warning:"):
warnings.append(line.removeprefix("warning:").strip())
elif line.startswith("wrote"):
pass
elif line:
warnings.append(line)
if not os.path.isdir(output_dir):
raise HTTPException(
status_code=422,
detail={"error": proc.stderr.strip() or "Decompilation produced no output"},
)
mss_files = {}
mapping = None
for fname in os.listdir(output_dir):
fpath = os.path.join(output_dir, fname)
if fname.endswith(".md") or fname.endswith(".mss.md"):
with open(fpath, "r", encoding="utf-8") as f:
mss_files[fname] = f.read()
elif fname.endswith(".json"):
with open(fpath, "r", encoding="utf-8") as f:
mapping = json.load(f)
return JSONResponse(
content={
"episodes": mss_files,
"asset_mapping": mapping,
"warnings": warnings,
}
)
except subprocess.TimeoutExpired:
raise HTTPException(status_code=504, detail="Decompilation timed out")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
# ── /validate ───────────────────────────────────────────────────────────
@app.post("/validate")
async def validate_script(
script: UploadFile = File(..., description="MSS script file (.md) to validate"),
assets: Optional[UploadFile] = File(default=None, description="Optional assets mapping JSON file"),
):
"""
Validate an MSS script for syntax errors without compiling.
Returns a validation report: valid (true/false) and any error messages.
"""
tmpdir = tempfile.mkdtemp(prefix="mss_validate_")
try:
script_bytes = await script.read()
script_text = script_bytes.decode("utf-8")
script_path = os.path.join(tmpdir, "script.md")
with open(script_path, "w", encoding="utf-8") as f:
f.write(script_text)
args = ["validate", script_path]
if assets is not None:
assets_bytes = await assets.read()
assets_text = assets_bytes.decode("utf-8")
assets_path = os.path.join(tmpdir, "assets.json")
with open(assets_path, "w", encoding="utf-8") as f:
f.write(assets_text)
args.append("--assets")
args.append(assets_path)
proc = _run_mss(*args, timeout=30)
return JSONResponse(
content={
"valid": proc.returncode == 0,
"errors": proc.stderr.strip() if proc.returncode != 0 else None,
"stdout": proc.stdout.strip() or None,
}
)
except subprocess.TimeoutExpired:
raise HTTPException(status_code=504, detail="Validation timed out")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
# ── /fix ────────────────────────────────────────────────────────────────
@app.post("/fix")
async def fix_script(
script: UploadFile = File(..., description="MSS script file (.md) to fix"),
check: bool = Query(default=False, description="Dry-run: report issues without writing changes"),
):
"""
Auto-fix common issues in an MSS script.
In fix mode (default): returns the fixed script text and a list of
fixes applied.
In check mode (?check=true): returns a list of issues found without
modifying the script (like `mss fix --check`).
"""
tmpdir = tempfile.mkdtemp(prefix="mss_fix_")
try:
script_bytes = await script.read()
script_text = script_bytes.decode("utf-8")
script_path = os.path.join(tmpdir, "script.md")
with open(script_path, "w", encoding="utf-8") as f:
f.write(script_text)
if check:
proc = _run_mss("fix", script_path, "--check", timeout=30)
return JSONResponse(
content={
"check": True,
"issues_found": proc.returncode != 0,
"report": proc.stderr.strip() or proc.stdout.strip() or None,
}
)
else:
output_path = os.path.join(tmpdir, "fixed.md")
proc = _run_mss("fix", script_path, "-o", output_path, timeout=30)
if proc.returncode != 0 and not os.path.exists(output_path):
raise HTTPException(status_code=422, detail={"error": proc.stderr.strip()})
if os.path.exists(output_path):
with open(output_path, "r", encoding="utf-8") as f:
fixed_text = f.read()
else:
fixed_text = script_text # unchanged
return JSONResponse(
content={
"check": False,
"fixed": fixed_text,
"changed": fixed_text != script_text,
"stderr": proc.stderr.strip() or None,
}
)
except subprocess.TimeoutExpired:
raise HTTPException(status_code=504, detail="Fix timed out")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
# ── / ───────────────────────────────────────────────────────────────────
@app.get("/")
async def root():
"""Root redirect to docs."""
return JSONResponse(
content={
"service": "MoonShort Script API",
"version": "1.2.0",
"endpoints": {
"health": "GET /health",
"compile": "POST /compile",
"compile-dir": "POST /compile-dir",
"decompile": "POST /decompile",
"validate": "POST /validate",
"fix": "POST /fix",
},
"docs": "/docs",
}
)
# ── /health ─────────────────────────────────────────────────────────────
@app.get("/health")
async def health():
"""Health check endpoint."""
if not MSS_BIN.exists():
return JSONResponse(
status_code=503,
content={"status": "unhealthy", "reason": "mss binary not found"},
)
return {"status": "ok"}