File size: 2,064 Bytes
af2a33c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
978295b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import subprocess
from pathlib import Path


def validate_rmd(path):
    rmd_path = Path(path)
    if not rmd_path.is_file():
        raise FileNotFoundError(f"File non trovato: {path}")

    report_dir = rmd_path.parent
    status = 200
    error_message = ""

    render_cmd = [
        "Rscript", "--vanilla", "-e",
        f"rmarkdown::render("
        f"input = '{rmd_path.as_posix()}', "
        f"output_format = c('html_document', 'latex_document'), "
        f"output_dir = '{report_dir.as_posix()}')"
    ]

    try:
        result = subprocess.run(
            render_cmd,
            check=True,
            capture_output=True,
            text=True,
            encoding='utf-8'
        )

        base_name = rmd_path.stem
        html_file = report_dir / f"{base_name}.html"
        tex_file = report_dir / f"{base_name}.tex"

        if not (html_file.exists() and tex_file.exists()):
            status = 404
            error_message = "File di output non generati correttamente"

    except subprocess.CalledProcessError as e:
        status = 404
        error_message = f"Errore durante il rendering:\n{e.stderr}"
    except Exception as e:
        status = 404
        error_message = f"Errore imprevisto: {str(e)}"

    status_file = report_dir / str(status)
    with open(status_file, 'w', encoding='utf-8') as f:
        if status == 404:
            f.write(error_message)

    return status, error_message if status == 404 else "OK"


def render_rmd_format(path, output_format):
    rmd_path = Path(path)
    if not rmd_path.is_file():
        raise FileNotFoundError(f"File non trovato: {path}")

    report_dir = rmd_path.parent

    render_cmd = [
        "Rscript", "--vanilla", "-e",
        f"rmarkdown::render("
        f"input = '{rmd_path.as_posix()}', "
        f"output_format = '{output_format}', "
        f"output_dir = '{report_dir.as_posix()}')"
    ]

    result = subprocess.run(
        render_cmd,
        check=True,
        capture_output=True,
        text=True,
        encoding='utf-8'
    )

    return result