Debian Codegraph @

inst/cvdemulator/server.R

raw
1 # -------------------------------------------------------------------
2 # - NAME: server.R
3 # - AUTHOR: Reto Stauffer
4 # - DATE: 2017-09-16
5 # -------------------------------------------------------------------
6 # - DESCRIPTION:
7 # -------------------------------------------------------------------
8 # - EDITORIAL: 2017-09-16, RS: Created file on thinkreto.
9 # -------------------------------------------------------------------
10 # - L@ST MODIFIED: 2018-10-08 18:59 on marvin
11 # -------------------------------------------------------------------
12
13
14 # Check if we are on a shiny server (e.g., my uberspace account) or not.
15 isUberspace <- function() {
16 if ( Sys.getenv('SHINY_PORT') == "" ) { return(FALSE) } else { return(TRUE) }
17 }
18
19 # Restrict upload file size to 1MB (online) and 50MB (local)
20 options(shiny.maxRequestSize=1*1024^2)
21 if ( ! isUberspace() ) {
22 options(shiny.maxRequestSize=50*1024^2)
23 }
24
25 # Define server logic to read selected file ----
26 shiny::shinyServer(function(input, output, session) {
27
28
29 values <- shiny::reactiveValues(emulated = NULL)
30
31 output$file_info <- shiny::renderText(paste("Select an image from your local",
32 "disc (PNG/JPG/JPEG) for which the color vision deficiency",
33 "should be emulated. Please note that the file size is limited",
34 sprintf("to %.1f Megabyte.", getOption("shiny.maxRequestSize") / 1024^2)))
35
36 # ----------------------------------------------------------------
37 # Package version information
38 # ----------------------------------------------------------------
39 output$version_info <- shiny::renderText(sprintf("<a href=\"%s\">R colorspace %s</a>",
40 "https://CRAN.R-project.org/package=colorspace",
41 packageVersion("colorspace")))
42 output$filebox <- shiny::renderUI({
43 shiny::fileInput("file", label=h2("Upload Image"),
44 multiple = FALSE, width = "100%",
45 accept = c("image/png","image/jpeg"))
46 })
47
48 # ----------------------------------------------------------------
49 # Dark mode on/off
50 # ----------------------------------------------------------------
51 shiny::observeEvent(input$darkmode, {
52 if ( ! input$darkmode ) {
53 shinyjs::removeClass(selector = "body", class = "darkmode")
54 } else {
55 shinyjs::addClass(selector = "body", class = "darkmode")
56 }
57 })
58
59 # ----------------------------------------------------------------
60 # Status observer
61 # ----------------------------------------------------------------
62 shiny::observe({
63 output$status <- shiny::renderText({paste("Please upload an image first.",
64 "After uploading the conversion needs few seconds, so please be patient!")})
65 for ( type in c("orig","desaturate","deutan","protan","tritan") ) showInit(type,output)
66 })
67
68
69 # ----------------------------------------------------------------
70 # Keyboard key bindings
71 # ----------------------------------------------------------------
72 shiny::observe({
73 if ( is.null(input$key_pressed) ) return()
74 # Switch a/s/d/f/g
75 if ( input$key_pressed == 65 ) { # a
76 selected = "Original"
77 } else if ( input$key_pressed == 83 ) { # s
78 selected = "Desaturated"
79 } else if ( input$key_pressed == 68 ) { # d
80 selected = "Deuteranope"
81 } else if ( input$key_pressed == 70 ) { # f
82 selected = "Protanope"
83 } else if ( input$key_pressed == 71 ) { # g
84 selected = "Tritanope"
85 } else if ( input$key_pressed == 72 ) { # h
86 selected = "All"
87 } else { return() }
88
89 shiny::updateTabsetPanel(session, "maintabs", selected = selected)
90 })
91
92 shiny::observe({ if ( !is.null(input$file) ) values$emulated <- NULL })
93
94 # ----------------------------------------------------------------
95 # File observer: does basically everything
96 # ----------------------------------------------------------------
97 shiny::observe({
98
99 if ( !is.null(values$emulated) ) return(FALSE)
100
101 # Info
102 if ( ! is.null(input$file) ) {
103 output$status <- shiny::renderText({"File uploaded, starting conversion ..."})
104 shiny::updateTabsetPanel(session, "maintabs", selected = "Original")
105 output$filebox <- shiny::renderUI({
106 shiny::fileInput("file", label=h2("Upload Image"),
107 multiple = FALSE, width = "100%",
108 accept = c("image/png","image/jpeg"))
109 })
110 }
111
112 # input$file1 will be NULL initially. After the user selects
113 # and uploads a file, head of that data file by default,
114 # or all rows if selected, will be shown.
115 # Is a data.frame containing one row (multiple file upload
116 # is not allowed),
117 # Columns: name, size, type (mime), datapath (temporary file location)
118 shiny::req(input$file)
119
120 ## Identify file type (file suffix)
121 file <- input$file$datapath[1]
122 filename <- input$file$name[1]
123 is_img <- colorspace:::check_image_type(filename)
124
125 # If is either png or jpeg: go ahead
126 if ( is_img$png | is_img$jpg ) {
127 if ( is_img$png ) {
128 img <- try(png::readPNG(file))
129 } else {
130 img <- try(jpeg::readJPEG(file))
131 }
132
133 # Broken image or no PNG/JPEG
134 if ( "try-error" %in% class(img) ) {
135 tmp <- paste("Sorry, image could not have been read. Seems that the file you",
136 "uploaded was no png/jpg/jpeg file or a broken file. Please check your file",
137 "and try again!")
138 output$status <- shiny::renderText({tmp})
139 return(FALSE)
140 }
141
142 # Resize image if width > 800
143 if ( dim(img)[2] > 800 ) img <- resizeImage(img,800)
144 ##if ( dim(img)[2] > 800 && Sys.getenv('SHINY_PORT') != "" ) img <- resizeImage(img,800)
145
146 # Show uploaded image
147 show(file, "orig", output)
148 # Convert
149 for ( type in c("desaturate", "deutan", "protan", "tritan") )
150 show(img, type, output, input$severity/100.)
151
152 # Delete uploaded file
153 file.remove( file )
154 rm(list=c("img","is_img","file","filename"))
155 output$status <- shiny::renderText({"Image successfully converted."})
156 values$emulated <- TRUE
157
158 return(TRUE)
159 } else {
160 tmp <- paste("Uploaded image has had unknown file name extension!",
161 "Please upload png, jpg or jpeg (not case sensitive).")
162 output$status <- shiny::renderText({tmp})
163 return(FALSE)
164 }
165 })
166
167 }) # End of shinyServer
168
169
170 # Resize the image (neares neighbor interpolation/approximation)
171 resizeImage = function(im, w.out=600, h.out) {
172
173 # Dimensions of the input image
174 din <- list("height"=dim(im)[1],"width"=dim(im)[2],"layers"=dim(im)[3])
175 # If h.out is missing: proportional scaling
176 if ( missing(h.out) ) h.out <- round(din$height/(din$width/w.out))
177 # Create empty array to store resized image
178 out = array(0,c(h.out,w.out,din$layers))
179 # Compute ratios -- final number of indices is n.out, spaced over range of 1:n.in
180 w_ratio = din$width / w.out
181 h_ratio = din$height / h.out
182 # Do resizing -- select appropriate indices
183 for ( l in 1:din$layers )
184 out[,,l] <- im[ floor(h_ratio* 1:h.out), floor(w_ratio* 1:w.out), l]
185
186 return(out)
187 }
188
189
190 # Function which converts the image and displays it in the shiny app
191 show <- function(img, type, output, severity = 1.0) {
192
193 if ( is.character(img) ) {
194 tmp <- img
195 rm <- FALSE
196 } else {
197 # Create temporary file name
198 tmp <- tempfile(sprintf("hclconvert_%s",type),fileext=".png")
199 # Convert image
200 colorspace:::cvd_image(img, type, tmp, severity = severity)
201 rm <- TRUE
202 }
203
204 # Base64-encode file
205 txt <- RCurl::base64Encode(readBin(tmp, "raw", file.info(tmp)[1, "size"]), "txt")
206 # Create inline image, save & open html file in browser
207 html <- sprintf('data:image/png;base64,%s', txt)
208 # Rendering images
209 output[[sprintf("image%s",type)]] <- shiny::renderUI({ img(src = html) })
210 output[[sprintf("all_image%s",type)]] <- shiny::renderUI({ img(src = html) })
211 # Delete temporary file
212 if ( rm ) file.remove(tmp)
213 }
214
215 # Show images when loading the app (included in www/images)
216 showInit <- function( type, output ) {
217 output[[sprintf("image%s",type)]] <- shiny::renderUI({img(src = sprintf("images/rainbow_%s.png",type))})
218 output[[sprintf("all_image%s",type)]] <- shiny::renderUI({img(src = sprintf("images/rainbow_%s.png",type))})
219 }
220