Datasets:
File size: 42,995 Bytes
84114a4 |
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 |
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"b78fb013688f49e09893f986b46e17b1": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HBoxModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HBoxModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HBoxView",
"box_style": "",
"children": [
"IPY_MODEL_26a0f5c6aa35438094ba329b2cca24d1",
"IPY_MODEL_6d2205226c584736b22ac0009a647e0e",
"IPY_MODEL_7c481d8f47474772bc804c8d26ecc2da"
],
"layout": "IPY_MODEL_6a1bd864209c4e5fb2d06ae0470d9350"
}
},
"26a0f5c6aa35438094ba329b2cca24d1": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_4fc282e7d6e647328ebcd013aefb774b",
"placeholder": "",
"style": "IPY_MODEL_bcb0a0dcf6044004867df51da0e3b307",
"value": "Batches: 100%"
}
},
"6d2205226c584736b22ac0009a647e0e": {
"model_module": "@jupyter-widgets/controls",
"model_name": "FloatProgressModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "FloatProgressModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "ProgressView",
"bar_style": "success",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_eb95669d0d0245aa9251ab35374307ce",
"max": 83,
"min": 0,
"orientation": "horizontal",
"style": "IPY_MODEL_cfed69b9f821407b8fd014d3748bd34f",
"value": 83
}
},
"7c481d8f47474772bc804c8d26ecc2da": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_d703773e6f7e42159e652bb40476a716",
"placeholder": "",
"style": "IPY_MODEL_e14ad5669d4f4df5a3a12dce60623ca9",
"value": " 83/83 [03:37<00:00, 2.39s/it]"
}
},
"6a1bd864209c4e5fb2d06ae0470d9350": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"4fc282e7d6e647328ebcd013aefb774b": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"bcb0a0dcf6044004867df51da0e3b307": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
},
"eb95669d0d0245aa9251ab35374307ce": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"cfed69b9f821407b8fd014d3748bd34f": {
"model_module": "@jupyter-widgets/controls",
"model_name": "ProgressStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "ProgressStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"bar_color": null,
"description_width": ""
}
},
"d703773e6f7e42159e652bb40476a716": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"e14ad5669d4f4df5a3a12dce60623ca9": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
}
}
}
},
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "sXhN8B0iqec4",
"outputId": "a6c8eb17-9fce-42ae-dfdc-7ef300d4c737"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/67.3 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m67.3/67.3 kB\u001b[0m \u001b[31m4.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[?25h Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n",
" Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n",
" Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m19.3/19.3 MB\u001b[0m \u001b[31m30.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m284.2/284.2 kB\u001b[0m \u001b[31m15.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.9/1.9 MB\u001b[0m \u001b[31m47.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m101.6/101.6 kB\u001b[0m \u001b[31m5.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m16.4/16.4 MB\u001b[0m \u001b[31m71.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m65.8/65.8 kB\u001b[0m \u001b[31m4.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m55.7/55.7 kB\u001b[0m \u001b[31m3.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m118.5/118.5 kB\u001b[0m \u001b[31m7.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m196.2/196.2 kB\u001b[0m \u001b[31m14.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m105.4/105.4 kB\u001b[0m \u001b[31m8.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m71.2/71.2 kB\u001b[0m \u001b[31m5.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m459.8/459.8 kB\u001b[0m \u001b[31m26.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m4.0/4.0 MB\u001b[0m \u001b[31m65.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m453.1/453.1 kB\u001b[0m \u001b[31m31.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m46.0/46.0 kB\u001b[0m \u001b[31m3.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m86.8/86.8 kB\u001b[0m \u001b[31m6.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[?25h Building wheel for pypika (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n",
"Reading package lists...\n",
"Building dependency tree...\n",
"Reading state information...\n",
"tesseract-ocr is already the newest version (4.1.1-2.1build1).\n",
"The following NEW packages will be installed:\n",
" poppler-utils\n",
"0 upgraded, 1 newly installed, 0 to remove and 35 not upgraded.\n",
"Need to get 186 kB of archives.\n",
"After this operation, 697 kB of additional disk space will be used.\n",
"Get:1 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 poppler-utils amd64 22.02.0-2ubuntu0.8 [186 kB]\n",
"Fetched 186 kB in 1s (371 kB/s)\n",
"Selecting previously unselected package poppler-utils.\n",
"(Reading database ... 126319 files and directories currently installed.)\n",
"Preparing to unpack .../poppler-utils_22.02.0-2ubuntu0.8_amd64.deb ...\n",
"Unpacking poppler-utils (22.02.0-2ubuntu0.8) ...\n",
"Setting up poppler-utils (22.02.0-2ubuntu0.8) ...\n",
"Processing triggers for man-db (2.10.2-1) ...\n"
]
}
],
"source": [
"# Step 1: Install dependencies\n",
"!pip install -q chromadb tiktoken\n",
"!apt-get -q install -y poppler-utils tesseract-ocr\n",
"!pip install -q pytesseract"
]
},
{
"cell_type": "code",
"source": [
"# Step 2: Setup folder structure\n",
"import os\n",
"\n",
"# Clean slate (optional)\n",
"!rm -rf /content/wwmad_workspace\n",
"\n",
"# Create working folders\n",
"os.makedirs(\"/content/wwmad_workspace/data\", exist_ok=True)\n",
"os.makedirs(\"/content/wwmad_workspace/chroma_db\", exist_ok=True)\n",
"\n",
"# Display where to upload\n",
"print(\"Upload your cleaned .txt files to: /content/wwmad_workspace/data/\")\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "BNwakG9IrcFi",
"outputId": "83ff44c8-abb5-42bb-f2ea-9137471a092f"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Upload your cleaned .txt files to: /content/wwmad_workspace/data/\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# Step 3: Enhanced Chunking with Heuristics and Metadata\n",
"import os\n",
"import re\n",
"import glob\n",
"import hashlib\n",
"from typing import List, Dict\n",
"\n",
"DATA_DIR = \"/content/wwmad_workspace/data\"\n",
"\n",
"def clean_and_chunk_text(path: str, chunk_size: int = 500, overlap: int = 50) -> List[Dict]:\n",
" with open(path, \"r\", encoding=\"utf-8\") as file:\n",
" raw_text = file.read()\n",
"\n",
" # Remove Project Gutenberg boilerplate (if present)\n",
" start_match = re.search(r\"\\*\\*\\* START OF.+?\\*\\*\\*\", raw_text, re.IGNORECASE)\n",
" if start_match:\n",
" raw_text = raw_text[start_match.end():]\n",
"\n",
" end_match = re.search(r\"\\*\\*\\* END OF.+?\\*\\*\\*\", raw_text, re.IGNORECASE)\n",
" if end_match:\n",
" raw_text = raw_text[:end_match.start()]\n",
"\n",
" # Normalize whitespace\n",
" raw_text = re.sub(r\"\\s+\", \" \", raw_text).strip()\n",
"\n",
" # Metadata extraction\n",
" file_name = os.path.basename(path)\n",
" title = os.path.splitext(file_name)[0].replace(\"_\", \" \").title()\n",
"\n",
" author_lookup = {\n",
" \"Meditations.txt\": \"Marcus Aurelius\",\n",
" \"ThoughtsMA.txt\": \"Marcus Aurelius\",\n",
" \"SelbstbetrachtungenMA.txt\": \"Marcus Aurelius\",\n",
" \"10_epictetus_quotes.txt\": \"Epictetus\",\n",
" \"200_epictetus_quotes.txt\": \"Epictetus\",\n",
" \"100_ma_quotes.txt\": \"Marcus Aurelius\",\n",
" \"100_seneca_quotes.txt\": \"Seneca\",\n",
" }\n",
" author = author_lookup.get(file_name, \"Unknown\")\n",
"\n",
" # Chunking\n",
" chunks = []\n",
" start = 0\n",
" chunk_id = 0\n",
" while start < len(raw_text):\n",
" end = start + chunk_size\n",
" chunk_text = raw_text[start:end]\n",
" chunk_hash = hashlib.md5(chunk_text.encode()).hexdigest()\n",
"\n",
" chunks.append({\n",
" \"content\": chunk_text,\n",
" \"metadata\": {\n",
" \"chunk_id\": chunk_id,\n",
" \"source\": file_name,\n",
" \"title\": title,\n",
" \"author\": author,\n",
" \"hash\": chunk_hash\n",
" }\n",
" })\n",
"\n",
" start += chunk_size - overlap\n",
" chunk_id += 1\n",
"\n",
" return chunks\n",
"\n",
"\n",
"# Run on all .txt files\n",
"all_chunks = []\n",
"file_paths = glob.glob(os.path.join(DATA_DIR, \"*.txt\"))\n",
"\n",
"for path in file_paths:\n",
" chunks = clean_and_chunk_text(path)\n",
" all_chunks.extend(chunks)\n",
"\n",
"print(f\"✅ Enriched {len(file_paths)} files into {len(all_chunks)} chunks with metadata.\")\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "NcI-GO6Lr3gC",
"outputId": "917abe43-b84d-4b46-b30d-ffef7e5593b3"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"✅ Enriched 7 files into 2632 chunks with metadata.\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# Install the updated ChromaDB (if not already done)\n",
"!pip install chromadb --upgrade --quiet\n",
"\n",
"# Correct import and setup\n",
"import chromadb\n",
"\n",
"CHROMA_DIR = \"/content/wwmad_workspace/chroma_db\"\n",
"\n",
"# Use the new client setup directly\n",
"client = chromadb.PersistentClient(path=CHROMA_DIR)\n",
"\n",
"# Create or load a collection\n",
"collection = client.get_or_create_collection(\"wwmad_quotes\")\n"
],
"metadata": {
"id": "fX6sbiDisCeN"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Prepare for ingestion\n",
"documents = [chunk[\"content\"] for chunk in all_chunks]\n",
"metadatas = [chunk[\"metadata\"] for chunk in all_chunks]\n",
"ids = [chunk[\"metadata\"][\"hash\"] for chunk in all_chunks] # Unique hash-based ID\n",
"\n",
"# Compute embeddings\n",
"model = SentenceTransformer(\"all-MiniLM-L6-v2\")\n",
"embeddings = model.encode(documents, show_progress_bar=True)\n",
"\n",
"# Add to ChromaDB collection\n",
"collection.add(\n",
" documents=documents,\n",
" metadatas=metadatas,\n",
" embeddings=embeddings,\n",
" ids=ids\n",
")\n",
"\n",
"print(f\"✅ Ingested {len(documents)} enriched chunks into ChromaDB.\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 66,
"referenced_widgets": [
"b78fb013688f49e09893f986b46e17b1",
"26a0f5c6aa35438094ba329b2cca24d1",
"6d2205226c584736b22ac0009a647e0e",
"7c481d8f47474772bc804c8d26ecc2da",
"6a1bd864209c4e5fb2d06ae0470d9350",
"4fc282e7d6e647328ebcd013aefb774b",
"bcb0a0dcf6044004867df51da0e3b307",
"eb95669d0d0245aa9251ab35374307ce",
"cfed69b9f821407b8fd014d3748bd34f",
"d703773e6f7e42159e652bb40476a716",
"e14ad5669d4f4df5a3a12dce60623ca9"
]
},
"id": "77olnzOOtfqu",
"outputId": "0892f837-cef5-4f46-8b70-285918350a04"
},
"execution_count": null,
"outputs": [
{
"output_type": "display_data",
"data": {
"text/plain": [
"Batches: 0%| | 0/83 [00:00<?, ?it/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "b78fb013688f49e09893f986b46e17b1"
}
},
"metadata": {}
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"✅ Ingested 2632 enriched chunks into ChromaDB.\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"query_text = \"What is Marcus Aurelius's view on pain and endurance?\"\n",
"query_embedding = model.encode([query_text])[0]\n",
"\n",
"results = collection.query(\n",
" query_embeddings=[query_embedding],\n",
" n_results=5,\n",
" include=[\"documents\", \"metadatas\", \"distances\"]\n",
")\n",
"\n",
"# Pretty print\n",
"for i in range(len(results[\"documents\"][0])):\n",
" doc = results[\"documents\"][0][i]\n",
" meta = results[\"metadatas\"][0][i]\n",
" distance = results[\"distances\"][0][i]\n",
" print(f\"\\n🔍 Result #{i+1}\")\n",
" print(f\"🧾 Document: {doc[:300]}...\")\n",
" print(f\"📎 Metadata: {meta}\")\n",
" print(f\"📏 Distance: {distance:.4f}\")\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "FdkRBLCOuTgH",
"outputId": "fc80d5ca-cc6f-4b76-c760-0bc70d76f4c8"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"\n",
"🔍 Result #1\n",
"🧾 Document: retreat; he has not that cheerful confidence which led Socrates through a life no less noble, to a death which was to bring him into the company of gods he had worshipped and men whom he had revered. But although Marcus Aurelius may have held intellectually that his soul was destined to be absorbed...\n",
"📎 Metadata: {'source': 'Meditations.txt', 'chunk_id': 56, 'title': 'Meditations', 'hash': '21e612782f4236bef39c5cf38b2a93ec', 'author': 'Marcus Aurelius'}\n",
"📏 Distance: 0.8549\n",
"\n",
"🔍 Result #2\n",
"🧾 Document: ity. Even when the gods stood on the side of righteousness, they were concerned with the act more than with the intent. But Marcus Aurelius knows that what the heart is full of, the man will do. 'Such as thy thoughts and ordinary cogitations are,' he says, 'such will thy mind be in time.' And every ...\n",
"📎 Metadata: {'hash': '1bed1717c3bcc21483a1593347e8186b', 'author': 'Marcus Aurelius', 'source': 'Meditations.txt', 'title': 'Meditations', 'chunk_id': 60}\n",
"📏 Distance: 0.8725\n",
"\n",
"🔍 Result #3\n",
"🧾 Document: there are many allusions to death as the natural end; doubtless he expected his soul one day to be absorbed into the universal soul, since nothing comes out of nothing, and nothing can be annihilated. His mood is one of strenuous weariness; he does his duty as a good soldier, waiting for the sound o...\n",
"📎 Metadata: {'chunk_id': 10, 'source': 'Meditations.txt', 'author': 'Unknown', 'title': 'Meditations'}\n",
"📏 Distance: 0.8927\n",
"\n",
"🔍 Result #4\n",
"🧾 Document: Marcus Aurelius. Pater’s “Marius the Epicurean” forms another outside commentary, which is of service in the imaginative attempt to create again the period. MARCUS AURELIUS ANTONINUS THE ROMAN EMPEROR HIS FIRST BOOK concerning HIMSELF: Wherein Antoninus recordeth, What and of whom, whether Parents, ...\n",
"📎 Metadata: {'source': 'Meditations.txt', 'author': 'Unknown', 'chunk_id': 12, 'title': 'Meditations'}\n",
"📏 Distance: 0.8959\n",
"\n",
"🔍 Result #5\n",
"🧾 Document: oung or turned out hateful, his life was one paradox. That nothing might lack, it was in camp before the face of the enemy that he passed away and went to his own place. The following is a list of the chief English translations of Marcus Aurelius: (1) By Meric Casaubon, 1634; (2) Jeremy Collier, 170...\n",
"📎 Metadata: {'author': 'Marcus Aurelius', 'source': 'Meditations.txt', 'hash': 'e5c533b25677c0517b36ec5051f4997f', 'title': 'Meditations', 'chunk_id': 65}\n",
"📏 Distance: 0.9105\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# Example query\n",
"query = \"How should I deal with adversity?\"\n",
"\n",
"# Embed the query\n",
"query_embedding = model.encode([query])\n",
"\n",
"# Query the ChromaDB collection\n",
"results = collection.query(\n",
" query_embeddings=query_embedding,\n",
" n_results=5,\n",
" include=[\"documents\", \"metadatas\", \"distances\"]\n",
")\n",
"\n",
"# Display results\n",
"for i, (doc, meta, dist) in enumerate(zip(results[\"documents\"][0], results[\"metadatas\"][0], results[\"distances\"][0]), 1):\n",
" print(f\"\\n🔹 Result #{i}\")\n",
" print(f\"Document: {doc}\")\n",
" print(f\"Metadata: {meta}\")\n",
" print(f\"Distance: {dist:.4f}\")\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "F5lsMUkw5d7E",
"outputId": "d4bf5842-60eb-4a18-be83-b61a16c8b1fd"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"\n",
"🔹 Result #1\n",
"Document: iting down one thing you can control and one thing you can't. Let go of the latter. 2. You Always Own Your Response ‘It is not the things themselves that disturb people but their judgements about those things.” Epictetus, Handbook, 5 Events happen, but our suffering begins with judgment. By managing our impressions and opinions, we reclaim agency, even in chaos. We then become true masters of how we view the world around us. Practice: Pause before reacting. Ask: “What am | adding to this situati\n",
"Metadata: {'author': 'Epictetus', 'title': '10 Epictetus Quotes', 'hash': '64d19f59da0c0ff214a013968496462f', 'chunk_id': 3, 'source': '10_epictetus_quotes.txt'}\n",
"Distance: 1.0127\n",
"\n",
"🔹 Result #2\n",
"Document: good and truly bad. But I that understand the nature of that which is good, that it only is to be desired, and of that which is bad, that it only is truly odious and shameful: who know moreover, that this transgressor, whosoever he be, is my kinsman, not by the same blood and seed, but by participation of the same reason, and of the same divine particle; How can I either be hurt by any of those, since it is not in their power to make me incur anything that is truly reproachful? or angry, and ill\n",
"Metadata: {'chunk_id': 109, 'title': 'Meditations', 'hash': '1b521172571b689ca371ce95a91b6e59', 'author': 'Marcus Aurelius', 'source': 'Meditations.txt'}\n",
"Distance: 1.2164\n",
"\n",
"🔹 Result #3\n",
"Document: and that thou art a man like others; and even if thou dost abstain from certain faults, still thou hast the disposition to commit them, though either through cowardice, or concern about reputation, or some such mean motive, thou dost abstain from such faults (i. 17). Fifth, consider that thou dost not even understand whether men are doing wrong or not, for many things are done with a certain reference to circumstances. And in short, a man must learn a great deal to enable him to pass a correct judgment on another man's acts (ix. 38; iv. 51). Sixth, consider when thou art much vexed or grieved, that man's life is only a moment, and after a short time we are all laid out dead (vii. 58; iv. 48). Seventh, that it is not men's acts which disturb us, for those acts have their foundation in men's ruling principles, but it is our own opinions which disturb us. Take away these opinions then, and resolve to dismiss thy judgment about an act as if it were something grievous, and thy anger is gone. How then shall I take away these opinions? By reflecting that no wrongful act of another brings shame on thee: for unless that which is shameful is alone bad, thou also must of necessity do many things wrong, and become a robber and everything else (v. 25; vii. 16). Eighth, consider how much more pain is brought on us by the anger and vexation caused by such acts than by the acts themselves, at which we are angry and vexed (iv. 39, 49; vii. 24). Ninth, consider that a good disposition is invincible if it be genuine, and not an affected smile and acting a part. For what will the most violent man do to thee, if thou continuest to be of a kind disposition towards him, and if, as opportunity offers, thou gently admonishest him and calmly correctest his errors at the very time when he is trying to do thee harm, saying, Not so, my child: we are constituted by nature for something else: I shall certainly not be injured, but thou art injuring thyself, my child.--And show him with gentle tact and by general principles that this is so, and that even bees do not do as he does, nor any animals which are formed by nature to be gregarious. And thou must do this neither with any double meaning nor in the way of reproach, but affectionately and without any rancor in thy soul; and not as if thou wert lecturing him, nor yet that any bystander may admire, but either when he is alone, and if others are present ...[A] [A] It appears that there is a defect in the text here. Remember these nine rules, as if thou hadst received them as a gift from the Muses, and begin at last to be a man while thou livest. But thou must equally avoid nattering men and being vexed at them, for\n",
"Metadata: {'title': 'ThoughtsMA', 'chunk_id': 150, 'author': 'Unknown', 'source': 'ThoughtsMA.txt'}\n",
"Distance: 1.2330\n",
"\n",
"🔹 Result #4\n",
"Document: to Overcome Self-Doubt A quote on the True Value “Look inward. Don’t let the true nature or value of anything elude you.” Marcus Aurelius Quotes: Over 100 Thoughts From a Stoic Emperor - Vi... VA srovce “ Post: How to Overcome Self-Doubt Il e “Dont waste the rest of your time here worrying about other people — unless it affects the common good. It will keep you from doing anything useful.” Marcus Aurelius, Meditations, Book 3.4 Post: How to Overcome Self-Doubt “You participate in a society by yo\n",
"Metadata: {'title': '100 Ma Quotes', 'chunk_id': 21, 'hash': 'e259f3daa1b6d7658834f546fcb588a0', 'author': 'Marcus Aurelius', 'source': '100_ma_quotes.txt'}\n",
"Distance: 1.2335\n",
"\n",
"🔹 Result #5\n",
"Document: ght way, and think and act in the right way. These two things are common both to the soul of God and to the soul of man, and to the soul of every rational being: not to be hindered by another; and to hold good to consist in the disposition to justice and the practice of it, and in this to let thy desire find its termination. 35. If this is neither my own badness, nor an effect of my own badness, and the common weal is not injured, why am I troubled about it, and what is the harm to the common we\n",
"Metadata: {'hash': 'd5cb9bf89dadc3aef915d95a0eb4821a', 'title': 'Thoughtsma', 'author': 'Marcus Aurelius', 'chunk_id': 495, 'source': 'ThoughtsMA.txt'}\n",
"Distance: 1.2486\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"import shutil\n",
"\n",
"shutil.make_archive(\"/content/chroma_db_export\", \"zip\", \"/content/wwmad_workspace/chroma_db\")\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"id": "XDyp5ppk6g5_",
"outputId": "68fe3f01-e6bc-4174-8f3a-60557166e2ef"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'/content/chroma_db_export.zip'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 18
}
]
},
{
"cell_type": "code",
"source": [
"from google.colab import files\n",
"files.download(\"/content/chroma_db_export.zip\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 17
},
"id": "pdN35dM06m42",
"outputId": "af4b9f72-c20c-4889-84eb-706c0b303581"
},
"execution_count": null,
"outputs": [
{
"output_type": "display_data",
"data": {
"text/plain": [
"<IPython.core.display.Javascript object>"
],
"application/javascript": [
"\n",
" async function download(id, filename, size) {\n",
" if (!google.colab.kernel.accessAllowed) {\n",
" return;\n",
" }\n",
" const div = document.createElement('div');\n",
" const label = document.createElement('label');\n",
" label.textContent = `Downloading \"${filename}\": `;\n",
" div.appendChild(label);\n",
" const progress = document.createElement('progress');\n",
" progress.max = size;\n",
" div.appendChild(progress);\n",
" document.body.appendChild(div);\n",
"\n",
" const buffers = [];\n",
" let downloaded = 0;\n",
"\n",
" const channel = await google.colab.kernel.comms.open(id);\n",
" // Send a message to notify the kernel that we're ready.\n",
" channel.send({})\n",
"\n",
" for await (const message of channel.messages) {\n",
" // Send a message to notify the kernel that we're ready.\n",
" channel.send({})\n",
" if (message.buffers) {\n",
" for (const buffer of message.buffers) {\n",
" buffers.push(buffer);\n",
" downloaded += buffer.byteLength;\n",
" progress.value = downloaded;\n",
" }\n",
" }\n",
" }\n",
" const blob = new Blob(buffers, {type: 'application/binary'});\n",
" const a = document.createElement('a');\n",
" a.href = window.URL.createObjectURL(blob);\n",
" a.download = filename;\n",
" div.appendChild(a);\n",
" a.click();\n",
" div.remove();\n",
" }\n",
" "
]
},
"metadata": {}
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"<IPython.core.display.Javascript object>"
],
"application/javascript": [
"download(\"download_2cd61887-507e-4bc6-a5ec-aee882e2720c\", \"chroma_db_export.zip\", 20504603)"
]
},
"metadata": {}
}
]
}
]
} |