TenkajinKB/start-server.py
2026-04-19 16:16:20 +08:00

99 lines
3.3 KiB
Python

#!/usr/bin/env python3
"""TH1 Dashboard server with map regeneration API."""
import http.server
import subprocess
import json
import time
import os
import sys
from pathlib import Path
PORT = 5173
class DashboardHandler(http.server.SimpleHTTPRequestHandler):
"""Serves static files + provides API for map regeneration."""
# Path to N01 map generation script (lives in project module, not root)
GENERATE_SCRIPT = str(Path(__file__).parent / '01_Active_Projects' / 'N01_植物帝国企划' / 'generate_map.py')
def do_POST(self):
if self.path == '/api/regenerate-map':
# Read parameters from POST body
content_len = int(self.headers.get('Content-Length', 0))
body = {}
if content_len > 0:
raw = self.rfile.read(content_len)
try:
body = json.loads(raw.decode('utf-8'))
except Exception:
pass
seed = body.get('seed', 0)
if not seed:
seed = int(time.time() * 1000) % 999999
seed = int(seed)
density = body.get('density', 'normal')
coastline = body.get('coastline', 'natural')
try:
cmd = [
sys.executable, self.GENERATE_SCRIPT,
'--seed', str(seed),
'--density', str(density),
'--coastline', str(coastline),
]
result = subprocess.run(
cmd,
capture_output=True, text=True, encoding='utf-8',
cwd=os.path.dirname(os.path.abspath(__file__)),
timeout=30
)
response = {
'success': result.returncode == 0,
'output': result.stdout,
'seed': seed,
'density': density,
'coastline': coastline,
}
if result.returncode != 0:
response['error'] = result.stderr
except subprocess.TimeoutExpired:
response = {'success': False, 'error': 'Generation timed out', 'seed': seed}
except Exception as e:
response = {'success': False, 'error': str(e), 'seed': seed}
self.send_response(200)
self.send_header('Content-Type', 'application/json; charset=utf-8')
self.end_headers()
self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))
else:
self.send_error(404)
def log_message(self, format, *args):
# Only log non-200 or API calls
if args and (str(args[1]) != '200' or '/api/' in str(args[0])):
super().log_message(format, *args)
def main():
os.chdir(Path(__file__).parent)
os.environ['PYTHONIOENCODING'] = 'utf-8'
print(f'TH1 Dashboard Server')
print(f'=' * 50)
print(f' http://localhost:{PORT}/Dashboard/pages/projects.html')
print(f' API: POST /api/regenerate-map')
print(f' Ctrl+C to stop')
print(f'=' * 50)
server = http.server.HTTPServer(('', PORT), DashboardHandler)
try:
server.serve_forever()
except KeyboardInterrupt:
print('\nServer stopped.')
if __name__ == '__main__':
main()