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) }