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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23766d1
 
 
 
 
 
 
 
 
 
 
 
b17b1a5
23766d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b17b1a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
import marimo

__generated_with = "0.13.0"
app = marimo.App(width="full")

with app.setup:
    # Initialization code that runs before all other cells
    import marimo as mo
    from typing import Dict, Optional, List, Union, Any
    from ibm_watsonx_ai import APIClient, Credentials
    from pathlib import Path
    import pandas as pd
    import mimetypes
    import requests
    import zipfile
    import tempfile
    import certifi
    import base64
    import polars
    import nltk
    import time
    import json
    import ast    
    import os
    import io
    import re

    def get_iam_token(api_key):
        return requests.post(
            'https://iam.cloud.ibm.com/identity/token',
            headers={'Content-Type': 'application/x-www-form-urlencoded'},
            data={'grant_type': 'urn:ibm:params:oauth:grant-type:apikey', 'apikey': api_key},
            verify=certifi.where()
        ).json()['access_token']

    def setup_task_credentials(client):
        # Get existing task credentials
        existing_credentials = client.task_credentials.get_details()

        # Delete existing credentials if any
        if "resources" in existing_credentials and existing_credentials["resources"]:
            for cred in existing_credentials["resources"]:
                cred_id = client.task_credentials.get_id(cred)
                client.task_credentials.delete(cred_id)

        # Store new credentials
        return client.task_credentials.store()

    def get_cred_value(key, creds_var_name="baked_in_creds", default=""): ### Helper for working with preset credentials
        """
        Helper function to safely get a value from a credentials dictionary.

        Args:
            key: The key to look up in the credentials dictionary.
            creds_var_name: The variable name of the credentials dictionary.
            default: The default value to return if the key is not found.

        Returns:
            The value from the credentials dictionary if it exists and contains the key,
            otherwise returns the default value.
        """
        # Check if the credentials variable exists in globals
        if creds_var_name in globals():
            creds_dict = globals()[creds_var_name]
            if isinstance(creds_dict, dict) and key in creds_dict:
                return creds_dict[key]
        return default

@app.cell
def client_variables(client_instantiation_form):
    if client_instantiation_form.value:
        client_setup = client_instantiation_form.value
    else:
        client_setup = None

    ### Extract Credential Variables:
    if client_setup is not None:
        wx_url = client_setup["wx_region"]
        wx_api_key = client_setup["wx_api_key"].strip()
        os.environ["WATSONX_APIKEY"] = wx_api_key

        if client_setup["project_id"] is not None:
            project_id = client_setup["project_id"].strip()
        else:
            project_id = None

        if client_setup["space_id"] is not None:
            space_id = client_setup["space_id"].strip()
        else:
            space_id = None

    else:
        os.environ["WATSONX_APIKEY"] = ""
        project_id = None
        space_id = None
        wx_api_key = None
        wx_url = None
    return client_setup, project_id, space_id, wx_api_key, wx_url


@app.cell
def _(client_setup, wx_api_key):
    if client_setup:
        token = get_iam_token(wx_api_key)
    else:
        token = None
    return

@app.cell
def _():
    baked_in_creds = {
            "purpose": "",
            "api_key": "",
            "project_id": "",
            "space_id": "",
        }
    return baked_in_creds


@app.cell
def client_instantiation(
    client_setup,
    project_id,
    space_id,
    wx_api_key,
    wx_url,
):
    ### Instantiate the watsonx.ai client
    if client_setup:
        wx_credentials = Credentials(
            url=wx_url,
            api_key=wx_api_key
        )

        if project_id:
            project_client = APIClient(credentials=wx_credentials, project_id=project_id)
        else:
            project_client = None

        if space_id:
            deployment_client = APIClient(credentials=wx_credentials, space_id=space_id)
        else:
            deployment_client = None

            
        if project_client is not None:
            task_credentials_details = setup_task_credentials(project_client)
        else:
            task_credentials_details = setup_task_credentials(deployment_client)
            
    else:
        wx_credentials = None
        project_client = None
        deployment_client = None
        task_credentials_details = None

    client_status = mo.md("### Client Instantiation Status will turn Green When Ready")

    if project_client is not None or deployment_client is not None:
        client_callout_kind = "success"
    else:
        client_callout_kind = "neutral"
    return (
        client_callout_kind,
        client_status,
        deployment_client,
        project_client,
    )


@app.cell
def _():
    mo.md(
        r"""
        #watsonx.ai Embedding Visualizer - Marimo Notebook

        #### This marimo notebook can be used to develop a more intuitive understanding of how vector embeddings work by creating a 3D visualization of vector embeddings based on chunked PDF document pages. 

        #### It can also serve as a useful tool for identifying gaps in model choice, chunking strategy or contents used in building collections by showing how far you are from what you want.
        <br>

        /// admonition
        Created by ***Milan Mrdenovic*** [[email protected]] for IBM Ecosystem Client Engineering, NCEE - ***version 5.3** - 20.04.2025*
        ///


        >Licensed under apache 2.0, users hold full accountability for any use or modification of the code.
        ><br>This asset is part of a set meant to support IBMers, IBM Partners, Clients in developing understanding of how to better utilize various watsonx features and generative AI as a subject matter.

        <br>
        """
    )
    return


@app.cell
def _():
    mo.md("""###Part 1 - Client Setup, File Preparation and Chunking""")
    return


@app.cell
def accordion_client_setup(client_selector, client_stack):
    ui_accordion_part_1_1 = mo.accordion(
        {
            "Instantiate Client": mo.vstack([client_stack, client_selector], align="center"),
        }
    )

    ui_accordion_part_1_1
    return


@app.cell
def accordion_file_upload(select_stack):
    ui_accordion_part_1_2 = mo.accordion(
        {
            "Select Model & Upload Files": select_stack
        }
    )

    ui_accordion_part_1_2
    return


@app.cell
def loaded_texts(
    create_temp_files_from_uploads,
    file_loader,
    pdf_reader,
    run_upload_button,
    set_text_state,
):
    if file_loader.value is not None and run_upload_button.value:
        filepaths = create_temp_files_from_uploads(file_loader.value)
        loaded_texts = load_pdf_data_with_progress(pdf_reader, filepaths, file_loader.value, show_progress=True)

        set_text_state(loaded_texts)
    else:
        filepaths = None
        loaded_texts = None
    return


@app.cell
def accordion_chunker_setup(chunker_setup):
    ui_accordion_part_1_3 = mo.accordion(
        {
            "Chunker Setup": chunker_setup
        }
    )

    ui_accordion_part_1_3
    return


@app.cell
def chunk_documents_to_nodes(
    get_text_state,
    sentence_splitter,
    sentence_splitter_config,
    set_chunk_state,
):
    if sentence_splitter_config.value and sentence_splitter and get_text_state() is not None:
        chunked_texts = chunk_documents(get_text_state(), sentence_splitter, show_progress=True)
        set_chunk_state(chunked_texts)
    else:
        chunked_texts = None
    return (chunked_texts,)


@app.cell
def _():
    mo.md(r"""###Part 2 - Query Setup and Visualization""")
    return


@app.cell
def accordion_chunk_range(chart_range_selection):
    ui_accordion_part_2_1 = mo.accordion(
        {
            "Chunk Range Selection": chart_range_selection
        }
    )
    ui_accordion_part_2_1
    return


@app.cell
def chunk_embedding(
    chunks_to_process,
    embedding,
    sentence_splitter_config,
    set_embedding_state,
):
    if sentence_splitter_config.value is not None and chunks_to_process is not None:
        with mo.status.spinner(title="Embedding Documents...", remove_on_exit=True) as _spinner:
            output_embeddings = embedding.embed_documents(chunks_to_process)
            _spinner.update("Almost Done")
            time.sleep(1.5)
            set_embedding_state(output_embeddings)
            _spinner.update("Documents Embedded")
    else:
        output_embeddings = None
    return


@app.cell
def preview_chunks(chunks_dict):
    if chunks_dict is not None:
        stats = create_stats(chunks_dict, 
                             bordered=True, 
                             object_names=['text','text'], 
                             group_by_row=True, 
                             items_per_row=5, 
                             gap=1,
                             label="Chunk")
        ui_chunk_viewer = mo.accordion(
            {
                "View Chunks": stats,
            }
        )
    else:
        ui_chunk_viewer = None

    ui_chunk_viewer
    return


@app.cell
def accordion_query_view(chart_visualization, query_stack):
    ui_accordion_part_2_2 = mo.accordion(
        {
            "Query": mo.vstack([query_stack, mo.hstack([chart_visualization])], align="center", gap=3)
        }
    )
    ui_accordion_part_2_2
    return


@app.cell
def chunker_setup(sentence_splitter_config):
    chunker_setup = mo.hstack([sentence_splitter_config], justify="space-around", align="center", widths=[0.55])
    return (chunker_setup,)


@app.cell
def file_and_model_select(
    file_loader,
    get_embedding_model_list,
    run_upload_button,
):
    select_stack = mo.hstack([get_embedding_model_list(), mo.vstack([file_loader, run_upload_button], align="center")], justify="space-around", align="center", widths=[0.3,0.3])
    return (select_stack,)


@app.cell
def client_instantiation_form():
    # Endpoints
    wx_platform_url = "https://api.dataplatform.cloud.ibm.com"
    regions = {
        "US": "https://us-south.ml.cloud.ibm.com",
        "EU": "https://eu-de.ml.cloud.ibm.com",
        "GB": "https://eu-gb.ml.cloud.ibm.com",
        "JP": "https://jp-tok.ml.cloud.ibm.com",
        "AU": "https://au-syd.ml.cloud.ibm.com",
        "CA": "https://ca-tor.ml.cloud.ibm.com"
    }

    # Create a form with multiple elements
    client_instantiation_form = (
        mo.md('''
        ###**watsonx.ai credentials:**
        
        {wx_region}
        
        {wx_api_key}
        
        {project_id}
        
        {space_id}
        
        > You can add either a project_id, space_id or both, **only one is required**.  
        > If you provide both you can switch the active one in the dropdown.
    ''')
        .batch(
            wx_region = mo.ui.dropdown(regions, label="Select your watsonx.ai region:", value="US", searchable=True),
            wx_api_key = mo.ui.text(placeholder="Add your IBM Cloud api-key...", label="IBM Cloud Api-key:", 
                                    kind="password", value=get_cred_value('api_key', creds_var_name='baked_in_creds')),
            project_id = mo.ui.text(placeholder="Add your watsonx.ai project_id...", label="Project_ID:", 
                                    kind="text", value=get_cred_value('project_id', creds_var_name='baked_in_creds')),
            space_id = mo.ui.text(placeholder="Add your watsonx.ai space_id...", label="Space_ID:", 
                                  kind="text", value=get_cred_value('space_id', creds_var_name='baked_in_creds'))
        ,)
        .form(show_clear_button=True, bordered=False)
    )
    return (client_instantiation_form,)


@app.cell
def instantiation_status(
    client_callout_kind,
    client_instantiation_form,
    client_status,
):
    client_callout = mo.callout(client_status, kind=client_callout_kind)
    client_stack = mo.hstack([client_instantiation_form, client_callout], align="center", justify="space-around", gap=10)
    return (client_stack,)


@app.cell
def client_selector(deployment_client, project_client):
    if deployment_client is not None:
        client_options = {"Deployment Client":deployment_client}
        
    elif project_client is not None:
        client_options = {"Project Client":project_client}

    elif project_client is not None and deployment_client is not None:
        client_options = {"Project Client":project_client,"Deployment Client":deployment_client}
    
    else:
        client_options = {"No Client": "Instantiate a Client"}

    default_client = next(iter(client_options))
    client_selector = mo.ui.dropdown(client_options, value=default_client, label="**Select your active client:**")
    
    return (client_selector,)


@app.cell
def active_client(client_selector):
    client_key = client_selector.value
    if client_key == "Instantiate a Client":
        client = None
    else:
        client = client_key
    return (client,)


@app.cell
def emb_model_selection(client, set_embedding_model_list):
    if client is not None:
        model_specs = client.foundation_models.get_embeddings_model_specs()
        # model_specs = client.foundation_models.get_model_specs()
        resources = model_specs["resources"]
        # Define embedding models reference data
        embedding_models = {
            "ibm/granite-embedding-107m-multilingual": {"max_tokens": 512, "embedding_dimensions": 384},
            "ibm/granite-embedding-278m-multilingual": {"max_tokens": 512, "embedding_dimensions": 768},
            "ibm/slate-125m-english-rtrvr-v2": {"max_tokens": 512, "embedding_dimensions": 768},
            "ibm/slate-125m-english-rtrvr": {"max_tokens": 512, "embedding_dimensions": 768},
            "ibm/slate-30m-english-rtrvr-v2": {"max_tokens": 512, "embedding_dimensions": 384},
            "ibm/slate-30m-english-rtrvr": {"max_tokens": 512, "embedding_dimensions": 384},
            "sentence-transformers/all-minilm-l6-v2": {"max_tokens": 128, "embedding_dimensions": 384},
            "sentence-transformers/all-minilm-l12-v2": {"max_tokens": 128, "embedding_dimensions": 384},
            "intfloat/multilingual-e5-large": {"max_tokens": 512, "embedding_dimensions": 1024}
        }

        # Get model IDs from resources
        model_id_list = []
        for resource in resources:
            model_id_list.append(resource["model_id"])

        # Create enhanced model data for the table
        embedding_model_data = []
        for model_id in model_id_list:
            model_entry = {"model_id": model_id}

            # Add properties if model exists in our reference, otherwise use 0
            if model_id in embedding_models:
                model_entry["max_tokens"] = embedding_models[model_id]["max_tokens"]
                model_entry["embedding_dimensions"] = embedding_models[model_id]["embedding_dimensions"]
            else:
                model_entry["max_tokens"] = 0
                model_entry["embedding_dimensions"] = 0

            embedding_model_data.append(model_entry)

        embedding_model_selection = mo.ui.table(
            embedding_model_data,
            selection="single",  # Only allow selecting one row
            label="Select an embedding model to use.",
            page_size=30,
            initial_selection=[1]
        )
        set_embedding_model_list(embedding_model_selection)
    else:
        default_model_data = [{
            "model_id": "ibm/granite-embedding-107m-multilingual",
            "max_tokens": 512,
            "embedding_dimensions": 384
        }]

        set_embedding_model_list(create_emb_model_selection_table(default_model_data, initial_selection=0, selection_type="single", label="Select a model to use."))
    return


@app.function
def create_emb_model_selection_table(model_data, initial_selection=0, selection_type="single", label="Select a model to use."):
    embedding_model_selection = mo.ui.table(
        model_data,
        selection=selection_type,  # Only allow selecting one row
        label=label,
        page_size=30,
        initial_selection=[initial_selection]
    )
    return embedding_model_selection


@app.cell
def embedding_model():
    get_embedding_model_list, set_embedding_model_list = mo.state(None)
    return get_embedding_model_list, set_embedding_model_list


@app.cell
def emb_model_parameters(emb_model_max_tk):
    from ibm_watsonx_ai.metanames import EmbedTextParamsMetaNames as EmbedParams
    if embedding_model is not None:
        embed_params = {
             EmbedParams.TRUNCATE_INPUT_TOKENS: emb_model_max_tk,
             EmbedParams.RETURN_OPTIONS: {
             'input_text': True
             }
         }
    else:
        embed_params = {
             EmbedParams.TRUNCATE_INPUT_TOKENS: 128,
             EmbedParams.RETURN_OPTIONS: {
             'input_text': True
             }
         }      
    return embed_params


@app.cell
def emb_model_state(get_embedding_model_list):
    embedding_model = get_embedding_model_list()
    return (embedding_model,)


@app.cell
def emb_model_setup(embedding_model):
    if embedding_model is not None:
        emb_model = embedding_model.value[0]['model_id']
        emb_model_max_tk = embedding_model.value[0]['max_tokens']
        emb_model_emb_dim = embedding_model.value[0]['embedding_dimensions']
    else:
        emb_model = None
        emb_model_max_tk = None
        emb_model_emb_dim = None
    return emb_model, emb_model_emb_dim, emb_model_max_tk


@app.cell
def emb_model_instantiation(client, emb_model, embed_params):
    from ibm_watsonx_ai.foundation_models import Embeddings
    if client is not None:
        embedding = Embeddings(
             model_id=emb_model,
             api_client=client,
             params=embed_params,
             batch_size=1000,
             concurrency_limit=10
             )
    else:
        embedding = None
    return (embedding,)


@app.cell
def _():
    get_embedding_state, set_embedding_state = mo.state(None)
    return get_embedding_state, set_embedding_state


@app.cell
def _():
    get_query_state, set_query_state = mo.state(None)
    return get_query_state, set_query_state


@app.cell
def file_loader_input():
    file_loader = mo.ui.file(
            kind="area",
            filetypes=[".pdf"],
            label="   Load .pdf files  ",
            multiple=True
        )
    return (file_loader,)


@app.cell
def file_loader_run(file_loader):
    if file_loader.value:
        run_upload_button = mo.ui.run_button(label="Load Files")
    else:
        run_upload_button = mo.ui.run_button(disabled=True, label="Load Files")
    return (run_upload_button,)


@app.cell
def helper_function_tempfiles():
    def create_temp_files_from_uploads(upload_results) -> List[str]:
        """
        Creates temporary files from a tuple of FileUploadResults objects and returns their paths.
        Args:
            upload_results: Object containing a value attribute that is a tuple of FileUploadResults
        Returns:
            List of temporary file paths
        """
        temp_file_paths = []

        # Get the number of items in the tuple
        num_items = len(upload_results)

        # Process each item by index
        for i in range(num_items):
            result = upload_results[i]  # Get item by index

            # Create a temporary file with the original filename
            temp_dir = tempfile.gettempdir()
            file_name = result.name
            temp_path = os.path.join(temp_dir, file_name)
            # Write the contents to the temp file
            with open(temp_path, 'wb') as temp_file:
                temp_file.write(result.contents)
            # Add the path to our list
            temp_file_paths.append(temp_path)

        return temp_file_paths

    def cleanup_temp_files(temp_file_paths: List[str]) -> None:
        """Delete temporary files after use."""
        for path in temp_file_paths:
            if os.path.exists(path):
                os.unlink(path)
    return (create_temp_files_from_uploads,)


@app.function
def load_pdf_data_with_progress(pdf_reader, filepaths, file_loader_value, show_progress=True):
    """
    Loads PDF data for each file path and organizes results by original filename.
    Args:
        pdf_reader: The PyMuPDFReader instance
        filepaths: List of temporary file paths
        file_loader_value: The original upload results value containing file information
        show_progress: Whether to show a progress bar during loading (default: False)
    Returns:
        Dictionary mapping original filenames to their loaded text content
    """
    results = {}

    # Process files with or without progress bar
    if show_progress:
        import marimo as mo
        # Use progress bar with the length of filepaths as total
        with mo.status.progress_bar(
            total=len(filepaths),
            title="Loading PDFs",
            subtitle="Processing documents...",
            completion_title="PDF Loading Complete",
            completion_subtitle=f"{len(filepaths)} documents processed",
            remove_on_exit=True
        ) as bar:
            # Process each file path
            for i, file_path in enumerate(filepaths):

                original_file_name = file_loader_value[i].name
                bar.update(subtitle=f"Processing {original_file_name}...")
                loaded_text = pdf_reader.load_data(file_path=file_path, metadata=True)

                # Store the result with the original filename as the key
                results[original_file_name] = loaded_text
                # Update progress bar
                bar.update(increment=1)
    else:
        # Original logic without progress bar
        for i, file_path in enumerate(filepaths):
            original_file_name = file_loader_value[i].name
            loaded_text = pdf_reader.load_data(file_path=file_path, metadata=True)
            results[original_file_name] = loaded_text

    return results


@app.cell
def file_readers():
    from llama_index.readers.file import PyMuPDFReader
    from llama_index.readers.file import FlatReader
    from llama_index.core.node_parser import SentenceSplitter

    ### File Readers
    pdf_reader = PyMuPDFReader()
    # flat_file_reader = FlatReader()
    return SentenceSplitter, pdf_reader


@app.cell
def sentence_splitter_setup():
    ### Chunker Setup
    sentence_splitter_config = (
        mo.md('''
        ###**Chunking Setup:**
    
        > Unless you want to do some advanced sentence splitting, it's best to stick to adjusting only the chunk size and overlap. Changing the other settings might result in unexpected results.
    
        Separator value is set to **" "** by default, while the paragraph separator is **"\\n\\n\\n"**.
    
        {chunk_size} 
        
        {chunk_overlap}
    
        {separator} {paragraph_separator}
    
        {secondary_chunking_regex} {include_metadata}
    
    ''')
        .batch(
            chunk_size = mo.ui.slider(start=100, stop=5000, step=1, label="**Chunk Size:**", value=350, show_value=True, full_width=True),
            chunk_overlap = mo.ui.slider(start=1, stop=1000, step=1, label="**Chunk Overlap** *(Must always be smaller than Chunk Size)* **:**", value=50, show_value=True, full_width=True),
            separator = mo.ui.text(placeholder="Define a separator", label="**Separator:**", kind="text", value=" "),
            paragraph_separator = mo.ui.text(placeholder="Define a paragraph separator", 
                                             label="**Paragraph Separator:**", kind="text", 
                                             value="\n\n\n"),
            secondary_chunking_regex = mo.ui.text(placeholder="Define a secondary chunking regex", 
                                                  label="**Chunking Regex:**", kind="text", 
                                                  value="[^,.;?!]+[,.;?!]?"),
            include_metadata= mo.ui.checkbox(value=True, label="**Include Metadata**")
        )
        .form(show_clear_button=True, bordered=False)
    )
    return (sentence_splitter_config,)


@app.cell
def sentence_splitter_instantiation(
    SentenceSplitter,
    sentence_splitter_config,
):
    ### Chunker/Sentence Splitter 
    def simple_whitespace_tokenizer(text):
        return text.split()
    
    if sentence_splitter_config.value is not None:
        sentence_splitter_config_values = sentence_splitter_config.value
        validated_chunk_overlap = min(sentence_splitter_config_values.get("chunk_overlap"), 
                     int(sentence_splitter_config_values.get("chunk_size") * 0.3))

        sentence_splitter = SentenceSplitter(
            chunk_size=sentence_splitter_config_values.get("chunk_size"),
            chunk_overlap=validated_chunk_overlap,
            separator=sentence_splitter_config_values.get("separator"),
            paragraph_separator=sentence_splitter_config_values.get("paragraph_separator"),
            secondary_chunking_regex=sentence_splitter_config_values.get("secondary_chunking_regex"),
            include_metadata=sentence_splitter_config_values.get("include_metadata"),
            tokenizer=simple_whitespace_tokenizer
        )

    else:
        sentence_splitter = SentenceSplitter(
            chunk_size=2048,
            chunk_overlap=204,
            separator=" ",
            paragraph_separator="\n\n\n",
            secondary_chunking_regex="[^,.;?!]+[,.;?!]?",
            include_metadata=True,
            tokenizer=simple_whitespace_tokenizer
        )
    return (sentence_splitter,)


@app.cell
def text_state():
    get_text_state, set_text_state = mo.state(None)
    return get_text_state, set_text_state


@app.cell
def chunk_state():
    get_chunk_state, set_chunk_state = mo.state(None)
    return get_chunk_state, set_chunk_state


@app.function
def chunk_documents(loaded_texts, sentence_splitter, show_progress=True):
    """
    Process each document in the loaded_texts dictionary using the sentence_splitter,
    with an optional marimo progress bar tracking progress at document level.

    Args:
        loaded_texts (dict): Dictionary containing lists of Document objects
        sentence_splitter: The sentence splitter object with get_nodes_from_documents method
        show_progress (bool): Whether to show a progress bar during processing

    Returns:
        dict: Dictionary with the same structure but containing chunked texts
    """
    chunked_texts_dict = {}

    # Get the total number of documents across all keys
    total_docs = sum(len(docs) for docs in loaded_texts.values())
    processed_docs = 0

    # Process with or without progress bar
    if show_progress:
        import marimo as mo
        # Use progress bar with the total number of documents as total
        with mo.status.progress_bar(
            total=total_docs,
            title="Processing Documents",
            subtitle="Chunking documents...",
            completion_title="Processing Complete",
            completion_subtitle=f"{total_docs} documents processed",
            remove_on_exit=True
        ) as bar:
            # Process each key-value pair in the loaded_texts dictionary
            for key, documents in loaded_texts.items():
                # Update progress bar subtitle to show current key
                doc_count = len(documents)
                bar.update(subtitle=f"Chunking {key}... ({doc_count} documents)")

                # Apply the sentence splitter to each list of documents
                chunked_texts = sentence_splitter.get_nodes_from_documents(
                    documents, 
                    show_progress=False  # Disable internal progress to avoid nested bars
                )

                # Store the result with the same key
                chunked_texts_dict[key] = chunked_texts
                time.sleep(0.15)

                # Update progress bar with the number of documents in this batch
                bar.update(increment=doc_count)
                processed_docs += doc_count
    else:
        # Process without progress bar
        for key, documents in loaded_texts.items():
            chunked_texts = sentence_splitter.get_nodes_from_documents(
                documents, 
                show_progress=True  # Use the internal progress bar if no marimo bar
            )
            chunked_texts_dict[key] = chunked_texts

    return chunked_texts_dict


@app.cell
def chunked_nodes(chunked_texts, get_chunk_state, sentence_splitter):
    if chunked_texts is not None and sentence_splitter:
        chunked_documents = get_chunk_state()
    else:
        chunked_documents = None
    return (chunked_documents,)


@app.cell
def prep_cumulative_df(chunked_documents, llamaindex_convert_docs_multi):
    if chunked_documents is not None:
        dict_from_nodes = llamaindex_convert_docs_multi(chunked_documents)
        nodes_from_dict = llamaindex_convert_docs_multi(dict_from_nodes)
    else:
        dict_from_nodes = None
        nodes_from_dict = None
    return (dict_from_nodes,)


@app.cell
def chunks_to_process(
    dict_from_nodes,
    document_range_stack,
    get_data_in_range_triplequote,
):
    if dict_from_nodes is not None and document_range_stack is not None:

        chunk_dict_df = create_cumulative_dataframe(dict_from_nodes)

        if document_range_stack.value is not None:
            chunk_start_idx = document_range_stack.value[0]
            chunk_end_idx = document_range_stack.value[1]
        else:
            chunk_start_idx = 0
            chunk_end_idx = len(chunk_dict_df)

        chunk_range_index = [chunk_start_idx, chunk_end_idx]
        chunks_dict = get_data_in_range_triplequote(chunk_dict_df,
                                                    index_range=chunk_range_index, 
                                                    columns_to_include=["text"])

        chunks_to_process = chunks_dict['text'] if 'text' in chunks_dict else []
    else:
        chunk_objects = None
        chunks_dict = None
        chunks_to_process = None
    return chunks_dict, chunks_to_process


@app.cell
def helper_function_doc_formatting():
    def llamaindex_convert_docs_multi(items):
        """
        Automatically convert between document objects and dictionaries.

        This function handles:
        - Converting dictionaries to document objects
        - Converting document objects to dictionaries
        - Processing lists or individual items
        - Supporting dictionary structures where values are lists of documents

        Args:
            items: A document object, dictionary, or list of either.
                  Can also be a dictionary mapping filenames to lists of documents.

        Returns:
            Converted item(s) maintaining the original structure
        """
        # Handle empty or None input
        if not items:
            return []

        # Handle dictionary mapping filenames to document lists (from load_pdf_data)
        if isinstance(items, dict) and all(isinstance(v, list) for v in items.values()):
            result = {}
            for filename, doc_list in items.items():
                result[filename] = llamaindex_convert_docs(doc_list)
            return result

        # Handle single items (not in a list)
        if not isinstance(items, list):
            # Single dictionary to document
            if isinstance(items, dict):
                # Determine document class
                doc_class = None
                if 'doc_type' in items:
                    import importlib
                    module_path, class_name = items['doc_type'].rsplit('.', 1)
                    module = importlib.import_module(module_path)
                    doc_class = getattr(module, class_name)
                if not doc_class:
                    from llama_index.core.schema import Document
                    doc_class = Document
                return doc_class.from_dict(items)
            # Single document to dictionary
            elif hasattr(items, 'to_dict'):
                return items.to_dict()
            # Return as is if can't convert
            return items

        # Handle list input
        result = []

        # Handle empty list
        if len(items) == 0:
            return result

        # Determine the type of conversion based on the first non-None item
        first_item = next((item for item in items if item is not None), None)

        # If we found no non-None items, return empty list
        if first_item is None:
            return result

        # Convert dictionaries to documents
        if isinstance(first_item, dict):
            # Get the right document class from the items themselves
            doc_class = None
            # Try to get doc class from metadata if available
            if 'doc_type' in first_item:
                import importlib
                module_path, class_name = first_item['doc_type'].rsplit('.', 1)
                module = importlib.import_module(module_path)
                doc_class = getattr(module, class_name)
            if not doc_class:
                # Fallback to default Document class from llama_index
                from llama_index.core.schema import Document
                doc_class = Document

            # Convert each dictionary to document
            for item in items:
                if isinstance(item, dict):
                    result.append(doc_class.from_dict(item))
                elif item is None:
                    result.append(None)
                elif isinstance(item, list):
                    result.append(llamaindex_convert_docs(item))
                else:
                    result.append(item)

        # Convert documents to dictionaries
        else:
            for item in items:
                if hasattr(item, 'to_dict'):
                    result.append(item.to_dict())
                elif item is None:
                    result.append(None)
                elif isinstance(item, list):
                    result.append(llamaindex_convert_docs(item))
                else:
                    result.append(item)

        return result

    def llamaindex_convert_docs(items):
        """
        Automatically convert between document objects and dictionaries.

        Args:
            items: A list of document objects or dictionaries

        Returns:
            List of converted items (dictionaries or document objects)
        """
        result = []

        # Handle empty or None input
        if not items:
            return result

        # Determine the type of conversion based on the first item
        if isinstance(items[0], dict):
            # Get the right document class from the items themselves
            # Look for a 'doc_type' or '__class__' field in the dictionary
            doc_class = None

            # Try to get doc class from metadata if available
            if 'doc_type' in items[0]:
                import importlib
                module_path, class_name = items[0]['doc_type'].rsplit('.', 1)
                module = importlib.import_module(module_path)
                doc_class = getattr(module, class_name)

            if not doc_class:
                # Fallback to default Document class from llama_index
                from llama_index.core.schema import Document
                doc_class = Document

            # Convert dictionaries to documents
            for item in items:
                if isinstance(item, dict):
                    result.append(doc_class.from_dict(item))
        else:
            # Convert documents to dictionaries
            for item in items:
                if hasattr(item, 'to_dict'):
                    result.append(item.to_dict())

        return result
    return (llamaindex_convert_docs_multi,)


@app.cell
def helper_function_create_df():
    def create_document_dataframes(dict_from_docs):
        """
        Creates a pandas DataFrame for each file in the dictionary.

        Args:
            dict_from_docs: Dictionary mapping filenames to lists of documents

        Returns:
            List of pandas DataFrames, each representing all documents from a single file
        """
        dataframes = []

        for filename, docs in dict_from_docs.items():
            # Create a list to hold all document records for this file
            file_records = []

            for i, doc in enumerate(docs):
                # Convert the document to a format compatible with DataFrame
                if hasattr(doc, 'to_dict'):
                    doc_data = doc.to_dict()
                elif isinstance(doc, dict):
                    doc_data = doc
                else:
                    doc_data = {'content': str(doc)}

                # Add document index information
                doc_data['doc_index'] = i

                # Add to the list of records for this file
                file_records.append(doc_data)

            # Create a single DataFrame for all documents in this file
            if file_records:
                df = pd.DataFrame(file_records)
                df['filename'] = filename  # Add filename as a column
                dataframes.append(df)

        return dataframes

    def create_dataframe_previews(dataframe_list, page_size=5):
        """
        Creates a list of mo.ui.dataframe components, one for each DataFrame in the input list.

        Args:
            dataframe_list: List of pandas DataFrames (output from create_document_dataframes)
            page_size: Number of rows to show per page for each component

        Returns:
            List of mo.ui.dataframe components
        """
        # Create a list of mo.ui.dataframe components
        preview_components = []

        for df in dataframe_list:
            # Create a mo.ui.dataframe component for this DataFrame
            preview = mo.ui.dataframe(df, page_size=page_size)
            preview_components.append(preview)

        return preview_components
    return


@app.cell
def helper_function_chart_preparation():
    import altair as alt
    import numpy as np
    import plotly.express as px
    from sklearn.manifold import TSNE

    def prepare_embedding_data(embeddings, texts, model_id=None, embedding_dimensions=None):
        """
        Prepare embedding data for visualization

        Args:
            embeddings: List of embeddings arrays
            texts: List of text strings
            model_id: Embedding model ID (optional)
            embedding_dimensions: Embedding dimensions (optional)

        Returns:
            DataFrame with processed data and metadata
        """
        # Flatten embeddings (in case they're nested)
        flattened_embeddings = []
        for emb in embeddings:
            if isinstance(emb, list) and len(emb) > 0 and isinstance(emb[0], list):
                flattened_embeddings.append(emb[0])  # Take first element if nested
            else:
                flattened_embeddings.append(emb)

        # Convert to numpy array
        embedding_array = np.array(flattened_embeddings)

        # Apply dimensionality reduction (t-SNE)
        tsne = TSNE(n_components=2, random_state=42, perplexity=min(30, len(embedding_array)-1))
        reduced_embeddings = tsne.fit_transform(embedding_array)

        # Create truncated texts for display
        truncated_texts = [text[:50] + "..." if len(text) > 50 else text for text in texts]

        # Create dataframe for visualization
        df = pd.DataFrame({
            "x": reduced_embeddings[:, 0],
            "y": reduced_embeddings[:, 1],
            "text": truncated_texts,
            "full_text": texts,
            "index": range(len(texts))
        })

        # Add metadata
        metadata = {
            "model_id": model_id,
            "embedding_dimensions": embedding_dimensions
        }

        return df, metadata

    def create_embedding_chart(df, metadata=None):
        """
        Create an Altair chart for embedding visualization

        Args:
            df: DataFrame with x, y coordinates and text
            metadata: Dictionary with model_id and embedding_dimensions

        Returns:
            Altair chart
        """
        model_id = metadata.get("model_id") if metadata else None
        embedding_dimensions = metadata.get("embedding_dimensions") if metadata else None

        selection = alt.selection_multi(fields=['index'])

        base = alt.Chart(df).encode(
            x=alt.X("x:Q", title="Dimension 1"),
            y=alt.Y("y:Q", title="Dimension 2"),
            tooltip=["text", "index"]
        )

        points = base.mark_circle(size=100).encode(
            color=alt.Color("index:N", legend=None),
            opacity=alt.condition(selection, alt.value(1), alt.value(0.2))
        ).add_selection(selection)  # Add this line to apply the selection

        text = base.mark_text(align="left", dx=7).encode(
            text="index:N"
        )

        return (points + text).properties(
            width=700, 
            height=500,
            title=f"Embedding Visualization{f' - Model: {model_id}' if model_id else ''}{f' ({embedding_dimensions} dimensions)' if embedding_dimensions else ''}"
        ).interactive()

    def show_selected_text(indices, texts):
        """
        Create markdown display for selected texts

        Args:
            indices: List of selected indices
            texts: List of all texts

        Returns:
            Markdown string
        """
        if not indices:
            return "No text selected"

        selected_texts = [texts[i] for i in indices if i < len(texts)]
        return "\n\n".join([f"**Document {i}**:\n{text}" for i, text in zip(indices, selected_texts)])

    def prepare_embedding_data_3d(embeddings, texts, model_id=None, embedding_dimensions=None):
            """
            Prepare embedding data for 3D visualization

            Args:
                embeddings: List of embeddings arrays
                texts: List of text strings
                model_id: Embedding model ID (optional)
                embedding_dimensions: Embedding dimensions (optional)

            Returns:
                DataFrame with processed data and metadata
            """
            # Flatten embeddings (in case they're nested)
            flattened_embeddings = []
            for emb in embeddings:
                if isinstance(emb, list) and len(emb) > 0 and isinstance(emb[0], list):
                    flattened_embeddings.append(emb[0])
                else:
                    flattened_embeddings.append(emb)

            # Convert to numpy array
            embedding_array = np.array(flattened_embeddings)

            # Handle the case of a single embedding differently
            if len(embedding_array) == 1:
                # For a single point, we don't need t-SNE, just use a fixed position
                reduced_embeddings = np.array([[0.0, 0.0, 0.0]])
            else:
                # Apply dimensionality reduction to 3D
                # Fix: Ensure perplexity is at least 1.0
                perplexity_value = max(1.0, min(30, len(embedding_array)-1))
                tsne = TSNE(n_components=3, random_state=42, perplexity=perplexity_value)
                reduced_embeddings = tsne.fit_transform(embedding_array)

            # Format texts for display
            formatted_texts = []
            for text in texts:
                # Truncate if needed
                if len(text) > 500:
                    text = text[:500] + "..."

                # Insert line breaks for wrapping
                wrapped_text = ""
                for i in range(0, len(text), 50):
                    wrapped_text += text[i:i+50] + "<br>"

                formatted_texts.append("<b>"+wrapped_text+"</b>")

            # Create dataframe for visualization
            df = pd.DataFrame({
                "x": reduced_embeddings[:, 0],
                "y": reduced_embeddings[:, 1],
                "z": reduced_embeddings[:, 2],
                "text": formatted_texts,
                "full_text": texts,
                "index": range(len(texts)),
                "embedding": flattened_embeddings  # Store the original embeddings for later use
            })

            # Add metadata
            metadata = {
                "model_id": model_id,
                "embedding_dimensions": embedding_dimensions
            }

            return df, metadata

    def create_3d_embedding_chart(df, metadata=None, chart_width=1200, chart_height=800, marker_size_var: int=3):
        """
        Create a 3D Plotly chart for embedding visualization with proximity-based coloring
        """
        model_id = metadata.get("model_id") if metadata else None
        embedding_dimensions = metadata.get("embedding_dimensions") if metadata else None

        # Calculate the proximity between points
        from scipy.spatial.distance import pdist, squareform
        # Get the coordinates as a numpy array
        coords = df[['x', 'y', 'z']].values

        # Calculate pairwise distances
        dist_matrix = squareform(pdist(coords))

        # For each point, find its average distance to all other points
        avg_distances = np.mean(dist_matrix, axis=1)

        # Add this to the dataframe - smaller values = closer to other points
        df['proximity'] = avg_distances

        # Create 3D scatter plot with proximity-based coloring
        fig = px.scatter_3d(
            df, 
            x='x', 
            y='y', 
            z='z',
            # x='petal_length',  # Changed from 'x' to 'petal_length'
            # y='petal_width',   # Changed from 'y' to 'petal_width'
            # z='petal_height',
            color='proximity',  # Color based on proximity
            color_continuous_scale='Viridis_r',  # Reversed so closer points are warmer colors
            hover_data=['text', 'index', 'proximity'],
            labels={'x': 'Dimension 1', 'y': 'Dimension 2', 'z': 'Dimension 3', 'proximity': 'Avg Distance'},
            # labels={'x': 'Dimension 1', 'y': 'Dimension 2', 'z': 'Dimension 3', 'proximity': 'Avg Distance'},
            title=f"<b>3D Embedding Visualization</b>{f' - Model: <b>{model_id}</b>' if model_id else ''}{f'  <i>({embedding_dimensions} dimensions)</i>' if embedding_dimensions else ''}",
            text='index',
            # size_max=marker_size_var
        )

        # Update marker size and layout
        # fig.update_traces(marker=dict(size=3), selector=dict(mode='markers'))
        fig.update_traces(
            marker=dict(
                size=marker_size_var,              # Very small marker size
                opacity=0.7,         # Slightly transparent 
                symbol="diamond",      # Use circle markers (other options: "square", "diamond", "cross", "x")
                line=dict(
                    width=0.5,       # Very thin border
                    color="white"    # White outline makes small dots more visible
                )
            ),
            textfont=dict(
                color="rgba(255, 255, 255, 0.3)",
                size=8
            ),
            # hovertemplate="<b>index=%{text}</b><br>%{customdata[0]}<br><br>Avg Distance=%{customdata[2]:.4f}<extra></extra>", ### Hover Changes
            hovertemplate="text:<br><b>%{customdata[0]}</b><br>index: <b>%{text}</b><br><br>Avg Distance: <b>%{customdata[2]:.4f}</b><extra></extra>",
            hoverinfo="text+name",
            hoverlabel=dict(
                bgcolor="white",     # White background for hover labels
                font_size=12         # Font size for hover text
            ),
            selector=dict(type='scatter3d')
        )

        # Keep your existing layout settings
        fig.update_layout(
            scene=dict(
                xaxis=dict(
                    title='Dimension 1',
                    nticks=40,
                    backgroundcolor="rgb(10, 10, 20, 0.1)",
                    gridcolor="white",
                    showbackground=True,
                    gridwidth=0.35,
                    zerolinecolor="white",
                ),
                yaxis=dict(
                    title='Dimension 2',
                    nticks=40,
                    backgroundcolor="rgb(10, 10, 20, 0.1)",
                    gridcolor="white",
                    showbackground=True,
                    gridwidth=0.35,
                    zerolinecolor="white",
                ),
                zaxis=dict(
                    title='Dimension 3',
                    nticks=40,
                    backgroundcolor="rgb(10, 10, 20, 0.1)",
                    gridcolor="white",
                    showbackground=True,
                    gridwidth=0.35,
                    zerolinecolor="white",
                ),
                # Control camera view angle
                camera=dict(
                    up=dict(x=0, y=0, z=1),
                    center=dict(x=0, y=0, z=0),
                    eye=dict(x=1.25, y=1.25, z=1.25),
                ),
                aspectratio=dict(x=1, y=1, z=1),
                aspectmode='data'
            ),
            width=int(chart_width),
            height=int(chart_height),
            margin=dict(r=20, l=10, b=10, t=50),
            paper_bgcolor="rgb(0, 0, 0)",
            plot_bgcolor="rgb(0, 0, 0)",
            coloraxis_colorbar=dict(
                title="Average Distance",
                thicknessmode="pixels", thickness=20,
                lenmode="pixels", len=400,
                yanchor="top", y=1,
                ticks="outside",
                dtick=0.1
            )
        )

        return fig
    return create_3d_embedding_chart, prepare_embedding_data_3d


@app.cell
def helper_function_text_preparation():
    def convert_table_to_json_docs(df, selected_columns=None):
        """
        Convert a pandas DataFrame or dictionary to a list of JSON documents.
        Dynamically includes columns based on user selection.
        Column names are standardized to lowercase with underscores instead of spaces
        and special characters removed.

        Args:
            df: The DataFrame or dictionary to process
            selected_columns: List of column names to include in the output documents

        Returns:
            list: A list of dictionaries, each representing a row as a JSON document
        """
        import pandas as pd
        import re

        def standardize_key(key):
            """Convert a column name to lowercase with underscores instead of spaces and no special characters"""
            if not isinstance(key, str):
                return str(key).lower()
            # Replace spaces with underscores and convert to lowercase
            key = key.lower().replace(' ', '_')
            # Remove special characters (keeping alphanumeric and underscores)
            return re.sub(r'[^\w]', '', key)

        # Handle case when input is a dictionary
        if isinstance(df, dict):
            # Filter the dictionary to include only selected columns
            if selected_columns:
                return [{standardize_key(k): df.get(k, None) for k in selected_columns}]
            else:
                # If no columns selected, return all key-value pairs with standardized keys
                return [{standardize_key(k): v for k, v in df.items()}]

        # Handle case when df is None
        if df is None:
            return []

        # Ensure df is a DataFrame
        if not isinstance(df, pd.DataFrame):
            try:
                df = pd.DataFrame(df)
            except:
                return []  # Return empty list if conversion fails

        # Now check if DataFrame is empty
        if df.empty:
            return []

        # If no columns are specifically selected, use all available columns
        if not selected_columns or not isinstance(selected_columns, list) or len(selected_columns) == 0:
            selected_columns = list(df.columns)

        # Determine which columns exist in the DataFrame
        available_columns = []
        columns_lower = {col.lower(): col for col in df.columns if isinstance(col, str)}

        for col in selected_columns:
            if col in df.columns:
                available_columns.append(col)
            elif isinstance(col, str) and col.lower() in columns_lower:
                available_columns.append(columns_lower[col.lower()])

        # If no valid columns found, return empty list
        if not available_columns:
            return []

        # Process rows
        json_docs = []
        for _, row in df.iterrows():
            doc = {}
            for col in available_columns:
                value = row[col]
                # Standardize the column name when adding to document
                std_col = standardize_key(col)
                doc[std_col] = None if pd.isna(value) else value
            json_docs.append(doc)

        return json_docs

    def get_column_values(df, columns_to_include):
        """
        Extract values from specified columns of a dataframe as lists.

        Args:
            df: A pandas DataFrame
            columns_to_include: A list of column names to extract

        Returns:
            Dictionary with column names as keys and their values as lists
        """
        result = {}

        # Validate that columns exist in the dataframe
        valid_columns = [col for col in columns_to_include if col in df.columns]
        invalid_columns = set(columns_to_include) - set(valid_columns)

        if invalid_columns:
            print(f"Warning: These columns don't exist in the dataframe: {list(invalid_columns)}")

        # Extract values for each valid column
        for col in valid_columns:
            result[col] = df[col].tolist()

        return result

    def get_data_in_range(doc_dict_df, index_range, columns_to_include):
        """
        Extract values from specified columns of a dataframe within a given index range.

        Args:
            doc_dict_df: The pandas DataFrame to extract data from
            index_range: An integer specifying the number of rows to include (from 0 to index_range-1)
            columns_to_include: A list of column names to extract

        Returns:
            Dictionary with column names as keys and their values (within the index range) as lists
        """
        # Validate the index range
        max_index = len(doc_dict_df)
        if index_range <= 0:
            print(f"Warning: Invalid index range {index_range}. Must be positive.")
            return {}

        # Adjust index_range if it exceeds the dataframe length
        if index_range > max_index:
            print(f"Warning: Index range {index_range} exceeds dataframe length {max_index}. Using maximum length.")
            index_range = max_index

        # Slice the dataframe to get rows from 0 to index_range-1
        df_subset = doc_dict_df.iloc[:index_range]

        # Use the provided get_column_values function to extract column data
        return get_column_values(df_subset, columns_to_include)

    def get_data_in_range_triplequote(doc_dict_df, index_range, columns_to_include):
        """
        Extract values from specified columns of a dataframe within a given index range.
        Wraps string values with triple quotes and escapes URLs.

        Args:
            doc_dict_df: The pandas DataFrame to extract data from
            index_range: A list of two integers specifying the start and end indices of rows to include
                        (e.g., [0, 10] includes rows from index 0 to 9 inclusive)
            columns_to_include: A list of column names to extract
        """
        # Validate the index range
        start_idx, end_idx = index_range
        max_index = len(doc_dict_df)

        # Validate start index
        if start_idx < 0:
            print(f"Warning: Invalid start index {start_idx}. Using 0 instead.")
            start_idx = 0

        # Validate end index
        if end_idx <= start_idx:
            print(f"Warning: End index {end_idx} must be greater than start index {start_idx}. Using {start_idx + 1} instead.")
            end_idx = start_idx + 1

        # Adjust end index if it exceeds the dataframe length
        if end_idx > max_index:
            print(f"Warning: End index {end_idx} exceeds dataframe length {max_index}. Using maximum length.")
            end_idx = max_index

        # Slice the dataframe to get rows from start_idx to end_idx-1
        # Using .loc with slice to preserve original indices
        df_subset = doc_dict_df.iloc[start_idx:end_idx]

        # Use the provided get_column_values function to extract column data
        result = get_column_values(df_subset, columns_to_include)

        # Process each string result to wrap in triple quotes
        for col in result:
            if isinstance(result[col], list):
                # Create a new list with items wrapped in triple quotes
                processed_items = []
                for item in result[col]:
                    if isinstance(item, str):
                        # Replace http:// and https:// with escaped versions
                        item = item.replace("http://", "http\\://").replace("https://", "https\\://")
                        # processed_items.append('"""' + item + '"""')
                        processed_items.append(item)
                    else:
                        processed_items.append(item)
                result[col] = processed_items
        return result
    return (get_data_in_range_triplequote,)


@app.cell
def prepare_doc_select(sentence_splitter_config):
    def prepare_document_selection(node_dict):
        """
        Creates document selection UI component.
        Args:
            node_dict: Dictionary mapping filenames to lists of documents
        Returns:
            mo.ui component for document selection
        """
        # Calculate total number of documents across all files
        total_docs = sum(len(docs) for docs in node_dict.values())

        # Create a combined DataFrame of all documents for table selection
        all_docs_records = []
        doc_index_global = 0
        for filename, docs in node_dict.items():
            for i, doc in enumerate(docs):
                # Convert the document to a format compatible with DataFrame
                if hasattr(doc, 'to_dict'):
                    doc_data = doc.to_dict()
                elif isinstance(doc, dict):
                    doc_data = doc
                else:
                    doc_data = {'content': str(doc)}

                # Add metadata
                doc_data['filename'] = filename
                doc_data['doc_index'] = i
                doc_data['global_index'] = doc_index_global
                all_docs_records.append(doc_data)
                doc_index_global += 1

        # Create UI component
        stop_value = max(total_docs, 1)
        llama_docs = mo.ui.range_slider(
            start=1, 
            stop=stop_value, 
            step=1, 
            full_width=True, 
            show_value=True, 
            label="**Select a Range of Chunks to Visualize:**"
        ).form(submit_button_disabled=check_state(sentence_splitter_config.value))

        return llama_docs
    return (prepare_document_selection,)


@app.cell
def document_range_selection(
    dict_from_nodes,
    prepare_document_selection,
    set_range_slider_state,
):
    if dict_from_nodes is not None:
        llama_docs = prepare_document_selection(dict_from_nodes)
        set_range_slider_state(llama_docs)
    else:
        bare_dict = {}
        llama_docs = prepare_document_selection(bare_dict)
    return


@app.function
def create_cumulative_dataframe(dict_from_docs):
    """
    Creates a cumulative DataFrame from a nested dictionary of documents.

    Args:
        dict_from_docs: Dictionary mapping filenames to lists of documents

    Returns:
        DataFrame with all documents flattened with global indices
    """
    # Create a list to hold all document records
    all_records = []
    global_idx = 1  # Start from 1 to match range slider expectations

    for filename, docs in dict_from_docs.items():
        for i, doc in enumerate(docs):
            # Convert the document to a dict format
            if hasattr(doc, 'to_dict'):
                doc_data = doc.to_dict()
            elif isinstance(doc, dict):
                doc_data = doc.copy()
            else:
                doc_data = {'content': str(doc)}

            # Add additional metadata
            doc_data['filename'] = filename
            doc_data['doc_index'] = i
            doc_data['global_index'] = global_idx

            # If there's 'content' but no 'text', create a 'text' field
            if 'content' in doc_data and 'text' not in doc_data:
                doc_data['text'] = doc_data['content']

            all_records.append(doc_data)
            global_idx += 1

    # Create DataFrame from all records
    return pd.DataFrame(all_records)


@app.function
def create_stats(texts_dict, bordered=False, object_names=None, group_by_row=False, items_per_row=6, gap=2, label="Chunk"):
    """
    Create a list of stat objects for each item in the specified dictionary.

    Parameters:
    - texts_dict (dict): Dictionary containing the text data
    - bordered (bool): Whether the stats should be bordered
    - object_names (list or tuple): Two object names to use for label and value
                                   [label_object, value_object]
    - group_by_row (bool): Whether to group stats in rows (horizontal stacks)
    - items_per_row (int): Number of stat objects per row when group_by_row is True

    Returns:
    - object: A vertical stack of stat objects or rows of stat objects
    """
    if not object_names or len(object_names) < 2:
        raise ValueError("You must provide two object names as a list or tuple")

    label_object = object_names[0]
    value_object = object_names[1]

    # Validate that both objects exist in the dictionary
    if label_object not in texts_dict:
        raise ValueError(f"Label object '{label_object}' not found in texts_dict")
    if value_object not in texts_dict:
        raise ValueError(f"Value object '{value_object}' not found in texts_dict")

    # Determine how many items to process (based on the label object length)
    num_items = len(texts_dict[label_object])

    # Create individual stat objects
    individual_stats = []
    for i in range(num_items):
        stat = mo.stat(
            label=texts_dict[label_object][i],
            value=f"{label} Number: {len(texts_dict[value_object][i])}",
            bordered=bordered
        )
        individual_stats.append(stat)

    # If grouping is not enabled, just return a vertical stack of all stats
    if not group_by_row:
        return mo.vstack(individual_stats, wrap=False)

    # Group stats into rows based on items_per_row
    rows = []
    for i in range(0, num_items, items_per_row):
        # Get a slice of stats for this row (up to items_per_row items)
        row_stats = individual_stats[i:i+items_per_row]
        # Create a horizontal stack for this row
        widths = [0.35] * len(row_stats)
        row = mo.hstack(row_stats, gap=gap, align="start", justify="center", widths=widths)
        rows.append(row)

    # Return a vertical stack of all rows
    return mo.vstack(rows)


@app.cell
def prepare_chart_embeddings(
    chunks_to_process,
    emb_model,
    emb_model_emb_dim,
    get_embedding_state,
    prepare_embedding_data_3d,
):
    # chart_dataframe, chart_metadata = None, None
    if chunks_to_process is not None and get_embedding_state() is not None:
        chart_dataframe, chart_metadata = prepare_embedding_data_3d(
            get_embedding_state(), 
            chunks_to_process,
            model_id=emb_model,
            embedding_dimensions=emb_model_emb_dim
        )
    else:
        chart_dataframe, chart_metadata = None, None
    return chart_dataframe, chart_metadata


@app.cell
def chart_dims():
    chart_dimensions = (
        mo.md('''
        > **Adjust Chart Window**

        {chart_height}

        {chat_width}

        ''').batch(
                chart_height = mo.ui.slider(start=500, step=30, stop=1000, label="**Height:**", value=800, show_value=True),
                chat_width = mo.ui.slider(start=900, step=50, stop=1400, label="**Width:**", value=1200, show_value=True)
            )
    )
    return (chart_dimensions,)


@app.cell
def chart_dim_values(chart_dimensions):
    chart_height = chart_dimensions.value['chart_height']
    chart_width = chart_dimensions.value['chat_width']
    return chart_height, chart_width


@app.cell
def create_baseline_chart(
    chart_dataframe,
    chart_height,
    chart_metadata,
    chart_width,
    create_3d_embedding_chart,
):
    if chart_dataframe is not None and chart_metadata is not None:
        emb_plot = create_3d_embedding_chart(chart_dataframe, chart_metadata, chart_width, chart_height, marker_size_var=9)
        chart = mo.ui.plotly(emb_plot)
    else:
        emb_plot = None
        chart = None
    return (emb_plot,)


@app.cell
def test_query(get_chunk_state):
    placeholder = """How can i use watsonx.data to perform vector search?"""

    query = mo.ui.text_area(label="**Write text to check:**", full_width=True, rows=8, value=placeholder).form(show_clear_button=True, submit_button_disabled=check_state(get_chunk_state()))
    return (query,)


@app.cell
def query_stack(chart_dimensions, query):
    # query_stack = mo.hstack([query], justify="space-around", align="center", widths=[0.65])
    query_stack = mo.hstack([query, chart_dimensions], justify="space-around", align="center", gap=15)
    return (query_stack,)


@app.function
def check_state(variable):
    return variable is None


@app.cell
def helper_function_add_query_to_chart():
    def add_query_to_embedding_chart(existing_chart, query_coords, query_text, marker_size=12):
        """
        Add a query point to an existing 3D embedding chart as a large red dot.

        Args:
            existing_chart: The existing plotly figure or chart data
            query_coords: Dictionary with 'x', 'y', 'z' coordinates for the query point
            query_text: Text of the query to display on hover
            marker_size: Size of the query marker (default: 18, typically 2x other markers)

        Returns:
            A modified plotly figure with the query point added as a red dot
        """
        import plotly.graph_objects as go

        # Create a deep copy of the existing chart to avoid modifying the original
        import copy
        chart_copy = copy.deepcopy(existing_chart)

        # Handle case where chart_copy is a dictionary or list (from mo.ui.plotly)
        if isinstance(chart_copy, (dict, list)):
            # Create a new plotly figure from the data
            import plotly.graph_objects as go

            if isinstance(chart_copy, list):
                # If it's a list, assume it's a list of traces
                fig = go.Figure(data=chart_copy)
            else:
                # If it's a dict with 'data' and 'layout'
                fig = go.Figure(data=chart_copy.get('data', []), layout=chart_copy.get('layout', {}))

            chart_copy = fig

        # Create the query trace
        query_trace = go.Scatter3d(
            x=[query_coords['x']],
            y=[query_coords['y']],
            z=[query_coords['z']],
            mode='markers',
            name='Query',
            marker=dict(
                size=marker_size,  # Typically 2x the size of other markers
                color='red',       # Bright red color
                symbol='circle',   # Circle shape
                opacity=0.70,       # Fully opaque
                line=dict(
                    width=1,       # Thin white border
                    color='white'
                )
            ),
            # text=['Query: ' + query_text],
            text=['<b>Query:</b><br>' + '<br>'.join([query_text[i:i+50] for i in range(0, len(query_text), 50)])], ### Text Wrapping
            hoverinfo="text+name"
        )

        # Add the query trace to the chart copy
        chart_copy.add_trace(query_trace)

        return chart_copy


    def get_query_coordinates(reference_embeddings=None, query_embedding=None):
        """
        Calculate appropriate coordinates for a query point based on reference embeddings.

        This function handles several scenarios:
        1. If both reference embeddings and query embedding are provided, it places the
           query near similar documents.
        2. If only reference embeddings are provided, it places the query at a visible 
           location near the center of the chart.
        3. If neither are provided, it returns default origin coordinates.

        Args:
            reference_embeddings: DataFrame with x, y, z coordinates from the main chart
            query_embedding: The embedding vector of the query

        Returns:
            Dictionary with x, y, z coordinates for the query point
        """
        import numpy as np

        # Default coordinates (origin with slight offset)
        default_coords = {'x': 0.0, 'y': 0.0, 'z': 0.0}

        # If we don't have reference embeddings, return default
        if reference_embeddings is None or len(reference_embeddings) == 0:
            return default_coords

        # If we have reference embeddings but no query embedding, 
        # position at a visible location near the center
        if query_embedding is None:
            center_coords = {
                'x': reference_embeddings['x'].mean(),
                'y': reference_embeddings['y'].mean(),
                'z': reference_embeddings['z'].mean()
            }
            return center_coords

        # If we have both reference embeddings and query embedding,
        # try to position near similar documents
        try:
            from sklearn.metrics.pairwise import cosine_similarity

            # Check if original embeddings are in the dataframe
            if 'embedding' in reference_embeddings.columns:
                # Get all document embeddings as a 2D array
                if isinstance(reference_embeddings['embedding'].iloc[0], list):
                    doc_embeddings = np.array(reference_embeddings['embedding'].tolist())
                else:
                    doc_embeddings = np.array([emb for emb in reference_embeddings['embedding'].values])

                # Reshape query embedding for comparison
                query_emb_array = np.array(query_embedding)
                if query_emb_array.ndim == 1:
                    query_emb_array = query_emb_array.reshape(1, -1)

                # Calculate cosine similarities
                similarities = cosine_similarity(query_emb_array, doc_embeddings)[0]

                # Find the closest document
                closest_idx = np.argmax(similarities)

                # Use the position of the closest document, with slight offset for visibility
                query_coords = {
                    'x': reference_embeddings['x'].iloc[closest_idx] + 0.2,
                    'y': reference_embeddings['y'].iloc[closest_idx] + 0.2,
                    'z': reference_embeddings['z'].iloc[closest_idx] + 0.2
                }
                return query_coords
        except Exception as e:
            print(f"Error positioning query near similar documents: {e}")

        # Fallback to center position if similarity calculation fails
        center_coords = {
            'x': reference_embeddings['x'].mean(),
            'y': reference_embeddings['y'].mean(),
            'z': reference_embeddings['z'].mean()
        }
        return center_coords
    return add_query_to_embedding_chart, get_query_coordinates


@app.cell
def combined_chart_visualization(
    add_query_to_embedding_chart,
    chart_dataframe,
    emb_plot,
    embedding,
    get_query_coordinates,
    get_query_state,
    query,
    set_chart_state,
    set_query_state,
):
    # Usage with highlight_closest=True
    if chart_dataframe is not None and query.value:
        with mo.status.spinner(title="Embedding Query...", remove_on_exit=True) as _spinner:
                query_emb = embedding.embed_documents([query.value])
                set_query_state(query_emb)
        
                _spinner.update("Preparing Query Coordinates") # --- --- ---
                time.sleep(1.0)
        
                # Get appropriate coordinates for the query
                query_coords = get_query_coordinates(
                    reference_embeddings=chart_dataframe,
                    query_embedding=get_query_state()
                )

                _spinner.update("Adding Query to Chart") # --- --- ---
                time.sleep(1.0)
        
                # Add the query to the chart with closest points highlighted
                result = add_query_to_embedding_chart(
                    existing_chart=emb_plot,
                    query_coords=query_coords,
                    query_text=query.value,
                )
        
                chart_with_query = result
        
                _spinner.update("Preparing Visualization") # --- --- ---
                time.sleep(1.0)
        
                # Create the visualization
                combined_viz = mo.ui.plotly(chart_with_query)
                set_chart_state(combined_viz)
        
                _spinner.update("Done") # --- --- ---
    else:
        combined_viz = None
    return


@app.cell
def _():
    get_range_slider_state, set_range_slider_state = mo.state(None)
    return get_range_slider_state, set_range_slider_state


@app.cell
def _(get_range_slider_state):
    if get_range_slider_state() is not None:
        document_range_stack = get_range_slider_state()
    else:
        document_range_stack = None
    return (document_range_stack,)


@app.cell
def _():
    get_chart_state, set_chart_state = mo.state(None)
    return get_chart_state, set_chart_state


@app.cell
def _(get_chart_state, query):
    if query.value is not None:
        chart_visualization = get_chart_state()
    else:
        chart_visualization = None
    return (chart_visualization,)


@app.cell
def c(document_range_stack):
    chart_range_selection = mo.hstack([document_range_stack], justify="space-around", align="center", widths=[0.65])
    return (chart_range_selection,)


if __name__ == "__main__":
    app.run()