File size: 93,403 Bytes
557ed35 8d66edb 557ed35 8d66edb c851db9 8d66edb 557ed35 8d66edb 557ed35 8d66edb 557ed35 8d66edb 557ed35 8d66edb 557ed35 8d66edb 7d720da 1d36204 c1035e2 1d36204 a29d97d 580e3ba c1035e2 a29d97d c1035e2 295ab37 c1035e2 295ab37 1d36204 a29d97d c1035e2 1d36204 c1035e2 7d720da 580e3ba 7d720da 580e3ba 7d720da 3610a6a 7d720da 8d66edb 557ed35 eab2534 557ed35 8d66edb 557ed35 8d66edb 557ed35 8d66edb 557ed35 7d720da 557ed35 3d1df6e | 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 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 | # server.R
library(shiny)
library(readxl)
library(DT)
library(dplyr)
# Source the warning overlay and long operations code
source("warning_overlay.R", local = TRUE)
source("long_operations.R", local = TRUE)
source("auth/hf_oauth.R", local = TRUE)
source("utils/supabase_r.R", local = TRUE)
# setwd("/Users/audrey/Downloads/research/ckweb/Tcellstates")
# Define server logic
function(input, output, session) {
# --- START: Environment Variable Diagnostic ---
print("=== Environment Variables Diagnostic ===")
all_env <- Sys.getenv()
# Print only relevant environment variables (filter sensitive ones)
relevant_vars <- c("SUPABASE_URL", "SUPABASE_KEY", "OAUTH_CLIENT_ID", "OAUTH_CLIENT_SECRET",
"SPACE_HOST", "SPACE_ID", "HF_TOKEN")
for (var_name in relevant_vars) {
var_value <- Sys.getenv(var_name, unset = "NOT_SET")
if (var_name %in% c("SUPABASE_KEY", "OAUTH_CLIENT_SECRET", "HF_TOKEN")) {
# Mask sensitive values
print(paste(var_name, ":", if(var_value == "NOT_SET") "NOT_SET" else "[REDACTED]"))
} else {
print(paste(var_name, ":", var_value))
}
}
print("========================================")
# --- END: Environment Variable Diagnostic ---
# --- START: OAuth and Supabase Initialization ---
oauth_config <- initialize_oauth()
supabase_client <- initialize_supabase()
# --- END: OAuth and Supabase Initialization ---
# --- START: TaijiChat R Callback for Python Agent Thoughts ---
python_agent_thought_callback <- function(thought_message_from_python) {
# Attempt to explicitly convert to R character and clean up
thought_message_text <- tryCatch({
as.character(thought_message_from_python)[1] # Take the first element after converting
}, error = function(e) {
print(paste("R Callback: Error converting thought to character:", e$message))
return(NULL)
})
if (!is.null(thought_message_text) && is.character(thought_message_text) && length(thought_message_text) == 1 && nzchar(trimws(thought_message_text))) {
# print(paste("R Callback: Valid thought from Python -", thought_message_text)) # For R console debugging
session$sendCustomMessage(type = "agent_new_thought", message = list(text = trimws(thought_message_text)))
} else {
# Log the original and potentially converted type for better debugging
print(paste("R Callback: Received invalid or empty thought. Original type:", class(thought_message_from_python), ", Value:", thought_message_from_python, ", Converted text:", thought_message_text))
}
}
# --- END: TaijiChat R Callback for Python Agent Thoughts ---
# --- START: TaijiChat Agent Initialization ---
# This assumes manager_agent_module is globally available from ui.R's sourcing.
# ui.R does: manager_agent_module <- reticulate::import("agents.manager_agent")
api_key_val <- NULL
# First try to get API key from environment variable
api_key_val <- Sys.getenv("OPENAI_API_KEY")
# If environment variable is not set, try reading from file
if (api_key_val == "") {
tryCatch({
api_key_content <- readLines("api_key.txt", warn = FALSE)
if (length(api_key_content) > 0 && nzchar(trimws(api_key_content[1]))) {
api_key_val <- trimws(api_key_content[1])
print("TaijiChat: API key successfully read from file in server.R.")
} else {
warning("TaijiChat: api_key.txt is empty or not found. LLM features may be disabled.")
print("TaijiChat: api_key.txt is empty or not found.")
}
}, error = function(e) {
warning(paste("TaijiChat: Error reading api_key.txt in server.R:", e$message))
print(paste("TaijiChat: Error reading api_key.txt:", e$message))
})
} else {
print("TaijiChat: API key successfully read from environment variable.")
}
py_openai_client_instance <- NULL
if (!is.null(api_key_val)) {
tryCatch({
# Ensure reticulate is configured to use the correct Python environment
if (reticulate::py_available(initialize = TRUE)) {
openai_py_module <- reticulate::import("openai", convert = FALSE) # convert=FALSE for raw Python objects
py_openai_client_instance <- openai_py_module$OpenAI(api_key = api_key_val)
print("TaijiChat: Python OpenAI client initialized successfully in server.R via reticulate.")
} else {
warning("TaijiChat: Python (reticulate) not available or not initialized. Cannot create OpenAI client.")
print("TaijiChat: Python (reticulate) not available. Cannot create OpenAI client.")
}
}, error = function(e) {
warning(paste("TaijiChat: Failed to initialize Python OpenAI client in server.R:", e$message))
print(paste("TaijiChat: Failed to initialize Python OpenAI client:", e$message))
py_openai_client_instance <- NULL
})
} else {
print("TaijiChat: API key is NULL, skipping Python OpenAI client initialization.")
}
rv_agent_instance <- reactiveVal(NULL)
# Attempt to create the agent instance once.
current_manager_agent_module <- NULL
tryCatch({
# Force reload the module to ensure we get the latest version
print("TaijiChat: Attempting to reload Python modules to ensure latest version...")
reticulate::py_run_string("
import sys
import importlib
if 'agents.manager_agent' in sys.modules:
print('Reloading agents.manager_agent module...')
importlib.reload(sys.modules['agents.manager_agent'])
")
current_manager_agent_module <- reticulate::import("agents.manager_agent", convert = FALSE)
if (is.null(current_manager_agent_module)) {
warning("TaijiChat: reticulate::import('agents.manager_agent') returned NULL in server.R.")
print("TaijiChat: reticulate::import('agents.manager_agent') returned NULL in server.R.")
} else {
print("TaijiChat: Successfully imported/retrieved 'agents.manager_agent' module in server.R.")
}
}, error = function(e) {
warning(paste("TaijiChat: Failed to import agents.manager_agent in server.R:", e$message))
print(paste("TaijiChat: Failed to import agents.manager_agent in server.R:", e$message))
})
if (!is.null(current_manager_agent_module)) {
# Module is available, now try to instantiate the agent
if (!is.null(py_openai_client_instance)) {
tryCatch({
supabase_py_client <- if (!is.null(supabase_client)) supabase_client else NULL
agent_inst <- current_manager_agent_module$ManagerAgent(
openai_client = py_openai_client_instance,
r_callback_fn = python_agent_thought_callback,
supabase_client = supabase_py_client,
user_id = NULL,
hf_user_id = NULL
)
rv_agent_instance(agent_inst)
print("TaijiChat: Python ManagerAgent instance created in server.R using pre-initialized client and R callback.")
}, error = function(e) {
warning(paste("TaijiChat: Failed to instantiate ManagerAgent in server.R with client & callback:", e$message))
print(paste("TaijiChat: Failed to instantiate ManagerAgent with client & callback:", e$message))
})
} else if (!is.null(api_key_val)) { # Try with API key if client object failed but key exists
tryCatch({
supabase_py_client <- if (!is.null(supabase_client)) supabase_client else NULL
agent_inst <- current_manager_agent_module$ManagerAgent(
openai_api_key = api_key_val,
r_callback_fn = python_agent_thought_callback,
supabase_client = supabase_py_client,
user_id = NULL,
hf_user_id = NULL
)
rv_agent_instance(agent_inst)
print("TaijiChat: Python ManagerAgent instance created in server.R with API key and R callback (client to be init by Python).")
}, error = function(e) {
warning(paste("TaijiChat: Failed to instantiate ManagerAgent with API key & callback in server.R:", e$message))
print(paste("TaijiChat: Failed to instantiate ManagerAgent with API key & callback:", e$message))
})
} else {
# Neither client nor API key is available for the agent
warning("TaijiChat: Cannot create ManagerAgent instance: OpenAI client/API key not available for agent constructor.")
print("TaijiChat: Cannot create ManagerAgent: OpenAI client/API key not available for agent constructor.")
}
} else {
# Module itself could not be imported/retrieved
warning("TaijiChat: agents.manager_agent module is NULL after import attempt. Agent not created.")
print("TaijiChat: agents.manager_agent module is NULL after import attempt. Agent not created.")
}
# --- END: TaijiChat Agent Initialization ---
# --- START: Authentication Handlers ---
# Handle login button click - generate OAuth URL (only once)
observeEvent(input$hfSignInBtn, {
req(input$hfSignInBtn)
# Check if we're in OAuth callback (code in URL)
query_string <- parseQueryString(session$clientData$url_search)
if (!is.null(query_string$code)) {
print("OAuth: In callback, skipping button redirect")
return()
}
if (!oauth_config$enabled) {
print("OAuth: Not enabled")
return()
}
print(paste("OAuth: Button clicked, count:", input$hfSignInBtn))
# Generate random state for CSRF protection
state <- generate_oauth_state()
session$userData$oauth_state <- state
# Get base URL - use SPACE_HOST if available (HF Spaces), otherwise use client URL
space_host <- Sys.getenv("SPACE_HOST", "")
if (space_host != "") {
redirect_uri <- paste0("https://", space_host)
} else {
redirect_uri <- paste0(session$clientData$url_protocol, "//",
session$clientData$url_hostname,
if (session$clientData$url_port != "") paste0(":", session$clientData$url_port) else "")
}
print(paste("OAuth: Redirect URI:", redirect_uri))
# Generate authorization URL
auth_url <- get_authorization_url(oauth_config, redirect_uri, state)
if (!is.null(auth_url)) {
print(paste("OAuth: Redirecting to:", auth_url))
# Send redirect message to JavaScript
session$sendCustomMessage(type = 'redirect_to_oauth', message = list(url = auth_url))
}
}, ignoreInit = TRUE, once = TRUE)
# Send initial auth state on session start
# Don't send if we're in OAuth callback (will be handled after auth completes)
observe({
isolate({
# Check if we're in OAuth callback by looking at URL parameters
query_string <- parseQueryString(session$clientData$url_search)
if (is.null(query_string$code)) {
# No OAuth code in URL, show login overlay
session$sendCustomMessage('auth_state', list(authenticated = FALSE))
}
})
})
# OAuth callback handler
observeEvent(input$oauth_code, {
if (!oauth_config$enabled || is.null(supabase_client)) {
print("OAuth: Not enabled or Supabase not configured")
return()
}
tryCatch({
# Get redirect URI - must match exactly what was used in authorization request
space_host <- Sys.getenv("SPACE_HOST", "")
if (space_host != "") {
redirect_uri <- paste0("https://", space_host)
} else {
redirect_uri <- paste0(session$clientData$url_protocol, "//",
session$clientData$url_hostname,
if (session$clientData$url_port != "") paste0(":", session$clientData$url_port) else "")
}
print(paste("OAuth: Token exchange using redirect_uri:", redirect_uri))
# Exchange code for token
token_result <- exchange_code_for_token(oauth_config, input$oauth_code, redirect_uri)
if (is.null(token_result)) {
print("OAuth: Failed to exchange code for token")
return()
}
# Get user info from HF
user_info <- get_user_info(token_result$access_token)
if (is.null(user_info)) {
print("OAuth: Failed to get user info")
return()
}
# Create or retrieve user in Supabase
supabase_user <- get_or_create_user(
supabase_client,
user_info$hf_user_id,
user_info$hf_username,
user_info$email
)
if (is.null(supabase_user)) {
print("OAuth: Failed to create/retrieve user in Supabase")
return()
}
# Store in session
session$userData$hf_user <- user_info
session$userData$supabase_user <- supabase_user
session$userData$access_token <- token_result$access_token
print(paste("OAuth: User authenticated -", user_info$hf_username))
# Hide login overlay
session$sendCustomMessage('auth_state', list(authenticated = TRUE))
# Show user info with quota
tokens_used <- supabase_user$tokens_used %||% 0
token_quota <- supabase_user$token_quota %||% 100000
quota_text <- paste(tokens_used, "/", token_quota)
session$sendCustomMessage('update_user_info', list(
username = user_info$hf_username,
quota = quota_text
))
}, error = function(e) {
print(paste("OAuth: Error in callback handler -", e$message))
})
})
# Logout handler
observeEvent(input$logoutBtn, {
logout_user(session)
session$sendCustomMessage('auth_state', list(authenticated = FALSE))
print("OAuth: User logged out")
})
# --- END: Authentication Handlers ---
# Server logic for home tab
output$home <- renderText({
"Welcome to the Home page"
})
observeEvent(input$read_now, {
# Trigger a redirect using JavaScript
session$sendCustomMessage(type = "redirect",
message = "https://doi.org/10.1101/2023.01.03.522354")
})
# NEW READ EXCEL FILE FOR TRANSPOSED DATASET
new_read_excel_file <- function(path) {
df <- read_excel(path)
colnames(df)[1] <- "Regulator Names"
# Transpose the dataframe
df_transposed <- as.data.frame(t(df))
# Fix the column names of the transposed dataframe (optional)
colnames(df_transposed) <- df_transposed[1, ] # Set first row as column names
df_transposed <- df_transposed[-1, ] # Remove the first row which is now used as column names
return(df_transposed)
}
# # NEW FILTER FUNCTION FOR TRANSPOSED DATASET
# new_filter_data <- function(df, keyword) {
#
# # Find the columns whose names contain the keyword
# matching_columns <- grepl(keyword, colnames(df), ignore.case = TRUE)
#
# # Check if any matching columns exist
# if (sum(matching_columns) == 0) {
# # If no matching columns are found, return an empty dataframe with proper structure
# return(data.frame())
# }
#
# # Subset the dataframe, ensuring the result is always a dataframe
# filtered_df <- df[, matching_columns, drop = FALSE]
#
# return(filtered_df)
# }
#NEW FILTER FUNCTION FOR MULTIPLE GENE SEARCH
# new_filter_data <- function(df, keywords) {
# # Split the keywords by commas and remove any leading/trailing whitespace
# keyword_list <- strsplit(keywords, ",")[[1]]
# keyword_list <- trimws(keyword_list)
#
# # Initialize an empty logical vector for matching columns
# matching_columns <- rep(FALSE, ncol(df))
#
# # Loop through each keyword and update the matching_columns vector
# for (keyword in keyword_list) {
# matching_columns <- matching_columns | grepl(keyword, colnames(df), ignore.case = TRUE)
# }
#
# # Check if any matching columns exist
# if (sum(matching_columns) == 0) {
# # If no matching columns are found, return an empty dataframe with proper structure
# return(data.frame())
# }
#
# # Subset the dataframe, ensuring the result is always a dataframe
# filtered_df <- df[, matching_columns, drop = FALSE]
#
# return(filtered_df)
# }
new_filter_data <- function(df, keywords) {
# If no keywords are provided, return the full dataset
if (is.null(keywords) || keywords == "") {
return(df)
}
# Split the keywords by commas and remove any leading/trailing whitespace
keyword_list <- strsplit(keywords, ",")[[1]]
keyword_list <- trimws(keyword_list) # Remove leading/trailing spaces
# Initialize an empty logical vector for matching columns
matching_columns <- rep(FALSE, ncol(df))
# Loop through each keyword and update the matching_columns vector
for (keyword in keyword_list) {
matching_columns <- matching_columns | grepl(keyword, colnames(df), ignore.case = TRUE)
}
# Check if any matching columns exist
if (sum(matching_columns) == 0) {
# If no matching columns are found, return an empty dataframe
return(data.frame())
}
# Subset the dataframe, ensuring the result is always a dataframe
filtered_df <- df[, matching_columns, drop = FALSE]
return(filtered_df)
}
# TESTING FUNCTIONS
#NEW ALL DATA SEARCH
data <- reactive({
new_read_excel_file("www/tablePagerank/Table_TF PageRank Scores for Audrey.xlsx")
})
# Track the current column page
column_page <- reactiveVal(1)
# Reset the column page when the search input changes for main page data
observeEvent(input$search_input, {
column_page(1) # Reset to page 1 when a new search is made
})
# Update the column page when buttons are clicked
observeEvent(input$next_btn, {
current_page <- column_page()
total_cols <- ncol(new_filter_data(data(), input$search_input))
# Calculate the maximum possible number of pages
max_page <- ceiling(total_cols / 4)
# Move to the next page, but do not exceed the max_page
if (current_page < max_page) {
column_page(current_page + 1)
}
# new_page <- column_page() + 1
# column_page(new_page)
})
observeEvent(input$prev_btn, {
current_page <- column_page()
column_page(max(current_page - 1, 1))
# new_page <- max(column_page() - 1, 1) # Ensure the page does not go below 1
# column_page(new_page)
})
# # OLD: Reactive for filtering the data based on input$search_input
# new_filtered_data <- reactive({
#
# df <- new_filter_data(data(), input$search_input)
#
# # Get the total number of columns in the filtered dataframe
# total_cols <- ncol(df)
#
# # Ensure there are columns after filtering
# if (total_cols == 0) {
# return(data.frame()) # Return an empty dataframe if no columns match the search
# }
#
# # Define the start and end index for columns based on the current page
# start_col <- (column_page() - 1) * 4 + 1
# end_col <- min(start_col + 3, total_cols) # Show up to 4 columns
#
# # Ensure start_col is within the number of columns
# if (start_col > total_cols) {
# return(df) # Return the filtered dataframe as-is if start_col exceeds the number of columns
# }
#
# # Subset the columns for the current page
# df_subset <- df[, start_col:end_col, drop = FALSE]
# return(df_subset)
# })
#NEW FILTER DATA TO INCLUDE ADDITIONAL DESCRIPTION ROW + WORKS WITH SEARCHING INDIVIDUAL GENES
new_filtered_data <- reactive({
# Filter the data and determine the total number of columns
df <- new_filter_data(data(), input$search_input)
total_cols <- ncol(df)
# Return empty dataframe if no columns match the search
if (total_cols == 0) return(data.frame())
# Define the column range for the current page
start_col <- (column_page() - 1) * 4 + 1
end_col <- min(start_col + 3, total_cols)
# Return filtered data if start_col exceeds the total columns
if (start_col > total_cols) return(df)
# Subset the dataframe for the current page
df_subset <- df[, start_col:end_col, drop = FALSE]
# Apply HTML formatting to description and "Cell state data" rows
if (nrow(df_subset) >= 2) {
description_row <- data.frame(
matrix(NA, nrow = 1, ncol = ncol(df_subset), dimnames = list(NULL, colnames(df_subset)))
)
# Define the HTML style for the description row (making "TF activity score" bold)
style <- "<h5 style='font-weight: bold;'>TF activity score</h5>"
# Apply style to both description and "Cell state data"
description_row[1, ] <- style
rownames(description_row)[1] <- "Cell state data"
# Combine the data with the description and styled "Cell state data" row
df_subset <- rbind(df_subset[1:2, , drop = FALSE], description_row, df_subset[-(1:2), , drop = FALSE])
}
# Return the data with HTML rendering enabled, show all 45 rows, and remove the search box
DT::datatable(df_subset, escape = FALSE, options = list(
pageLength = 45,
lengthChange = FALSE,
searching = FALSE, # Remove the search box
rowCallback = JS(
"function(row, data, index) {
var highlightedRow = 2; // Adjust this index to the row you want highlighted
if (index === highlightedRow) {
$('td', row).css({
'background-color': '#95a5a6',
'color': 'white',
'font-weight': 'bold'
});
}
}"
)
))
})
# Rendering the filtered data table and showing all rows
output$table <- renderDT({
new_filtered_data()
}, options = list(pageLength = nrow(new_filtered_data()), dom = 't'))
#NEW NAIVE SEARCH
naive_data <- reactive({
new_read_excel_file("www/tablePagerank/Naive.xlsx")
})
# Track the current column page for naive data
naive_column_page <- reactiveVal(1)
# Reset the column page when the search input changes for naive data
observeEvent(input$search_input_naive, {
naive_column_page(1) # Reset to page 1 when a new search is made
})
# Reset the column page when the search input changes for naive data
observeEvent(input$search_input_naive, {
naive_column_page(1) # Reset to page 1 when a new search is made
})
# Update the column page when buttons are clicked for naive data
observeEvent(input$naive_next_btn, {
current_page <- naive_column_page()
total_cols <- ncol(new_filter_data(naive_data(), input$search_input_naive))
# Calculate the maximum possible number of pages
max_page <- ceiling(total_cols / 4)
# Move to the next page, but do not exceed the max_page
if (current_page < max_page) {
naive_column_page(current_page + 1)
}
# new_page <- naive_column_page() + 1
# naive_column_page(new_page)
})
observeEvent(input$naive_prev_btn, {
current_page <- naive_column_page()
naive_column_page(max(current_page - 1, 1))
# new_page <- max(naive_column_page() - 1, 1) # Ensure the page does not go below 1
# naive_column_page(new_page)
})
#OLD FILTERED DATA
# filtered_naive_data <- reactive({
#
# df <- new_filter_data(naive_data(), input$search_input_naive)
#
# # Get the total number of columns in the filtered dataframe
# total_cols <- ncol(df)
#
# # Ensure there are columns after filtering
# if (total_cols == 0) {
# return(data.frame()) # Return an empty dataframe if no columns match the search
# }
#
# # Define the start and end index for columns based on the current page
# start_col <- (naive_column_page() - 1) * 4 + 1
# end_col <- min(start_col + 3, total_cols) # Show up to 4 columns
#
# # Ensure start_col is within the number of columns
# if (start_col > total_cols) {
# return(df) # Return the filtered dataframe as-is if start_col exceeds the number of columns
# }
#
# # Subset the columns for the current page
# df_subset <- df[, start_col:end_col, drop = FALSE]
# return(df_subset)
# })
#NEW FILTERED DATA
filtered_naive_data <- reactive({
# Filter the naive data and determine the total number of columns
df <- new_filter_data(naive_data(), input$search_input_naive)
total_cols <- ncol(df)
# Return empty dataframe if no columns match the search
if (total_cols == 0) return(data.frame())
# Define the column range for the current page
start_col <- (naive_column_page() - 1) * 4 + 1
end_col <- min(start_col + 3, total_cols)
# Return filtered data if start_col exceeds the total columns
if (start_col > total_cols) return(df)
# Subset the dataframe for the current page
df_subset <- df[, start_col:end_col, drop = FALSE]
# Apply HTML formatting to description and "Cell state data" rows, moving them to the first row
if (nrow(df_subset) >= 2) {
description_row <- data.frame(
matrix(NA, nrow = 1, ncol = ncol(df_subset), dimnames = list(NULL, colnames(df_subset)))
)
# Define the HTML style for the description row (making "TF activity score" bold with white font and background color)
style <- "<h5 style='font-weight: bold; color: white;'>TF activity score</h5>"
# Apply style to both description and "Cell state data"
description_row[1, ] <- style
rownames(description_row)[1] <- "Cell state data"
# Move the description row to the first row of the subset
df_subset <- rbind(description_row, df_subset) # Move this styled row to the first position
}
# Return the data with HTML rendering enabled, show all 45 rows, and remove the search box
DT::datatable(df_subset, escape = FALSE, options = list(
pageLength = 45,
lengthChange = FALSE,
searching = FALSE, # Remove the search box
rowCallback = JS(
"function(row, data, index) {
var highlightedRow = 0; // Apply styling to the first row
if (index === highlightedRow) {
$('td', row).css({
'background-color': '#95a5a6',
'color': 'white',
'font-weight': 'bold'
});
}
}"
)
))
})
output$table_naive <- renderDT({
filtered_naive_data()
}, options = list(pageLength = nrow(filtered_naive_data()), dom = 't'))
#NEW TE SEARCH
te_data <- reactive({
new_read_excel_file("www/tablePagerank/TE.xlsx")
})
# Track the current column page for "te" data
te_column_page <- reactiveVal(1)
# Reset the column page when the search input changes for "te" data
observeEvent(input$search_input_te, {
te_column_page(1) # Reset to page 1 when a new search is made
})
# Update the column page when buttons are clicked for "te" data
observeEvent(input$te_next_btn, {
current_page <- te_column_page()
total_cols <- ncol(new_filter_data(te_data(), input$search_input_te))
# Calculate the maximum possible number of pages
max_page <- ceiling(total_cols / 4)
# Move to the next page, but do not exceed the max_page
if (current_page < max_page) {
te_column_page(current_page + 1)
}
})
observeEvent(input$te_prev_btn, {
current_page <- te_column_page()
te_column_page(max(current_page - 1, 1)) # Ensure the page does not go below 1
})
#OLD: Reactive for filtering and paginating the "te" page data
# filtered_te_data <- reactive({
# df <- new_filter_data(te_data(), input$search_input_te)
#
# # Get the total number of columns in the filtered dataframe
# total_cols <- ncol(df)
#
# # Ensure there are columns after filtering
# if (total_cols == 0) {
# return(data.frame()) # Return an empty dataframe if no columns match the search
# }
#
# # Define the start and end index for columns based on the current page
# start_col <- (te_column_page() - 1) * 4 + 1
# end_col <- min(start_col + 3, total_cols) # Show up to 4 columns
#
# # If start_col exceeds the total number of columns, return the last valid subset
# if (start_col > total_cols) {
# start_col <- (ceiling(total_cols / 4) - 1) * 4 + 1 # Set start_col to the last valid page
# end_col <- total_cols # End with the last column
# }
#
# # Subset the columns for the current page
# df_subset <- df[, start_col:end_col, drop = FALSE]
#
# return(df_subset)
# })
#NEW FILTERED DATA
filtered_te_data <- reactive({
# Filter the TE data and determine the total number of columns
df <- new_filter_data(te_data(), input$search_input_te)
total_cols <- ncol(df)
# Return empty dataframe if no columns match the search
if (total_cols == 0) return(data.frame())
# Define the column range for the current page
start_col <- (te_column_page() - 1) * 4 + 1
end_col <- min(start_col + 3, total_cols)
# Return filtered data if start_col exceeds the total columns
if (start_col > total_cols) return(df)
# Subset the dataframe for the current page
df_subset <- df[, start_col:end_col, drop = FALSE]
# Apply HTML formatting to description and "Cell state data" rows, moving them to the first row
if (nrow(df_subset) >= 2) {
description_row <- data.frame(
matrix(NA, nrow = 1, ncol = ncol(df_subset), dimnames = list(NULL, colnames(df_subset)))
)
# Define the HTML style for the description row (making "TF activity score" bold with white font and background color)
style <- "<h5 style='font-weight: bold; color: white;'>TF activity score</h5>"
# Apply style to both description and "Cell state data"
description_row[1, ] <- style
rownames(description_row)[1] <- "Cell state data"
# Move the description row to the first row of the subset
df_subset <- rbind(description_row, df_subset) # Move this styled row to the first position
}
# Return the data with HTML rendering enabled, show all 45 rows, and remove the search box
DT::datatable(df_subset, escape = FALSE, options = list(
pageLength = 45,
lengthChange = FALSE,
searching = FALSE, # Remove the search box
rowCallback = JS(
"function(row, data, index) {
var highlightedRow = 0; // Apply styling to the first row
if (index === highlightedRow) {
$('td', row).css({
'background-color': '#95a5a6',
'color': 'white',
'font-weight': 'bold'
});
}
}"
)
))
})
# Rendering the filtered "te" page data table and showing all rows
output$table_te <- renderDT({
filtered_te_data() # Use the filtered data with pagination logic applied
}, options = list(
pageLength = nrow(filtered_te_data()), # Show all rows
dom = 't', # Remove the row length dropdown
scrollX = TRUE # Enable horizontal scrolling if needed
))
#NEW MP SEARCH
mp_data <- reactive({
new_read_excel_file("www/tablePagerank/MP.xlsx")
})
# Track the current column page for "mp" data
mp_column_page <- reactiveVal(1)
# Reset the column page when the search input changes for "mp" data
observeEvent(input$search_input_mp, {
mp_column_page(1) # Reset to page 1 when a new search is made
})
# Update the column page when buttons are clicked for "mp" data
observeEvent(input$mp_next_btn, {
current_page <- mp_column_page()
total_cols <- ncol(new_filter_data(mp_data(), input$search_input_mp))
# Calculate the maximum possible number of pages
max_page <- ceiling(total_cols / 4)
# Move to the next page, but do not exceed the max_page
if (current_page < max_page) {
mp_column_page(current_page + 1)
}
})
observeEvent(input$mp_prev_btn, {
current_page <- mp_column_page()
mp_column_page(max(current_page - 1, 1)) # Ensure the page does not go below 1
})
#OLD: Reactive for filtering and paginating the "mp" page data
# filtered_mp_data <- reactive({
# df <- new_filter_data(mp_data(), input$search_input_mp)
#
# # Get the total number of columns in the filtered dataframe
# total_cols <- ncol(df)
#
# # Ensure there are columns after filtering
# if (total_cols == 0) {
# return(data.frame()) # Return an empty dataframe if no columns match the search
# }
#
# # Define the start and end index for columns based on the current page
# start_col <- (mp_column_page() - 1) * 4 + 1
# end_col <- min(start_col + 3, total_cols) # Show up to 4 columns
#
# # If start_col exceeds the total number of columns, return the last valid subset
# if (start_col > total_cols) {
# start_col <- (ceiling(total_cols / 4) - 1) * 4 + 1 # Set start_col to the last valid page
# end_col <- total_cols # End with the last column
# }
#
# # Subset the columns for the current page
# df_subset <- df[, start_col:end_col, drop = FALSE]
#
# return(df_subset)
# })
#NEW FILTERED DATA
filtered_mp_data <- reactive({
# Filter the MP data and determine the total number of columns
df <- new_filter_data(mp_data(), input$search_input_mp)
total_cols <- ncol(df)
# Return empty dataframe if no columns match the search
if (total_cols == 0) return(data.frame())
# Define the column range for the current page
start_col <- (mp_column_page() - 1) * 4 + 1
end_col <- min(start_col + 3, total_cols)
# Return filtered data if start_col exceeds the total columns
if (start_col > total_cols) return(df)
# Subset the dataframe for the current page
df_subset <- df[, start_col:end_col, drop = FALSE]
# Apply HTML formatting to description and "Cell state data" rows, moving them to the first row
if (nrow(df_subset) >= 2) {
description_row <- data.frame(
matrix(NA, nrow = 1, ncol = ncol(df_subset), dimnames = list(NULL, colnames(df_subset)))
)
# Define the HTML style for the description row (making "TF activity score" bold with white font and background color)
style <- "<h5 style='font-weight: bold; color: white;'>TF activity score</h5>"
# Apply style to both description and "Cell state data"
description_row[1, ] <- style
rownames(description_row)[1] <- "Cell state data"
# Move the description row to the first row of the subset
df_subset <- rbind(description_row, df_subset) # Move this styled row to the first position
}
# Return the data with HTML rendering enabled, show all 45 rows, and remove the search box
DT::datatable(df_subset, escape = FALSE, options = list(
pageLength = 45,
lengthChange = FALSE,
searching = FALSE, # Remove the search box
rowCallback = JS(
"function(row, data, index) {
var highlightedRow = 0; // Apply styling to the first row
if (index === highlightedRow) {
$('td', row).css({
'background-color': '#95a5a6',
'color': 'white',
'font-weight': 'bold'
});
}
}"
)
))
})
# Rendering the filtered "mp" page data table and showing all rows
output$table_mp <- renderDT({
filtered_mp_data() # Use the filtered data with pagination logic applied
}, options = list(
pageLength = nrow(filtered_mp_data()), # Show all rows
dom = 't', # Remove the row length dropdown
scrollX = TRUE # Enable horizontal scrolling if needed
))
#NEW TCM SEARCH
tcm_data <- reactive({
new_read_excel_file("www/tablePagerank/TCM.xlsx")
})
# Track the current column page for "tcm" data
tcm_column_page <- reactiveVal(1)
# Reset the column page when the search input changes for "tcm" data
observeEvent(input$search_input_tcm, {
tcm_column_page(1) # Reset to page 1 when a new search is made
})
# Update the column page when buttons are clicked for "tcm" data
observeEvent(input$tcm_next_btn, {
current_page <- tcm_column_page()
total_cols <- ncol(new_filter_data(tcm_data(), input$search_input_tcm))
# Calculate the maximum possible number of pages
max_page <- ceiling(total_cols / 4)
# Move to the next page, but do not exceed the max_page
if (current_page < max_page) {
tcm_column_page(current_page + 1)
}
})
observeEvent(input$tcm_prev_btn, {
current_page <- tcm_column_page()
tcm_column_page(max(current_page - 1, 1)) # Ensure the page does not go below 1
})
#OLD: Reactive for filtering and paginating the "tcm" page data
# filtered_tcm_data <- reactive({
# df <- new_filter_data(tcm_data(), input$search_input_tcm)
#
# # Get the total number of columns in the filtered dataframe
# total_cols <- ncol(df)
#
# # Ensure there are columns after filtering
# if (total_cols == 0) {
# return(data.frame()) # Return an empty dataframe if no columns match the search
# }
#
# # Define the start and end index for columns based on the current page
# start_col <- (tcm_column_page() - 1) * 4 + 1
# end_col <- min(start_col + 3, total_cols) # Show up to 4 columns
#
# # If start_col exceeds the total number of columns, return the last valid subset
# if (start_col > total_cols) {
# start_col <- (ceiling(total_cols / 4) - 1) * 4 + 1 # Set start_col to the last valid page
# end_col <- total_cols # End with the last column
# }
#
# # Subset the columns for the current page
# df_subset <- df[, start_col:end_col, drop = FALSE]
#
# return(df_subset)
# })
#NEW FILTERED DATA
filtered_tcm_data <- reactive({
# Filter the TCM data and determine the total number of columns
df <- new_filter_data(tcm_data(), input$search_input_tcm)
total_cols <- ncol(df)
# Return empty dataframe if no columns match the search
if (total_cols == 0) return(data.frame())
# Define the column range for the current page
start_col <- (tcm_column_page() - 1) * 4 + 1
end_col <- min(start_col + 3, total_cols)
# Return filtered data if start_col exceeds the total columns
if (start_col > total_cols) return(df)
# Subset the dataframe for the current page
df_subset <- df[, start_col:end_col, drop = FALSE]
# Apply HTML formatting to description and "Cell state data" rows, moving them to the first row
if (nrow(df_subset) >= 2) {
description_row <- data.frame(
matrix(NA, nrow = 1, ncol = ncol(df_subset), dimnames = list(NULL, colnames(df_subset)))
)
# Define the HTML style for the description row (making "TF activity score" bold with white font and background color)
style <- "<h5 style='font-weight: bold; color: white;'>TF activity score</h5>"
# Apply style to both description and "Cell state data"
description_row[1, ] <- style
rownames(description_row)[1] <- "Cell state data"
# Move the description row to the first row of the subset
df_subset <- rbind(description_row, df_subset) # Move this styled row to the first position
}
# Return the data with HTML rendering enabled, show all 45 rows, and remove the search box
DT::datatable(df_subset, escape = FALSE, options = list(
pageLength = 45,
lengthChange = FALSE,
searching = FALSE, # Remove the search box
rowCallback = JS(
"function(row, data, index) {
var highlightedRow = 0; // Apply styling to the first row
if (index === highlightedRow) {
$('td', row).css({
'background-color': '#95a5a6',
'color': 'white',
'font-weight': 'bold'
});
}
}"
)
))
})
# Rendering the filtered "tcm" page data table and showing all rows
output$table_tcm <- renderDT({
filtered_tcm_data() # Use the filtered data with pagination logic applied
}, options = list(
pageLength = nrow(filtered_tcm_data()), # Show all rows
dom = 't', # Remove the row length dropdown
scrollX = TRUE # Enable horizontal scrolling if needed
))
#NEW TEM SEARCH
tem_data <- reactive({
new_read_excel_file("www/tablePagerank/TEM.xlsx")
})
# Track the current column page for "tem" data
tem_column_page <- reactiveVal(1)
# Reset the column page when the search input changes for "tem" data
observeEvent(input$search_input_tem, {
tem_column_page(1) # Reset to page 1 when a new search is made
})
# Update the column page when buttons are clicked for "tem" data
observeEvent(input$tem_next_btn, {
current_page <- tem_column_page()
total_cols <- ncol(new_filter_data(tem_data(), input$search_input_tem))
# Calculate the maximum possible number of pages
max_page <- ceiling(total_cols / 4)
# Move to the next page, but do not exceed the max_page
if (current_page < max_page) {
tem_column_page(current_page + 1)
}
})
observeEvent(input$tem_prev_btn, {
current_page <- tem_column_page()
tem_column_page(max(current_page - 1, 1)) # Ensure the page does not go below 1
})
#OLD: Reactive for filtering and paginating the "tem" page data
# filtered_tem_data <- reactive({
# df <- new_filter_data(tem_data(), input$search_input_tem)
#
# # Get the total number of columns in the filtered dataframe
# total_cols <- ncol(df)
#
# # Ensure there are columns after filtering
# if (total_cols == 0) {
# return(data.frame()) # Return an empty dataframe if no columns match the search
# }
#
# # Define the start and end index for columns based on the current page
# start_col <- (tem_column_page() - 1) * 4 + 1
# end_col <- min(start_col + 3, total_cols) # Show up to 4 columns
#
# # If start_col exceeds the total number of columns, return the last valid subset
# if (start_col > total_cols) {
# start_col <- (ceiling(total_cols / 4) - 1) * 4 + 1 # Set start_col to the last valid page
# end_col <- total_cols # End with the last column
# }
#
# # Subset the columns for the current page
# df_subset <- df[, start_col:end_col, drop = FALSE]
#
# return(df_subset)
# })
#NEW FILTERED DATA
filtered_tem_data <- reactive({
# Filter the TEM data and determine the total number of columns
df <- new_filter_data(tem_data(), input$search_input_tem)
total_cols <- ncol(df)
# Return empty dataframe if no columns match the search
if (total_cols == 0) return(data.frame())
# Define the column range for the current page
start_col <- (tem_column_page() - 1) * 4 + 1
end_col <- min(start_col + 3, total_cols)
# Return filtered data if start_col exceeds the total columns
if (start_col > total_cols) return(df)
# Subset the dataframe for the current page
df_subset <- df[, start_col:end_col, drop = FALSE]
# Apply HTML formatting to description and "Cell state data" rows, moving them to the first row
if (nrow(df_subset) >= 2) {
description_row <- data.frame(
matrix(NA, nrow = 1, ncol = ncol(df_subset), dimnames = list(NULL, colnames(df_subset)))
)
# Define the HTML style for the description row (making "TF activity score" bold with white font and background color)
style <- "<h5 style='font-weight: bold; color: white;'>TF activity score</h5>"
# Apply style to both description and "Cell state data"
description_row[1, ] <- style
rownames(description_row)[1] <- "Cell state data"
# Move the description row to the first row of the subset
df_subset <- rbind(description_row, df_subset) # Move this styled row to the first position
}
# Return the data with HTML rendering enabled, show all 45 rows, and remove the search box
DT::datatable(df_subset, escape = FALSE, options = list(
pageLength = 45,
lengthChange = FALSE,
searching = FALSE, # Remove the search box
rowCallback = JS(
"function(row, data, index) {
var highlightedRow = 0; // Apply styling to the first row
if (index === highlightedRow) {
$('td', row).css({
'background-color': '#95a5a6',
'color': 'white',
'font-weight': 'bold'
});
}
}"
)
))
})
# Rendering the filtered "tem" page data table and showing all rows
output$table_tem <- renderDT({
filtered_tem_data() # Use the filtered data with pagination logic applied
}, options = list(
pageLength = nrow(filtered_tem_data()), # Show all rows
dom = 't', # Remove the row length dropdown
scrollX = TRUE # Enable horizontal scrolling if needed
))
#NEW TRM SEARCH
trm_data <- reactive({
new_read_excel_file("www/tablePagerank/TRM.xlsx")
})
# Track the current column page for "trmm" data
trm_column_page <- reactiveVal(1)
# Reset the column page when the search input changes for "trmm" data
observeEvent(input$search_input_trm, {
trm_column_page(1) # Reset to page 1 when a new search is made
})
# Update the column page when buttons are clicked for "trmm" data
observeEvent(input$trm_next_btn, {
current_page <- trm_column_page()
total_cols <- ncol(new_filter_data(trm_data(), input$search_input_trm))
# Calculate the maximum possible number of pages
max_page <- ceiling(total_cols / 4)
# Move to the next page, but do not exceed the max_page
if (current_page < max_page) {
trm_column_page(current_page + 1)
}
})
observeEvent(input$trm_prev_btn, {
current_page <- trm_column_page()
trm_column_page(max(current_page - 1, 1)) # Ensure the page does not go below 1
})
#OLD: Reactive for filtering and paginating the "trmm" page data
# filtered_trm_data <- reactive({
# df <- new_filter_data(trm_data(), input$search_input_trm)
#
# # Get the total number of columns in the filtered dataframe
# total_cols <- ncol(df)
#
# # Ensure there are columns after filtering
# if (total_cols == 0) {
# return(data.frame()) # Return an empty dataframe if no columns match the search
# }
#
# # Define the start and end index for columns based on the current page
# start_col <- (trm_column_page() - 1) * 4 + 1
# end_col <- min(start_col + 3, total_cols) # Show up to 4 columns
#
# # If start_col exceeds the total number of columns, return the last valid subset
# if (start_col > total_cols) {
# start_col <- (ceiling(total_cols / 4) - 1) * 4 + 1 # Set start_col to the last valid page
# end_col <- total_cols # End with the last column
# }
#
# # Subset the columns for the current page
# df_subset <- df[, start_col:end_col, drop = FALSE]
#
# return(df_subset)
# })
#NEW FILTERED DATA
filtered_trm_data <- reactive({
# Filter the TRM data and determine the total number of columns
df <- new_filter_data(trm_data(), input$search_input_trm)
total_cols <- ncol(df)
# Return empty dataframe if no columns match the search
if (total_cols == 0) return(data.frame())
# Define the column range for the current page
start_col <- (trm_column_page() - 1) * 4 + 1
end_col <- min(start_col + 3, total_cols)
# Return filtered data if start_col exceeds the total columns
if (start_col > total_cols) return(df)
# Subset the dataframe for the current page
df_subset <- df[, start_col:end_col, drop = FALSE]
# Apply HTML formatting to description and "Cell state data" rows, moving them to the first row
if (nrow(df_subset) >= 2) {
description_row <- data.frame(
matrix(NA, nrow = 1, ncol = ncol(df_subset), dimnames = list(NULL, colnames(df_subset)))
)
# Define the HTML style for the description row (making "TF activity score" bold with white font and background color)
style <- "<h5 style='font-weight: bold; color: white;'>TF activity score</h5>"
# Apply style to both description and "Cell state data"
description_row[1, ] <- style
rownames(description_row)[1] <- "Cell state data"
# Move the description row to the first row of the subset
df_subset <- rbind(description_row, df_subset) # Move this styled row to the first position
}
# Return the data with HTML rendering enabled, show all 45 rows, and remove the search box
DT::datatable(df_subset, escape = FALSE, options = list(
pageLength = 45,
lengthChange = FALSE,
searching = FALSE, # Remove the search box
rowCallback = JS(
"function(row, data, index) {
var highlightedRow = 0; // Apply styling to the first row
if (index === highlightedRow) {
$('td', row).css({
'background-color': '#95a5a6',
'color': 'white',
'font-weight': 'bold'
});
}
}"
)
))
})
# Rendering the filtered "trmm" page data table and showing all rows
output$table_trm <- renderDT({
filtered_trm_data() # Use the filtered data with pagination logic applied
}, options = list(
pageLength = nrow(filtered_trm_data()), # Show all rows
dom = 't', # Remove the row length dropdown
scrollX = TRUE # Enable horizontal scrolling if needed
))
#NEW TEX PROG SEARCH
texprog_data <- reactive({
new_read_excel_file("www/tablePagerank/TEXprog.xlsx")
})
# Track the current column page for "texprog" data
texprog_column_page <- reactiveVal(1)
# Reset the column page when the search input changes for "texprog" data
observeEvent(input$search_input_texprog, {
texprog_column_page(1) # Reset to page 1 when a new search is made
})
# Update the column page when buttons are clicked for "texprog" data
observeEvent(input$texprog_next_btn, {
current_page <- texprog_column_page()
total_cols <- ncol(new_filter_data(texprog_data(), input$search_input_texprog))
# Calculate the maximum possible number of pages
max_page <- ceiling(total_cols / 4)
# Move to the next page, but do not exceed the max_page
if (current_page < max_page) {
texprog_column_page(current_page + 1)
}
})
observeEvent(input$texprog_prev_btn, {
current_page <- texprog_column_page()
texprog_column_page(max(current_page - 1, 1)) # Ensure the page does not go below 1
})
#OLD: Reactive for filtering and paginating the "texprog" page data
# filtered_texprog_data <- reactive({
# df <- new_filter_data(texprog_data(), input$search_input_texprog)
#
# # Get the total number of columns in the filtered dataframe
# total_cols <- ncol(df)
#
# # Ensure there are columns after filtering
# if (total_cols == 0) {
# return(data.frame()) # Return an empty dataframe if no columns match the search
# }
#
# # Define the start and end index for columns based on the current page
# start_col <- (texprog_column_page() - 1) * 4 + 1
# end_col <- min(start_col + 3, total_cols) # Show up to 4 columns
#
# # If start_col exceeds the total number of columns, return the last valid subset
# if (start_col > total_cols) {
# start_col <- (ceiling(total_cols / 4) - 1) * 4 + 1 # Set start_col to the last valid page
# end_col <- total_cols # End with the last column
# }
#
# # Subset the columns for the current page
# df_subset <- df[, start_col:end_col, drop = FALSE]
#
# return(df_subset)
# })
#NEW FILTERED DATA
filtered_texprog_data <- reactive({
# Filter the TEXprog data and determine the total number of columns
df <- new_filter_data(texprog_data(), input$search_input_texprog)
total_cols <- ncol(df)
# Return empty dataframe if no columns match the search
if (total_cols == 0) return(data.frame())
# Define the column range for the current page
start_col <- (texprog_column_page() - 1) * 4 + 1
end_col <- min(start_col + 3, total_cols)
# Return filtered data if start_col exceeds the total columns
if (start_col > total_cols) return(df)
# Subset the dataframe for the current page
df_subset <- df[, start_col:end_col, drop = FALSE]
# Apply HTML formatting to description and "Cell state data" rows, moving them to the first row
if (nrow(df_subset) >= 2) {
description_row <- data.frame(
matrix(NA, nrow = 1, ncol = ncol(df_subset), dimnames = list(NULL, colnames(df_subset)))
)
# Define the HTML style for the description row (making "TF activity score" bold with white font and background color)
style <- "<h5 style='font-weight: bold; color: white;'>TF activity score</h5>"
# Apply style to both description and "Cell state data"
description_row[1, ] <- style
rownames(description_row)[1] <- "Cell state data"
# Move the description row to the first row of the subset
df_subset <- rbind(description_row, df_subset) # Move this styled row to the first position
}
# Return the data with HTML rendering enabled, show all 45 rows, and remove the search box
DT::datatable(df_subset, escape = FALSE, options = list(
pageLength = 45,
lengthChange = FALSE,
searching = FALSE, # Remove the search box
rowCallback = JS(
"function(row, data, index) {
var highlightedRow = 0; // Apply styling to the first row
if (index === highlightedRow) {
$('td', row).css({
'background-color': '#95a5a6',
'color': 'white',
'font-weight': 'bold'
});
}
}"
)
))
})
# Rendering the filtered "texprog" page data table and showing all rows
output$table_texprog <- renderDT({
filtered_texprog_data() # Use the filtered data with pagination logic applied
}, options = list(
pageLength = nrow(filtered_texprog_data()), # Show all rows
dom = 't', # Remove the row length dropdown
scrollX = TRUE # Enable horizontal scrolling if needed
))
#NEW TEX EFF LIKE SEARCH
texefflike_data <- reactive({
new_read_excel_file("www/tablePagerank/TEXeff.xlsx")
})
# Track the current column page for "texefflike" data
texefflike_column_page <- reactiveVal(1)
# Reset the column page when the search input changes for "texefflike" data
observeEvent(input$search_input_texefflike, {
texefflike_column_page(1) # Reset to page 1 when a new search is made
})
# Update the column page when buttons are clicked for "texefflike" data
observeEvent(input$texefflike_next_btn, {
current_page <- texefflike_column_page()
total_cols <- ncol(new_filter_data(texefflike_data(), input$search_input_texefflike))
# Calculate the maximum possible number of pages
max_page <- ceiling(total_cols / 4)
# Move to the next page, but do not exceed the max_page
if (current_page < max_page) {
texefflike_column_page(current_page + 1)
}
})
observeEvent(input$texefflike_prev_btn, {
current_page <- texefflike_column_page()
texefflike_column_page(max(current_page - 1, 1)) # Ensure the page does not go below 1
})
#OLD: Reactive for filtering and paginating the "texefflike" page data
# filtered_texefflike_data <- reactive({
# df <- new_filter_data(texefflike_data(), input$search_input_texefflike)
#
# # Get the total number of columns in the filtered dataframe
# total_cols <- ncol(df)
#
# # Ensure there are columns after filtering
# if (total_cols == 0) {
# return(data.frame()) # Return an empty dataframe if no columns match the search
# }
#
# # Define the start and end index for columns based on the current page
# start_col <- (texefflike_column_page() - 1) * 4 + 1
# end_col <- min(start_col + 3, total_cols) # Show up to 4 columns
#
# # If start_col exceeds the total number of columns, return the last valid subset
# if (start_col > total_cols) {
# start_col <- (ceiling(total_cols / 4) - 1) * 4 + 1 # Set start_col to the last valid page
# end_col <- total_cols # End with the last column
# }
#
# # Subset the columns for the current page
# df_subset <- df[, start_col:end_col, drop = FALSE]
#
# return(df_subset)
# })
#NEW FILTERED DATA
filtered_texefflike_data <- reactive({
# Filter the TEXefflike data and determine the total number of columns
df <- new_filter_data(texefflike_data(), input$search_input_texefflike)
total_cols <- ncol(df)
# Return empty dataframe if no columns match the search
if (total_cols == 0) return(data.frame())
# Define the column range for the current page
start_col <- (texefflike_column_page() - 1) * 4 + 1
end_col <- min(start_col + 3, total_cols)
# Return filtered data if start_col exceeds the total columns
if (start_col > total_cols) return(df)
# Subset the dataframe for the current page
df_subset <- df[, start_col:end_col, drop = FALSE]
# Apply HTML formatting to description and "Cell state data" rows, moving them to the first row
if (nrow(df_subset) >= 2) {
description_row <- data.frame(
matrix(NA, nrow = 1, ncol = ncol(df_subset), dimnames = list(NULL, colnames(df_subset)))
)
# Define the HTML style for the description row (making "TF activity score" bold with white font and background color)
style <- "<h5 style='font-weight: bold; color: white;'>TF activity score</h5>"
# Apply style to both description and "Cell state data"
description_row[1, ] <- style
rownames(description_row)[1] <- "Cell state data"
# Move the description row to the first row of the subset
df_subset <- rbind(description_row, df_subset) # Move this styled row to the first position
}
# Return the data with HTML rendering enabled, show all 45 rows, and remove the search box
DT::datatable(df_subset, escape = FALSE, options = list(
pageLength = 45,
lengthChange = FALSE,
searching = FALSE, # Remove the search box
rowCallback = JS(
"function(row, data, index) {
var highlightedRow = 0; // Apply styling to the first row
if (index === highlightedRow) {
$('td', row).css({
'background-color': '#95a5a6',
'color': 'white',
'font-weight': 'bold'
});
}
}"
)
))
})
# Rendering the filtered "texefflike" page data table and showing all rows
output$table_texefflike <- renderDT({
filtered_texefflike_data() # Use the filtered data with pagination logic applied
}, options = list(
pageLength = nrow(filtered_texefflike_data()), # Show all rows
dom = 't', # Remove the row length dropdown
scrollX = TRUE # Enable horizontal scrolling if needed
))
#NEW TEX TERM SEARCH
texterm_data <- reactive({
new_read_excel_file("www/tablePagerank/TEXterm.xlsx")
})
# Track the current column page for "texterm" data
texterm_column_page <- reactiveVal(1)
# Reset the column page when the search input changes for "texterm" data
observeEvent(input$search_input_texterm, {
texterm_column_page(1) # Reset to page 1 when a new search is made
})
# Update the column page when buttons are clicked for "texterm" data
observeEvent(input$texterm_next_btn, {
current_page <- texterm_column_page()
total_cols <- ncol(new_filter_data(texterm_data(), input$search_input_texterm))
# Calculate the maximum possible number of pages
max_page <- ceiling(total_cols / 4)
# Move to the next page, but do not exceed the max_page
if (current_page < max_page) {
texterm_column_page(current_page + 1)
}
})
observeEvent(input$texterm_prev_btn, {
current_page <- texterm_column_page()
texterm_column_page(max(current_page - 1, 1)) # Ensure the page does not go below 1
})
#OLD: Reactive for filtering and paginating the "texterm" page data
# filtered_texterm_data <- reactive({
# df <- new_filter_data(texterm_data(), input$search_input_texterm)
#
# # Get the total number of columns in the filtered dataframe
# total_cols <- ncol(df)
#
# # Ensure there are columns after filtering
# if (total_cols == 0) {
# return(data.frame()) # Return an empty dataframe if no columns match the search
# }
#
# # Define the start and end index for columns based on the current page
# start_col <- (texterm_column_page() - 1) * 4 + 1
# end_col <- min(start_col + 3, total_cols) # Show up to 4 columns
#
# # If start_col exceeds the total number of columns, return the last valid subset
# if (start_col > total_cols) {
# start_col <- (ceiling(total_cols / 4) - 1) * 4 + 1 # Set start_col to the last valid page
# end_col <- total_cols # End with the last column
# }
#
# # Subset the columns for the current page
# df_subset <- df[, start_col:end_col, drop = FALSE]
#
# return(df_subset)
# })
#NEW FILTERED DATA
filtered_texterm_data <- reactive({
# Filter the TEXterm data and determine the total number of columns
df <- new_filter_data(texterm_data(), input$search_input_texterm)
total_cols <- ncol(df)
# Return empty dataframe if no columns match the search
if (total_cols == 0) return(data.frame())
# Define the column range for the current page
start_col <- (texterm_column_page() - 1) * 4 + 1
end_col <- min(start_col + 3, total_cols)
# Return filtered data if start_col exceeds the total columns
if (start_col > total_cols) return(df)
# Subset the dataframe for the current page
df_subset <- df[, start_col:end_col, drop = FALSE]
# Apply HTML formatting to description and "Cell state data" rows, moving them to the first row
if (nrow(df_subset) >= 2) {
description_row <- data.frame(
matrix(NA, nrow = 1, ncol = ncol(df_subset), dimnames = list(NULL, colnames(df_subset)))
)
# Define the HTML style for the description row (making "TF activity score" bold with white font and background color)
style <- "<h5 style='font-weight: bold; color: white;'>TF activity score</h5>"
# Apply style to both description and "Cell state data"
description_row[1, ] <- style
rownames(description_row)[1] <- "Cell state data"
# Move the description row to the first row of the subset
df_subset <- rbind(description_row, df_subset) # Move this styled row to the first position
}
# Return the data with HTML rendering enabled, show all 45 rows, and remove the search box
DT::datatable(df_subset, escape = FALSE, options = list(
pageLength = 45,
lengthChange = FALSE,
searching = FALSE, # Remove the search box
rowCallback = JS(
"function(row, data, index) {
var highlightedRow = 0; // Apply styling to the first row
if (index === highlightedRow) {
$('td', row).css({
'background-color': '#95a5a6',
'color': 'white',
'font-weight': 'bold'
});
}
}"
)
))
})
# Rendering the filtered "texterm" page data table and showing all rows
output$table_texterm <- renderDT({
filtered_texterm_data() # Use the filtered data with pagination logic applied
}, options = list(
pageLength = nrow(filtered_texterm_data()), # Show all rows
dom = 't', # Remove the row length dropdown
scrollX = TRUE # Enable horizontal scrolling if needed
))
# # ORIGINAL READ EXCEL FILE
# read_excel_file <- function(path) {
# df <- read_excel(path)
# colnames(df)[1] <- "Regulator Names"
# return(df)
# }
#
# # ORIGINAL FILTER FUNCTION
# filter_data <- function(data, keyword) {
# if (is.null(keyword) || is.na(keyword) || keyword == "") {
# return(data)
# } else {
# keyword <- tolower(keyword)
# return(data[apply(data, 1, function(x) any(grepl(keyword, tolower(x)))), ])
# }
# }
#
# #ORIGINAL DISPLAY TABLE FUNCTION
# # Main page data
# data <- reactive({
# read_excel_file("www/tablePagerank/Table_TF PageRank Scores for Audrey.xlsx")
# })
#
# filtered_data <- reactive({
# filter_data(data(), input$search_input)
# })
#
# output$table <- renderDT({
# filtered_data()
# })
# Server logic for naive tab
output$naive <- renderText({
"TF Activity Score: Naive"
})
# OLD NAIVE DATA TABLE
# naive_data <- reactive({
# read_excel_file("www/tablePagerank/Naive.xlsx")
# })
#
# filtered_naive_data <- reactive({
# filter_data(naive_data(), input$search_input_naive)
# })
#
# output$table_naive <- renderDT({
# filtered_naive_data()
# })
# Server logic for TE tab
output$te <- renderText({
"TF Activity Score: TE"
})
# OLD TE DATA TABLE
# te_data <- reactive({
# read_excel_file("www/tablePagerank/TE.xlsx")
# })
#
# filtered_te_data <- reactive({
# filter_data(te_data(), input$search_input_te)
# })
#
# output$table_te <- renderDT({
# filtered_te_data()
# })
# Server logic for MP tab
output$mp <- renderText({
"TF Activity Score: MP"
})
# OLD MP DATA
# mp_data <- reactive({
# read_excel_file("www/tablePagerank/MP.xlsx")
# })
#
# filtered_mp_data <- reactive({
# filter_data(mp_data(), input$search_input_mp)
# })
#
# output$table_mp <- renderDT({
# filtered_mp_data()
# })
# Server logic for T CM tab
output$tcm <- renderText({
"TF Activity Score: T CM"
})
# OLD TCM DATA
# tcm_data <- reactive({
# read_excel_file("www/tablePagerank/TCM.xlsx")
# })
#
# filtered_tcm_data <- reactive({
# filter_data(tcm_data(), input$search_input_tcm)
# })
#
# output$table_tcm <- renderDT({
# filtered_tcm_data()
# })
# Server logic for T EM tab
output$tem <- renderText({
"TF Activity Score: T EM"
})
# OLD TEM DATA
# tem_data <- reactive({
# read_excel_file("www/tablePagerank/TEM.xlsx")
# })
#
# filtered_tem_data <- reactive({
# filter_data(tem_data(), input$search_input_tem)
# })
#
# output$table_tem <- renderDT({
# filtered_tem_data()
# })
#
# # Server logic for T RM tab
# output$trm <- renderText({
# "TF Activity Score: T RM"
# })
# OLD TRM DATA
# trm_data <- reactive({
# read_excel_file("www/tablePagerank/TRM.xlsx")
# })
#
# filtered_trm_data <- reactive({
# filter_data(trm_data(), input$search_input_trm)
# })
#
# output$table_trm <- renderDT({
# filtered_trm_data()
# })
# Server logic for Tex Prog tab
output$texprog <- renderText({
"TF Activity Score: Tex Prog"
})
# OLD TEX PROG DATA
# texprog_data <- reactive({
# read_excel_file("www/tablePagerank/TEXprog.xlsx")
# })
#
# filtered_texprog_data <- reactive({
# filter_data(texprog_data(), input$search_input_texprog)
# })
#
# output$table_texprog <- renderDT({
# filtered_texprog_data()
# })
# Server logic for Tex Eff-like tab
output$texefflike <- renderText({
"TF Activity Score: Tex Eff-like"
})
# OLD TEX EFF LIKE DATA
# texefflike_data <- reactive({
# read_excel_file("www/tablePagerank/TEXeff.xlsx")
# })
#
# filtered_texefflike_data <- reactive({
# filter_data(texefflike_data(), input$search_input_texefflike)
# })
#
# output$table_texefflike <- renderDT({
# filtered_texefflike_data()
# })
# Server logic for Tex Term tab
output$texterm <- renderText({
"TF Activity Score: Tex Term"
})
# OLD TEX TERM DATA
# texterm_data <- reactive({
# read_excel_file("www/tablePagerank/TEXterm.xlsx")
# })
#
# filtered_texterm_data <- reactive({
# filter_data(texterm_data(), input$search_input_texterm)
# })
#
# output$table_texterm <- renderDT({
# filtered_texterm_data()
# })
#click image code for TF Wave Analysis
observeEvent(input$c1_link, {
updateNavbarPage(session, "mainNav", selected = "c1")
})
observeEvent(input$c2_link, {
updateNavbarPage(session, "mainNav", selected = "c2")
})
observeEvent(input$c3_link, {
updateNavbarPage(session, "mainNav", selected = "c3")
})
observeEvent(input$c4_link, {
updateNavbarPage(session, "mainNav", selected = "c4")
})
observeEvent(input$c5_link, {
updateNavbarPage(session, "mainNav", selected = "c5")
})
observeEvent(input$c6_link, {
updateNavbarPage(session, "mainNav", selected = "c6")
})
observeEvent(input$c7_link, {
updateNavbarPage(session, "mainNav", selected = "c7")
})
# Handle specific image part clicks to navigate to the subpages
observeEvent(input$to_tfcat, {
updateNavbarPage(session, "mainNav", selected = "tfcatpage")
})
observeEvent(input$to_tfwave, {
updateNavbarPage(session, "mainNav", selected = "overview")
})
observeEvent(input$to_tfnet, {
updateNavbarPage(session, "mainNav", selected = "tfnetpage")
})
# SEARCH FOR A TF AND FIND OUT WHICH WAVE THEY ARE APART OF
# Function to read the file and assign proper column names
read_searchwave_file <- function(path) {
df <- read_excel(path) # Read the Excel file
colnames(df) <- c("Wave1", "Wave2", "Wave3", "Wave4", "Wave5", "Wave6", "Wave7") # Customize as needed
return(df)
return(df)
}
# Load data reactively
searchwavedata <- reactive({
# Provide the path to your Excel file
read_searchwave_file("www/waveanalysis/searchtfwaves.xlsx") # Path to your file
})
# Reactive function to search and filter the data based on the wave search input
filtered_wave_data <- reactive({
# Get the search input
search_term <- input$search_input_wave
# If no search term, return the entire dataset in the desired transposed format
if (is.null(search_term) || search_term == "") {
# Initialize an empty list to store the gene names for each wave
wave_genes <- list()
# Iterate over each wave column and get the associated genes
for (col in colnames(searchwavedata())) {
wave_genes[[col]] <- searchwavedata()[[col]] # Store all gene names for each wave
}
# Create a data frame with waves as columns and genes as rows
result_df <- data.frame(wave_genes)
# Return the transposed data frame with wave numbers as column headers and genes as rows
return(result_df)
}
# Initialize an empty list to store the result
result <- list()
# Iterate through each column and check if the search term exists
for (col in colnames(searchwavedata())) {
# Filter genes for each column where the search term matches
matching_genes <- searchwavedata()[[col]][grepl(search_term, searchwavedata()[[col]], ignore.case = TRUE)]
# If there are matching genes, store them
if (length(matching_genes) > 0) {
result[[col]] <- paste(matching_genes, collapse = ", ") # Combine matching genes as a string
}
}
# If no results are found, return an empty dataframe
if (length(result) == 0) {
return(data.frame(Wave = character(0), Gene = character(0))) # Return empty data frame if nothing matches
}
# Convert the result list to a data frame
result_df <- data.frame(
Wave = names(result), # Column names as 'Wave'
Gene = unlist(result), # Concatenated list of matching gene names
stringsAsFactors = FALSE
)
# Remove any duplicate wave names (keep only one occurrence per wave)
result_df <- result_df[!duplicated(result_df$Wave), ]
# Remove rows where Gene column is NA or empty
result_df <- result_df[!is.na(result_df$Gene) & result_df$Gene != "", ]
# Create a matrix with wave names as columns and gene names as rows
transposed_df <- matrix(unlist(result_df$Gene), nrow = 1) # Convert the gene names to a row
# Set the column names to the wave numbers, replacing "Wave 1" instead of "wave.1"
colnames(transposed_df) <- paste("Wave", seq_along(result_df$Wave))
# Return the transposed result
return(as.data.frame(transposed_df))
})
# Render the table output based on the filtered and transposed data
output$table_wave <- renderDT({
# Get the filtered and transposed data
df <- filtered_wave_data()
# Render the data table without row names and disable the default search box
datatable(df, options = list(searching = FALSE), rownames = FALSE)
})
# # Function to read Excel files
# read_regulator_file <- function(path) {
# df <- read_excel(path)
# colnames(df)[1] <- " " # Adjust column name as needed
# return(df)
# }
#
# # Load data initially
# tfregulated_data <- reactive({
# read_regulator_file("www/networkanalysis/comp_log2FC_RegulatedData_TRMTEXterm.xlsx")
# })
#
# # Filtered data based on search input
# filtered_tfregulated_data <- reactive({
# req(tfregulated_data()) # Ensure tfregulated_data() is available
# if (is.null(input$search_tfregulated_data) || input$search_tfregulated_data == "") {
# return(tfregulated_data())
# } else {
# # Perform filtering based on input$search_tfregulated_data
# # Example filtering logic:
# # filtered_data <- tfregulated_data() %>%
# # filter(...) # Add your filtering logic here
# # return(filtered_data)
# # Replace the above with your actual filtering logic
# return(tfregulated_data()) # Placeholder for now
# }
# })
#
# # Render the DataTable
# output$table_tfregulated_data <- renderDT({
# datatable(filtered_tfregulated_data())
# })
# ORIGINALLY SEARCH TRM TEXterm COORELATION
# Load Excel file when the app starts
data_tftfimage <- read_excel("www/TFcorintextrm/TF-TFcorTRMTEX.xlsx")
# Reactive function to filter the data based on the search input (case-insensitive)
filtered_data_tftfimage <- reactive({
req(input$search) # Ensure search input is available
# Convert both the column and search input to lowercase for case-insensitive comparison
data_filtered <- data_tftfimage[tolower(data_tftfimage[["TF Name"]]) == tolower(input$search), ]
return(data_filtered)
})
# Render the first column (Gene Names) as clickable links
output$gene_list_table <- renderUI({
tagList(
lapply(data_tftfimage[[1]], function(gene_name) { # Assuming the first column contains gene names
tags$div(
actionLink(
inputId = paste0("gene_", gene_name), # Unique input ID for each gene
label = gene_name
),
style = "margin-bottom: 10px;" # Add spacing between links
)
})
)
})
# Generate dynamic observers for each gene link
lapply(data_tftfimage[[1]], function(gene_name) {
observeEvent(input[[paste0("gene_", gene_name)]], {
# Find the row corresponding to the clicked gene
selected_gene_data <- data_tftfimage[data_tftfimage[[1]] == gene_name, ]
img_src <- selected_gene_data[["TF Merged Graph Path"]] # Replace with the actual image column name
# Update the image gallery output with the selected gene's image
output$image_gallery <- renderUI({
if (!is.null(img_src) && nchar(img_src) > 0) {
tags$div(
style = "text-align: center;",
tags$img(src = img_src, style = "max-width: 100%; height: auto;"),
tags$p(gene_name) # Optionally display the gene name below the image
)
} else {
"No image available for the selected gene."
}
})
})
})
# Event to handle search functionality (unchanged from your original code)
observeEvent(input$search_btn, {
output$result_table <- renderTable({
if (nrow(filtered_data_tftfimage()) > 0) {
filtered_data_tftfimage()[, -which(names(filtered_data_tftfimage()) == "TF Merged Graph Path")] # Show all columns except the image path
} else {
NULL # If no results, display nothing
}
})
output$image_gallery <- renderUI({
if (nrow(filtered_data_tftfimage()) > 0) {
image_list <- lapply(1:nrow(filtered_data_tftfimage()), function(i) {
img_src <- filtered_data_tftfimage()[[ "TF Merged Graph Path" ]][i]
tags$div(
style = "text-align: center; margin-bottom: 20px;",
tags$img(src = img_src, style = "max-width: 100%; height: auto;")
)
})
do.call(tags$div, image_list)
} else {
"TF not found. Please search for a valid TF."
}
})
})
#tf communities
# Read the first Excel file directly from the specified path
datatrm <- read_excel("www/tfcommunities/trmcommunities.xlsx")
# Read the second Excel file directly from the specified path
datatex <- read_excel("www/tfcommunities/texcommunities.xlsx")
# Render the first table without the search button
output$trmcom <- renderDT({
datatable(
datatrm,
options = list(
lengthChange = FALSE,
pageLength = 5,
searching = FALSE # Disable the search button
)
)
})
# Render the second table without the search button
output$texcom <- renderDT({
datatable(
datatex,
options = list(
lengthChange = FALSE,
pageLength = 5,
searching = FALSE # Disable the search button
)
)
})
# Load your multiomics file
multiexcel_data <- read_excel("www/multi-omicsdata.xlsx")
# #Render data table + hyperlinks author's name to DOI
# output$multiomicsdatatable <- renderDT({
# # Transform the "author" column to contain hyperlinks using the "DOI" column
# multiexcel_data <- multiexcel_data %>%
# mutate(
# Author = paste0(
# "<a href='",
# DOI, # Column with the full DOI URLs
# "' target='_blank'>",
# Author, # Column with the display text (e.g., author name)
# "</a>"
# )
# ) %>%
# select(-DOI) # Remove the "DOI" column after linking it to the "author" column
#
# # Dynamically remove empty columns ("18", "19", etc.)
# multiexcel_data <- multiexcel_data %>%
# select(where(~ !all(is.na(.)) & !all(. == ""))) # Keep only non-empty columns
#
# # Render the data table with HTML content and no row names
# datatable(multiexcel_data,
# options = list(searching = FALSE),
# rownames = FALSE,
# escape = FALSE) # Allow HTML rendering
# })
#Render and hyperlink table + edit size so that everything fits into webpage
output$multiomicsdatatable <- renderDT({
# Transform the "author" column to contain hyperlinks using the "DOI" column
multiexcel_data <- multiexcel_data %>%
mutate(
Author = paste0(
"<a href='",
DOI, # Column with the full DOI URLs
"' target='_blank'>",
Author, # Column with the display text (e.g., author name)
"</a>"
)
) %>%
select(-DOI) # Remove the "DOI" column after linking it to the "author" column
# Dynamically remove empty columns ("18", "19", etc.)
multiexcel_data <- multiexcel_data %>%
select(where(~ !all(is.na(.)) & !all(. == ""))) # Keep only non-empty columns
# Render the data table with fit-to-page options
datatable(
multiexcel_data,
options = list(
autoWidth = TRUE, # Adjust column widths automatically
scrollX = TRUE, # Enable horizontal scrolling
pageLength = 10 # Limit rows displayed per page (adjustable)
),
rownames = FALSE,
escape = FALSE # Allow HTML rendering for links
)
})
# --- START: TaijiChat Message Handling ---
chat_history <- reactiveVal(list()) # Stores list of lists: list(role="user/assistant", content="message")
observeEvent(input$user_chat_message, {
req(input$user_chat_message)
user_message_text <- trimws(input$user_chat_message)
print(paste("TaijiChat: Received user_chat_message -", user_message_text))
if (nzchar(user_message_text)) {
# Check authentication (implement OAuth later in ui.R)
# For now, system works without auth, but logs as "anonymous"
current_user <- session$userData$hf_user
hf_user_id <- if (!is.null(current_user)) current_user$hf_user_id else "anonymous"
# Check quota before processing
if (!is.null(supabase_client) && !is.null(current_user)) {
quota_result <- check_user_quota(supabase_client, hf_user_id)
if (!quota_result$has_quota) {
session$sendCustomMessage(type = "agent_response", message = list(
text = paste("Token quota exceeded. Used:", quota_result$tokens_used, "Remaining: 0")
))
return()
}
}
current_hist <- chat_history()
updated_hist_user <- append(current_hist, list(list(role = "user", content = user_message_text)))
chat_history(updated_hist_user)
agent_instance_val <- rv_agent_instance()
# Set user context in agent
if (!is.null(agent_instance_val) && !is.null(current_user)) {
supabase_user <- session$userData$supabase_user
agent_instance_val$set_user_context(
user_id = supabase_user$id,
hf_user_id = hf_user_id
)
}
if (!is.null(agent_instance_val)) {
# Ensure history is a list of R named lists, then r_to_py will convert to list of Python dicts
py_hist_for_agent <- lapply(updated_hist_user, function(turn) {
list(role = turn$role, content = turn$content)
})
# py_hist_for_agent_converted <- reticulate::r_to_py(py_hist_for_agent)
# Send a "Thinking..." message to UI before long computation
session$sendCustomMessage(type = "agent_thinking_started", message = list(text = "Thinking..."))
tryCatch({
print(paste("TaijiChat: Sending to Python agent - Query:", user_message_text))
# For debugging, convert history to JSON string to see its structure if needed
# hist_json_debug <- jsonlite::toJSON(py_hist_for_agent, auto_unbox = TRUE)
# print(paste("TaijiChat: Conversation history (JSON for debug):", hist_json_debug))
# Get literature search preference (default to FALSE if not set)
literature_enabled <- if (is.null(input$literature_search_enabled)) FALSE else input$literature_search_enabled
print(paste("TaijiChat: Literature search enabled:", literature_enabled))
# Call Python agent method with literature preference
# The process_single_query method in Python expects history as a list of dicts.
# reticulate::r_to_py should handle the conversion of the list of R named lists.
agent_reply_py <- agent_instance_val$process_single_query_with_preferences(
user_query_text = user_message_text,
conversation_history_from_r = py_hist_for_agent, # Pass the R list of lists
literature_enabled = literature_enabled
)
# Explicitly convert potential Python object to R character string
agent_reply_text <- as.character(agent_reply_py)
print(paste("TaijiChat: Received from Python agent -", agent_reply_text))
# Check if this is an image response
if (startsWith(agent_reply_text, "TAIJICHAT_IMAGE_RESPONSE:")) {
# Extract the JSON part - START AFTER THE COLON IN THE PREFIX
json_str <- substr(agent_reply_text, 26, nchar(agent_reply_text))
# Debug the JSON string
print(paste("Attempting to parse JSON:", json_str))
# Try parsing in a safer way
tryCatch({
# Remove any leading/trailing whitespace and ensure proper JSON format
json_str <- trimws(json_str)
# Try to parse the JSON
image_info <- NULL
if (nchar(json_str) > 0) {
# Attempt to parse using various approaches
image_info <- tryCatch({
jsonlite::fromJSON(json_str)
}, error = function(e1) {
tryCatch({
# Try unescaping first
jsonlite::fromJSON(gsub('\\\\"', '"', json_str))
}, error = function(e2) {
NULL
})
})
}
if (!is.null(image_info) && !is.null(image_info$image_path)) {
# Debug image path
image_path_original <- image_info$image_path
image_path_normalized <- sub("^www/", "", image_info$image_path)
# Check if file exists
file_exists_check <- file.exists(image_path_original)
print(paste("Image path debug - Original:", image_path_original,
"Normalized:", image_path_normalized,
"File exists:", file_exists_check))
# Add a special marker to the message to trigger image display in UI
image_html <- paste0(
'<div class="chat-image-container">',
'<img src="', image_path_normalized, '" class="chat-image-preview" onclick="showFullImage(\'',
image_path_normalized, '\')">',
'</div>'
)
# Get original response or use a default
original_response <- ifelse(!is.null(image_info$original_response),
image_info$original_response,
"I've analyzed this image.")
# Combine the image HTML with the original text response
enhanced_reply <- paste0(
image_html,
"<br>",
original_response
)
agent_reply_text <- enhanced_reply
# Send a custom message to ensure the image display script is active
session$sendCustomMessage(type = "activate_image_viewer", message = list())
} else {
warning("Failed to extract image path from JSON")
agent_reply_text <- paste("I analyzed an image but had trouble displaying it. Here's what I found:",
gsub("TAIJICHAT_IMAGE_RESPONSE:.*", "", agent_reply_text))
}
}, error = function(e) {
warning(paste("JSON parsing error:", e$message, "- JSON string:", json_str))
print(paste("JSON parsing error:", e$message, "- JSON string:", json_str))
# Just use the original text in case of parsing error
agent_reply_text <- paste("I analyzed an image but had trouble displaying it. Here's what I found:",
substr(agent_reply_text, 25, nchar(agent_reply_text)))
})
}
final_hist <- append(updated_hist_user, list(list(role = "assistant", content = agent_reply_text)))
chat_history(final_hist)
session$sendCustomMessage(type = "agent_chat_response", message = list(text = agent_reply_text))
# Update quota display after successful query
if (!is.null(supabase_client) && !is.null(current_user)) {
quota_result <- check_user_quota(supabase_client, hf_user_id)
tokens_used <- quota_result$tokens_used
token_quota <- session$userData$supabase_user$token_quota %||% 100000
quota_text <- paste(tokens_used, "/", token_quota)
session$sendCustomMessage('update_quota', list(quota = quota_text))
}
}, error = function(e) {
error_message <- paste("TaijiChat: Error calling Python agent or processing response:", e$message)
warning(error_message)
print(error_message)
session$sendCustomMessage(type = "agent_chat_response", message = list(text = paste("Sorry, an error occurred with the agent.")))
})
} else {
warning("TaijiChat: Agent instance is NULL. Cannot process chat message.")
print("TaijiChat: Agent instance is NULL. Cannot process chat message.")
session$sendCustomMessage(type = "agent_chat_response", message = list(text = "The chat agent is not available. Please check server logs."))
}
} else {
print("TaijiChat: Received empty user_chat_message.")
}
})
# --- END: TaijiChat Message Handling ---
#Render and hyperlink table + edit size so that everything fits into webpage
output$multiomicsdatatable <- renderDT({
# Transform the "author" column to contain hyperlinks using the "DOI" column
multiexcel_data <- multiexcel_data %>%
mutate(
Author = paste0(
"<a href='",
DOI, # Column with the full DOI URLs
"' target='_blank'>",
Author, # Column with the display text (e.g., author name)
"</a>"
)
) %>%
select(-DOI) # Remove the "DOI" column after linking it to the "author" column
# Dynamically remove empty columns ("18", "19", etc.)
multiexcel_data <- multiexcel_data %>%
select(where(~ !all(is.na(.)) & !all(. == ""))) # Keep only non-empty columns
# Render the data table with fit-to-page options
datatable(
multiexcel_data,
options = list(
autoWidth = TRUE, # Adjust column widths automatically
scrollX = TRUE, # Enable horizontal scrolling
pageLength = 10 # Limit rows displayed per page (adjustable)
),
rownames = FALSE,
escape = FALSE # Allow HTML rendering for links
)
})
# Update reactive expressions to use warning overlay
output$tfData <- renderDT({
withWarningOverlayReactive(session, {
# Your existing reactive code here
# This will automatically show the warning overlay for long-running operations
}, "get_processed_tf_data")
})
}
# # ############################## CODE GRAVEYARD ############################## |