File size: 40,752 Bytes
1f855fb
f6a9c5a
 
5573196
 
 
 
 
 
1f855fb
f6a9c5a
1f855fb
5573196
 
f6a9c5a
 
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d61f21
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ef6ecc
 
 
 
 
 
 
 
 
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a9c5a
 
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d61f21
5573196
 
 
 
f6a9c5a
1f855fb
5573196
 
 
0d61f21
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a9c5a
 
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a9c5a
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a9c5a
5573196
 
 
 
 
 
 
f6a9c5a
 
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a9c5a
5573196
 
 
 
 
 
 
 
 
f6a9c5a
5573196
f6a9c5a
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a9c5a
5573196
 
 
 
 
f6a9c5a
 
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a9c5a
 
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a9c5a
1f855fb
 
f6a9c5a
 
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a9c5a
 
 
5573196
 
 
 
 
f6a9c5a
5573196
f6a9c5a
 
5573196
 
 
 
 
 
1f855fb
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a9c5a
 
 
5573196
f6a9c5a
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a9c5a
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a9c5a
5573196
 
f6a9c5a
 
 
5573196
 
f6a9c5a
5573196
f6a9c5a
 
 
 
5573196
f6a9c5a
 
 
 
5573196
f6a9c5a
 
5573196
f6a9c5a
5573196
 
f6a9c5a
1f855fb
f6a9c5a
 
 
 
5573196
f6a9c5a
 
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a9c5a
5573196
 
 
 
 
 
 
 
 
 
f6a9c5a
5573196
f6a9c5a
 
 
 
 
 
5573196
f6a9c5a
5573196
 
 
f6a9c5a
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a9c5a
 
5573196
f6a9c5a
 
 
 
 
 
5573196
 
 
 
f6a9c5a
5573196
 
 
 
 
 
 
 
 
f6a9c5a
 
5573196
f6a9c5a
5573196
f6a9c5a
 
5573196
f6a9c5a
 
5573196
 
 
 
 
 
 
 
f6a9c5a
 
 
5573196
 
 
 
 
 
 
 
 
f6a9c5a
 
5573196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f855fb
 
f6a9c5a
5573196
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
library(shiny)
library(ellmer)
library(purrr)
library(pdftools)
library(magick)
library(base64enc)

# Maximum pages for image-based extraction (free app limit)
MAX_IMAGE_PAGES = 5

num_example_fields = 2



# Define UI for the app
ui = shiny::fluidPage(
  # Add Miami theme CSS and favicon
  shiny::tags$head(
    shiny::tags$link(rel = "icon", type = "image/svg+xml", href = "favicon.svg"),
    shiny::tags$link(rel = "stylesheet", type = "text/css", href = "miami-theme.css"),
    shiny::tags$title("AI-Powered Text Extraction Tool")
  ),

  # Custom header with Miami branding
  shiny::div(
    class = "app-header",
    shiny::div(
      class = "header-content",
      shiny::div(
        class = "header-left",
        shiny::tags$h1("AI-Powered Text Extraction Tool"),
        shiny::p(class = "subtitle", "Extract Structured Data from Text, Documents, and Images")
      ),
      shiny::div(
        class = "header-right",
        shiny::p("Version 2.0.1 | January 2026"),
        shiny::p(
          shiny::tags$strong("Authors: "),
          "Fadel M. Megahed, Ying-Ju (Tessa) Chen, Allison Jones-Farmer, Ibrahim Yousif, and Inez M. Zwetsloot"
        ),
        shiny::p(
          shiny::tags$strong("Contact: "),
          shiny::tags$a(
            href = "mailto:fmegahed@miamioh.edu",
            style = "color: #EFDB72;",
            "fmegahed@miamioh.edu"
          )
        )
      )
    )
  ),

  # University logos section
  shiny::div(
    class = "logo-container",
    shiny::tags$img(
      src = "miami-logo.png",
      alt = "Miami University Logo",
      style = "height: 55px;"
    ),
    shiny::div(class = "logo-divider"),
    shiny::tags$img(
      src = "university-of-dayton-vector-logo.png",
      alt = "University of Dayton Logo",
      style = "height: 50px;"
    ),
    shiny::div(class = "logo-divider"),
    shiny::tags$img(
      src = "uva-compacte-logo.png",
      alt = "University of Amsterdam Logo",
      style = "height: 50px;"
    ),
    shiny::div(
      style = "margin-left: auto; font-size: 0.85em; color: #666;",
      shiny::p(
        style = "margin: 0;",
        "A collaboration between",
        shiny::tags$strong("Miami University,"),
        "the",
        shiny::tags$strong("University of Dayton,"),
        "and the",
        shiny::tags$strong("University of Amsterdam")
      )
    )
  ),

  # How to use section
  shiny::div(
    class = "how-to-use",
    shiny::div(
      style = "display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;",
      shiny::tags$h4(
        style = "margin: 0;",
        shiny::icon("circle-info"),
        " How to Use This App"
      ),
      shiny::tags$button(
        id = "open-video-modal",
        class = "btn btn-video-tutorial",
        shiny::icon("play-circle"),
        " Watch Video Tutorial"
      )
    ),
    shiny::tags$h5(
      style = "color: #C41230; margin-top: 0;",
      shiny::icon("bolt"),
      " Quick Demo"
    ),
    shiny::p(
      "Click the ",
      shiny::tags$strong("'Load Examples'"),
      " button to load two sample NHTSA recall notices with pre-configured extraction fields. ",
      "Then click ",
      shiny::tags$strong("'Extract Data'"),
      " to see the AI extract structured information from the text. ",
      "You can also add more fields, change field labels, and modify descriptions. ",
      shiny::tags$em(
        "(Note: Field labels only affect how data is stored and displayed, not extraction performance.)"
      )
    ),
    shiny::tags$h5(
      style = "color: #C41230; margin-top: 15px;",
      shiny::icon("file-import"),
      " Input Methods"
    ),
    shiny::p(
      "Choose from six input methods to provide your source content:"
    ),
    shiny::tags$ul(
      style = "margin-bottom: 10px;",
      shiny::tags$li(
        shiny::tags$strong("Demo Data:"),
        " Try the app with pre-loaded NHTSA vehicle recall examples."
      ),
      shiny::tags$li(
        shiny::tags$strong("Paste Text:"),
        " Directly paste text content. Separate multiple items with double line breaks."
      ),
      shiny::tags$li(
        shiny::tags$strong("Text File:"),
        " Upload .txt, .csv (single column), or .md files."
      ),
      shiny::tags$li(
        shiny::tags$strong("Readable PDF:"),
        " Upload a machine-readable PDF. Text is extracted automatically."
      ),
      shiny::tags$li(
        shiny::tags$strong("Scanned PDF:"),
        " Upload scanned/image-based PDFs. Pages are converted to images for vision processing."
      ),
      shiny::tags$li(
        shiny::tags$strong("Upload Images:"),
        " Upload images (PNG, JPEG, WebP, GIF) for AI vision-based extraction."
      )
    ),
    shiny::p(
      style = "font-size: 0.9em; color: #666;",
      shiny::icon("info-circle"),
      " ",
      shiny::tags$em("Notes:"),
      shiny::tags$ul(
        style = "margin: -0.5em 0 0 1.25em; padding: 0; line-height: 1.2;",
        shiny::tags$li(style = "margin: 0; padding: 0;",
                       "PDF, Image, and Scanned PDF modes are limited to 5 pages/items in this free demo."
        ),
        shiny::tags$li(style = "margin: 0; padding: 0;",
                       "Any uploaded file must be less than 5 MB (Shiny default for this free app) to keep the demo responsive and avoid upload timeouts."
        )
      )
    ),
    shiny::tags$h5(
      style = "color: #C41230; margin-top: 15px;",
      shiny::icon("edit"),
      " Custom Fields"
    ),
    shiny::p(
      "Customize your extraction by adjusting:"
    ),
    shiny::tags$ul(
      style = "margin-bottom: 10px;",
      shiny::tags$li("The ", shiny::tags$strong("number of fields"), " to extract"),
      shiny::tags$li("Your own ", shiny::tags$strong("field labels"), " (for storage/display only)"),
      shiny::tags$li("Detailed ", shiny::tags$strong("field descriptions"), " to guide the AI")
    ),
    shiny::p(
      shiny::icon("lightbulb"),
      " ",
      shiny::tags$em(
        "The more specific your field descriptions, the better the extraction results."
      )
    )
  ),

  # Video Modal
  shiny::div(
    id = "video-modal",
    class = "video-modal",
    shiny::div(
      class = "video-modal-content",
      shiny::tags$span(
        id = "close-video-modal",
        class = "video-modal-close",
        shiny::HTML("×")
      ),
      shiny::tags$h4(
        style = "color: #C41230; margin-top: 0; margin-bottom: 15px;",
        shiny::icon("play-circle"),
        " Video Tutorial"
      ),
      shiny::div(
        class = "video-modal-wrapper",
        # Placeholder - replace VIDEO_ID_PLACEHOLDER with actual YouTube video ID
        shiny::tags$iframe(
          id = "tutorial-video",
          src = "https://www.youtube.com/embed/y6Uit4Drf9w",
          allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",
          allowfullscreen = NA
        )
      )
    )
  ),

  # JavaScript for video modal
  shiny::tags$script(shiny::HTML("
    var videoUrl = 'https://www.youtube.com/embed/y6Uit4Drf9w';
    var modal = document.getElementById('video-modal');
    var openBtn = document.getElementById('open-video-modal');
    var closeBtn = document.getElementById('close-video-modal');
    var videoIframe = document.getElementById('tutorial-video');

    openBtn.onclick = function() {
      modal.style.display = 'flex';
      videoIframe.src = videoUrl;
    }

    closeBtn.onclick = function() {
      modal.style.display = 'none';
      videoIframe.src = '';
    }

    window.onclick = function(event) {
      if (event.target == modal) {
        modal.style.display = 'none';
        videoIframe.src = '';
      }
    }

    document.addEventListener('keydown', function(event) {
      if (event.key === 'Escape' && modal.style.display === 'flex') {
        modal.style.display = 'none';
        videoIframe.src = '';
      }
    });

    // Input tab switching
    function switchInputTab(tab) {
      var tabs = ['demo', 'paste', 'textfile', 'pdf', 'scanned', 'image'];
      tabs.forEach(function(t) {
        var tabEl = document.getElementById('tab-' + t);
        var panelEl = document.getElementById('panel-' + t);
        if (t === tab) {
          tabEl.classList.add('active');
          panelEl.style.display = 'block';
        } else {
          tabEl.classList.remove('active');
          panelEl.style.display = 'none';
        }
      });
      // Update Shiny with the current input method
      Shiny.setInputValue('input_method', tab);
    }
    // Initialize input method
    Shiny.setInputValue('input_method', 'demo');
  ")),

  shiny::sidebarLayout(
    shiny::sidebarPanel(
      width = 4,
      class = "sidebar-panel",

      shiny::tags$h4(
        style = "color: #C41230; margin-top: 0; margin-bottom: 15px;",
        shiny::icon("file-alt"),
        " Input Configuration"
      ),

      # Input method tabs (3 rows for 5 tabs)
      shiny::div(
        class = "input-tabs-container",
        shiny::div(
          class = "input-tabs",
          shiny::tags$button(
            id = "tab-demo",
            class = "input-tab active",
            onclick = "switchInputTab('demo')",
            shiny::icon("flask"),
            " Demo Data"
          ),
          shiny::tags$button(
            id = "tab-paste",
            class = "input-tab",
            onclick = "switchInputTab('paste')",
            shiny::icon("paste"),
            " Paste Text"
          )
        ),
        shiny::div(
          class = "input-tabs",
          shiny::tags$button(
            id = "tab-textfile",
            class = "input-tab",
            onclick = "switchInputTab('textfile')",
            shiny::icon("file-lines"),
            " Text File"
          ),
          shiny::tags$button(
            id = "tab-pdf",
            class = "input-tab",
            onclick = "switchInputTab('pdf')",
            shiny::icon("file-pdf"),
            " Readable PDF"
          )
        ),
        shiny::div(
          class = "input-tabs",
          shiny::tags$button(
            id = "tab-scanned",
            class = "input-tab",
            onclick = "switchInputTab('scanned')",
            shiny::icon("file-image"),
            " Scanned PDF"
          ),
          shiny::tags$button(
            id = "tab-image",
            class = "input-tab",
            onclick = "switchInputTab('image')",
            shiny::icon("images"),
            " Upload Images"
          )
        )
      ),

      # Demo data panel
      shiny::div(
        id = "panel-demo",
        class = "input-panel",
        shiny::p(
          "Try the app with pre-loaded NHTSA vehicle recall data. Click the button below to load sample text and pre-configured extraction fields."
        ),
        shiny::actionButton(
          "load_example",
          shiny::tags$span(shiny::icon("play"), " Load Demo Data"),
          class = "btn-primary",
          style = "margin-top: 10px;"
        ),
        shiny::uiOutput("demo_preview_ui")
      ),

      # Paste text panel
      shiny::div(
        id = "panel-paste",
        class = "input-panel",
        style = "display: none;",
        shiny::textAreaInput(
          "input_text",
          NULL,
          rows = 8,
          placeholder = "Paste your text content here.\n\nTo process multiple items at once, separate each block of text with a double line break (press Enter twice).\n\nIMPORTANT: Before extracting, scroll down to configure your extraction fields:\n1. Set the number of fields you need\n2. Update each field label (e.g., 'product_name', 'price')\n3. Write clear descriptions for each field\n\nThen click 'Extract Data' to see results."
        )
      ),

      # Text file upload panel
      shiny::div(
        id = "panel-textfile",
        class = "input-panel",
        style = "display: none;",
        shiny::fileInput(
          "text_file",
          NULL,
          accept = c(".txt", ".csv", ".md"),
          placeholder = "No file selected",
          buttonLabel = shiny::tags$span(shiny::icon("upload"), " Browse...")
        ),
        shiny::helpText(
          shiny::icon("info-circle"),
          " Upload a text file (.txt, .csv, .md). Content will be extracted automatically."
        ),
        shiny::div(
          class = "file-format-note",
          shiny::tags$strong("File format guidelines:"),
          shiny::tags$ul(
            style = "margin: 5px 0 0 0; padding-left: 20px; font-size: 0.85em;",
            shiny::tags$li(".txt: Plain text, separate items with double line breaks"),
            shiny::tags$li(".csv: Single column of text entries (one per row)"),
            shiny::tags$li(".md: Markdown file treated as plain text")
          )
        ),
        shiny::uiOutput("textfile_preview_ui")
      ),

      # PDF upload panel (machine-readable)
      shiny::div(
        id = "panel-pdf",
        class = "input-panel",
        style = "display: none;",
        shiny::fileInput(
          "pdf_file",
          NULL,
          accept = ".pdf",
          placeholder = "No file selected",
          buttonLabel = shiny::tags$span(shiny::icon("upload"), " Browse...")
        ),
        shiny::helpText(
          shiny::icon("info-circle"),
          " Upload a machine-readable PDF. Text will be extracted automatically."
        ),
        shiny::div(
          class = "image-limit-note",
          shiny::icon("exclamation-circle"),
          shiny::tags$em(paste(" Free app limit: Only the first", MAX_IMAGE_PAGES, "pages will be processed."))
        ),
        shiny::uiOutput("pdf_preview_ui")
      ),

      # Image upload panel
      shiny::div(
        id = "panel-image",
        class = "input-panel",
        style = "display: none;",
        shiny::fileInput(
          "image_file",
          NULL,
          accept = c(".png", ".jpg", ".jpeg", ".webp", ".gif"),
          multiple = TRUE,
          placeholder = "No file selected",
          buttonLabel = shiny::tags$span(shiny::icon("upload"), " Browse...")
        ),
        shiny::helpText(
          shiny::icon("info-circle"),
          " Upload image(s) containing text to extract. Supports PNG, JPEG, WebP, and GIF."
        ),
        shiny::div(
          class = "image-limit-note",
          shiny::icon("exclamation-circle"),
          shiny::tags$em(paste(" Free app limit: Maximum", MAX_IMAGE_PAGES, "images will be processed."))
        ),
        shiny::uiOutput("image_preview_ui")
      ),

      # Scanned PDF panel
      shiny::div(
        id = "panel-scanned",
        class = "input-panel",
        style = "display: none;",
        shiny::fileInput(
          "scanned_pdf_file",
          NULL,
          accept = ".pdf",
          placeholder = "No file selected",
          buttonLabel = shiny::tags$span(shiny::icon("upload"), " Browse...")
        ),
        shiny::helpText(
          shiny::icon("info-circle"),
          " Upload a scanned/image-based PDF. Pages will be converted to images for AI vision processing."
        ),
        shiny::div(
          class = "image-limit-note",
          shiny::icon("exclamation-circle"),
          shiny::tags$em(paste(" Free app limit: Only the first", MAX_IMAGE_PAGES, "pages will be processed."))
        ),
        shiny::uiOutput("scanned_pdf_preview_ui")
      ),

      shiny::hr(class = "field-separator"),

      shiny::numericInput(
        "num_fields",
        shiny::tags$span(
          shiny::icon("list-ol"),
          " Number of Fields to Extract:"
        ),
        value = num_example_fields,
        min = 1,
        max = 10
      ),

      shiny::helpText(
        shiny::icon("info-circle"),
        " Define each field with a clear label (e.g., 'manufacturer') and description (e.g., 'The name of the company recalling the vehicles')."
      ),

      shiny::hr(class = "field-separator"),

      shiny::tags$h5(
        style = "color: #C41230; margin-bottom: 10px;",
        shiny::icon("tags"),
        " Field Definitions"
      ),

      shiny::uiOutput("fields_ui"),

      shiny::div(
        style = "margin-top: 20px;",
        shiny::actionButton(
          "extract_btn",
          shiny::tags$span(shiny::icon("magic"), " Extract Data"),
          class = "btn-primary"
        )
      )
    ),

    shiny::mainPanel(
      width = 8,
      class = "main-panel",

      shiny::div(
        class = "info-card",
        shiny::tags$h3(
          class = "section-heading",
          shiny::icon("table"),
          " Structured Data Extracted Using AI"
        ),
        shiny::div(
          class = "results-placeholder",
          id = "results-placeholder",
          shiny::icon("arrow-left"),
          " Configure your extraction fields and click 'Extract Data' to see results here"
        ),
        shiny::tableOutput("extracted_table"),
        shiny::uiOutput("download_btn_ui")
      ),

      shiny::div(
        class = "tips-section",
        shiny::tags$h4(shiny::icon("lightbulb"), " Tips for Better Results"),
        shiny::tags$ul(
          shiny::tags$li("Use ", shiny::tags$strong("specific field descriptions"), " to guide the AI accurately"),
          shiny::tags$li("Start with ", shiny::tags$strong("more fields"), " and remove unnecessary ones later"),
          shiny::tags$li("If results are inaccurate, try ", shiny::tags$strong("rephrasing"), " your field descriptions"),
          shiny::tags$li("For ", shiny::tags$strong("multiple text blocks"), ", separate each with a double line break"),
          shiny::tags$li("Each text block should contain ", shiny::tags$strong("complete information"), " for all fields you want to extract")
        )
      ),

      shiny::div(
        class = "note-section",
        shiny::tags$h4(shiny::icon("cog"), " Technical Note"),
        shiny::p(
          "To ensure timely results (since this is hosted on a CPU), we utilize ",
          shiny::tags$code("gpt-5-mini-2025-08-07"),
          " for this demo."
        ),
        shiny::p(
          "For ",
          shiny::tags$strong("complete privacy"),
          ", consider using local open-weight models via ",
          shiny::tags$a(
            href = "https://ellmer.tidyverse.org/reference/chat_ollama.html",
            target = "_blank",
            shiny::tags$code("chat_ollama()")
          ),
          " from the ",
          shiny::tags$a(
            href = "https://ellmer.tidyverse.org/",
            target = "_blank",
            "ellmer"
          ),
          " library, which connects to ",
          shiny::tags$a(
            href = "https://ollama.com/",
            target = "_blank",
            "Ollama"
          ),
          " for running models locally on your machine."
        ),
        shiny::p(
          "Alternatively, for higher accuracy requirements, users can leverage more performant closed models (e.g., ",
          shiny::tags$em("gpt-5.2-2025-12-11"),
          ", ",
          shiny::tags$em("claude-opus-4-5-20251101"),
          ", or ",
          shiny::tags$em("gemini-3-pro-preview"),
          ") depending on the application needs. ",
          "Note that Claude models require ",
          shiny::tags$a(
            href = "https://ellmer.tidyverse.org/reference/chat_anthropic.html",
            target = "_blank",
            shiny::tags$code("chat_anthropic()")
          ),
          " and Gemini models require ",
          shiny::tags$a(
            href = "https://ellmer.tidyverse.org/reference/chat_google_gemini.html",
            target = "_blank",
            shiny::tags$code("chat_google_gemini()")
          ),
          ", each with their respective API keys configured in the R environment."
        ),
        shiny::p(
          shiny::tags$em(
            "This demo uses ",
            shiny::tags$code("chat_openai()"),
            " only and does not provide an option to change the gpt-5-mini-2025-08-07 model."
          )
        )
      )
    )
  ),

  # Footer
  shiny::div(
    class = "app-footer",
    shiny::p(
      "Built with ",
      shiny::tags$a(href = "https://shiny.posit.co/", target = "_blank", "Shiny"),
      " and ",
      shiny::tags$a(href = "https://ellmer.tidyverse.org/", target = "_blank", "ellmer"),
      " | ",
      "Powered by OpenAI"
    ),
    shiny::p(
      shiny::tags$em(
        "Companion app to: 'What Should Quality Engineers Know about Generative AI', submitted by the app's authors to ",
        shiny::tags$a(
          href = "https://www.tandfonline.com/journals/lqen20",
          target = "_blank",
          "Quality Engineering."
        )
      )
    ),
    # shiny::p(
    #   "\u00A9 2026 Developed by researchers from Miami University, the University of Dayton, and the University of Amsterdam."
    # )
  )
)

# Define server logic required to generate dynamic UI and extract data
server = function(input, output, session) {

  # Reactive value to store demo text
  demo_text = shiny::reactiveVal("")

  # Reactive value to store extracted results (for table display and CSV download)
  extracted_results = shiny::reactiveVal(NULL)

  # Observer to clear data when switching tabs
  shiny::observeEvent(input$input_method, {
    # Clear the extracted results table
    extracted_results(NULL)
    output$extracted_table = shiny::renderTable(NULL)

    # Clear the text area when switching to paste tab (so placeholder shows)
    if (input$input_method == "paste") {
      shiny::updateTextAreaInput(session, "input_text", value = "")
    }
  }, ignoreInit = TRUE)

  # Load example data
  shiny::observeEvent(input$load_example, {
    example_text = "Ford Motor Company (Ford) is recalling certain 2021-2022 Bronco vehicles equipped with rearview camera systems and 8-inch screen displays. The rearview camera image may still be displayed after a backing event has ended. As such, these vehicles fail to comply with the requirements of Federal Motor Vehicle Safety Standard number 111, \"Rear Visibility.\"\n\nHonda (American Honda Motor Co.) is recalling certain 2022-2025 Acura MDX Type-S, 2023-2025 Honda Pilot, and 2021-2025 Acura TLX Type-S vehicles. A software error in the fuel injection electronic control unit (FI-ECU) may cause an engine stall or a loss of power."

    # Store demo text
    demo_text(example_text)

    # Also update the text area for extraction
    shiny::updateTextAreaInput(session, "input_text", value = example_text)

    # Set up example fields
    shiny::updateNumericInput(session, "num_fields", value = num_example_fields)

    shiny::showNotification(
      "Demo data loaded! Click 'Extract Data' to see results.",
      type = "message",
      duration = 3
    )
  })

  # Render demo preview
  output$demo_preview_ui = shiny::renderUI({
    text = demo_text()
    if (is.null(text) || nchar(text) == 0) return(NULL)

    preview_text = if (nchar(text) > 500) {
      paste0(substr(text, 1, 500), "...")
    } else {
      text
    }

    shiny::div(
      class = "pdf-preview",
      style = "margin-top: 15px;",
      shiny::tags$strong("Loaded Demo Text:"),
      shiny::tags$pre(preview_text)
    )
  })

  # Reactive value to store PDF extracted text
  pdf_text = shiny::reactiveVal("")

  # Process uploaded PDF
  shiny::observeEvent(input$pdf_file, {
    shiny::req(input$pdf_file)

    tryCatch({
      # Extract text from PDF
      pdf_path = input$pdf_file$datapath
      extracted = pdftools::pdf_text(pdf_path)

      # Limit to MAX_IMAGE_PAGES
      total_pages = length(extracted)
      if (total_pages > MAX_IMAGE_PAGES) {
        extracted = extracted[1:MAX_IMAGE_PAGES]
        shiny::showNotification(
          paste("Only the first", MAX_IMAGE_PAGES, "pages will be processed (free app limit)."),
          type = "warning",
          duration = 5
        )
      }

      # Combine all pages with double line breaks
      combined_text = paste(extracted, collapse = "\n\n")

      # Clean up the text (remove excessive whitespace)
      combined_text = gsub("\\s+", " ", combined_text)
      combined_text = trimws(combined_text)

      # Store the extracted text
      pdf_text(combined_text)

      # Update the text area with extracted text
      shiny::updateTextAreaInput(session, "input_text", value = combined_text)

      shiny::showNotification(
        paste("PDF processed successfully!", length(extracted), "page(s) extracted."),
        type = "message",
        duration = 3
      )
    }, error = function(e) {
      shiny::showNotification(
        paste("Error reading PDF:", e$message),
        type = "error",
        duration = NULL
      )
    })
  })

  # Render PDF text preview
  output$pdf_preview_ui = shiny::renderUI({
    text = pdf_text()
    if (is.null(text) || nchar(text) == 0) return(NULL)

    preview_text = if (nchar(text) > 500) {
      paste0(substr(text, 1, 500), "...")
    } else {
      text
    }

    shiny::div(
      class = "pdf-preview",
      shiny::tags$strong("Extracted Text Preview:"),
      shiny::tags$pre(preview_text)
    )
  })

  # Reactive value for text file content
  textfile_text = shiny::reactiveVal("")

  # Process uploaded text file
  shiny::observeEvent(input$text_file, {
    shiny::req(input$text_file)

    tryCatch({
      file_path = input$text_file$datapath
      file_name = input$text_file$name
      file_ext = tolower(tools::file_ext(file_name))

      extracted_text = ""

      if (file_ext == "csv") {
        # Read CSV - assume single column or use first column
        csv_data = utils::read.csv(file_path, header = TRUE, stringsAsFactors = FALSE)
        if (ncol(csv_data) >= 1) {
          # Use first column, combine rows with double line breaks
          extracted_text = paste(csv_data[[1]], collapse = "\n\n")
        }
      } else {
        # Read txt or md as plain text
        extracted_text = paste(readLines(file_path, warn = FALSE), collapse = "\n")
      }

      # Clean up the text
      extracted_text = trimws(extracted_text)

      # Store the extracted text
      textfile_text(extracted_text)

      # Update the text area with extracted text
      shiny::updateTextAreaInput(session, "input_text", value = extracted_text)

      shiny::showNotification(
        paste("File processed successfully!"),
        type = "message",
        duration = 3
      )
    }, error = function(e) {
      shiny::showNotification(
        paste("Error reading file:", e$message),
        type = "error",
        duration = NULL
      )
    })
  })

  # Render text file preview
  output$textfile_preview_ui = shiny::renderUI({
    text = textfile_text()
    if (is.null(text) || nchar(text) == 0) return(NULL)

    preview_text = if (nchar(text) > 500) {
      paste0(substr(text, 1, 500), "...")
    } else {
      text
    }

    shiny::div(
      class = "pdf-preview",
      shiny::tags$strong("Extracted Text Preview:"),
      shiny::tags$pre(preview_text)
    )
  })

  # Reactive values to store image paths for vision-based extraction
  image_paths = shiny::reactiveVal(NULL)
  scanned_pdf_paths = shiny::reactiveVal(NULL)

  # Process uploaded images
  shiny::observeEvent(input$image_file, {
    shiny::req(input$image_file)

    tryCatch({
      files = input$image_file
      # Limit to MAX_IMAGE_PAGES
      n_files = min(nrow(files), MAX_IMAGE_PAGES)

      if (nrow(files) > MAX_IMAGE_PAGES) {
        shiny::showNotification(
          paste("Only the first", MAX_IMAGE_PAGES, "images will be processed (free app limit)."),
          type = "warning",
          duration = 5
        )
      }

      # Store paths of uploaded images
      paths = files$datapath[1:n_files]
      image_paths(paths)

      shiny::showNotification(
        paste(n_files, "image(s) uploaded successfully!"),
        type = "message",
        duration = 3
      )
    }, error = function(e) {
      shiny::showNotification(
        paste("Error uploading images:", e$message),
        type = "error",
        duration = NULL
      )
    })
  })

  # Render image preview
  output$image_preview_ui = shiny::renderUI({
    paths = image_paths()
    if (is.null(paths) || length(paths) == 0) return(NULL)

    shiny::tagList(
      shiny::div(
        class = "image-preview-grid",
        lapply(seq_along(paths), function(i) {
          shiny::div(
            class = "image-preview-item",
            shiny::tags$img(
              src = base64enc::dataURI(file = paths[i], mime = "image/png"),
              alt = paste("Image", i)
            )
          )
        })
      ),
      shiny::div(
        class = "image-preview-count",
        paste(length(paths), "image(s) ready for extraction")
      )
    )
  })

  # Process scanned PDF (convert to images)
  shiny::observeEvent(input$scanned_pdf_file, {
    shiny::req(input$scanned_pdf_file)

    tryCatch({
      pdf_path = input$scanned_pdf_file$datapath

      # Get number of pages
      pdf_info = pdftools::pdf_info(pdf_path)
      n_pages = min(pdf_info$pages, MAX_IMAGE_PAGES)

      if (pdf_info$pages > MAX_IMAGE_PAGES) {
        shiny::showNotification(
          paste("Only the first", MAX_IMAGE_PAGES, "pages will be processed (free app limit)."),
          type = "warning",
          duration = 5
        )
      }

      shiny::showNotification(
        "Converting PDF pages to images...",
        type = "message",
        duration = NULL,
        id = "convert_notif"
      )

      # Convert PDF pages to images using magick
      pdf_images = magick::image_read_pdf(pdf_path, pages = 1:n_pages, density = 150)

      # Save images to temp files
      temp_paths = sapply(1:n_pages, function(i) {
        temp_file = tempfile(fileext = ".png")
        magick::image_write(pdf_images[i], temp_file, format = "png")
        temp_file
      })

      scanned_pdf_paths(temp_paths)

      shiny::removeNotification(id = "convert_notif")
      shiny::showNotification(
        paste(n_pages, "page(s) converted successfully!"),
        type = "message",
        duration = 3
      )
    }, error = function(e) {
      shiny::removeNotification(id = "convert_notif")
      shiny::showNotification(
        paste("Error processing scanned PDF:", e$message),
        type = "error",
        duration = NULL
      )
    })
  })

  # Render scanned PDF preview
  output$scanned_pdf_preview_ui = shiny::renderUI({
    paths = scanned_pdf_paths()
    if (is.null(paths) || length(paths) == 0) return(NULL)

    shiny::tagList(
      shiny::div(
        class = "image-preview-grid",
        lapply(seq_along(paths), function(i) {
          shiny::div(
            class = "image-preview-item",
            shiny::tags$img(
              src = base64enc::dataURI(file = paths[i], mime = "image/png"),
              alt = paste("Page", i)
            )
          )
        })
      ),
      shiny::div(
        class = "image-preview-count",
        paste(length(paths), "page(s) ready for extraction")
      )
    )
  })

  # Dynamically generate UI elements for each field's label and description
  output$fields_ui = shiny::renderUI({
    n = input$num_fields
    input_method = input$input_method
    if (is.null(n) || n < 1) return(NULL)
    if (is.null(input_method)) input_method = "demo"

    # Use NHTSA example fields only for demo mode
    if (input_method == "demo") {
      example_labels = c("manufacturer", "defect_summary", "models", "model_years", "component", "fmvss_number", "root_cause", "risk")
      example_descs = c(
        "The name of the company recalling the vehicles.",
        "Summary of the main defect.",
        "List of affected vehicle models.",
        "List of model years affected.",
        "The part or system affected by the defect.",
        "The FMVSS number mentioned, if any.",
        "The root cause of the defect.",
        "The risk or consequence posed by the defect."
      )
    } else {
      # Generic placeholders for non-demo modes
      example_labels = character(0)
      example_descs = character(0)
    }

    fields = purrr::map(1:n, function(i) {
      # Set default values - use examples for demo, generic for others
      if (input_method == "demo" && i <= length(example_labels)) {
        default_label = example_labels[i]
        default_desc = example_descs[i]
      } else {
        default_label = paste0("field_", i)
        default_desc = "Describe what to extract for this field"
      }

      shiny::div(
        style = "background-color: #EDECE2; padding: 12px; border-radius: 6px; margin-bottom: 12px;",
        shiny::tags$span(
          style = "color: #C41230; font-weight: 600; font-size: 0.9em;",
          paste("Field", i)
        ),
        shiny::textInput(
          paste0("field_label_", i),
          "Label:",
          value = default_label
        ),
        shiny::textInput(
          paste0("field_desc_", i),
          "Description:",
          value = default_desc
        )
      )
    })
    do.call(shiny::tagList, fields)
  })

  # Build a custom type_object based on user-specified fields
  create_type_object = shiny::reactive({
    n = input$num_fields
    if (is.null(n) || n < 1) return(NULL)

    # Build a list of field definitions
    type_list = list()
    for (i in 1:n) {
      label = input[[paste0("field_label_", i)]]
      desc = input[[paste0("field_desc_", i)]]
      if (!is.null(label) && label != "") {
        type_list[[label]] = ellmer::type_string(desc, required = FALSE)
      }
    }
    # Dynamically create the type object
    do.call(ellmer::type_object, type_list)
  })

  # When the extract button is clicked, perform extraction
  shiny::observeEvent(input$extract_btn, {
    # Get the current input method
    input_method = input$input_method
    if (is.null(input_method)) input_method = "demo"

    # Validate input based on method with helpful error messages
    has_data = FALSE
    error_msg = ""

    # Suffix to add to error messages reminding about field configuration
    field_reminder = " Also, make sure to update the field labels and descriptions for your data."

    if (input_method == "demo") {
      # Check if demo data was loaded
      if (is.null(demo_text()) || nchar(demo_text()) == 0) {
        error_msg = "Please click 'Load Demo Data' first to load the sample data."
      } else {
        has_data = TRUE
      }
    } else if (input_method == "paste") {
      # Check if text was pasted
      if (is.null(input$input_text) || nchar(trimws(input$input_text)) == 0) {
        error_msg = paste0("Please paste your text content in the text area.", field_reminder)
      } else {
        has_data = TRUE
      }
    } else if (input_method == "textfile") {
      # Check if text file was uploaded
      if (is.null(textfile_text()) || nchar(textfile_text()) == 0) {
        error_msg = paste0("Please upload a text file (.txt, .csv, or .md) first.", field_reminder)
      } else {
        has_data = TRUE
      }
    } else if (input_method == "pdf") {
      # Check if PDF was uploaded
      if (is.null(pdf_text()) || nchar(pdf_text()) == 0) {
        error_msg = paste0("Please upload a readable PDF file first.", field_reminder)
      } else {
        has_data = TRUE
      }
    } else if (input_method == "image") {
      # Check if images were uploaded
      if (is.null(image_paths()) || length(image_paths()) == 0) {
        error_msg = paste0("Please upload one or more image files first.", field_reminder)
      } else {
        has_data = TRUE
      }
    } else if (input_method == "scanned") {
      # Check if scanned PDF was uploaded
      if (is.null(scanned_pdf_paths()) || length(scanned_pdf_paths()) == 0) {
        error_msg = paste0("Please upload a scanned PDF file first.", field_reminder)
      } else {
        has_data = TRUE
      }
    }

    # Show error if no data
    if (!has_data) {
      shiny::showNotification(
        shiny::tags$span(
          shiny::icon("exclamation-triangle"),
          " ",
          error_msg
        ),
        type = "error",
        duration = 5
      )
      return()
    }

    # Show processing indicator
    shiny::showNotification(
      shiny::tags$span(
        shiny::icon("spinner", class = "fa-spin"),
        " Processing extraction request..."
      ),
      type = "message",
      duration = NULL,
      id = "extract_notif"
    )

    custom_type_object = create_type_object()

    # Initialize the chat object using the OpenAI API key from your environment
    tryCatch({
      # Check if API key is available
      if (Sys.getenv("OPENAI_API_KEY") == "") {
        stop("OpenAI API key not found. Please set the OPENAI_API_KEY environment variable.")
      }

      chat = ellmer::chat_openai(
        model = "gpt-5-mini-2025-08-07",
      )

      all_results = list()

      if (input_method %in% c("demo", "paste", "pdf", "textfile")) {
        # Text-based extraction
        # Split text by double linebreaks to process multiple entities
        text_blocks = unlist(strsplit(input$input_text, "\n\n"))
        text_blocks = text_blocks[text_blocks != ""] # Remove empty blocks

        # Process each text block
        for (i in seq_along(text_blocks)) {
          result = chat$chat_structured(text_blocks[i], type = custom_type_object)
          if (is.list(result)) {
            result$source_id = i
            all_results[[i]] = result
          }
        }

      } else if (input_method == "image") {
        # Vision-based extraction from uploaded images
        paths = image_paths()

        for (i in seq_along(paths)) {
          # Create image content for the model
          image_content = ellmer::content_image_file(paths[i], resize = "high")
          result = chat$chat_structured(image_content, type = custom_type_object)
          if (is.list(result)) {
            result$source_id = paste("Image", i)
            all_results[[i]] = result
          }
        }

      } else if (input_method == "scanned") {
        # Vision-based extraction from scanned PDF pages
        paths = scanned_pdf_paths()

        for (i in seq_along(paths)) {
          # Create image content for the model
          image_content = ellmer::content_image_file(paths[i], resize = "high")
          result = chat$chat_structured(image_content, type = custom_type_object)
          if (is.list(result)) {
            result$source_id = paste("Page", i)
            all_results[[i]] = result
          }
        }
      }

      # Combine all results into a single data frame
      if (length(all_results) > 0) {
        combined_results = do.call(rbind, lapply(all_results, function(x) {
          # Ensure all results have the same columns by converting to data frame
          as.data.frame(x)
        }))

        # Store results for CSV download
        extracted_results(combined_results)

        # Render the output as a table
        output$extracted_table = shiny::renderTable(
          {
            combined_results
          },
          rownames = TRUE,
          striped = TRUE,
          hover = TRUE,
          bordered = TRUE
        )
      } else {
        # Handle the case when no valid results are returned
        extracted_results(NULL)
        output$extracted_table = shiny::renderTable({
          data.frame(Message = "No valid data could be extracted. Please check your input and field definitions.")
        })
      }

      # Remove notification
      shiny::removeNotification(id = "extract_notif")
      shiny::showNotification(
        shiny::tags$span(
          shiny::icon("check-circle"),
          " Extraction complete!"
        ),
        type = "message",
        duration = 3
      )
    }, error = function(e) {
      # Handle errors
      shiny::removeNotification(id = "extract_notif")
      shiny::showNotification(
        shiny::tags$span(
          shiny::icon("exclamation-triangle"),
          " Error: ",
          e$message
        ),
        type = "error",
        duration = NULL
      )
    })
  })

  # Render download button only when results are available
  output$download_btn_ui = shiny::renderUI({
    results = extracted_results()
    if (is.null(results) || nrow(results) == 0) return(NULL)

    shiny::div(
      style = "margin-top: 15px;",
      shiny::downloadButton(
        "download_csv",
        "Download as CSV",
        class = "btn-info"
      )
    )
  })

  # Download handler for CSV export
  output$download_csv = shiny::downloadHandler(
    filename = function() {
      paste0("extracted_data_", format(Sys.time(), "%Y%m%d_%H%M%S"), ".csv")
    },
    content = function(file) {
      results = extracted_results()
      if (!is.null(results)) {
        utils::write.csv(results, file, row.names = FALSE)
      }
    }
  )
}

# Run the Shiny app
shiny::shinyApp(ui = ui, server = server)