-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.R
More file actions
1553 lines (1345 loc) · 50.9 KB
/
app.R
File metadata and controls
1553 lines (1345 loc) · 50.9 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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
library(shiny)
library(shinyjs)
library(shinyWidgets)
library(data.table)
library(corrplot)
library(ggplot2)
library(ggrepel)
library(png)
library(grid)
source("posterior.R")
source("utils.R")
ui <- fluidPage(
tags$head(
tags$link(
rel = "icon",
type = "image/x-icon",
href = "favicon.ico"
)
),
useShinyjs(),
# Custom CSS for modern styling
tags$head(
tags$style(HTML("
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: linear-gradient(135deg, #1e3a5f 0%, #2c5f8d 100%);
min-height: 100vh;
padding: 20px;
}
.container-fluid {
max-width: 1400px;
margin: 0 auto;
}
h2, h3, h4, h5 {
font-weight: 600;
color: #2d3748;
}
.btn {
border-radius: 8px;
font-weight: 500;
transition: all 0.3s ease;
border: none;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
.btn-primary {
background: linear-gradient(135deg, #2c7da0 0%, #014f86 100%);
}
.btn-primary:hover {
background: linear-gradient(135deg, #236a87 0%, #013d6a 100%);
}
.btn-secondary {
background: #718096;
}
.btn-secondary:hover {
background: #4a5568;
}
.btn-success {
background: #2a9d8f;
}
.btn-success:hover {
background: #21867a;
}
.btn-danger {
background: #e76f51;
}
.btn-danger:hover {
background: #d4603f;
}
.btn-info {
background: #457b9d;
}
.btn-info:hover {
background: #3a6785;
}
.well {
background: white;
border: none;
border-radius: 12px;
box-shadow: 0 4px 6px rgba(0,0,0,0.07);
}
.nav-tabs {
border-bottom: 2px solid #e2e8f0;
}
.nav-tabs > li > a {
border-radius: 8px 8px 0 0;
color: #4a5568;
font-weight: 500;
}
.nav-tabs > li.active > a {
background: linear-gradient(135deg, #2c7da0 0%, #014f86 100%);
color: white;
border: none;
}
.selectize-input {
border-radius: 8px;
border: 2px solid #e2e8f0;
box-shadow: 0 1px 3px rgba(0,0,0,0.05);
transition: all 0.2s ease;
}
.selectize-input:focus {
border-color: #2c7da0;
box-shadow: 0 0 0 3px rgba(44, 125, 160, 0.1);
}
.form-control {
border-radius: 8px;
border: 2px solid #e2e8f0;
transition: all 0.2s ease;
}
.form-control:focus {
border-color: #2c7da0;
box-shadow: 0 0 0 3px rgba(44, 125, 160, 0.1);
}
.alert {
border-radius: 8px;
border: none;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.alert-success {
background: #d4edda;
color: #155724;
}
.alert-danger {
background: #f8d7da;
color: #721c24;
}
.header-card {
background: white;
border-radius: 16px;
padding: 30px;
box-shadow: 0 10px 30px rgba(0,0,0,0.1);
margin-bottom: 20px;
}
.stats-card {
background: white;
border-radius: 12px;
padding: 20px;
box-shadow: 0 4px 6px rgba(0,0,0,0.07);
}
.rating-card {
background: white;
border-radius: 12px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.08);
transition: all 0.3s ease;
}
.rating-card:hover {
box-shadow: 0 8px 16px rgba(0,0,0,0.12);
transform: translateY(-2px);
}
.irs-bar {
background: linear-gradient(135deg, #2c7da0 0%, #014f86 100%);
}
.irs-from, .irs-to, .irs-single {
background: #2c7da0;
}
"))
),
# Header with badge
div(
class = "header-card",
div(
style = "display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap;",
div(
h2(style = "margin: 0; color: #2c7da0;", "🍩 ", span("Krapfen Rating Explorer", style = "background: linear-gradient(135deg, #2c7da0 0%, #014f86 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;"))
),
div(
tags$a(
href = "https://github.com/JudithBernett/Krapfenrating",
target = "_blank",
tags$img(
src = "https://img.shields.io/badge/Feature%20Request-GitHub-blue?logo=github",
alt = "Feature request on GitHub"
)
)
)
)
),
uiOutput("app_content")
)
server <- function(input, output, session) {
# --- Data file path (works both locally and in Docker) -------------------
data_dir <- "data"
if (!dir.exists(data_dir)) {
dir.create(data_dir)
}
background_file <- file.path(data_dir, "KrapfenRating.csv")
rating_file <- file.path(data_dir, "real_ratings.csv")
# Load data (reactive to refresh after submissions) --------------------
background_data <- reactiveVal(fread(background_file))
rating_data <- reactiveVal(fread(rating_file))
# Reactive value to track if user has submitted/exists
user_authenticated <- reactiveVal(FALSE)
current_rater <- reactiveVal("")
is_new_user <- reactiveVal(TRUE)
new_user_submitted <- reactiveVal(FALSE)
# which view of the app is active?
app_mode <- reactiveVal("login_page_ui")
# values: "login_page_ui", "view", "rate_all", "rate_single"
# Get krapfen names (all columns except first one which is Rater)
krapfen_names <- reactive({
names(background_data())[-1]
})
expert_rated_krapfen <- reactive({
r <- copy(rating_data())
rated <- names(r)[colSums(!is.na(r)) > 0]
rated <- rated[rated != "Rater"]
return(rated)
})
# Get list of existing raters
existing_raters <- reactive({
background_data()$Rater
})
# --- Render app content conditionally ------------------------------------
output$app_content <- renderUI({
if (!user_authenticated()) {
return(uiOutput("login_page_ui"))
}
if (app_mode() == "rate_all") {
# Show rating page for new users or users who want to rate
return(uiOutput("ratings_page"))
}
if (app_mode() == "rate_single") {
return(uiOutput("single_rating_page"))
}
return(uiOutput("view_page_ui"))
})
output$login_page_ui <- renderUI({
# Show login page
existing <- sort(existing_raters())
# Calculate stats
num_raters <- length(existing)
num_krapfen <- length(krapfen_names())
total_ratings <- sum(!is.na(background_data()[, -1]))
num_expert_ratings <- sum(!is.na(rating_data()[, -1]))
num_experts <- length(unique(rating_data()$Rater))
div(
style = "padding: 20px;",
div(
class = "stats-card",
style = "max-width: 550px; margin: 0 auto; padding: 40px;",
h3("Welcome to Krapfen Rating! 👋", style = "text-align: center; color: #2d3748; margin-bottom: 25px;"),
p("Select your name from the list or type a new name:", style = "color: #4a5568; text-align: center; margin-bottom: 20px;"),
selectizeInput(
inputId = "rater_name",
label = "Your Name:",
choices = existing,
selected = NULL,
options = list(
create = TRUE,
placeholder = "Select or type your name..."
)
),
br(),
actionButton(
inputId = "check_name_btn",
label = "Continue →",
class = "btn-primary",
style = "width: 100%; padding: 12px; font-size: 16px;"
),
div(id = "name_message", style = "margin-top: 20px;")
),
br(), br(),
div(
class = "stats-card",
style = "max-width: 550px; margin: 0 auto; padding: 30px;",
h4("📊 Current Statistics", style = "margin-top: 0; color: #2d3748; margin-bottom: 20px; text-align: center;"),
div(
style = "display: grid; grid-template-columns: 1fr 1fr; gap: 20px;",
div(
style = "text-align: center; padding: 20px; background: linear-gradient(135deg, #2c7da015 0%, #014f8615 100%); border-radius: 10px;",
div(style = "font-size: 32px; font-weight: 700; color: #2c7da0;", num_raters),
div(style = "font-size: 14px; color: #718096; margin-top: 5px;", "Total Raters")
),
div(
style = "text-align: center; padding: 20px; background: linear-gradient(135deg, #2c7da015 0%, #014f8615 100%); border-radius: 10px;",
div(style = "font-size: 32px; font-weight: 700; color: #014f86;", num_krapfen),
div(style = "font-size: 14px; color: #718096; margin-top: 5px;", "Krapfen Types")
),
div(
style = "text-align: center; padding: 20px; background: linear-gradient(135deg, #2c7da015 0%, #014f8615 100%); border-radius: 10px;",
div(style = "font-size: 32px; font-weight: 700; color: #014f86;", num_expert_ratings),
div(style = "font-size: 14px; color: #718096; margin-top: 5px;", "Single Krapfen Tastings")
),
div(
style = "text-align: center; padding: 20px; background: linear-gradient(135deg, #2c7da015 0%, #014f8615 100%); border-radius: 10px;",
div(style = "font-size: 32px; font-weight: 700; color: #014f86;", num_experts),
div(style = "font-size: 14px; color: #718096; margin-top: 5px;", "Total Tasters")
)
)
)
)
})
output$view_page_ui <- renderUI({
# Show visualizations after rating is submitted or for existing users viewing results
sidebarLayout(
sidebarPanel(
width = 3,
style = "background: white; border-radius: 12px; padding: 20px; box-shadow: 0 4px 6px rgba(0,0,0,0.07);",
div(
style = "text-align: center; margin-bottom: 20px; padding: 15px; background: linear-gradient(135deg, #2c7da015 0%, #014f8615 100%); border-radius: 8px;",
div(style = "font-size: 24px; margin-bottom: 5px;", "👤"),
div(style = "font-weight: 600; color: #2d3748;", current_rater())
),
p("Explore correlations and average ratings of different Krapfen.", style = "color: #718096; font-size: 14px; text-align: center;"),
hr(style = "border-color: #e2e8f0;"),
actionButton(
inputId = "back_to_rating_btn",
label = "📝 Rate All Krapfen",
class = "btn-secondary",
style = "width: 100%; margin-bottom: 10px; padding: 10px;"
),
actionButton(
inputId = "rate_single_btn",
label = "🍩 Rate Single Krapfen",
class = "btn-success",
style = "width: 100%; margin-bottom: 10px; padding: 10px;"
),
hr(style = "border-color: #e2e8f0;"),
actionButton(
inputId = "logout_btn",
label = "🚪 Logout",
class = "btn-danger",
style = "width: 100%; padding: 10px;"
)
),
mainPanel(
style = "background: white; border-radius: 12px; padding: 25px; box-shadow: 0 4px 6px rgba(0,0,0,0.07);",
tabsetPanel(
tabPanel(
"Krapfen Similarity",
# Krapfen logo above the plot
tags$div(
style = "text-align:center;display:block; margin-left:auto; margin-right:auto; margin-bottom:20px;",
tags$img(src = "Krapfenlogo.png", height = "300px", style = "max-width: 100%;")
),
# Correlation method selector
div(
style = "text-align: center; margin-bottom: 30px;",
shinyWidgets::switchInput(
inputId = "corr_method_switch",
label = "Correlation Method",
onLabel = "Spearman",
offLabel = "Pearson",
value = FALSE
)
),
# Main correlation cards
h4("Your Taste Similarity", style = "text-align: center; color: #2d3748; margin-bottom: 20px;"),
uiOutput("correlation_cards"),
br(), br(),
# Collapsible full matrix section
div(
style = "text-align: center; margin-top: 30px;",
actionButton(
inputId = "toggle_matrix_btn",
label = "📊 Show Full Correlation Matrix",
class = "btn-info",
style = "padding: 10px 20px;"
)
),
br(),
# Collapsible matrix container
shinyjs::hidden(
div(
id = "matrix_container",
style = "margin-top: 20px;",
div(
style = "text-align: center; margin-bottom: 15px;",
shinyWidgets::switchInput(
inputId = "corr_display_switch",
label = "Show Coefficients",
onLabel = "Yes",
offLabel = "No",
value = FALSE
)
),
plotOutput("corrPlot", height = "1000px")
)
),
),
tabPanel(
"Expected Rating Results",
h4(
"This is the Krapfen rating based on the surveys: Which Krapfen is expected to taste best?",
style = "text-align: center; color: #2d3748; margin-bottom: 30px; margin-top: 20px;"
),
plotOutput("avgPlot", height = "1000px"),
br(),
# Collapsible heatmap section
div(
style = "text-align: center; margin-top: 20px;",
actionButton(
inputId = "toggle_heatmap_btn",
label = "🔥 Show Rating Heatmap",
class = "btn-info",
style = "padding: 10px 20px;"
)
),
br(),
# Collapsible heatmap container
shinyjs::hidden(
div(
id = "heatmap_container",
style = "margin-top: 20px;",
plotOutput("ratingHeatmap", height = "800px")
)
)
),
tabPanel(
"Actual Rating Results",
h4(
"This is the actual Krapfen rating after tasting: Which Krapfen actually tasted best?",
style = "text-align: center; color: #2d3748; margin-bottom: 30px; margin-top: 20px;"
),
plotOutput("avgPlotPost", height = "1000px"),
# Collapsible heatmap section
div(
style = "text-align: center; margin-top: 20px;",
actionButton(
inputId = "toggle_heatmap_btn_post",
label = "🔥 Show Rating Heatmap",
class = "btn-info",
style = "padding: 10px 20px;"
)
),
br(),
# Collapsible heatmap container
shinyjs::hidden(
div(
id = "heatmap_container_post",
style = "margin-top: 20px;",
plotOutput("ratingHeatmapPost", height = "800px")
)
)
),
tabPanel(
"Posterior Rating Results",
h4(
"This is the posterior rating. Here, we can gather insights like 'Which Krapfen was the most surprising'?",
style = "text-align: center; color: #2d3748; margin-bottom: 30px; margin-top: 20px;"
),
plotOutput("avgPlotPosterior", height = "1000px")
),
tabPanel(
"Prediction Accuracy",
h4("How well can you predict taste from appearance?",
style = "text-align: center; color: #2d3748; margin-bottom: 30px; margin-top: 20px;"),
# User's personal accuracy card
uiOutput("user_accuracy_card"),
br(), br(),
# Scatter plot comparing predictions vs reality
plotOutput("predictionScatterPlot", height = "500px"),
br(),
# All users accuracy comparison
h4("Prediction Accuracy Across All Raters",
style = "text-align: center; color: #2d3748; margin-top: 30px; margin-bottom: 20px;"),
plotOutput("accuracyComparisonPlot", height = "400px")
),
tabPanel(
"Posterior Distribution",
div(
style = "text-align: center; margin-bottom: 20px; margin-top: 10px;",
p(
"Learn more about the methodology in our ",
tags$a(
href = "https://github.com/JudithBernett/Krapfenrating/blob/main/paper.pdf",
target = "_blank",
"paper",
style = "color: #2c7da0; font-weight: 600;"
),
style = "color: #718096; font-size: 14px;"
)
),
# Picker to select Krapfen
pickerInput(
inputId = "selected_krapfen",
label = "Select Krapfen:",
choices = expert_rated_krapfen(),
selected = expert_rated_krapfen()[1],
options = list(`live-search` = TRUE)
),
plotOutput("posteriorPlot", height = "500px")
)
)
)
)
})
# --- User accuracy card ---------------------------------------------------
output$user_accuracy_card <- renderUI({
current_user <- current_rater()
bg_data <- copy(background_data())
exp_data <- copy(rating_data())
# Check if user exists in both datasets
if (!(current_user %in% bg_data$Rater) || !(current_user %in% exp_data$Rater)) {
return(
div(
class = "stats-card",
style = "max-width: 700px; margin: 0 auto; padding: 30px; text-align: center;",
p("Complete your expert ratings to see your prediction accuracy!",
style = "color: #718096; font-size: 16px;")
)
)
}
# Get user's ratings
bg_ratings <- as.numeric(bg_data[Rater == current_user, -1])
exp_ratings <- as.numeric(exp_data[Rater == current_user, -1])
# Find pairs where both exist
valid_pairs <- !is.na(bg_ratings) & !is.na(exp_ratings)
if (sum(valid_pairs) == 0) {
return(
div(
class = "stats-card",
style = "max-width: 700px; margin: 0 auto; padding: 30px; text-align: center;",
p("Rate some Krapfen you've tasted to see your prediction accuracy!",
style = "color: #718096; font-size: 16px;")
)
)
}
bg_valid <- bg_ratings[valid_pairs]
exp_valid <- exp_ratings[valid_pairs]
# Calculate metrics
rmse <- sqrt(mean((bg_valid - exp_valid)^2))
# Handle correlation with potential NA or NaN values
correlation <- cor(bg_valid, exp_valid)
if (is.na(correlation) || is.nan(correlation)) {
correlation <- 0
}
n_compared <- sum(valid_pairs)
# Determine accuracy level and color
if (rmse < 1.5) {
accuracy_text <- "Excellent Predictor! 🎯"
accuracy_color <- "#2a9d8f"
bg_color <- "linear-gradient(135deg, #2a9d8f15 0%, #2a9d8f25 100%)"
border_color <- "#2a9d8f"
} else if (rmse < 2.5) {
accuracy_text <- "Good Predictor 👍"
accuracy_color <- "#457b9d"
bg_color <- "linear-gradient(135deg, #457b9d15 0%, #457b9d25 100%)"
border_color <- "#457b9d"
} else {
accuracy_text <- "Surprises Await! 🎉"
accuracy_color <- "#e76f51"
bg_color <- "linear-gradient(135deg, #e76f5115 0%, #e76f5125 100%)"
border_color <- "#e76f51"
}
div(
class = "stats-card",
style = paste0("max-width: 700px; margin: 0 auto; padding: 30px; background: ", bg_color, "; border-left: 4px solid ", border_color, ";"),
h4(accuracy_text, style = paste0("text-align: center; color: ", accuracy_color, "; margin-bottom: 20px;")),
div(
style = "display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; text-align: center;",
div(
div(style = "font-size: 32px; font-weight: 700; color: #2d3748;", sprintf("%.2f", rmse)),
div(style = "font-size: 12px; color: #718096; margin-top: 5px;", "Root Mean Squared Error")
),
div(
div(style = "font-size: 32px; font-weight: 700; color: #2d3748;", sprintf("%.2f", correlation)),
div(style = "font-size: 12px; color: #718096; margin-top: 5px;", "Correlation")
),
div(
div(style = "font-size: 32px; font-weight: 700; color: #2d3748;", n_compared),
div(style = "font-size: 12px; color: #718096; margin-top: 5px;", "Krapfen Compared")
)
),
p(style = "text-align: center; color: #718096; font-size: 14px; margin-top: 20px; margin-bottom: 0;",
"Lower RMSE means better prediction accuracy. Perfect prediction = 0.")
)
})
# --- Prediction scatter plot ----------------------------------------------
output$predictionScatterPlot <- renderPlot({
current_user <- current_rater()
bg_data <- copy(background_data())
exp_data <- copy(rating_data())
# Check if user exists in both datasets
if (!(current_user %in% bg_data$Rater) || !(current_user %in% exp_data$Rater)) {
plot(1, type = "n", axes = FALSE, xlab = "", ylab = "")
text(1, 1, "Complete your expert ratings to see comparison", cex = 1.5, col = "gray40")
return()
}
# Get user's ratings
bg_ratings <- as.numeric(bg_data[Rater == current_user, -1])
exp_ratings <- as.numeric(exp_data[Rater == current_user, -1])
krapfen_names <- names(bg_data)[-1]
# Find pairs where both exist
valid_pairs <- !is.na(bg_ratings) & !is.na(exp_ratings)
if (sum(valid_pairs) == 0) {
plot(1, type = "n", axes = FALSE, xlab = "", ylab = "")
text(1, 1, "No Krapfen with both predictions and expert ratings yet", cex = 1.5, col = "gray40")
return()
}
# Create data frame
plot_data <- data.frame(
Krapfen = krapfen_names[valid_pairs],
Predicted = bg_ratings[valid_pairs],
Actual = exp_ratings[valid_pairs]
)
ggplot(plot_data, aes(x = Predicted, y = Actual)) +
geom_abline(intercept = 0, slope = 1, linetype = "dashed", color = "#718096", size = 1) +
geom_point(size = 4, alpha = 0.7, color = "#2c7da0") +
geom_text_repel(aes(label = Krapfen), vjust = -0.8, size = 3.5, color = "#2d3748") +
scale_x_continuous(limits = c(1, 10), breaks = 1:10) +
scale_y_continuous(limits = c(1, 10), breaks = 1:10) +
labs(
title = paste0("Predicted vs Actual Ratings (", current_user, ")"),
x = "Predicted Rating (Background)",
y = "Actual Rating (Expert)",
caption = "Dashed line = perfect prediction"
) +
theme_minimal(base_size = 14) +
theme(
plot.title = element_text(hjust = 0.5, face = "bold", size = 16),
panel.grid.minor = element_blank(),
plot.caption = element_text(color = "#718096", hjust = 0.5)
)
})
# --- Accuracy comparison plot ---------------------------------------------
output$accuracyComparisonPlot <- renderPlot({
bg_data <- copy(background_data())
exp_data <- copy(rating_data())
# Calculate RMSE for each rater who has both types of ratings
accuracy_list <- list()
for (rater in bg_data$Rater) {
if (rater %in% exp_data$Rater) {
bg_ratings <- as.numeric(bg_data[Rater == rater, -1])
exp_ratings <- as.numeric(exp_data[Rater == rater, -1])
valid_pairs <- !is.na(bg_ratings) & !is.na(exp_ratings)
if (sum(valid_pairs) > 0) {
rmse <- sqrt(mean((bg_ratings[valid_pairs] - exp_ratings[valid_pairs])^2))
n_compared <- sum(valid_pairs)
accuracy_list[[length(accuracy_list) + 1]] <- data.frame(
Rater = rater,
RMSE = rmse,
N = n_compared,
IsCurrentUser = rater == current_rater()
)
}
}
}
if (length(accuracy_list) == 0) {
plot(1, type = "n", axes = FALSE, xlab = "", ylab = "")
text(1, 1, "No raters with both prediction and expert ratings yet", cex = 1.5, col = "gray40")
return()
}
accuracy_df <- do.call(rbind, accuracy_list)
accuracy_df <- accuracy_df[order(accuracy_df$RMSE), ]
accuracy_df$Rater <- factor(accuracy_df$Rater, levels = accuracy_df$Rater)
ggplot(accuracy_df, aes(x = Rater, y = RMSE, fill = IsCurrentUser)) +
geom_bar(stat = "identity") +
geom_text(aes(label = sprintf("%.2f", RMSE)), vjust = -0.5, size = 3) +
scale_fill_manual(values = c("FALSE" = "#2c7da0", "TRUE" = "#2a9d8f"), guide = "none") +
labs(
title = "Prediction Accuracy by Rater (Lower is Better)",
x = "Rater",
y = "Root Mean Squared Error"
) +
theme_minimal(base_size = 14) +
theme(
plot.title = element_text(hjust = 0.5, face = "bold", size = 16),
axis.text.x = element_text(angle = 45, hjust = 1),
panel.grid.major.x = element_blank()
)
})
# --- Render existing names list -------------------------------------------
output$existing_names_list <- renderUI({
existing <- existing_raters()
if (length(existing) == 0) {
p("No raters yet.")
} else {
tags$ul(
lapply(existing, function(name) {
tags$li(name)
})
)
}
})
# --- Name check handler ---------------------------------------------------
observeEvent(input$check_name_btn, {
name <- trimws(input$rater_name)
existing <- existing_raters()
if (name == "") {
shinyjs::runjs("document.getElementById('name_message').innerHTML = '<div class=\"alert alert-danger\">Please enter your name!</div>';");
return()
}
current_rater(name)
if (name %in% existing) {
# Existing user - navigate to view page (plots)
is_new_user(FALSE)
user_authenticated(TRUE)
app_mode("view")
} else {
# New user - navigate to rating page
is_new_user(TRUE)
user_authenticated(TRUE)
app_mode("rate_all")
}
})
# --- Rating inputs UI -----------------------------------------------------
output$rating_inputs <- renderUI({
krapfen <- krapfen_names()
existing <- existing_raters()
# Show different message based on whether user exists or not
if (current_rater() %in% existing) {
intro_text <- div(
style = "padding: 20px; background: #c6f6d5; border-radius: 12px; margin-bottom: 25px; text-align: center;",
p(style = "color: #22543d; font-weight: 600; margin: 0; font-size: 16px;",
"✅ Welcome back! You've already rated before. Your ratings are saved.")
)
} else {
intro_text <- div(
style = "padding: 20px; background: linear-gradient(135deg, #2c7da015 0%, #014f8615 100%); border-radius: 12px; margin-bottom: 25px; text-align: center;",
p(style = "color: #2d3748; font-weight: 600; margin: 0; font-size: 16px;",
"🍩 Welcome! How would you think these Krapfen taste based on how they look and sound? Please rate each Krapfen on a scale of 1-10.")
)
}
rating_divs <- lapply(krapfen, function(k) {
# Use krapfen name directly as image filename with .png extension
img_path <- paste0(k, ".png")
default_value <- 5
if(current_rater() %in% existing) {
b <- background_data()
# b has krapfen as a column and raters as rows
default_value <- as.numeric(b[Rater == current_rater(), get(k)])
}
div(
class = "rating-card",
div(
style = "display: flex; gap: 20px; align-items: flex-start;",
div(
style = "flex-shrink: 0;",
img(
src = img_path,
width = "150px",
height = "150px",
style = "border-radius: 12px; object-fit: cover; box-shadow: 0 2px 8px rgba(0,0,0,0.1);"
)
),
div(
style = "flex-grow: 1;",
h4(k, style = "color: #2d3748; margin-top: 0;"),
sliderInput(
inputId = paste0("rating_", gsub(" ", "_", k)),
label = "Rating (1-10):",
min = 1,
max = 10,
value = default_value,
step = 1,
width = "100%"
)
)
)
)
})
do.call(tagList, c(list(intro_text), rating_divs))
})
# --- Ratings page UI (shown after name entry) ----------------------------
output$ratings_page <- renderUI({
if (!user_authenticated() & !is_new_user()) {
app_mode("rate_single")
return(NULL)
}
# Create button list based on whether it's a new user and if they've submitted
buttons <- list(
actionButton(
inputId = "submit_ratings",
label = "✓ Submit Ratings",
class = "btn-primary",
style = "padding: 12px 24px; font-size: 16px;"
)
)
# Only show "View Results" button if it's an existing user OR new user has submitted
if (!is_new_user() || new_user_submitted()) {
buttons[[2]] <- actionButton(
inputId = "view_results_btn",
label = "📊 View Results",
class = "btn-info",
style = "padding: 12px 24px; font-size: 16px; margin-left: 10px;"
)
}
# Add logout button
buttons[[length(buttons) + 1]] <- actionButton(
inputId = "cancel_ratings",
label = "🚪 Logout",
class = "btn-secondary",
style = "padding: 12px 24px; font-size: 16px; margin-left: 10px;"
)
div(
style = "padding: 20px;",
div(
class = "stats-card",
style = "max-width: 900px; margin: 0 auto; padding: 30px;",
h3(paste("🍩 Rate Krapfen as", current_rater()), style = "color: #2d3748; margin-top: 0; text-align: center;"),
uiOutput("rating_inputs"),
br(),
div(
style = "text-align: center;",
do.call(tagList, buttons)
),
div(id = "submit_message", style = "margin-top: 20px;")
)
)
})
output$single_rating_page <- renderUI({
r <- copy(rating_data())
if(current_rater() %in% r$Rater){
krapfen_choices <- colnames(r)[which(is.na(r[Rater == current_rater()]))]
}else{
krapfen_choices <- krapfen_names()
}
div(
style = "padding: 20px;",
div(
class = "stats-card",
style = "max-width: 800px; margin: 0 auto; padding: 40px;",
h3("Rate a Krapfen you've tried 🍩", style = "text-align: center; color: #2d3748; margin-top: 0;"),
# Show existing ratings plot
plotOutput("user_ratings_plot", height = "300px"),
br(),
pickerInput(
"single_krapfen",
"Select Krapfen:",
choices = krapfen_choices,
options = list(`live-search` = TRUE)
),
sliderInput(
"single_score",
"Your rating:",
min = 1, max = 10, value = 5, step = 1
),
br(),
div(
style = "text-align: center;",
actionButton(
"submit_single_rating",
"✓ Submit rating",
class = "btn-primary",
style = "padding: 12px 24px; font-size: 16px;"
),
actionButton(
"cancel_single_rating",
"← Back",
class = "btn-secondary",
style = "padding: 12px 24px; font-size: 16px; margin-left: 10px;"
)
),
div(id = "single_submit_msg", style = "margin-top: 20px;")
)
)
})
# --- User ratings plot ---
output$user_ratings_plot <- renderPlot({
r <- copy(rating_data())
user_row <- r[Rater == current_rater()]
# Get only rated krapfen (non-NA values)
user_ratings <- unlist(user_row[, -1]) # Exclude Rater column
user_ratings <- user_ratings[!is.na(user_ratings)]
if (length(user_ratings) == 0) {
# If no ratings yet, show message
plot(1, type = "n", axes = FALSE, xlab = "", ylab = "")
text(1, 1, "You haven't rated any Krapfen yet!", cex = 1.5, col = "gray40")
return()
}
# Create data frame for plotting
df <- data.frame(
Krapfen = names(user_ratings),
Rating = as.numeric(user_ratings)
)
ggplot(df, aes(x = reorder(Krapfen, Rating), y = Rating)) +
geom_bar(stat = "identity", fill = "#3d98d3") +