-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.R
334 lines (221 loc) · 9 KB
/
app.R
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# Wordclouds version 2.0.0 by Eric Hochberger
# 11/20/19
#
# install.packages("shiny", "rvest", "tidyverse", "janitor", "wordcloud", "tm", "RColorBrewer", "jpeg", "shinyWidgets", "shinythemes", "png", "jsonlite")
library(shiny)
library(rvest)
library(tidyverse)
library(janitor)
library(wordcloud)
library(tm)
library(RColorBrewer)
library(jpeg)
library(shinyWidgets)
library(shinythemes)
library(png)
library(jsonlite)
ui <- fluidPage(
# Application title
titlePanel(
h1("Album Word Cloud Generator")),
sidebarLayout(
sidebarPanel(id = "sidebar",
textInput("text", label = (h3("Please type the artist's name whose albums you wish to explore: ")),
value = "Kanye West"),
prettyRadioButtons(inputId = "palette",
label = h3("Choose color palette:"),
choices = c("Default", "Album Cover"),
animation = "jelly",
selected = "Album Cover"
),
uiOutput('variables'),
helpText("All data courtesy of ", a(href = "https://genius.com", "Genius.com,")," the world's biggest collection of song lyrics and musical knowledge.",
"The wordcloud tab displays the most frequently used words on the album with size corresponding to their relative frequency.
The summary tab displays a histogram of the 10 most frequently used words ordered by the total number of mentions on the album."),
htmlOutput("picture")
),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Cloud",
h1(textOutput("title1"), align = "center"),
tags$head(tags$style("#title1{color: red;
font-size: 30px;
font-style: italic;
}"
)
),
plotOutput("Plot", width = "100%", height = "600px")),
tabPanel("Summary",
h1(textOutput("title"), align = "center"),
tags$head(tags$style(paste("#title{color: red;
font-size: 30px;
font-style: italic;
}", sep = "")
)
),
plotOutput("sum_Plot", width = "100%", height = "600px")
)
) #end of tabsetPanel
) #end of mainPanel
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
url <- reactive({
name_formatted <- input$text %>% str_replace_all("[[:punct:]]", "") %>% str_replace_all(" ", "-")
paste("https://genius.com/artists/", name_formatted, sep = "")
})
metadata <- reactive({
read_html(url()) %>%
html_nodes("meta[itemprop='page_data']") %>% #Access page metadata
html_attr("content") %>% #Render metadata as JSON
fromJSON()
})
albumlist <- reactive({
metadata <- metadata()
metadata$artist_albums$name
})
output$variables = renderUI({
selectInput('variables2', 'Albums', albumlist())
})
tib <- reactive({
metadata <- metadata()
tibble(
y = metadata$artist_albums$name,
x = metadata$artist_albums$url
)
})
album_url <- reactive({
tib <- tib() %>% filter(y == input$variables2) %>% select(x)
return(tib[[1]])
})
# Wordcloud section (all input$text below here should be album_url) -------
src <- reactive({
album_url() %>% read_html() %>% html_node('img.cover_art-image') %>% html_attr("src")
})
pal <- reactive({
z <- tempfile()
download.file(src(),z,mode="wb") # save album cover jpeg to tempfile
if (str_detect(src(), ".png") == TRUE) {
pic <- readPNG(z)
file.remove(z)
pic <- writeJPEG(pic, quality = 1)
pic <- readJPEG(pic)
}
else {
pic <- readJPEG(z)
file.remove(z) #remove tempfile
}
palette_tbl <- tibble(
R = as.vector(pic[,,1]),
G = as.vector(pic[,,2]),
B = as.vector(pic[,,3])
)
k_means <- kmeans(palette_tbl, centers = 10, iter.max = 50)
rgb(k_means$centers)[1:10]
})
album_songs <- reactive({
album_url() %>% read_html() %>% html_nodes('.chart_row-content-title') %>% html_text() %>%
trimws() %>%
str_replace_all("Lyrics", " ") %>%
str_replace_all("\n", " ") %>%
trimws() %>%
make_clean_names() %>%
str_replace_all("_", "-")
})
artist <- reactive({
album_url() %>%
str_extract("(?<=albums).*/") %>% str_remove_all("/")
})
lyrics <- reactive({
words <- ""
for(i in album_songs() ) {
url <- paste("https://genius.com/", artist(), "-", i, sep = "") %>%
str_remove("-lyrics") %>%
str_remove("-ft-.*") %>%
str_remove("-number") %>%
paste("-lyrics", sep = "")
if (str_detect(url, "credits") == TRUE) next
try(
words <-url %>% read_html() %>% html_node("div.song_body-lyrics") %>%
html_text() %>%
str_replace_all("\n|\\[.*?\\]|,|-|More on Genius|Lyrics", " ") %>%
str_replace_all("\'", "") %>%
str_replace_all(album_url() %>% read_html() %>% html_node("a.header_with_cover_art-primary_info-primary_artist") %>% html_text(), " ") %>%
str_replace_all("([a-z])([A-Z])", "\\1 \\2") %>%
append(words)
)
}
# Process album lyrics --------------------------------------
words <- Corpus(VectorSource(words))
words <- tm_map(words, stripWhitespace)
words <- tm_map(words, content_transformer(tolower))
words <- tm_map(words, removeWords, stopwords('english'))
words <- tm_map(words, removePunctuation)
words
})
# Wordcloud ---------------------------------------------------------------
output$Plot <- renderPlot({
pal_input <- switch (input$palette,
"Album Cover" = pal(),
"Default" = brewer.pal(10, "Paired")
)
lyrics() %>% wordcloud(colors = pal_input, random.order = FALSE, random.color = FALSE, rot.per = .25, max.words = 100, scale = c(5, 0.5))
})
# Histogram ---------------------------------------------------------------
output$sum_Plot <- renderPlot({
pal_input <- switch (input$palette,
"Album Cover" = pal(),
"Default" = brewer.pal(10, "Paired")
)
lyrics1 <- TermDocumentMatrix(lyrics()) %>% as.matrix()
sort(rowSums(lyrics1), decreasing = TRUE) %>% enframe() %>%
filter(row_number() <= 10) %>% ggplot(aes(fct_reorder(name, desc(value)), value)) +
geom_col(aes(fill = name), color = "gray29") +
theme_minimal() +
scale_fill_manual(values = pal_input ) +
scale_x_discrete(NULL) +
scale_y_continuous("Count\n", expand = c(0,0)) +
theme(
axis.text = element_text(size = 18, face = "bold", colour = "black"),
axis.title = element_text(size = 20, face = "bold"),
legend.position = "none"
)
})
# Album cover -------------------------------------------------------------
picture <- reactive({
c('<img src="',src(),'">')
})
output$picture<-renderText({
picture()
})
# Title -------------------------------------------------------------------
output$title <- renderText({
album_title <- album_url() %>% read_html() %>%
html_nodes('li.breadcrumb.breadcrumb-current_page') %>%
html_text() %>%
str_remove_all("\n") %>%
trimws()
artist_name <- album_url() %>%
read_html() %>%
html_node("a.header_with_cover_art-primary_info-primary_artist") %>%
html_text()
paste(album_title, "by", artist_name, sep = " ")
})
#Duplicate of title so title is stylized correctly in both tabs
output$title1 <- renderText({
album_title <- album_url() %>%
read_html() %>%
html_nodes('li.breadcrumb.breadcrumb-current_page') %>%
html_text() %>%
str_remove_all("\n") %>%
trimws()
artist_name <- album_url() %>%
read_html() %>%
html_node("a.header_with_cover_art-primary_info-primary_artist") %>%
html_text()
paste(album_title, "by", artist_name, sep = " ")
})
}
# Run the application
shinyApp(ui = ui, server = server)