forked from sudhir-voleti/basic-text-analysis-shinyapp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.R
More file actions
502 lines (337 loc) · 12.4 KB
/
server.R
File metadata and controls
502 lines (337 loc) · 12.4 KB
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
#################################################
# Basic Text Analysis #
#################################################
shinyServer(function(input, output,session) {
set.seed=2092014
dataset <- reactive({
if (is.null(input$file)) {return(NULL)}
else {
if(file_ext(input$file$datapath)=="txt"){
Document = readLines(input$file$datapath)
#colnames(Document) <- c("Doc.id","Document")
Doc.id=seq(1:length(Document))
calib=data.frame(Doc.id,Document)
print(input$file$name)
return(calib)}
else{
Document = read.csv(input$file$datapath ,header=TRUE, sep = ",", stringsAsFactors = F)
Document[,1] <- str_to_title(Document[,1])
Document[,1] <- make.names(Document[,1], unique=TRUE)
Document[,1] <- tolower(Document[,1])
Document[,1] <- str_replace_all(Document[,1],"\\.","_")
Document<-Document[complete.cases(Document), ]
Document <- Document[!(duplicated(Document[,1])), ]
rownames(Document) <- Document[,1]
# colnames(Document) <- c("Doc.id","Document")
#Doc.id=seq(1:length(Document))
# calib=data.frame(Doc.id,Document)
#print(input$file$name)
return(Document)
}
}
})
cols <- reactive({colnames(dataset())})
output$pre_proc1 <- renderUI({if(is.null(dataset())){
return(NULL)
}else{
checkboxInput('html',"Remove HTML tags",value = TRUE)
}
})
output$pre_proc2 <- renderUI({if(is.null(dataset())){
return(NULL)
}else{
checkboxInput('num',"Remove Numbers",value = TRUE)
}
})
y_col <- reactive({
x <- match(input$x,cols())
y_col <- cols()[-x]
return(y_col)
})
output$id_var <- renderUI({
print(cols())
selectInput("x","Select ID Column",choices = cols())
})
output$doc_var <- renderUI({
selectInput("y","Select Text Column",choices = y_col())
})
dtm_tcm = eventReactive(input$apply,{
textb = dataset()[,input$y]
ids = dataset()[,input$x]
dtm.tcm = dtm.tcm.creator(text = textb,
id = ids,
std.clean = TRUE,
std.stop.words = TRUE,
stop.words.additional = unlist(strsplit(input$stopw,",")),
bigram.encoding = TRUE,
# bigram.min.freq = 20,
min.dtm.freq = input$freq,
skip.grams.window = 10,
html_tags=input$html,
numbers = input$num)
#if (input$ws == "weightTf") {
dtm = as.matrix(dtm.tcm$dtm)
dtm
dtm_tcm_obj = list(dtm = dtm)#, tcm = tcm)
dtm_tcm_obj
# }
# if (input$ws == "weightTfIdf"){
# model_tfidf = TfIdf$new()
# dtm = round(as.matrix(model_tfidf$fit_transform(dtm.tcm$dtm)),2)
#
# tempd = dtm*0
# tempd[dtm > 0] = 1
# dtm = dtm + tempd
# }
#
# # tcm = dtm.tcm$tcm
# dtm_tcm_obj = list(dtm = dtm)#, tcm = tcm)
})
dtm_idf = eventReactive(input$apply,{
textb = dataset()[,input$y]
ids = dataset()[,input$x]
dtm.tcm = dtm.tcm.creator(text = textb,
id = ids,
std.clean = TRUE,
std.stop.words = TRUE,
stop.words.additional = unlist(strsplit(input$stopw,",")),
bigram.encoding = TRUE,
# bigram.min.freq = 20,
min.dtm.freq = input$freq,
skip.grams.window = 10)
# if (input$ws == "weightTf") {
# dtm = as.matrix(dtm.tcm$dtm)
# }
# if (input$ws == "weightTfIdf"){
model_tfidf = TfIdf$new()
dtm = round(as.matrix(model_tfidf$fit_transform(dtm.tcm$dtm)),2)
tempd = dtm*0
tempd[dtm > 0] = 1
dtm = dtm + tempd
# }
# tcm = dtm.tcm$tcm
dtm_tcm_obj = list(dtm = dtm)#, tcm = tcm)
dtm_tcm_obj
})
ordered_dtm_idf<- reactive({if (is.null(input$file)) {return(NULL)}
else{
mat1= dtm_idf()$dtm
a = colSums(mat1)
b = order(-a) # nice syntax for ordering vector in decr order
mat2 = mat1[,b]
return(mat2)
}
})
ordered_dtm <- reactive({if (is.null(input$file)) {return(NULL)}
else{
mat1= dtm_tcm()$dtm
a = colSums(mat1)
b = order(-a) # nice syntax for ordering vector in decr order
mat2 = mat1[,b]
return(mat2)
}
})
output$idf_table <- renderDataTable({
temp <- ordered_dtm_idf()[1:10,1:10]
# temp <- tem[1:10,1:10]
return(temp)
# a = colSums(mat1) # collect colsums into a vector obj a
#
# diag(mat2) = 0
})
output$dtm_table <- renderDataTable({
temp <- ordered_dtm()[1:10,1:10]
# temp <- tem[1:10,1:10]
return(temp)
# a = colSums(mat1) # collect colsums into a vector obj a
#
# diag(mat2) = 0
})
idfwordcounts = reactive({
return(dtm.word.count(dtm_idf()$dtm))
})
wordcounts = reactive({
return(dtm.word.count(dtm_tcm()$dtm))
})
output$idf_wordcloud <- renderPlot({
if (is.null(input$file)) {return(NULL)}
else{
tsum = idfwordcounts()
tsum = tsum[order(tsum, decreasing = T)]
dtm.word.cloud(count = tsum,max.words = input$max,title = 'TF-IDF Wordcloud')
}
})
output$wordcloud <- renderPlot({
if (is.null(input$file)) {return(NULL)}
else{
tsum = wordcounts()
tsum = tsum[order(tsum, decreasing = T)]
dtm.word.cloud(count = tsum,max.words = input$max,title = 'Term Frequency Wordcloud')
}
})
output$cog.idf <- renderVisNetwork({
if (is.null(input$file)|input$apply==0) {return(NULL)}
else{
distill.cog.tcm(mat1=dtm_idf()$dtm, # input TCM MAT
mattype = "DTM",
title = "COG from TF-IDF Adjacency", # title for the graph
s=input$nodes, # no. of central nodes
k1 = input$connection) # No. of Connection with central Nodes
}
})
output$cog.dtm <- renderVisNetwork({
if (is.null(input$file)|input$apply==0) {return(NULL)}
else{
distill.cog.tcm(mat1=dtm_tcm()$dtm, # input TCM MAT
mattype = "DTM",
title = "COG from DTM Adjacency", # title for the graph
s=input$nodes, # no. of central nodes
k1 = input$connection) # No. of Connection with central Nodes
}
})
# output$cog.tcm <- renderPlot({
#
# distill.cog.tcm(mat1=dtm_tcm()$tcm, # input TCM MAT,
# mattype = "TCM",
# title = "TCM from glove algorithm - Graph ", # title for the graph
# s=input$nodes, # no. of central nodes
# k1 = input$connection) # No. of Connection with central Nodes
#
# })
# output$dtmsummary <- renderPrint({
# if (is.null(input$file)) {return(NULL)}
# else {
# sortedobj = dtm_tcm()$dtm[,order(wordcounts(), decreasing = T)]
# (t(sortedobj[1:10,1:10]))
# }
# })
output$idf_size <- renderPrint({
if (is.null(input$file)|input$apply==0) {return(NULL)}
else {
size = dim(t(dtm_idf()$dtm))
dtm_size = paste("TF-IDF matrix size is ", size[1]," X ", size[2],". Below are the first 10 docs X top 10 tokens")
return(dtm_size)
}
})
output$dtmsize <- renderPrint({
if (is.null(input$file)|input$apply==0) {return(NULL)}
else {
size = dim(t(dtm_tcm()$dtm))
dtm_size = paste("Term Document Matrix (TDM) size is ", size[1]," X ", size[2],". Below are the first 10 docs X top 10 tokens")
return(dtm_size)
}
})
output$dtmsummary2 <- renderDataTable({
if (is.null(input$file)|input$apply==0) {return(NULL)}
else {
data.frame(score = idfwordcounts()[order(idfwordcounts(), decreasing = T)][1:input$max])
}
})
output$dtmsummary1 <- renderDataTable({
if (is.null(input$file)|input$apply==0) {return(NULL)}
else {
data.frame(Counts = wordcounts()[order(wordcounts(), decreasing = T)][1:input$max])
}
})
# This is your reactive element.
df_reactive <- eventReactive(input$apply,{
if (is.null(input$file)|input$apply==0) {return(NULL)}
else{
a0 = concordance.r(dataset()[,input$y],input$concord.word, input$window,input$regx)
a0
# a0 %>%
# # Filter if input is anywhere, even in other words.
# filter_all(any_vars(grepl(input$concord.word, ., T, T))) %>%
# # Replace complete words with same in HTML.
# mutate_all(~ gsub(
# paste(c("\\b(", input$concord.word, ")\\b"), collapse = ""),
# "<span style='background-color:#6ECFEA;'>\\1</span>",
# .,
# TRUE,
# TRUE
# )
# )
}
})
output$concordance = renderDataTable({
# a0 = concordance.r(dataset()$Document,input$concord.word, input$window)
# concordance = a0
# datatable(concordance, escape = F, options = list(dom = "lt"))
datatable(df_reactive(), escape = F, options = list(dom = "lt"))
})
bi_gram <- reactive({
if (is.null(input$file)|input$apply==0) {return(NULL)}
else{
a1 = dataset()[,input$y] %>% split_by_puncts(puncts,.) #N-------------
a2 = tibble(phrases = unlist(a1));
a0 = bigram.collocation(a2)
# a0 = bigram.collocation(dataset()$Document)
a0$coll.ratio <- round(a0$coll.ratio,2)
a0 = a0[order(a0$n, decreasing = T),]
if (nrow(a0) > 100){
a1 = a0[1:100,]
} else {
a1 = a0
}
a1
}
})
output$bi.grams = renderDataTable({
bi_gram()
})
output$bi_word_cloud <- renderPlot({
if (is.null(input$file)|input$apply==0) {return(NULL)}
else{
wordcloud(bi_gram()$bigram_united, bi_gram()$n, # words, their freqs
scale = c(4, 1), # range of word sizes
min.freq = .01, # min.freq of words to consider
max.words = input$max, # max #words
colors = brewer.pal(8, "Dark2"))
}
})
output$dtm_text <- renderText({
size = dim(ordered_dtm())
dtm_size = paste("DTM has ", size[1],"(rows)"," X ", size[2],"(columns)","")
})
output$tfidf_text <- renderText({
size = dim(ordered_dtm_idf())
dtm_size = paste("TF-IDF has ", size[1],"(rows)"," X ", size[2],"(columns)","")
})
output$bi_text <- renderText({
size = dim(bigram_data())
dtm_size = paste("Bi-gram corpus has ", size[1],"(rows)"," X ", size[2],"(columns)","")
})
output$download_tfidf <- downloadHandler(
filename = function() {paste(str_split(input$file$name,"\\.")[[1]][1],"_tfidf.csv",collapse = "") },
content = function(file) {
new_dtm <- ordered_dtm_idf()
write.csv(new_dtm, file, row.names=T)
}
)
output$download_dtm <- downloadHandler(
filename = function() {paste(str_split(input$file$name,"\\.")[[1]][1],"_dtm.csv",collapse = "") },
content = function(file) {
new_dtm <- ordered_dtm()
write.csv(new_dtm, file, row.names=T)
}
)
bigram_data <- reactive({
bigrammed_corpus = replace_bigram(dataset(),
min_freq = 2,
stopw_list=unlist(strsplit(input$stopw,","))
)
return(bigrammed_corpus[,2:3])
})
output$download_bigram <- downloadHandler(
filename = function() { paste(str_split(input$file$name,"\\.")[[1]][1],"_bigram_corpus.csv",collapse = " ") },
content = function(file) {
write.csv(bigram_data(), file,row.names=FALSE)
}
)
output$downloadData1 <- downloadHandler(
filename = function() { "Nokia_Lumia_reviews.txt" },
content = function(file) {
writeLines(readLines("data/Nokia_Lumia_reviews.txt"), file)
}
)
})