File size: 7,048 Bytes
65da30d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""FastAPI backend for rmscript web demo."""

import logging
from pathlib import Path
from typing import Any, Dict, List
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel

from rmscript import compile_script

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Create FastAPI app
app = FastAPI(
    title="RMScript Web Demo API",
    description="Backend API for compiling and validating rmscript code",
    version="1.0.0"
)

# Enable CORS for local development
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # In production, specify exact origins
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Set up paths for serving frontend
BACKEND_DIR = Path(__file__).parent
FRONTEND_DIR = BACKEND_DIR.parent / "frontend"

# Mount static files (CSS, JS)
if FRONTEND_DIR.exists():
    app.mount("/static", StaticFiles(directory=str(FRONTEND_DIR)), name="static")


class ScriptInput(BaseModel):
    """Input model for script compilation."""

    source: str


class CompilationError(BaseModel):
    """Compilation error model."""

    line: int
    column: int
    message: str
    severity: str


class VerifyResponse(BaseModel):
    """Response model for script verification."""

    success: bool
    errors: List[Dict[str, Any]]
    warnings: List[Dict[str, Any]]
    name: str = ""
    description: str = ""


class IRActionModel(BaseModel):
    """Simplified IR action model for JSON serialization."""

    type: str  # "action", "wait", "picture", "sound"
    duration: float = 0.0
    # For movement actions
    head_pose: List[List[float]] | None = None  # 4x4 matrix as nested list
    antennas: List[float] | None = None  # [left, right] in radians
    body_yaw: float | None = None  # radians
    # For sound actions
    sound_name: str | None = None
    blocking: bool = False
    loop: bool = False
    # Metadata
    source_line: int = 0


class CompileResponse(BaseModel):
    """Response model for script compilation."""

    success: bool
    errors: List[Dict[str, Any]]
    warnings: List[Dict[str, Any]]
    name: str = ""
    description: str = ""
    ir: List[IRActionModel]


@app.get("/")
async def root():
    """Serve the frontend application."""
    index_path = FRONTEND_DIR / "index.html"
    if index_path.exists():
        return FileResponse(index_path)
    return {
        "name": "RMScript Web Demo API",
        "version": "1.0.0",
        "endpoints": {
            "/api/verify": "POST - Verify rmscript syntax and semantics",
            "/api/compile": "POST - Compile rmscript to IR",
        }
    }


@app.post("/api/verify", response_model=VerifyResponse)
async def verify_script(input: ScriptInput):
    """Verify rmscript without generating IR.

    Args:
        input: Script source code

    Returns:
        Verification result with errors and warnings

    """
    logger.info(f"Verifying script ({len(input.source)} chars)")

    try:
        result = compile_script(input.source)

        # Convert errors and warnings to dict format
        errors = [
            {
                "line": e.line,
                "column": e.column,
                "message": e.message,
                "severity": e.severity
            }
            for e in result.errors
        ]

        warnings = [
            {
                "line": w.line,
                "column": w.column,
                "message": w.message,
                "severity": w.severity
            }
            for w in result.warnings
        ]

        return VerifyResponse(
            success=result.success,
            errors=errors,
            warnings=warnings,
            name=result.name,
            description=result.description
        )

    except Exception as e:
        logger.error(f"Verification error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/api/compile", response_model=CompileResponse)
async def compile_rmscript(input: ScriptInput):
    """Compile rmscript to intermediate representation.

    Args:
        input: Script source code

    Returns:
        Compilation result with IR

    """
    logger.info(f"Compiling script ({len(input.source)} chars)")

    try:
        from rmscript.ir import IRAction, IRWaitAction, IRPictureAction, IRPlaySoundAction

        result = compile_script(input.source)

        # Convert errors and warnings to dict format
        errors = [
            {
                "line": e.line,
                "column": e.column,
                "message": e.message,
                "severity": e.severity
            }
            for e in result.errors
        ]

        warnings = [
            {
                "line": w.line,
                "column": w.column,
                "message": w.message,
                "severity": w.severity
            }
            for w in result.warnings
        ]

        # Convert IR to JSON-serializable format
        ir_json = []
        for action in result.ir:
            if isinstance(action, IRAction):
                ir_json.append(IRActionModel(
                    type="action",
                    duration=action.duration,
                    head_pose=action.head_pose.tolist() if action.head_pose is not None else None,
                    antennas=action.antennas if action.antennas is not None else None,
                    body_yaw=action.body_yaw,
                    source_line=action.source_line
                ))
            elif isinstance(action, IRWaitAction):
                ir_json.append(IRActionModel(
                    type="wait",
                    duration=action.duration,
                    source_line=action.source_line
                ))
            elif isinstance(action, IRPictureAction):
                ir_json.append(IRActionModel(
                    type="picture",
                    source_line=action.source_line
                ))
            elif isinstance(action, IRPlaySoundAction):
                ir_json.append(IRActionModel(
                    type="sound",
                    duration=action.duration or 0.0,
                    sound_name=action.sound_name,
                    blocking=action.blocking,
                    loop=action.loop,
                    source_line=action.source_line
                ))

        logger.info(f"Compiled {len(ir_json)} IR actions")

        return CompileResponse(
            success=result.success,
            errors=errors,
            warnings=warnings,
            name=result.name,
            description=result.description,
            ir=ir_json
        )

    except Exception as e:
        logger.error(f"Compilation error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8001, log_level="info")