Spaces:
Sleeping
Sleeping
File size: 100,190 Bytes
950a339 |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "e549bafd-78b1-4a83-80b4-2cb597efff79",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import json\n",
"from google.oauth2 import service_account\n",
"from googleapiclient.discovery import build\n",
"from googleapiclient.http import MediaIoBaseDownload\n",
"import openai\n",
"from dotenv import load_dotenv, dotenv_values\n",
"import io"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "04361235-7896-4439-9d04-1400e043528b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"load_dotenv()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "9ae411c5-c84b-4bfd-b089-69b5c5ba70ae",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"OPENAI_API_KEY\n",
"ANTHROPIC_API_KEY\n",
"GOOGLE_SERVICE_ACCOUNT_FILE\n"
]
}
],
"source": [
"config = dotenv_values(\".env\")\n",
"for key in config.keys():\n",
" print(key)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "7622a0e4-64a6-4848-b588-bd65d56c55e0",
"metadata": {},
"outputs": [],
"source": [
"from openai import OpenAI\n",
"openai.api_key = os.getenv('OPENAI_API_KEY')\n",
"openai = OpenAI(api_key = openai.api_key)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "2ead7c59-1f11-478a-bb69-2928ddc38901",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello! How can I assist you today?\n"
]
}
],
"source": [
"response = openai.chat.completions.create(\n",
" model = \"gpt-4o-mini\",\n",
" messages = [\n",
" {\"role\":\"system\", \"content\":\"you are a helpful assistant\"},\n",
" {\"role\":\"user\", \"content\":\"hi\"}\n",
" ])\n",
"\n",
"reply = response.choices[0].message.content\n",
"print(reply)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "b3bcbada-6a72-4cc8-a166-d2e596cd1fc4",
"metadata": {},
"outputs": [],
"source": [
"service_account_file_path = os.getenv(\"GOOGLE_SERVICE_ACCOUNT_FILE\")"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "81c59a6d-0831-4bff-b3fc-fbe3d4cc1e31",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"openai activated\n",
"service_account_file_path activated\n"
]
}
],
"source": [
"#troubleshoot\n",
"if openai is None:\n",
" print(\"openai not activated\")\n",
"else: \n",
" print (\"openai activated\")\n",
"\n",
"if service_account_file_path is None:\n",
" print(\"service_account_file_path not activated\")\n",
"else: \n",
" print (\"service_account_file_path activated\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a70f32aa-9e43-4175-8cca-d6af723aef91",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 8,
"id": "0efe325d-badd-4533-affe-47d572ef128e",
"metadata": {},
"outputs": [],
"source": [
"class GPTDriveIntegration:\n",
" def __init__(self):\n",
" # Initialize Google Drive API\n",
" self.credentials = service_account.Credentials.from_service_account_file(\n",
" os.getenv('GOOGLE_SERVICE_ACCOUNT_FILE'),\n",
" scopes=['https://www.googleapis.com/auth/drive.readonly']\n",
" )\n",
" self.drive_service = build('drive', 'v3', credentials=self.credentials)\n",
" \n",
" # Initialize OpenAI\n",
" openai.api_key = os.getenv('OPENAI_API_KEY')\n",
" \n",
" def search_files(self, query, file_types=None):\n",
" \"\"\"Search for files in Google Drive\"\"\"\n",
" search_query = f\"name contains '{query}'\"\n",
" \n",
" if file_types:\n",
" type_queries = []\n",
" for file_type in file_types:\n",
" if file_type.lower() == 'pdf':\n",
" type_queries.append(\"mimeType='application/pdf'\")\n",
" elif file_type.lower() in ['doc', 'docx']:\n",
" type_queries.append(\"mimeType contains 'document'\")\n",
" elif file_type.lower() in ['xls', 'xlsx']:\n",
" type_queries.append(\"mimeType contains 'spreadsheet'\")\n",
" \n",
" if type_queries:\n",
" search_query += f\" and ({' or '.join(type_queries)})\"\n",
" \n",
" results = self.drive_service.files().list(\n",
" q=search_query,\n",
" fields=\"files(id, name, mimeType, size)\"\n",
" ).execute()\n",
" \n",
" return results.get('files', [])\n",
" \n",
" def get_file_content(self, file_id, mime_type):\n",
" \"\"\"Download and extract text content from file\"\"\"\n",
" try:\n",
" if 'text' in mime_type or 'document' in mime_type:\n",
" # For Google Docs, export as plain text\n",
" if 'document' in mime_type:\n",
" request = self.drive_service.files().export_media(\n",
" fileId=file_id, mimeType='text/plain'\n",
" )\n",
" else:\n",
" request = self.drive_service.files().get_media(fileId=file_id)\n",
" \n",
" file_content = io.BytesIO()\n",
" downloader = MediaIoBaseDownload(file_content, request)\n",
" done = False\n",
" while done is False:\n",
" status, done = downloader.next_chunk()\n",
" \n",
" return file_content.getvalue().decode('utf-8')\n",
" \n",
" elif 'spreadsheet' in mime_type:\n",
" # For Google Sheets, export as CSV\n",
" request = self.drive_service.files().export_media(\n",
" fileId=file_id, mimeType='text/csv'\n",
" )\n",
" file_content = io.BytesIO()\n",
" downloader = MediaIoBaseDownload(file_content, request)\n",
" done = False\n",
" while done is False:\n",
" status, done = downloader.next_chunk()\n",
" \n",
" return file_content.getvalue().decode('utf-8')\n",
" \n",
" elif mime_type == 'application/pdf':\n",
" # For PDF files, download binary content and extract text\n",
" request = self.drive_service.files().get_media(fileId=file_id)\n",
" file_content = io.BytesIO()\n",
" downloader = MediaIoBaseDownload(file_content, request)\n",
" done = False\n",
" while done is False:\n",
" status, done = downloader.next_chunk()\n",
" \n",
" # Extract text from PDF using PyPDF2 or pdfplumber\n",
" file_content.seek(0) # Reset buffer position\n",
" \n",
" # Option 1: Using PyPDF2\n",
" try:\n",
" import PyPDF2\n",
" pdf_reader = PyPDF2.PdfReader(file_content)\n",
" text = \"\"\n",
" for page in pdf_reader.pages:\n",
" text += page.extract_text() + \"\\n\"\n",
" return text\n",
" except ImportError:\n",
" pass\n",
" \n",
" # Option 2: Using pdfplumber (better for complex PDFs)\n",
" try:\n",
" import pdfplumber\n",
" text = \"\"\n",
" with pdfplumber.open(file_content) as pdf:\n",
" for page in pdf.pages:\n",
" page_text = page.extract_text()\n",
" if page_text:\n",
" text += page_text + \"\\n\"\n",
" return text\n",
" except ImportError:\n",
" pass\n",
" \n",
" # Option 3: Using pymupdf (fitz) - fastest option\n",
" try:\n",
" import fitz # pymupdf\n",
" pdf_document = fitz.open(stream=file_content.read(), filetype=\"pdf\")\n",
" text = \"\"\n",
" for page_num in range(pdf_document.page_count):\n",
" page = pdf_document[page_num]\n",
" text += page.get_text() + \"\\n\"\n",
" pdf_document.close()\n",
" return text\n",
" except ImportError:\n",
" pass\n",
" \n",
" return \"PDF text extraction requires PyPDF2, pdfplumber, or pymupdf library\"\n",
" \n",
" else:\n",
" return \"File type not supported for text extraction\"\n",
" \n",
" except Exception as e:\n",
" return f\"Error reading file: {str(e)}\"\n",
" \n",
" def query_gpt_with_context(self, user_query, file_contents):\n",
" \"\"\"Send query to GPT with file context\"\"\"\n",
" context = \"\\n\\n\".join([\n",
" f\"File: {content['name']}\\nContent: {content['text'][:2000]}...\"\n",
" for content in file_contents\n",
" ])\n",
" \n",
" messages = [\n",
" {\n",
" \"role\": \"system\", \n",
" \"content\": \"\"\"\n",
" You are an AI assistant that can analyze documents from Google Drive. \n",
" Use the provided file contents to answer user questions.\"\"\"\n",
" },\n",
" {\n",
" \"role\": \"user\", \n",
" \"content\": f\"Context from Google Drive files:\\n{context}\\n\\nUser Question: {user_query}\"\n",
" }\n",
" ]\n",
" \n",
" response = openai.chat.completions.create(\n",
" model=\"gpt-4o-mini\",\n",
" messages=messages,\n",
" max_tokens=1000\n",
" )\n",
" \n",
" return response.choices[0].message.content\n",
" \n",
" def process_query(self, user_query, search_terms=None):\n",
" \"\"\"Main function to process user queries\"\"\"\n",
" # Extract search terms from query if not provided\n",
" if not search_terms:\n",
" search_terms = user_query.split()[:3] # Simple extraction\n",
" \n",
" # Search for relevant files\n",
" files = []\n",
" for term in search_terms:\n",
" files.extend(self.search_files(term))\n",
" \n",
" # Remove duplicates\n",
" unique_files = {f['id']: f for f in files}.values()\n",
" \n",
" # Get content from top 3 most relevant files\n",
" file_contents = []\n",
" for file in list(unique_files)[:3]:\n",
" content = self.get_file_content(file['id'], file['mimeType'])\n",
" file_contents.append({\n",
" 'name': file['name'],\n",
" 'text': content\n",
" })\n",
" \n",
" # Query GPT with context\n",
" if file_contents:\n",
" response = self.query_gpt_with_context(user_query, file_contents)\n",
" return {\n",
" 'answer': response,\n",
" 'sources': [f['name'] for f in file_contents]\n",
" }\n",
" else:\n",
" return {\n",
" 'answer': \"No relevant files found in your Google Drive.\",\n",
" 'sources': []\n",
" }"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "3c2c1ccf-9ade-482d-a170-978e97bc1c08",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Answer: The transmission of nerves is called \"nerve conduction.\" This process involves the propagation of electrical impulses along the nerve fibers, allowing for communication between different parts of the body.\n",
"Sources: ['Neuro Note Dr Clement.docx']\n"
]
}
],
"source": [
"if __name__ == \"__main__\":\n",
" integration = GPTDriveIntegration()\n",
" \n",
" # Test query\n",
" result = integration.process_query(\n",
" \"The transmission of nerves is called?\",\n",
" search_terms=[\"nerves\", \"Dr Clement\"]\n",
" )\n",
" \n",
" print(\"Answer:\", result['answer'])\n",
" print(\"Sources:\", result['sources'])"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "120e7c93-b38a-4c89-8e76-5b0170d22548",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "61e976a6-1fe4-45de-a63d-3cf849eedbe1",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 11,
"id": "c514b8af-1af4-4497-9044-139a71aedd36",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"* Running on local URL: http://127.0.0.1:7860\n",
"* Running on public URL: https://5320171f6af3e2eef9.gradio.live\n",
"\n",
"This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n"
]
},
{
"data": {
"text/html": [
"<div><iframe src=\"https://5320171f6af3e2eef9.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Keyboard interruption in main thread... closing server.\n",
"Killing tunnel 127.0.0.1:7860 <> https://5320171f6af3e2eef9.gradio.live\n"
]
}
],
"source": [
"gpt_drive = GPTDriveIntegration()\n",
"\n",
"def process_user_query(query, search_terms_input):\n",
" \"\"\"Process user query and return formatted response\"\"\"\n",
" if not query.strip():\n",
" return \"Please enter a question.\", \"\"\n",
" \n",
" # Parse search terms if provided\n",
" search_terms = None\n",
" # if search_terms_input.strip():\n",
" # search_terms = [term.strip() for term in search_terms_input.split(',')]\n",
" \n",
" # Process the query\n",
" result = gpt_drive.process_query(query, search_terms)\n",
" \n",
" # Format the response\n",
" answer = result['answer']\n",
" sources = result['sources']\n",
" \n",
" sources_text = \"\"\n",
" if sources:\n",
" sources_text = \"**Sources used:**\\n\" + \"\\n\".join([f\"β’ {source}\" for source in sources])\n",
" \n",
" return answer, sources_text\n",
"\n",
"def check_setup():\n",
" \"\"\"Check if the APIs are properly configured\"\"\"\n",
" status_messages = []\n",
" \n",
" # Check Google Drive API\n",
" if gpt_drive.drive_initialized:\n",
" status_messages.append(\"β
Google Drive API: Connected\")\n",
" else:\n",
" status_messages.append(f\"β Google Drive API: {getattr(gpt_drive, 'drive_error', 'Not configured')}\")\n",
" \n",
" # Check OpenAI API\n",
" if gpt_drive.openai_initialized:\n",
" status_messages.append(\"β
OpenAI API: Connected\")\n",
" else:\n",
" status_messages.append(f\"β OpenAI API: {getattr(gpt_drive, 'openai_error', 'Not configured')}\")\n",
" \n",
" return \"\\n\".join(status_messages)\n",
"\n",
"# Create Gradio interface\n",
"with gr.Blocks(title=\"Augusta's Anatomy Reading Assistant\", theme=gr.themes.Soft()) as app:\n",
" gr.Markdown(\"# π€ Augusta's Anatomy bot\")\n",
" gr.Markdown(\"Ask questions about your anatomy books using AI!\")\n",
" \n",
" with gr.Row():\n",
" with gr.Column(scale=2):\n",
" # Main query interface\n",
" with gr.Group():\n",
" gr.Markdown(\"### Ask a Question\")\n",
" query_input = gr.Textbox(\n",
" label=\"Your Question\",\n",
" placeholder=\"Ask me any question about your anatomy books?\",\n",
" lines=3\n",
" )\n",
" \n",
" search_terms_input = gr.Textbox(\n",
" label=\"Search Terms (optional)\",\n",
" placeholder=\"Enter comma-separated terms to search for specific files\",\n",
" lines=1\n",
" )\n",
" \n",
" submit_btn = gr.Button(\"Search & Ask\", variant=\"primary\", size=\"lg\")\n",
" \n",
" # Results section\n",
" with gr.Group():\n",
" gr.Markdown(\"### Answer\")\n",
" answer_output = gr.Textbox(\n",
" label=\"AI Response\",\n",
" lines=10,\n",
" interactive=False\n",
" )\n",
" \n",
" sources_output = gr.Textbox(\n",
" label=\"Sources\",\n",
" lines=3,\n",
" interactive=False\n",
" )\n",
" \n",
" with gr.Column(scale=1):\n",
" # Status and setup info\n",
" with gr.Group():\n",
" gr.Markdown(\"### System Status\")\n",
" status_btn = gr.Button(\"Check Status\", size=\"sm\")\n",
" status_output = gr.Textbox(\n",
" label=\"API Status\",\n",
" lines=4,\n",
" interactive=False\n",
" )\n",
" \n",
" with gr.Group():\n",
" gr.Markdown(\"### Setup Instructions\")\n",
" gr.Markdown(\"\"\"\n",
" **Important Notes:**\n",
" 1.Only documents shared with it, it can answer\n",
" \n",
" **File Types Supported:**\n",
" - Google Docs\n",
" - Google Sheets \n",
" - PDF files\n",
" - Text files\n",
" \n",
" **Tips:**\n",
" - Use specific search terms for better results\n",
" - The system searches the top 3 most relevant files\n",
" - Ask clear, specific questions for better answers\n",
" \"\"\")\n",
" \n",
" # Event handlers\n",
" submit_btn.click(\n",
" fn=process_user_query,\n",
" inputs=[query_input, search_terms_input],\n",
" outputs=[answer_output, sources_output]\n",
" )\n",
" \n",
" status_btn.click(\n",
" fn=check_setup,\n",
" outputs=status_output\n",
" )\n",
" \n",
" # Example queries\n",
" with gr.Row():\n",
" gr.Examples(\n",
" examples=[\n",
" [\"What is morbid Anatomy?\", \"morbid, Anatomy\"],\n",
" [\"The transmission of nerves from one neuron to another is as a result of what?\", \"neuron, nerves, Dr Clement\"],\n",
" ],\n",
" inputs=[query_input, search_terms_input],\n",
" )\n",
"\n",
"# Launch the app\n",
"if __name__ == \"__main__\":\n",
" app.launch(\n",
" share=True,debug =True)"
]
},
{
"cell_type": "code",
"execution_count": 42,
"id": "593c4f63-cdda-46e8-aad6-9f9d7db66615",
"metadata": {},
"outputs": [],
"source": [
"#Gradio\n",
"# !pip install gradio"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "859060a9-56f9-49e9-bb41-04ccf7b10d3f",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "d893999c-4f3f-4306-8b0b-072e3fbb8236",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 10,
"id": "01b70311-ff22-4c88-bf22-64dc441afaab",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"C:\\Users\\Uche Buzz\\anaconda3\\envs\\RAG\\Lib\\site-packages\\tqdm\\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
" from .autonotebook import tqdm as notebook_tqdm\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"* Running on local URL: http://127.0.0.1:7860\n",
"* Running on public URL: https://8fac475cac6193423b.gradio.live\n",
"\n",
"This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n"
]
},
{
"data": {
"text/html": [
"<div><iframe src=\"https://8fac475cac6193423b.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Keyboard interruption in main thread... closing server.\n",
"Killing tunnel 127.0.0.1:7860 <> https://8fac475cac6193423b.gradio.live\n"
]
}
],
"source": [
"import gradio as gr\n",
"import os\n",
"import io\n",
"import openai\n",
"from google.oauth2 import service_account\n",
"from googleapiclient.discovery import build\n",
"from googleapiclient.http import MediaIoBaseDownload\n",
"\n",
"class GPTDriveIntegration:\n",
" def __init__(self):\n",
" # Initialize Google Drive API\n",
" try:\n",
" self.credentials = service_account.Credentials.from_service_account_file(\n",
" os.getenv('GOOGLE_SERVICE_ACCOUNT_FILE'),\n",
" scopes=['https://www.googleapis.com/auth/drive.readonly']\n",
" )\n",
" self.drive_service = build('drive', 'v3', credentials=self.credentials)\n",
" self.drive_initialized = True\n",
" except Exception as e:\n",
" self.drive_initialized = False\n",
" self.drive_error = str(e)\n",
" \n",
" # Initialize OpenAI\n",
" try:\n",
" openai.api_key = os.getenv('OPENAI_API_KEY')\n",
" self.openai_initialized = True\n",
" except Exception as e:\n",
" self.openai_initialized = False\n",
" self.openai_error = str(e)\n",
" \n",
" def search_files(self, query, file_types=None):\n",
" \"\"\"Search for files in Google Drive\"\"\"\n",
" if not self.drive_initialized:\n",
" return []\n",
" \n",
" search_query = f\"name contains '{query}'\"\n",
" \n",
" if file_types:\n",
" type_queries = []\n",
" for file_type in file_types:\n",
" if file_type.lower() == 'pdf':\n",
" type_queries.append(\"mimeType='application/pdf'\")\n",
" elif file_type.lower() in ['doc', 'docx']:\n",
" type_queries.append(\"mimeType contains 'document'\")\n",
" elif file_type.lower() in ['xls', 'xlsx']:\n",
" type_queries.append(\"mimeType contains 'spreadsheet'\")\n",
" \n",
" if type_queries:\n",
" search_query += f\" and ({' or '.join(type_queries)})\"\n",
" \n",
" try:\n",
" results = self.drive_service.files().list(\n",
" q=search_query,\n",
" fields=\"files(id, name, mimeType, size)\"\n",
" ).execute()\n",
" \n",
" return results.get('files', [])\n",
" except Exception as e:\n",
" return []\n",
" \n",
" def get_file_content(self, file_id, mime_type):\n",
" \"\"\"Download and extract text content from file\"\"\"\n",
" try:\n",
" if 'text' in mime_type or 'document' in mime_type:\n",
" # For Google Docs, export as plain text\n",
" if 'document' in mime_type:\n",
" request = self.drive_service.files().export_media(\n",
" fileId=file_id, mimeType='text/plain'\n",
" )\n",
" else:\n",
" request = self.drive_service.files().get_media(fileId=file_id)\n",
" \n",
" file_content = io.BytesIO()\n",
" downloader = MediaIoBaseDownload(file_content, request)\n",
" done = False\n",
" while done is False:\n",
" status, done = downloader.next_chunk()\n",
" \n",
" return file_content.getvalue().decode('utf-8')\n",
" \n",
" elif 'spreadsheet' in mime_type:\n",
" # For Google Sheets, export as CSV\n",
" request = self.drive_service.files().export_media(\n",
" fileId=file_id, mimeType='text/csv'\n",
" )\n",
" file_content = io.BytesIO()\n",
" downloader = MediaIoBaseDownload(file_content, request)\n",
" done = False\n",
" while done is False:\n",
" status, done = downloader.next_chunk()\n",
" \n",
" return file_content.getvalue().decode('utf-8')\n",
" \n",
" else:\n",
" return \"File type not supported for text extraction\"\n",
" \n",
" except Exception as e:\n",
" return f\"Error reading file: {str(e)}\"\n",
" \n",
" def query_gpt_with_context(self, user_query, file_contents):\n",
" \"\"\"Send query to GPT with file context\"\"\"\n",
" context = \"\\n\\n\".join([\n",
" f\"File: {content['name']}\\nContent: {content['text'][:2000]}...\"\n",
" for content in file_contents\n",
" ])\n",
" \n",
" messages = [\n",
" {\n",
" \"role\": \"system\", \n",
" \"content\": \"\"\"\n",
" You are an AI assistant that can analyze anatomy documents from Google Drive. \n",
" Use the provided file contents to answer user questions. Always answer straightforwardly. Don't Hallucinate.\n",
" Always end with 'Do you have any other question?'\n",
" \n",
" \"\"\"\n",
" },\n",
" {\n",
" \"role\": \"user\", \n",
" \"content\": f\"Context from Google Drive files:\\n{context}\\n\\nUser Question: {user_query}\"\n",
" }\n",
" ]\n",
" \n",
" try:\n",
" response = openai.chat.completions.create(\n",
" model=\"gpt-4o-mini\",\n",
" messages=messages,\n",
" max_tokens=1000\n",
" )\n",
" \n",
" return response.choices[0].message.content\n",
" except Exception as e:\n",
" return f\"Error querying OpenAI: {str(e)}\"\n",
" \n",
" def process_query(self, user_query, search_terms=None):\n",
" \"\"\"Main function to process user queries\"\"\"\n",
" # Check if services are initialized\n",
" if not self.drive_initialized:\n",
" return {\n",
" 'answer': f\"Google Drive API not initialized: {getattr(self, 'drive_error', 'Unknown error')}\",\n",
" 'sources': []\n",
" }\n",
" \n",
" if not self.openai_initialized:\n",
" return {\n",
" 'answer': f\"OpenAI API not initialized: {getattr(self, 'openai_error', 'Unknown error')}\",\n",
" 'sources': []\n",
" }\n",
" \n",
" # Extract search terms from query if not provided\n",
" if not search_terms:\n",
" search_terms = user_query.split()[:3] # Simple extraction\n",
" \n",
" # Search for relevant files\n",
" files = []\n",
" for term in search_terms:\n",
" files.extend(self.search_files(term))\n",
" \n",
" # Remove duplicates\n",
" unique_files = {f['id']: f for f in files}.values()\n",
" \n",
" # Get content from top 3 most relevant files\n",
" file_contents = []\n",
" for file in list(unique_files)[:3]:\n",
" content = self.get_file_content(file['id'], file['mimeType'])\n",
" file_contents.append({\n",
" 'name': file['name'],\n",
" 'text': content\n",
" })\n",
" \n",
" # Query GPT with context\n",
" if file_contents:\n",
" response = self.query_gpt_with_context(user_query, file_contents)\n",
" return {\n",
" 'answer': response,\n",
" 'sources': [f['name'] for f in file_contents]\n",
" }\n",
" else:\n",
" return {\n",
" 'answer': \"No relevant files found in your Google Drive.\",\n",
" 'sources': []\n",
" }\n",
"\n",
"# Initialize the GPT Drive Integration\n",
"gpt_drive = GPTDriveIntegration()\n",
"\n",
"def process_user_query(query, search_terms_input):\n",
" \"\"\"Process user query and return formatted response\"\"\"\n",
" if not query.strip():\n",
" return \"Please enter a question.\", \"\"\n",
" \n",
" # Parse search terms if provided\n",
" search_terms = None\n",
" if search_terms_input.strip():\n",
" search_terms = [term.strip() for term in search_terms_input.split(',')]\n",
" \n",
" # Process the query\n",
" result = gpt_drive.process_query(query, search_terms)\n",
" \n",
" # Format the response\n",
" answer = result['answer']\n",
" sources = result['sources']\n",
" \n",
" sources_text = \"\"\n",
" if sources:\n",
" sources_text = \"**Sources used:**\\n\" + \"\\n\".join([f\"β’ {source}\" for source in sources])\n",
" \n",
" return answer, sources_text\n",
"\n",
"def check_setup():\n",
" \"\"\"Check if the APIs are properly configured\"\"\"\n",
" status_messages = []\n",
" \n",
" # Check Google Drive API\n",
" if gpt_drive.drive_initialized:\n",
" status_messages.append(\"β
Google Drive API: Connected\")\n",
" else:\n",
" status_messages.append(f\"β Google Drive API: {getattr(gpt_drive, 'drive_error', 'Not configured')}\")\n",
" \n",
" # Check OpenAI API\n",
" if gpt_drive.openai_initialized:\n",
" status_messages.append(\"β
OpenAI API: Connected\")\n",
" else:\n",
" status_messages.append(f\"β OpenAI API: {getattr(gpt_drive, 'openai_error', 'Not configured')}\")\n",
" \n",
" return \"\\n\".join(status_messages)\n",
"\n",
"# Create Gradio interface\n",
"with gr.Blocks(title=\"Augusta's Anatomy Reading Assistant\", theme=gr.themes.Soft()) as app:\n",
" gr.Markdown(\"# π€ Augusta's Anatomy bot\")\n",
" gr.Markdown(\"Ask questions about your anatomy books using AI!\")\n",
" \n",
" with gr.Row():\n",
" with gr.Column(scale=2):\n",
" # Main query interface\n",
" with gr.Group():\n",
" gr.Markdown(\"### Ask a Question\")\n",
" query_input = gr.Textbox(\n",
" label=\"Your Question\",\n",
" placeholder=\"Ask me any question about your anatomy books?\",\n",
" lines=3\n",
" )\n",
" \n",
" search_terms_input = gr.Textbox(\n",
" label=\"Search Terms (optional)\",\n",
" placeholder=\"Enter comma-separated terms to search for specific files\",\n",
" lines=1\n",
" )\n",
" \n",
" submit_btn = gr.Button(\"Search & Ask\", variant=\"primary\", size=\"lg\")\n",
" \n",
" # Results section\n",
" with gr.Group():\n",
" gr.Markdown(\"### Answer\")\n",
" answer_output = gr.Textbox(\n",
" label=\"AI Response\",\n",
" lines=10,\n",
" interactive=False\n",
" )\n",
" \n",
" sources_output = gr.Textbox(\n",
" label=\"Sources\",\n",
" lines=3,\n",
" interactive=False\n",
" )\n",
" \n",
" with gr.Column(scale=1):\n",
" # Status and setup info\n",
" with gr.Group():\n",
" gr.Markdown(\"### System Status\")\n",
" status_btn = gr.Button(\"Check Status\", size=\"sm\")\n",
" status_output = gr.Textbox(\n",
" label=\"API Status\",\n",
" lines=4,\n",
" interactive=False\n",
" )\n",
" \n",
" with gr.Group():\n",
" gr.Markdown(\"### Setup Instructions\")\n",
" gr.Markdown(\"\"\"\n",
" **Important Notes:**\n",
" 1.Only documents shared with it, it can answer\n",
" \n",
" **File Types Supported:**\n",
" - Google Docs\n",
" - Google Sheets \n",
" - PDF files\n",
" - Text files\n",
" \n",
" **Tips:**\n",
" - Use specific search terms for better results\n",
" - The system searches the top 3 most relevant files\n",
" - Ask clear, specific questions for better answers\n",
" \"\"\")\n",
" \n",
" # Event handlers\n",
" submit_btn.click(\n",
" fn=process_user_query,\n",
" inputs=[query_input, search_terms_input],\n",
" outputs=[answer_output, sources_output]\n",
" )\n",
" \n",
" status_btn.click(\n",
" fn=check_setup,\n",
" outputs=status_output\n",
" )\n",
" \n",
" # Example queries\n",
" with gr.Row():\n",
" gr.Examples(\n",
" examples=[\n",
" [\"What is morbid Anatomy?\", \"morbid, Anatomy\"],\n",
" [\"The transmission of nerves from one neuron to another is as a result of what?\", \"neuron, nerves, Dr Clement\"],\n",
" ],\n",
" inputs=[query_input, search_terms_input],\n",
" )\n",
"\n",
"# Launch the app\n",
"if __name__ == \"__main__\":\n",
" app.launch(\n",
" share=True,\n",
" debug=True\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a6fd9c8c-e8e9-4b1c-8d21-d7ea2c42303a",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "95c85a4f-470f-4858-8172-78d7f9d04d1a",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "f237c114-7924-4074-9c11-c7ba13833293",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "a2f9c7ae-35bb-4261-adc4-f24c6ab5c8a1",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "aaa446b0-a14e-4c98-b466-f503a521f052",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "5770d683-7bfc-49e9-a3c4-a67060e27620",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "2ef7744c-1346-4692-ac28-013ae0e8c4ac",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "08643ace-f94f-4a4a-bbc1-3289b7fc29a1",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "70849fd3-6f4e-4c57-b780-bda53db83e14",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "c18d5d20-439a-45a7-a847-25f659fd4a10",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 11,
"id": "634b9787-d493-46e5-8114-0851c6172ed6",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"π Starting Google Drive API Diagnostic...\n",
"==================================================\n",
"\n",
"1οΈβ£ Checking service account file...\n",
"β
Service account file is valid\n",
" π§ Service account email: rag-base@rag-system-463320.iam.gserviceaccount.com\n",
" ποΈ Project ID: rag-system-463320\n",
"\n",
"2οΈβ£ Checking credentials...\n",
"β
Credentials created successfully\n",
"\n",
"3οΈβ£ Testing API connection...\n",
"β
Successfully connected to Google Drive API\n",
" π€ Connected as: rag-base@rag-system-463320.iam.gserviceaccount.com\n",
"\n",
"4οΈβ£ Checking basic permissions...\n",
"β
Can access Drive API - found 0 files in test query\n",
"β οΈ No files found - this might mean:\n",
" β’ Service account has no shared files\n",
" β’ No files are shared with the service account\n",
"\n",
"5οΈβ£ Testing access to 'Blue berry' folder...\n",
"β Folder 'Blue berry' not found or not accessible\n",
"π‘ Possible solutions:\n",
" β’ Make sure the folder exists in Google Drive\n",
" β’ Share the folder with your service account email\n",
" β’ Check folder name spelling (case sensitive)\n",
"\n",
"β
All basic checks passed!\n"
]
}
],
"source": [
"import json\n",
"from google.auth.exceptions import RefreshError\n",
"from googleapiclient.errors import HttpError\n",
"\n",
"class GPTDriveTroubleshooter:\n",
" def __init__(self, service_account_file_path):\n",
" self.service_account_file = service_account_file_path\n",
" self.credentials = None\n",
" self.drive_service = None\n",
" \n",
" def run_full_diagnostic(self):\n",
" \"\"\"Run complete diagnostic check\"\"\"\n",
" print(\"π Starting Google Drive API Diagnostic...\")\n",
" print(\"=\" * 50)\n",
" \n",
" # Step 1: Check service account file\n",
" if not self.check_service_account_file():\n",
" return False\n",
" \n",
" # Step 2: Check credentials\n",
" if not self.check_credentials():\n",
" return False\n",
" \n",
" # Step 3: Test API connection\n",
" if not self.test_api_connection():\n",
" return False\n",
" \n",
" # Step 4: Check permissions\n",
" if not self.check_basic_permissions():\n",
" return False\n",
" \n",
" # Step 5: Test folder access\n",
" self.test_folder_access()\n",
" \n",
" print(\"\\nβ
All basic checks passed!\")\n",
" return True\n",
" \n",
" def check_service_account_file(self):\n",
" \"\"\"Check if service account file exists and is valid\"\"\"\n",
" print(\"\\n1οΈβ£ Checking service account file...\")\n",
" \n",
" if not os.path.exists(self.service_account_file):\n",
" print(f\"β Service account file not found: {self.service_account_file}\")\n",
" print(\"π‘ Make sure you've downloaded the JSON key file from Google Cloud Console\")\n",
" return False\n",
" \n",
" try:\n",
" with open(self.service_account_file, 'r') as f:\n",
" service_account_info = json.load(f)\n",
" \n",
" required_fields = ['type', 'project_id', 'private_key_id', 'private_key', 'client_email']\n",
" missing_fields = [field for field in required_fields if field not in service_account_info]\n",
" \n",
" if missing_fields:\n",
" print(f\"β Service account file missing required fields: {missing_fields}\")\n",
" return False\n",
" \n",
" print(f\"β
Service account file is valid\")\n",
" print(f\" π§ Service account email: {service_account_info['client_email']}\")\n",
" print(f\" ποΈ Project ID: {service_account_info['project_id']}\")\n",
" \n",
" return True\n",
" \n",
" except json.JSONDecodeError:\n",
" print(\"β Service account file is not valid JSON\")\n",
" return False\n",
" except Exception as e:\n",
" print(f\"β Error reading service account file: {e}\")\n",
" return False\n",
" \n",
" def check_credentials(self):\n",
" \"\"\"Check if credentials can be created\"\"\"\n",
" print(\"\\n2οΈβ£ Checking credentials...\")\n",
" \n",
" try:\n",
" self.credentials = service_account.Credentials.from_service_account_file(\n",
" self.service_account_file,\n",
" scopes=['https://www.googleapis.com/auth/drive.readonly']\n",
" )\n",
" print(\"β
Credentials created successfully\")\n",
" return True\n",
" \n",
" except Exception as e:\n",
" print(f\"β Failed to create credentials: {e}\")\n",
" print(\"π‘ Check if your service account key file is corrupted\")\n",
" return False\n",
" \n",
" def test_api_connection(self):\n",
" \"\"\"Test basic API connection\"\"\"\n",
" print(\"\\n3οΈβ£ Testing API connection...\")\n",
" \n",
" try:\n",
" self.drive_service = build('drive', 'v3', credentials=self.credentials)\n",
" \n",
" # Try a simple API call\n",
" about = self.drive_service.about().get(fields=\"user, storageQuota\").execute()\n",
" print(\"β
Successfully connected to Google Drive API\")\n",
" print(f\" π€ Connected as: {about.get('user', {}).get('emailAddress', 'Unknown')}\")\n",
" \n",
" return True\n",
" \n",
" except HttpError as e:\n",
" print(f\"β HTTP Error connecting to API: {e}\")\n",
" if e.resp.status == 403:\n",
" print(\"π‘ This is likely a permissions issue - check if Drive API is enabled\")\n",
" return False\n",
" except Exception as e:\n",
" print(f\"β Failed to connect to API: {e}\")\n",
" return False\n",
" \n",
" def check_basic_permissions(self):\n",
" \"\"\"Check basic file listing permissions\"\"\"\n",
" print(\"\\n4οΈβ£ Checking basic permissions...\")\n",
" \n",
" try:\n",
" # Try to list files (this should work with readonly access)\n",
" results = self.drive_service.files().list(\n",
" pageSize=1,\n",
" fields=\"files(id, name)\"\n",
" ).execute()\n",
" \n",
" files = results.get('files', [])\n",
" print(f\"β
Can access Drive API - found {len(files)} files in test query\")\n",
" \n",
" if len(files) == 0:\n",
" print(\"β οΈ No files found - this might mean:\")\n",
" print(\" β’ Service account has no shared files\")\n",
" print(\" β’ No files are shared with the service account\")\n",
" \n",
" return True\n",
" \n",
" except HttpError as e:\n",
" print(f\"β Permission error: {e}\")\n",
" if e.resp.status == 403:\n",
" print(\"π‘ Common causes:\")\n",
" print(\" β’ Google Drive API not enabled in Google Cloud Console\")\n",
" print(\" β’ Service account doesn't have proper permissions\")\n",
" return False\n",
" except Exception as e:\n",
" print(f\"β Error checking permissions: {e}\")\n",
" return False\n",
" \n",
" def test_folder_access(self, folder_name=\"Blue berry\"):\n",
" \"\"\"Test access to specific folder\"\"\"\n",
" print(f\"\\n5οΈβ£ Testing access to '{folder_name}' folder...\")\n",
" \n",
" try:\n",
" # Search for the folder\n",
" query = f\"name='{folder_name}' and mimeType='application/vnd.google-apps.folder' and trashed=false\"\n",
" results = self.drive_service.files().list(\n",
" q=query,\n",
" fields=\"files(id, name, owners, permissions)\"\n",
" ).execute()\n",
" \n",
" folders = results.get('files', [])\n",
" \n",
" if not folders:\n",
" print(f\"β Folder '{folder_name}' not found or not accessible\")\n",
" print(\"π‘ Possible solutions:\")\n",
" print(\" β’ Make sure the folder exists in Google Drive\")\n",
" print(\" β’ Share the folder with your service account email\")\n",
" print(\" β’ Check folder name spelling (case sensitive)\")\n",
" return False\n",
" \n",
" folder = folders[0]\n",
" print(f\"β
Found folder '{folder_name}'\")\n",
" print(f\" π Folder ID: {folder['id']}\")\n",
" \n",
" # Test listing files in the folder\n",
" files_in_folder = self.drive_service.files().list(\n",
" q=f\"'{folder['id']}' in parents and trashed=false\",\n",
" fields=\"files(id, name, mimeType)\"\n",
" ).execute()\n",
" \n",
" files = files_in_folder.get('files', [])\n",
" print(f\" π Contains {len(files)} files\")\n",
" \n",
" if files:\n",
" print(\" π Sample files:\")\n",
" for file in files[:3]: # Show first 3 files\n",
" print(f\" β’ {file['name']} ({file['mimeType']})\")\n",
" \n",
" return True\n",
" \n",
" except HttpError as e:\n",
" print(f\"β HTTP Error accessing folder: {e}\")\n",
" return False\n",
" except Exception as e:\n",
" print(f\"β Error accessing folder: {e}\")\n",
" return False\n",
" \n",
" def check_file_permissions(self, file_id):\n",
" \"\"\"Check permissions for a specific file\"\"\"\n",
" print(f\"\\nπ Checking permissions for file ID: {file_id}\")\n",
" \n",
" try:\n",
" file_info = self.drive_service.files().get(\n",
" fileId=file_id,\n",
" fields=\"id, name, mimeType, owners, permissions, capabilities\"\n",
" ).execute()\n",
" \n",
" print(f\"β
File: {file_info['name']}\")\n",
" print(f\" π Type: {file_info['mimeType']}\")\n",
" print(f\" π€ Owner: {file_info.get('owners', [{}])[0].get('emailAddress', 'Unknown')}\")\n",
" \n",
" capabilities = file_info.get('capabilities', {})\n",
" print(f\" π Can read: {capabilities.get('canDownload', False)}\")\n",
" print(f\" π€ Can export: {capabilities.get('canExport', False)}\")\n",
" \n",
" except HttpError as e:\n",
" print(f\"β Cannot access file: {e}\")\n",
" except Exception as e:\n",
" print(f\"β Error: {e}\")\n",
" \n",
" def get_sharing_instructions(self):\n",
" \"\"\"Provide step-by-step sharing instructions\"\"\"\n",
" print(\"\\nπ HOW TO SHARE FOLDER WITH SERVICE ACCOUNT:\")\n",
" print(\"=\" * 50)\n",
" \n",
" if self.credentials:\n",
" service_email = self.credentials.service_account_email\n",
" print(f\"1. Copy this service account email: {service_email}\")\n",
" else:\n",
" print(\"1. Find your service account email in the JSON key file (client_email field)\")\n",
" \n",
" print(\"2. Open Google Drive in your browser\")\n",
" print(\"3. Right-click on your 'Blue berry' folder\")\n",
" print(\"4. Select 'Share'\")\n",
" print(\"5. Paste the service account email\")\n",
" print(\"6. Set permission to 'Viewer' or 'Editor'\")\n",
" print(\"7. Click 'Send' (you can uncheck 'Notify people')\")\n",
" print(\"8. Wait a few minutes for permissions to propagate\")\n",
" \n",
" def run_connection_test(self):\n",
" \"\"\"Quick connection test\"\"\"\n",
" print(\"π Quick Connection Test\")\n",
" print(\"-\" * 30)\n",
" \n",
" try:\n",
" self.credentials = service_account.Credentials.from_service_account_file(\n",
" self.service_account_file,\n",
" scopes=['https://www.googleapis.com/auth/drive.readonly']\n",
" )\n",
" \n",
" service = build('drive', 'v3', credentials=self.credentials)\n",
" \n",
" # Test basic query\n",
" results = service.files().list(pageSize=5).execute()\n",
" files = results.get('files', [])\n",
" \n",
" print(f\"β
Connected! Found {len(files)} accessible files\")\n",
" print(f\"π§ Service account: {self.credentials.service_account_email}\")\n",
" \n",
" return True\n",
" \n",
" except Exception as e:\n",
" print(f\"β Connection failed: {e}\")\n",
" return False\n",
"\n",
"# Usage Examples\n",
"def troubleshoot_drive_access():\n",
" \"\"\"Main troubleshooting function\"\"\"\n",
" service_account_file = os.getenv('GOOGLE_SERVICE_ACCOUNT_FILE')\n",
" \n",
" if not service_account_file:\n",
" print(\"β GOOGLE_SERVICE_ACCOUNT_FILE environment variable not set\")\n",
" print(\"π‘ Add this to your .env file:\")\n",
" print(\"GOOGLE_SERVICE_ACCOUNT_FILE=path/to/your/service-account-key.json\")\n",
" return\n",
" \n",
" troubleshooter = GPTDriveTroubleshooter(service_account_file)\n",
" \n",
" # Run full diagnostic\n",
" success = troubleshooter.run_full_diagnostic()\n",
" \n",
" if not success:\n",
" print(\"\\n\" + \"=\"*50)\n",
" troubleshooter.get_sharing_instructions()\n",
" \n",
" return success\n",
"\n",
"# Quick test function\n",
"def quick_test():\n",
" \"\"\"Quick test to verify everything works\"\"\"\n",
" service_account_file = os.getenv('GOOGLE_SERVICE_ACCOUNT_FILE')\n",
" troubleshooter = GPTDriveTroubleshooter(service_account_file)\n",
" return troubleshooter.run_connection_test()\n",
"\n",
"if __name__ == \"__main__\":\n",
" # Uncomment the test you want to run:\n",
" \n",
" # Full diagnostic (recommended for first-time setup)\n",
" troubleshoot_drive_access()\n",
" \n",
" # Quick test (for regular checks)\n",
" # quick_test()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6b336789-d402-455d-a631-26e987d79ed6",
"metadata": {},
"outputs": [],
"source": [
"troubleshooter = GPTDriveTroubleshooter(GOOGLE_SERVICE_ACCOUNT_FILE)\n",
"troubleshooter.test_folder_access(\"Blue berry\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e2786c67-215e-46b0-b3ca-2c3176bd8971",
"metadata": {},
"outputs": [],
"source": [
"# Add this test function to verify access\n",
"def test_folder_access():\n",
" integration = GPTDriveIntegration()\n",
" folder_id = integration.find_folder_by_name(\"Blue berry\")\n",
" if folder_id:\n",
" print(\"β
Successfully found 'Blue berry' folder!\")\n",
" \n",
" # List files in the folder\n",
" results = integration.drive_service.files().list(\n",
" q=f\"'{folder_id}' in parents and trashed=false\",\n",
" fields=\"files(id, name, mimeType)\"\n",
" ).execute()\n",
" \n",
" files = results.get('files', [])\n",
" print(f\"Found {len(files)} files in the folder:\")\n",
" for file in files[:5]: # Show first 5 files\n",
" print(f\" - {file['name']} ({file['mimeType']})\")\n",
" else:\n",
" print(\"β Could not access 'Blue berry' folder\")\n",
" print(\"Make sure you've shared the folder with your service account\")\n",
"\n",
"# Run this test first\n",
"test_folder_access()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c3dede9f-5e01-436d-a7b7-905e1646baf9",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "b933c8b6-add6-40fc-827f-e5e07447ac00",
"metadata": {},
"outputs": [],
"source": [
"#Troubleshooting"
]
},
{
"cell_type": "code",
"execution_count": 32,
"id": "b63a1f4b-1315-44fe-ba84-93fb1c2655cc",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"π Searching for 'Blue Berry' folder...\n",
"Total folders found: 2\n",
"\n",
"β
Found 1 'Blue Berry' folder(s):\n",
"π Anatomy Books \n",
" Full Path: Anatomy Books \n",
" Folder ID: 125NdiCL7moQsNYWRuHojVM7If88Bxh0q\n",
"\n"
]
}
],
"source": [
"import os\n",
"from google.oauth2 import service_account\n",
"from googleapiclient.discovery import build\n",
"\n",
"class DrivefolderLister:\n",
" def __init__(self):\n",
" # Initialize Google Drive API\n",
" self.credentials = service_account.Credentials.from_service_account_file(\n",
" os.getenv('GOOGLE_SERVICE_ACCOUNT_FILE'),\n",
" scopes=['https://www.googleapis.com/auth/drive.readonly']\n",
" )\n",
" self.drive_service = build('drive', 'v3', credentials=self.credentials)\n",
" \n",
" def get_all_folders(self):\n",
" \"\"\"Get ALL folders in the Google Drive\"\"\"\n",
" try:\n",
" # Query to get all folders (not trashed)\n",
" query = \"mimeType='application/vnd.google-apps.folder' and trashed=false\"\n",
" \n",
" all_folders = []\n",
" page_token = None\n",
" \n",
" while True:\n",
" results = self.drive_service.files().list(\n",
" q=query,\n",
" fields=\"nextPageToken, files(id, name, parents)\",\n",
" pageSize=1000, # Maximum allowed\n",
" pageToken=page_token\n",
" ).execute()\n",
" \n",
" folders = results.get('files', [])\n",
" all_folders.extend(folders)\n",
" \n",
" page_token = results.get('nextPageToken')\n",
" if not page_token:\n",
" break\n",
" \n",
" print(f\"Total folders found: {len(all_folders)}\")\n",
" return all_folders\n",
" \n",
" except Exception as e:\n",
" print(f\"Error retrieving folders: {e}\")\n",
" return []\n",
" \n",
" def build_folder_tree(self, folders):\n",
" \"\"\"Build a tree structure from the flat list of folders\"\"\"\n",
" # Create a dictionary for quick lookup\n",
" folder_dict = {folder['id']: folder for folder in folders}\n",
" \n",
" # Add root folder\n",
" folder_dict['root'] = {'id': 'root', 'name': 'My Drive', 'parents': []}\n",
" \n",
" # Build the tree structure\n",
" tree = {}\n",
" \n",
" def build_path(folder_id, visited=None):\n",
" if visited is None:\n",
" visited = set()\n",
" \n",
" if folder_id in visited: # Prevent infinite loops\n",
" return \"CIRCULAR_REFERENCE\"\n",
" \n",
" visited.add(folder_id)\n",
" \n",
" if folder_id not in folder_dict:\n",
" return \"UNKNOWN\"\n",
" \n",
" folder = folder_dict[folder_id]\n",
" \n",
" if folder_id == 'root':\n",
" return \"My Drive\"\n",
" \n",
" parents = folder.get('parents', [])\n",
" if not parents:\n",
" return folder['name']\n",
" \n",
" parent_path = build_path(parents[0], visited.copy())\n",
" return f\"{parent_path}/{folder['name']}\"\n",
" \n",
" # Build paths for all folders\n",
" folder_paths = []\n",
" for folder in folders:\n",
" path = build_path(folder['id'])\n",
" folder_paths.append({\n",
" 'name': folder['name'],\n",
" 'id': folder['id'],\n",
" 'path': path\n",
" })\n",
" \n",
" return folder_paths\n",
" \n",
" def search_folder_by_name(self, folder_name, folders_with_paths):\n",
" \"\"\"Search for folders by name (case-insensitive)\"\"\"\n",
" matches = []\n",
" search_name = folder_name.lower()\n",
" \n",
" for folder in folders_with_paths:\n",
" if search_name in folder['name'].lower():\n",
" matches.append(folder)\n",
" \n",
" return matches\n",
" \n",
" def display_all_folders(self, folders_with_paths, search_term=None):\n",
" \"\"\"Display all folders in a readable format\"\"\"\n",
" if search_term:\n",
" print(f\"\\n=== Searching for folders containing '{search_term}' ===\")\n",
" matches = self.search_folder_by_name(search_term, folders_with_paths)\n",
" if matches:\n",
" print(f\"Found {len(matches)} matching folders:\")\n",
" for folder in matches:\n",
" print(f\"π {folder['name']}\")\n",
" print(f\" Path: {folder['path']}\")\n",
" print(f\" ID: {folder['id']}\")\n",
" print()\n",
" else:\n",
" print(f\"No folders found containing '{search_term}'\")\n",
" else:\n",
" print(f\"\\n=== All {len(folders_with_paths)} folders in your Google Drive ===\")\n",
" \n",
" # Sort by path for better readability\n",
" sorted_folders = sorted(folders_with_paths, key=lambda x: x['path'])\n",
" \n",
" for folder in sorted_folders:\n",
" print(f\"π {folder['path']}\")\n",
" # print(f\" ID: {folder['id']}\") # Uncomment if you need IDs\n",
" \n",
" def find_blue_berry_folder(self):\n",
" \"\"\"Specifically look for the Anatomy Books folder\"\"\"\n",
" print(\"π Searching for 'Blue Berry' folder...\")\n",
" \n",
" folders = self.get_all_folders()\n",
" if not folders:\n",
" print(\"No folders found or error occurred.\")\n",
" return\n",
" \n",
" folders_with_paths = self.build_folder_tree(folders)\n",
" \n",
" # Search for Anatomy Books specifically\n",
" blue_berry_matches = self.search_folder_by_name(\"Anatomy Books\", folders_with_paths)\n",
" \n",
" if blue_berry_matches:\n",
" print(f\"\\nβ
Found {len(blue_berry_matches)} 'Blue Berry' folder(s):\")\n",
" for folder in blue_berry_matches:\n",
" print(f\"π {folder['name']}\")\n",
" print(f\" Full Path: {folder['path']}\")\n",
" print(f\" Folder ID: {folder['id']}\")\n",
" print()\n",
" else:\n",
" print(\"\\nβ No 'Blue Berry' folder found.\")\n",
" print(\"Let me show you all folders to help you locate it:\")\n",
" \n",
" # Show all folders if Blue Berry not found\n",
" self.display_all_folders(folders_with_paths)\n",
" \n",
" def interactive_folder_search(self):\n",
" \"\"\"Interactive search for any folder\"\"\"\n",
" print(\"π Google Drive Folder Explorer\")\n",
" print(\"=\" * 40)\n",
" \n",
" folders = self.get_all_folders()\n",
" if not folders:\n",
" print(\"No folders found or error occurred.\")\n",
" return\n",
" \n",
" folders_with_paths = self.build_folder_tree(folders)\n",
" \n",
" while True:\n",
" print(\"\\nOptions:\")\n",
" print(\"1. Search for a specific folder\")\n",
" print(\"2. Show all folders\")\n",
" print(\"3. Find 'Blue Berry' folder\")\n",
" print(\"4. Exit\")\n",
" \n",
" choice = input(\"\\nEnter your choice (1-4): \").strip()\n",
" \n",
" if choice == '1':\n",
" search_term = input(\"Enter folder name to search: \").strip()\n",
" if search_term:\n",
" self.display_all_folders(folders_with_paths, search_term)\n",
" \n",
" elif choice == '2':\n",
" self.display_all_folders(folders_with_paths)\n",
" \n",
" elif choice == '3':\n",
" blue_berry_matches = self.search_folder_by_name(\"blue berry\", folders_with_paths)\n",
" if blue_berry_matches:\n",
" print(f\"\\nβ
Found 'Blue Berry' folder(s):\")\n",
" for folder in blue_berry_matches:\n",
" print(f\"π {folder['name']} -> {folder['path']}\")\n",
" else:\n",
" print(\"\\nβ 'Blue Berry' folder not found in your Drive.\")\n",
" \n",
" elif choice == '4':\n",
" print(\"Goodbye!\")\n",
" break\n",
" \n",
" else:\n",
" print(\"Invalid choice. Please try again.\")\n",
"\n",
"def main():\n",
" \"\"\"Main function to run the folder lister\"\"\"\n",
" try:\n",
" lister = DrivefolderLister()\n",
" \n",
" # Quick search for Blue Berry folder\n",
" lister.find_blue_berry_folder()\n",
" \n",
" # Uncomment the line below for interactive mode\n",
" # lister.interactive_folder_search()\n",
" \n",
" except Exception as e:\n",
" print(f\"Error initializing Drive connection: {e}\")\n",
" print(\"Make sure your GOOGLE_SERVICE_ACCOUNT_FILE environment variable is set correctly.\")\n",
"\n",
"if __name__ == \"__main__\":\n",
" main()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "29a61039-9043-44d5-94b1-4847350b2200",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 31,
"id": "7350d687-f76e-46f4-a30b-0518e5b8236e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"π Google Drive API Diagnostic Tool\n",
"==================================================\n",
"π§ Testing Environment Variables...\n",
"----------------------------------------\n",
"β
GOOGLE_SERVICE_ACCOUNT_FILE: C:/Users/Uche Buzz/myprojects/RAG/rag-system-463320-f292991d0516.json\n",
"β
Service account file exists\n",
"β
Service account file is valid JSON\n",
"β
All required fields present in service account file\n",
"π§ Service account email: rag-base@rag-system-463320.iam.gserviceaccount.com\n",
"β
OPENAI_API_KEY: ************************************************************************************************************************************************************K1OkRRkA\n",
"\n",
"π Testing Credentials Loading...\n",
"----------------------------------------\n",
"\n",
"Testing scope set 1: ['https://www.googleapis.com/auth/drive.readonly']\n",
"β
Credentials loaded successfully with scopes: ['https://www.googleapis.com/auth/drive.readonly']\n",
"\n",
"π§ Testing Drive Service Creation...\n",
"----------------------------------------\n",
"β
Google Drive service created successfully\n",
"\n",
"π‘ Testing Basic API Call...\n",
"----------------------------------------\n",
"β
API call successful!\n",
"π§ Connected as: rag-base@rag-system-463320.iam.gserviceaccount.com\n",
"π€ Display name: rag-base@rag-system-463320.iam.gserviceaccount.com\n",
"\n",
"π Testing Root Folder Access...\n",
"----------------------------------------\n",
"β
Root folder accessible\n",
"π Root folder name: My Drive\n",
"π Items in root folder: 0\n",
"\n",
"π Testing File Listing...\n",
"----------------------------------------\n",
"Test 1: Listing all files (including documents)...\n",
"β
Found 7 files total\n",
"π First few files:\n",
" - Neuro Note Dr Clement.docx (application/vnd.openxmlformats-officedocument.wordprocessingml.document)\n",
" - Morbid Anatomy - ANA 3107.pdf (application/pdf)\n",
" - ANT & POST TRIANGLES OF THE NECK.pdf (application/pdf)\n",
" - Anatomy Books (application/vnd.google-apps.folder)\n",
" - Blue Berry (application/vnd.google-apps.folder)\n",
"\n",
"Test 2: Listing folders only...\n",
"β
Found 2 folders\n",
"π Folders found:\n",
" - Anatomy Books (ID: 125NdiCL7moQsNYWRuHojVM7If88Bxh0q)\n",
" - Blue Berry (ID: 1AYaS0yt_srFlgdE4mSNlqA6FLm10rdt4)\n",
"\n",
"β
All diagnostic tests passed!\n",
"π Your Google Drive API connection is working correctly!\n"
]
}
],
"source": [
"import os\n",
"from google.oauth2 import service_account\n",
"from googleapiclient.discovery import build\n",
"from googleapiclient.errors import HttpError\n",
"import json\n",
"\n",
"class DriveConnectionDiagnostic:\n",
" def __init__(self):\n",
" self.credentials = None\n",
" self.drive_service = None\n",
" self.setup_success = False\n",
" \n",
" def test_environment_variables(self):\n",
" \"\"\"Test if environment variables are set correctly\"\"\"\n",
" print(\"π§ Testing Environment Variables...\")\n",
" print(\"-\" * 40)\n",
" \n",
" service_account_file = os.getenv('GOOGLE_SERVICE_ACCOUNT_FILE')\n",
" openai_key = os.getenv('OPENAI_API_KEY')\n",
" \n",
" if service_account_file:\n",
" print(f\"β
GOOGLE_SERVICE_ACCOUNT_FILE: {service_account_file}\")\n",
" \n",
" # Check if file exists\n",
" if os.path.exists(service_account_file):\n",
" print(f\"β
Service account file exists\")\n",
" \n",
" # Check if file is readable\n",
" try:\n",
" with open(service_account_file, 'r') as f:\n",
" service_data = json.load(f)\n",
" print(f\"β
Service account file is valid JSON\")\n",
" \n",
" # Check required fields\n",
" required_fields = ['type', 'project_id', 'private_key_id', 'private_key', 'client_email']\n",
" missing_fields = [field for field in required_fields if field not in service_data]\n",
" \n",
" if missing_fields:\n",
" print(f\"β Missing required fields in service account file: {missing_fields}\")\n",
" return False\n",
" else:\n",
" print(f\"β
All required fields present in service account file\")\n",
" print(f\"π§ Service account email: {service_data.get('client_email')}\")\n",
" \n",
" except json.JSONDecodeError:\n",
" print(f\"β Service account file is not valid JSON\")\n",
" return False\n",
" except Exception as e:\n",
" print(f\"β Error reading service account file: {e}\")\n",
" return False\n",
" \n",
" else:\n",
" print(f\"β Service account file does not exist at: {service_account_file}\")\n",
" return False\n",
" else:\n",
" print(f\"β GOOGLE_SERVICE_ACCOUNT_FILE environment variable not set\")\n",
" return False\n",
" \n",
" if openai_key:\n",
" print(f\"β
OPENAI_API_KEY: {'*' * (len(openai_key) - 8) + openai_key[-8:]}\")\n",
" else:\n",
" print(f\"β οΈ OPENAI_API_KEY not set (not required for folder listing)\")\n",
" \n",
" return True\n",
" \n",
" def test_credentials_loading(self):\n",
" \"\"\"Test if credentials can be loaded\"\"\"\n",
" print(\"\\nπ Testing Credentials Loading...\")\n",
" print(\"-\" * 40)\n",
" \n",
" try:\n",
" service_account_file = os.getenv('GOOGLE_SERVICE_ACCOUNT_FILE')\n",
" \n",
" # Try different scope combinations\n",
" scopes_to_test = [\n",
" ['https://www.googleapis.com/auth/drive.readonly'],\n",
" ['https://www.googleapis.com/auth/drive'],\n",
" ['https://www.googleapis.com/auth/drive.metadata.readonly'],\n",
" ['https://www.googleapis.com/auth/drive.file']\n",
" ]\n",
" \n",
" for i, scopes in enumerate(scopes_to_test):\n",
" try:\n",
" print(f\"\\nTesting scope set {i+1}: {scopes}\")\n",
" self.credentials = service_account.Credentials.from_service_account_file(\n",
" service_account_file,\n",
" scopes=scopes\n",
" )\n",
" print(f\"β
Credentials loaded successfully with scopes: {scopes}\")\n",
" return True\n",
" except Exception as e:\n",
" print(f\"β Failed to load credentials with scopes {scopes}: {e}\")\n",
" \n",
" return False\n",
" \n",
" except Exception as e:\n",
" print(f\"β Error loading credentials: {e}\")\n",
" return False\n",
" \n",
" def test_drive_service_creation(self):\n",
" \"\"\"Test if Drive service can be created\"\"\"\n",
" print(\"\\nπ§ Testing Drive Service Creation...\")\n",
" print(\"-\" * 40)\n",
" \n",
" try:\n",
" if not self.credentials:\n",
" print(\"β No credentials available\")\n",
" return False\n",
" \n",
" self.drive_service = build('drive', 'v3', credentials=self.credentials)\n",
" print(\"β
Google Drive service created successfully\")\n",
" return True\n",
" \n",
" except Exception as e:\n",
" print(f\"β Error creating Drive service: {e}\")\n",
" return False\n",
" \n",
" def test_basic_api_call(self):\n",
" \"\"\"Test basic API functionality\"\"\"\n",
" print(\"\\nπ‘ Testing Basic API Call...\")\n",
" print(\"-\" * 40)\n",
" \n",
" try:\n",
" if not self.drive_service:\n",
" print(\"β No Drive service available\")\n",
" return False\n",
" \n",
" # Test getting user info\n",
" about = self.drive_service.about().get(fields=\"user\").execute()\n",
" user_info = about.get('user', {})\n",
" print(f\"β
API call successful!\")\n",
" print(f\"π§ Connected as: {user_info.get('emailAddress', 'Unknown')}\")\n",
" print(f\"π€ Display name: {user_info.get('displayName', 'Unknown')}\")\n",
" \n",
" return True\n",
" \n",
" except HttpError as e:\n",
" print(f\"β HTTP Error: {e}\")\n",
" if e.resp.status == 403:\n",
" print(\" This might be a permissions issue. Check:\")\n",
" print(\" 1. Is the service account enabled?\")\n",
" print(\" 2. Does it have the right permissions?\")\n",
" print(\" 3. Is the Google Drive API enabled in your project?\")\n",
" return False\n",
" except Exception as e:\n",
" print(f\"β Error making API call: {e}\")\n",
" return False\n",
" \n",
" def test_file_listing(self):\n",
" \"\"\"Test different file listing approaches\"\"\"\n",
" print(\"\\nπ Testing File Listing...\")\n",
" print(\"-\" * 40)\n",
" \n",
" if not self.drive_service:\n",
" print(\"β No Drive service available\")\n",
" return False\n",
" \n",
" # Test 1: List any files (not just folders)\n",
" try:\n",
" print(\"Test 1: Listing all files (including documents)...\")\n",
" results = self.drive_service.files().list(\n",
" q=\"trashed=false\",\n",
" fields=\"files(id, name, mimeType)\",\n",
" pageSize=10\n",
" ).execute()\n",
" \n",
" files = results.get('files', [])\n",
" print(f\"β
Found {len(files)} files total\")\n",
" \n",
" if files:\n",
" print(\"π First few files:\")\n",
" for file in files[:5]:\n",
" print(f\" - {file['name']} ({file['mimeType']})\")\n",
" \n",
" except Exception as e:\n",
" print(f\"β Error listing files: {e}\")\n",
" return False\n",
" \n",
" # Test 2: List only folders\n",
" try:\n",
" print(f\"\\nTest 2: Listing folders only...\")\n",
" results = self.drive_service.files().list(\n",
" q=\"mimeType='application/vnd.google-apps.folder' and trashed=false\",\n",
" fields=\"files(id, name, parents)\",\n",
" pageSize=10\n",
" ).execute()\n",
" \n",
" folders = results.get('files', [])\n",
" print(f\"β
Found {len(folders)} folders\")\n",
" \n",
" if folders:\n",
" print(\"π Folders found:\")\n",
" for folder in folders:\n",
" print(f\" - {folder['name']} (ID: {folder['id']})\")\n",
" else:\n",
" print(\"β οΈ No folders found - this might indicate:\")\n",
" print(\" 1. Your Google Drive is empty\")\n",
" print(\" 2. The service account doesn't have access to your personal Drive\")\n",
" print(\" 3. You need to share folders with the service account\")\n",
" \n",
" return len(folders) > 0\n",
" \n",
" except Exception as e:\n",
" print(f\"β Error listing folders: {e}\")\n",
" return False\n",
" \n",
" def test_root_access(self):\n",
" \"\"\"Test access to root folder\"\"\"\n",
" print(\"\\nπ Testing Root Folder Access...\")\n",
" print(\"-\" * 40)\n",
" \n",
" try:\n",
" if not self.drive_service:\n",
" print(\"β No Drive service available\")\n",
" return False\n",
" \n",
" # Try to get root folder info\n",
" root_info = self.drive_service.files().get(\n",
" fileId='root',\n",
" fields=\"id, name, mimeType\"\n",
" ).execute()\n",
" \n",
" print(f\"β
Root folder accessible\")\n",
" print(f\"π Root folder name: {root_info.get('name', 'My Drive')}\")\n",
" \n",
" # Try to list contents of root\n",
" results = self.drive_service.files().list(\n",
" q=\"'root' in parents and trashed=false\",\n",
" fields=\"files(id, name, mimeType)\",\n",
" pageSize=10\n",
" ).execute()\n",
" \n",
" root_contents = results.get('files', [])\n",
" print(f\"π Items in root folder: {len(root_contents)}\")\n",
" \n",
" if root_contents:\n",
" print(\"π Root folder contents:\")\n",
" for item in root_contents[:5]:\n",
" item_type = \"π\" if \"folder\" in item['mimeType'] else \"π\"\n",
" print(f\" {item_type} {item['name']}\")\n",
" \n",
" return True\n",
" \n",
" except Exception as e:\n",
" print(f\"β Error accessing root folder: {e}\")\n",
" return False\n",
" \n",
" def run_full_diagnostic(self):\n",
" \"\"\"Run complete diagnostic\"\"\"\n",
" print(\"π Google Drive API Diagnostic Tool\")\n",
" print(\"=\" * 50)\n",
" \n",
" # Step 1: Environment variables\n",
" if not self.test_environment_variables():\n",
" print(\"\\nβ Environment setup failed. Please check your service account file.\")\n",
" return False\n",
" \n",
" # Step 2: Credentials\n",
" if not self.test_credentials_loading():\n",
" print(\"\\nβ Credentials loading failed.\")\n",
" return False\n",
" \n",
" # Step 3: Service creation\n",
" if not self.test_drive_service_creation():\n",
" print(\"\\nβ Drive service creation failed.\")\n",
" return False\n",
" \n",
" # Step 4: Basic API call\n",
" if not self.test_basic_api_call():\n",
" print(\"\\nβ Basic API call failed.\")\n",
" return False\n",
" \n",
" # Step 5: Root access\n",
" if not self.test_root_access():\n",
" print(\"\\nβ Root folder access failed.\")\n",
" return False\n",
" \n",
" # Step 6: File listing\n",
" if not self.test_file_listing():\n",
" print(\"\\nβ File listing failed or no folders found.\")\n",
" print(\"\\nπ§ SOLUTION SUGGESTIONS:\")\n",
" print(\"1. If you're using a service account, you need to SHARE folders with it\")\n",
" print(\"2. Share your 'Blue Berry' folder with the service account email\")\n",
" print(\"3. Or consider using OAuth2 instead of service account for personal Drive access\")\n",
" return False\n",
" \n",
" print(\"\\nβ
All diagnostic tests passed!\")\n",
" print(\"π Your Google Drive API connection is working correctly!\")\n",
" return True\n",
" \n",
" def show_service_account_sharing_instructions(self):\n",
" \"\"\"Show instructions for sharing with service account\"\"\"\n",
" print(\"\\nπ SERVICE ACCOUNT SHARING INSTRUCTIONS:\")\n",
" print(\"=\" * 50)\n",
" print(\"If you're using a service account, you need to share folders with it:\")\n",
" print()\n",
" print(\"1. Open Google Drive in your browser\")\n",
" print(\"2. Find the folder you want to access (e.g., 'Blue Berry')\")\n",
" print(\"3. Right-click the folder β 'Share'\")\n",
" print(\"4. Add the service account email address\")\n",
" print(\"5. Give it 'Viewer' or 'Editor' permissions\")\n",
" print(\"6. Click 'Send'\")\n",
" print()\n",
" \n",
" if self.credentials:\n",
" try:\n",
" service_account_file = os.getenv('GOOGLE_SERVICE_ACCOUNT_FILE')\n",
" with open(service_account_file, 'r') as f:\n",
" service_data = json.load(f)\n",
" email = service_data.get('client_email')\n",
" print(f\"π§ Your service account email: {email}\")\n",
" print(\" ^ Share your folders with this email address\")\n",
" except:\n",
" print(\"β Could not read service account email\")\n",
"\n",
"def main():\n",
" diagnostic = DriveConnectionDiagnostic()\n",
" success = diagnostic.run_full_diagnostic()\n",
" \n",
" if not success:\n",
" diagnostic.show_service_account_sharing_instructions()\n",
"\n",
"if __name__ == \"__main__\":\n",
" main()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e3374b17-d2fa-4c80-a70b-76b8bf94c702",
"metadata": {},
"outputs": [],
"source": [
"#flask"
]
},
{
"cell_type": "code",
"execution_count": 30,
"id": "c8ac4c93-8b36-49d2-b8e1-efb7d1c4b104",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" * Serving Flask app '__main__'\n",
" * Debug mode: on\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.\n",
" * Running on http://127.0.0.1:5000\n",
"Press CTRL+C to quit\n",
" * Restarting with stat\n"
]
},
{
"ename": "SystemExit",
"evalue": "1",
"output_type": "error",
"traceback": [
"An exception has occurred, use %tb to see the full traceback.\n",
"\u001b[31mSystemExit\u001b[39m\u001b[31m:\u001b[39m 1\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"C:\\Users\\Uche Buzz\\anaconda3\\envs\\RAG\\Lib\\site-packages\\IPython\\core\\interactiveshell.py:3680: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.\n",
" warn(\"To exit: use 'exit', 'quit', or Ctrl-D.\", stacklevel=1)\n"
]
}
],
"source": [
"from flask import Flask, request, jsonify, render_template_string\n",
"\n",
"app = Flask(__name__)\n",
"integration = GPTDriveIntegration()\n",
"\n",
"HTML_TEMPLATE = \"\"\"\n",
"<!DOCTYPE html>\n",
"<html>\n",
"<head>\n",
" <title>GPT-Drive Integration</title>\n",
" <style>\n",
" body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }\n",
" .query-box { width: 100%; padding: 10px; margin: 10px 0; }\n",
" .result { background: #f5f5f5; padding: 15px; margin: 10px 0; border-radius: 5px; }\n",
" .sources { color: #666; font-size: 0.9em; }\n",
" </style>\n",
"</head>\n",
"<body>\n",
" <h1>GPT-Google Drive Integration</h1>\n",
" <form id=\"queryForm\">\n",
" <input type=\"text\" id=\"query\" class=\"query-box\" placeholder=\"Ask something about your Google Drive files...\">\n",
" <button type=\"submit\">Search & Ask</button>\n",
" </form>\n",
" <div id=\"results\"></div>\n",
"\n",
" <script>\n",
" document.getElementById('queryForm').onsubmit = async function(e) {\n",
" e.preventDefault();\n",
" const query = document.getElementById('query').value;\n",
" const response = await fetch('/query', {\n",
" method: 'POST',\n",
" headers: {'Content-Type': 'application/json'},\n",
" body: JSON.stringify({query: query})\n",
" });\n",
" const result = await response.json();\n",
" document.getElementById('results').innerHTML = \n",
" `<div class=\"result\">\n",
" <strong>Answer:</strong> ${result.answer}\n",
" <div class=\"sources\"><strong>Sources:</strong> ${result.sources.join(', ')}</div>\n",
" </div>`;\n",
" };\n",
" </script>\n",
"</body>\n",
"</html>\n",
"\"\"\"\n",
"\n",
"@app.route('/')\n",
"def home():\n",
" return render_template_string(HTML_TEMPLATE)\n",
"\n",
"@app.route('/query', methods=['POST'])\n",
"def query():\n",
" data = request.json\n",
" result = integration.process_query(data['query'])\n",
" return jsonify(result)\n",
"\n",
"if __name__ == '__main__':\n",
" app.run(debug=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "caef8af5-73f9-4627-9203-0e9c8d098db0",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "ff7582bd-f80c-46c4-a51b-b20fd7493b0e",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "96ea63b3-3cf3-41c1-b160-72d677ab0949",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "a8a64f0d-c9b5-4ce7-a887-e1b60de4dac3",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 12,
"id": "abbc0f6c-5350-4fd9-8711-de68d4aa739d",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "02ae258f-bef0-469b-a696-1edf6a7b5921",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 13,
"id": "09a0b418-eb0e-486e-bf05-bc7b43645784",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"* Running on local URL: http://127.0.0.1:7860\n",
"* Running on public URL: https://a9ef60dd3438b2ef0e.gradio.live\n",
"\n",
"This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n"
]
},
{
"data": {
"text/html": [
"<div><iframe src=\"https://a9ef60dd3438b2ef0e.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Keyboard interruption in main thread... closing server.\n",
"Killing tunnel 127.0.0.1:7860 <> https://a9ef60dd3438b2ef0e.gradio.live\n"
]
}
],
"source": [
"gpt_drive = GPTDriveIntegration()\n",
"\n",
"def process_user_query(query, search_terms_input):\n",
" \"\"\"Process user query and return formatted response\"\"\"\n",
" if not query.strip():\n",
" return \"Please enter a question.\", \"\"\n",
" \n",
" # Parse search terms if provided\n",
" search_terms = None\n",
" # if search_terms_input.strip():\n",
" # search_terms = [term.strip() for term in search_terms_input.split(',')]\n",
" \n",
" # Process the query\n",
" result = gpt_drive.process_query(query, search_terms)\n",
" \n",
" # Format the response\n",
" answer = result['answer']\n",
" sources = result['sources']\n",
" \n",
" sources_text = \"\"\n",
" if sources:\n",
" sources_text = \"**Sources used:**\\n\" + \"\\n\".join([f\"β’ {source}\" for source in sources])\n",
" \n",
" return answer, sources_text\n",
"\n",
"def check_setup():\n",
" \"\"\"Check if the APIs are properly configured\"\"\"\n",
" status_messages = []\n",
" \n",
" # Check Google Drive API\n",
" if gpt_drive.drive_initialized:\n",
" status_messages.append(\"β
Google Drive API: Connected\")\n",
" else:\n",
" status_messages.append(f\"β Google Drive API: {getattr(gpt_drive, 'drive_error', 'Not configured')}\")\n",
" \n",
" # Check OpenAI API\n",
" if gpt_drive.openai_initialized:\n",
" status_messages.append(\"β
OpenAI API: Connected\")\n",
" else:\n",
" status_messages.append(f\"β OpenAI API: {getattr(gpt_drive, 'openai_error', 'Not configured')}\")\n",
" \n",
" return \"\\n\".join(status_messages)\n",
"\n",
"# Create Gradio interface\n",
"with gr.Blocks(title=\"Augusta's Anatomy Reading Assistant\", theme=gr.themes.Soft()) as app:\n",
" gr.Markdown(\"# π€ Augusta's Anatomy bot\")\n",
" gr.Markdown(\"Ask questions about your anatomy books using AI!\")\n",
" \n",
" with gr.Row():\n",
" with gr.Column(scale=2):\n",
" # Main query interface\n",
" with gr.Group():\n",
" gr.Markdown(\"### Ask a Question\")\n",
" query_input = gr.Textbox(\n",
" label=\"Your Question\",\n",
" placeholder=\"Ask me any question about your anatomy books?\",\n",
" lines=3\n",
" )\n",
" \n",
" search_terms_input = gr.Textbox(\n",
" label=\"Search Terms (optional)\",\n",
" placeholder=\"Enter comma-separated terms to search for specific files\",\n",
" lines=1\n",
" )\n",
" \n",
" submit_btn = gr.Button(\"Search & Ask\", variant=\"primary\", size=\"lg\")\n",
" \n",
" # Results section\n",
" with gr.Group():\n",
" gr.Markdown(\"### Answer\")\n",
" answer_output = gr.Textbox(\n",
" label=\"AI Response\",\n",
" lines=10,\n",
" interactive=False\n",
" )\n",
" \n",
" sources_output = gr.Textbox(\n",
" label=\"Sources\",\n",
" lines=3,\n",
" interactive=False\n",
" )\n",
" \n",
" with gr.Column(scale=1):\n",
" # Status and setup info\n",
" with gr.Group():\n",
" gr.Markdown(\"### System Status\")\n",
" status_btn = gr.Button(\"Check Status\", size=\"sm\")\n",
" status_output = gr.Textbox(\n",
" label=\"API Status\",\n",
" lines=4,\n",
" interactive=False\n",
" )\n",
" \n",
" with gr.Group():\n",
" gr.Markdown(\"### Setup Instructions\")\n",
" gr.Markdown(\"\"\"\n",
" **Important Notes:**\n",
" 1.Only documents shared with it, it can answer\n",
" \n",
" **File Types Supported:**\n",
" - Google Docs\n",
" - Google Sheets \n",
" - PDF files\n",
" - Text files\n",
" \n",
" **Tips:**\n",
" - Use specific search terms for better results\n",
" - The system searches the top 3 most relevant files\n",
" - Ask clear, specific questions for better answers\n",
" \"\"\")\n",
" \n",
" # Event handlers\n",
" submit_btn.click(\n",
" fn=process_user_query,\n",
" inputs=[query_input, search_terms_input],\n",
" outputs=[answer_output, sources_output]\n",
" )\n",
" \n",
" status_btn.click(\n",
" fn=check_setup,\n",
" outputs=status_output\n",
" )\n",
" \n",
" # Example queries\n",
" with gr.Row():\n",
" gr.Examples(\n",
" examples=[\n",
" [\"What is morbid Anatomy?\", \"morbid, Anatomy\"],\n",
" [\"The transmission of nerves from one neuron to another is as a result of what?\", \"neuron, nerves, Dr Clement\"],\n",
" ],\n",
" inputs=[query_input, search_terms_input],\n",
" )\n",
"\n",
"# Launch the app\n",
"if __name__ == \"__main__\":\n",
" app.launch(\n",
" share=True,debug =True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "35d0a347-2cc6-4f4e-bb70-cc47067eaf53",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|