File size: 997 Bytes
6ca4b94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import subprocess
from pathlib import Path
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.templating import Jinja2Templates

router = APIRouter()

templates = Jinja2Templates(directory="./src/templates")

R_SCRIPTS_DIR = Path("src/R")

@router.post("/r/demo")
async def execute_r_script(applicant_count: int, hire_count: int, base_rate: int, validity: float):

    script_path = f"{R_SCRIPTS_DIR}/demo.R"
    
    proc = subprocess.run(
        ["Rscript", script_path, str(applicant_count), str(hire_count), str(base_rate), str(validity)],
        capture_output=True, text=True
    )
    if proc.returncode != 0:
        # bubble up R errors
        raise HTTPException(status_code=500, detail=proc.stderr.strip())
        
    try:
        data = json.loads(proc.stdout)
    except json.JSONDecodeError:
        raise HTTPException(status_code=500, detail="Invalid JSON from R")

    return data