File size: 7,027 Bytes
6c1954b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
library(dampack)
library(readr)
library(assertthat)
library(jsonlite)
library(httr)

#* @apiTitle DARTH Health Economic Model API
#* 
#* @apiDescription This API runs a health economic Markov model (Sick-Sicker) 
#* for probabilistic sensitivity analysis. Hosted on Hugging Face Spaces.
#* Users send their own parameter CSV data from their local machine.
#* Supports multiple CSV inputs (e.g., base parameters + clinical inputs) that get merged.

#* Welcome page - API info
#* @get /
function() {
  list(
    name = "DARTH Health Economic Model API",
    version = "1.0",
    status = "running",
    endpoints = list(
      "GET /" = "This welcome page",
      "GET /health" = "Health check",
      "POST /runDARTHmodel" = "Run the DARTH model with your CSV data"
    )
  )
}

#* Health check endpoint
#* @get /health
function() {
  list(status = "healthy", timestamp = Sys.time())
}

#* Run the DARTH model
#* @serializer csv
#* @param psa_inputs_json JSON string containing the base parameter distributions data from client's local CSV
#* @param clinical_inputs_json JSON string containing clinical input parameters (optional, merged with psa_inputs)
#* @param param_updates JSON string with optional parameter overrides (applied after merging all inputs)
#* @post /runDARTHmodel
function(psa_inputs_json = NULL, clinical_inputs_json = NULL, param_updates = NULL) {
  
  # Source the model functions from Hugging Face (local) or Private GitHub
  # Local path = inside Docker container on Hugging Face after deployment
  model_functions_path <- "/app/model/darth_funcs.R"
  
  # Private GitHub repo URL for model code
  # Repo: https://github.com/Veenalim/API_Site2.git
  # Path: model/darth_funcs.R
  github_raw_url <- "https://raw.githubusercontent.com/Veenalim/API_Site2/main/model/darth_funcs.R"
  
  model_loaded <- FALSE
  
  # Option 1: Try local file on Hugging Face first (fastest, most reliable)
  if (file.exists(model_functions_path)) {
    source(model_functions_path)
    model_loaded <- TRUE
    message("Model loaded from Hugging Face local file")
  }
  
  # Option 2: Try Private GitHub repo (uses token for authentication)
  if (!model_loaded) {
    tryCatch({
      # Get GitHub token from environment variable (set in Hugging Face secrets)
      github_token <- Sys.getenv("GITHUB_TOKEN")
      
      if (github_token == "") {
        stop("GITHUB_TOKEN environment variable not set")
      }
      
      # Fetch file from private GitHub repo with authentication
      response <- httr::GET(
        github_raw_url,
        httr::add_headers(
          Authorization = paste("token", github_token),
          Accept = "application/vnd.github.v3.raw"
        )
      )
      
      # Check if request was successful
      if (httr::status_code(response) != 200) {
        stop(paste("GitHub returned status:", httr::status_code(response)))
      }
      
      # Save to temp file and source
      temp_file <- tempfile(fileext = ".R")
      writeLines(httr::content(response, "text", encoding = "UTF-8"), temp_file)
      source(temp_file)
      
      # Clean up temp file
      unlink(temp_file)
      
      model_loaded <- TRUE
      message("Model loaded from Private GitHub repo")
    }, error = function(e) {
      message("GitHub source failed: ", e$message)
    })
  }
  
  # No fallback - fail if model cannot be loaded
  if (!model_loaded) {
    stop("ERROR: Could not load model. Check GITHUB_TOKEN is set and repo is accessible.")
  }
  
  # Helper function to parse and validate CSV JSON input
  parse_csv_json <- function(json_input, input_name) {
    if (is.null(json_input) || json_input == "") {
      return(NULL)
    }
    
    tryCatch({
      df <- jsonlite::fromJSON(json_input)
      df <- as.data.frame(df)
      
      # Validate required columns exist
      required_cols <- c("parameter", "distribution", "v1", "v2")
      if (!all(required_cols %in% names(df))) {
        stop(paste("Error:", input_name, "must contain columns:", paste(required_cols, collapse = ", ")))
      }
      
      # Ensure v1 and v2 are numeric (handle NULL/NA values)
      df$v1 <- as.numeric(df$v1)
      df$v2 <- as.numeric(df$v2)
      
      # Replace NA with 0 for v2 (needed for 'fixed' distributions)
      df$v2[is.na(df$v2)] <- 0
      
      return(df)
    }, error = function(e) {
      stop(paste("Error parsing", input_name, "JSON:", e$message))
    })
  }
  
  # Parse the base PSA inputs (required)
  if (is.null(psa_inputs_json) || psa_inputs_json == "") {
    stop("Error: psa_inputs_json is required. Please send your local CSV data.")
  }
  
  psa_inputs <- parse_csv_json(psa_inputs_json, "psa_inputs_json")
  
  # Parse clinical inputs if provided (optional, merged with psa_inputs)
  clinical_inputs <- parse_csv_json(clinical_inputs_json, "clinical_inputs_json")
  
  if (!is.null(clinical_inputs)) {
    # Merge clinical inputs with base inputs (clinical inputs are appended)
    # If duplicate parameters exist, clinical inputs take precedence
    existing_params <- psa_inputs$parameter
    new_params <- clinical_inputs$parameter
    
    # Remove any duplicate parameters from psa_inputs (clinical takes precedence)
    duplicates <- existing_params %in% new_params
    if (any(duplicates)) {
      psa_inputs <- psa_inputs[!duplicates, ]
    }
    
    # Combine the data frames
    psa_inputs <- rbind(psa_inputs, clinical_inputs)
  }
  
  # Parse param_updates if provided (for additional overrides)
  if (!is.null(param_updates) && param_updates != "") {
    # Handle both JSON string and data frame input
    if (is.character(param_updates)) {
      param_updates <- jsonlite::fromJSON(param_updates)
    }
    
    # Convert to data frame if needed
    if (!is.data.frame(param_updates)) {
      param_updates <- as.data.frame(param_updates)
    }
    
    # For each row of the data-frame containing the variables to be changed...
    for(n in 1:nrow(param_updates)) {
      # Update parameters from API input
      psa_inputs <- overwrite_parameter_value(
        existing_df = psa_inputs,
        parameter = param_updates[n, "parameter"], 
        distribution = param_updates[n, "distribution"],
        v1 = param_updates[n, "v1"],
        v2 = param_updates[n, "v2"]
      )
    }
  }
  
  # Run the model using the single run-model function
  results <- run_model(psa_inputs)
  
  # Check that the model results being returned are the correct dimensions
  assertthat::assert_that(
    all(dim(x = results) == c(1000, 6)),
    class(results) == "data.frame",
    msg = "Dimensions or type of data are incorrect, please check the model code."
  )
  
  # Check that no sensitive data is included in the output
  assertthat::assert_that(
    all(psa_inputs[, 1] %in% as.character(unlist(x = results, recursive = TRUE)) == FALSE)
  )
  
  return(results)
}