Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/__pycache__/__init__.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/__init__.py +943 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/pyspark_dataframe.py +91 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/python.py +19 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/quip.py +249 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/readthedocs.py +218 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/recursive_url_loader.py +582 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/reddit.py +143 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/roam.py +25 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rocksetdb.py +122 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rspace.py +125 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rss.py +133 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rst.py +59 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rtf.py +59 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/s3_directory.py +140 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/s3_file.py +138 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/scrapfly.py +70 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/scrapingant.py +66 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/sharepoint.py +208 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/sitemap.py +236 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/slack_directory.py +107 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/snowflake_loader.py +124 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/spider.py +94 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/spreedly.py +55 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/sql_database.py +137 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/srt.py +29 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/stripe.py +52 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/surrealdb.py +95 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/telegram.py +268 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tencent_cos_directory.py +47 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tencent_cos_file.py +45 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tensorflow_datasets.py +77 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/text.py +61 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tidb.py +67 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tomarkdown.py +30 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/toml.py +43 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/trello.py +169 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tsv.py +42 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/twitter.py +110 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/unstructured.py +509 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/url.py +161 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/url_playwright.py +264 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/url_selenium.py +176 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/vsdx.py +54 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/weather.py +46 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/web_base.py +406 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/whatsapp_chat.py +64 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/wikipedia.py +59 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/word_document.py +139 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/xml.py +49 -0
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (531 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/__init__.py
ADDED
|
@@ -0,0 +1,943 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""**Document Loaders** are classes to load Documents.
|
| 2 |
+
|
| 3 |
+
**Document Loaders** are usually used to load a lot of Documents in a single run.
|
| 4 |
+
|
| 5 |
+
**Class hierarchy:**
|
| 6 |
+
|
| 7 |
+
.. code-block::
|
| 8 |
+
|
| 9 |
+
BaseLoader --> <name>Loader # Examples: TextLoader, UnstructuredFileLoader
|
| 10 |
+
|
| 11 |
+
**Main helpers:**
|
| 12 |
+
|
| 13 |
+
.. code-block::
|
| 14 |
+
|
| 15 |
+
Document, <name>TextSplitter
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import importlib
|
| 19 |
+
from typing import TYPE_CHECKING, Any
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
from langchain_community.document_loaders.acreom import (
|
| 23 |
+
AcreomLoader,
|
| 24 |
+
)
|
| 25 |
+
from langchain_community.document_loaders.airbyte import (
|
| 26 |
+
AirbyteCDKLoader,
|
| 27 |
+
AirbyteGongLoader,
|
| 28 |
+
AirbyteHubspotLoader,
|
| 29 |
+
AirbyteSalesforceLoader,
|
| 30 |
+
AirbyteShopifyLoader,
|
| 31 |
+
AirbyteStripeLoader,
|
| 32 |
+
AirbyteTypeformLoader,
|
| 33 |
+
AirbyteZendeskSupportLoader,
|
| 34 |
+
)
|
| 35 |
+
from langchain_community.document_loaders.airbyte_json import (
|
| 36 |
+
AirbyteJSONLoader,
|
| 37 |
+
)
|
| 38 |
+
from langchain_community.document_loaders.airtable import (
|
| 39 |
+
AirtableLoader,
|
| 40 |
+
)
|
| 41 |
+
from langchain_community.document_loaders.apify_dataset import (
|
| 42 |
+
ApifyDatasetLoader,
|
| 43 |
+
)
|
| 44 |
+
from langchain_community.document_loaders.arcgis_loader import (
|
| 45 |
+
ArcGISLoader,
|
| 46 |
+
)
|
| 47 |
+
from langchain_community.document_loaders.arxiv import (
|
| 48 |
+
ArxivLoader,
|
| 49 |
+
)
|
| 50 |
+
from langchain_community.document_loaders.assemblyai import (
|
| 51 |
+
AssemblyAIAudioLoaderById,
|
| 52 |
+
AssemblyAIAudioTranscriptLoader,
|
| 53 |
+
)
|
| 54 |
+
from langchain_community.document_loaders.astradb import (
|
| 55 |
+
AstraDBLoader,
|
| 56 |
+
)
|
| 57 |
+
from langchain_community.document_loaders.async_html import (
|
| 58 |
+
AsyncHtmlLoader,
|
| 59 |
+
)
|
| 60 |
+
from langchain_community.document_loaders.athena import (
|
| 61 |
+
AthenaLoader,
|
| 62 |
+
)
|
| 63 |
+
from langchain_community.document_loaders.azlyrics import (
|
| 64 |
+
AZLyricsLoader,
|
| 65 |
+
)
|
| 66 |
+
from langchain_community.document_loaders.azure_ai_data import (
|
| 67 |
+
AzureAIDataLoader,
|
| 68 |
+
)
|
| 69 |
+
from langchain_community.document_loaders.azure_blob_storage_container import (
|
| 70 |
+
AzureBlobStorageContainerLoader,
|
| 71 |
+
)
|
| 72 |
+
from langchain_community.document_loaders.azure_blob_storage_file import (
|
| 73 |
+
AzureBlobStorageFileLoader,
|
| 74 |
+
)
|
| 75 |
+
from langchain_community.document_loaders.bibtex import (
|
| 76 |
+
BibtexLoader,
|
| 77 |
+
)
|
| 78 |
+
from langchain_community.document_loaders.bigquery import (
|
| 79 |
+
BigQueryLoader,
|
| 80 |
+
)
|
| 81 |
+
from langchain_community.document_loaders.bilibili import (
|
| 82 |
+
BiliBiliLoader,
|
| 83 |
+
)
|
| 84 |
+
from langchain_community.document_loaders.blackboard import (
|
| 85 |
+
BlackboardLoader,
|
| 86 |
+
)
|
| 87 |
+
from langchain_community.document_loaders.blob_loaders import (
|
| 88 |
+
Blob,
|
| 89 |
+
BlobLoader,
|
| 90 |
+
CloudBlobLoader,
|
| 91 |
+
FileSystemBlobLoader,
|
| 92 |
+
YoutubeAudioLoader,
|
| 93 |
+
)
|
| 94 |
+
from langchain_community.document_loaders.blockchain import (
|
| 95 |
+
BlockchainDocumentLoader,
|
| 96 |
+
)
|
| 97 |
+
from langchain_community.document_loaders.brave_search import (
|
| 98 |
+
BraveSearchLoader,
|
| 99 |
+
)
|
| 100 |
+
from langchain_community.document_loaders.browserbase import (
|
| 101 |
+
BrowserbaseLoader,
|
| 102 |
+
)
|
| 103 |
+
from langchain_community.document_loaders.browserless import (
|
| 104 |
+
BrowserlessLoader,
|
| 105 |
+
)
|
| 106 |
+
from langchain_community.document_loaders.cassandra import (
|
| 107 |
+
CassandraLoader,
|
| 108 |
+
)
|
| 109 |
+
from langchain_community.document_loaders.chatgpt import (
|
| 110 |
+
ChatGPTLoader,
|
| 111 |
+
)
|
| 112 |
+
from langchain_community.document_loaders.chm import (
|
| 113 |
+
UnstructuredCHMLoader,
|
| 114 |
+
)
|
| 115 |
+
from langchain_community.document_loaders.chromium import (
|
| 116 |
+
AsyncChromiumLoader,
|
| 117 |
+
)
|
| 118 |
+
from langchain_community.document_loaders.college_confidential import (
|
| 119 |
+
CollegeConfidentialLoader,
|
| 120 |
+
)
|
| 121 |
+
from langchain_community.document_loaders.concurrent import (
|
| 122 |
+
ConcurrentLoader,
|
| 123 |
+
)
|
| 124 |
+
from langchain_community.document_loaders.confluence import (
|
| 125 |
+
ConfluenceLoader,
|
| 126 |
+
)
|
| 127 |
+
from langchain_community.document_loaders.conllu import (
|
| 128 |
+
CoNLLULoader,
|
| 129 |
+
)
|
| 130 |
+
from langchain_community.document_loaders.couchbase import (
|
| 131 |
+
CouchbaseLoader,
|
| 132 |
+
)
|
| 133 |
+
from langchain_community.document_loaders.csv_loader import (
|
| 134 |
+
CSVLoader,
|
| 135 |
+
UnstructuredCSVLoader,
|
| 136 |
+
)
|
| 137 |
+
from langchain_community.document_loaders.cube_semantic import (
|
| 138 |
+
CubeSemanticLoader,
|
| 139 |
+
)
|
| 140 |
+
from langchain_community.document_loaders.datadog_logs import (
|
| 141 |
+
DatadogLogsLoader,
|
| 142 |
+
)
|
| 143 |
+
from langchain_community.document_loaders.dataframe import (
|
| 144 |
+
DataFrameLoader,
|
| 145 |
+
)
|
| 146 |
+
from langchain_community.document_loaders.dedoc import (
|
| 147 |
+
DedocAPIFileLoader,
|
| 148 |
+
DedocFileLoader,
|
| 149 |
+
)
|
| 150 |
+
from langchain_community.document_loaders.diffbot import (
|
| 151 |
+
DiffbotLoader,
|
| 152 |
+
)
|
| 153 |
+
from langchain_community.document_loaders.directory import (
|
| 154 |
+
DirectoryLoader,
|
| 155 |
+
)
|
| 156 |
+
from langchain_community.document_loaders.discord import (
|
| 157 |
+
DiscordChatLoader,
|
| 158 |
+
)
|
| 159 |
+
from langchain_community.document_loaders.doc_intelligence import (
|
| 160 |
+
AzureAIDocumentIntelligenceLoader,
|
| 161 |
+
)
|
| 162 |
+
from langchain_community.document_loaders.docugami import (
|
| 163 |
+
DocugamiLoader,
|
| 164 |
+
)
|
| 165 |
+
from langchain_community.document_loaders.docusaurus import (
|
| 166 |
+
DocusaurusLoader,
|
| 167 |
+
)
|
| 168 |
+
from langchain_community.document_loaders.dropbox import (
|
| 169 |
+
DropboxLoader,
|
| 170 |
+
)
|
| 171 |
+
from langchain_community.document_loaders.duckdb_loader import (
|
| 172 |
+
DuckDBLoader,
|
| 173 |
+
)
|
| 174 |
+
from langchain_community.document_loaders.email import (
|
| 175 |
+
OutlookMessageLoader,
|
| 176 |
+
UnstructuredEmailLoader,
|
| 177 |
+
)
|
| 178 |
+
from langchain_community.document_loaders.epub import (
|
| 179 |
+
UnstructuredEPubLoader,
|
| 180 |
+
)
|
| 181 |
+
from langchain_community.document_loaders.etherscan import (
|
| 182 |
+
EtherscanLoader,
|
| 183 |
+
)
|
| 184 |
+
from langchain_community.document_loaders.evernote import (
|
| 185 |
+
EverNoteLoader,
|
| 186 |
+
)
|
| 187 |
+
from langchain_community.document_loaders.excel import (
|
| 188 |
+
UnstructuredExcelLoader,
|
| 189 |
+
)
|
| 190 |
+
from langchain_community.document_loaders.facebook_chat import (
|
| 191 |
+
FacebookChatLoader,
|
| 192 |
+
)
|
| 193 |
+
from langchain_community.document_loaders.fauna import (
|
| 194 |
+
FaunaLoader,
|
| 195 |
+
)
|
| 196 |
+
from langchain_community.document_loaders.figma import (
|
| 197 |
+
FigmaFileLoader,
|
| 198 |
+
)
|
| 199 |
+
from langchain_community.document_loaders.firecrawl import (
|
| 200 |
+
FireCrawlLoader,
|
| 201 |
+
)
|
| 202 |
+
from langchain_community.document_loaders.gcs_directory import (
|
| 203 |
+
GCSDirectoryLoader,
|
| 204 |
+
)
|
| 205 |
+
from langchain_community.document_loaders.gcs_file import (
|
| 206 |
+
GCSFileLoader,
|
| 207 |
+
)
|
| 208 |
+
from langchain_community.document_loaders.geodataframe import (
|
| 209 |
+
GeoDataFrameLoader,
|
| 210 |
+
)
|
| 211 |
+
from langchain_community.document_loaders.git import (
|
| 212 |
+
GitLoader,
|
| 213 |
+
)
|
| 214 |
+
from langchain_community.document_loaders.gitbook import (
|
| 215 |
+
GitbookLoader,
|
| 216 |
+
)
|
| 217 |
+
from langchain_community.document_loaders.github import (
|
| 218 |
+
GithubFileLoader,
|
| 219 |
+
GitHubIssuesLoader,
|
| 220 |
+
)
|
| 221 |
+
from langchain_community.document_loaders.glue_catalog import (
|
| 222 |
+
GlueCatalogLoader,
|
| 223 |
+
)
|
| 224 |
+
from langchain_community.document_loaders.google_speech_to_text import (
|
| 225 |
+
GoogleSpeechToTextLoader,
|
| 226 |
+
)
|
| 227 |
+
from langchain_community.document_loaders.googledrive import (
|
| 228 |
+
GoogleDriveLoader,
|
| 229 |
+
)
|
| 230 |
+
from langchain_community.document_loaders.gutenberg import (
|
| 231 |
+
GutenbergLoader,
|
| 232 |
+
)
|
| 233 |
+
from langchain_community.document_loaders.hn import (
|
| 234 |
+
HNLoader,
|
| 235 |
+
)
|
| 236 |
+
from langchain_community.document_loaders.html import (
|
| 237 |
+
UnstructuredHTMLLoader,
|
| 238 |
+
)
|
| 239 |
+
from langchain_community.document_loaders.html_bs import (
|
| 240 |
+
BSHTMLLoader,
|
| 241 |
+
)
|
| 242 |
+
from langchain_community.document_loaders.hugging_face_dataset import (
|
| 243 |
+
HuggingFaceDatasetLoader,
|
| 244 |
+
)
|
| 245 |
+
from langchain_community.document_loaders.hugging_face_model import (
|
| 246 |
+
HuggingFaceModelLoader,
|
| 247 |
+
)
|
| 248 |
+
from langchain_community.document_loaders.ifixit import (
|
| 249 |
+
IFixitLoader,
|
| 250 |
+
)
|
| 251 |
+
from langchain_community.document_loaders.image import (
|
| 252 |
+
UnstructuredImageLoader,
|
| 253 |
+
)
|
| 254 |
+
from langchain_community.document_loaders.image_captions import (
|
| 255 |
+
ImageCaptionLoader,
|
| 256 |
+
)
|
| 257 |
+
from langchain_community.document_loaders.imsdb import (
|
| 258 |
+
IMSDbLoader,
|
| 259 |
+
)
|
| 260 |
+
from langchain_community.document_loaders.iugu import (
|
| 261 |
+
IuguLoader,
|
| 262 |
+
)
|
| 263 |
+
from langchain_community.document_loaders.joplin import (
|
| 264 |
+
JoplinLoader,
|
| 265 |
+
)
|
| 266 |
+
from langchain_community.document_loaders.json_loader import (
|
| 267 |
+
JSONLoader,
|
| 268 |
+
)
|
| 269 |
+
from langchain_community.document_loaders.kinetica_loader import KineticaLoader
|
| 270 |
+
from langchain_community.document_loaders.lakefs import (
|
| 271 |
+
LakeFSLoader,
|
| 272 |
+
)
|
| 273 |
+
from langchain_community.document_loaders.larksuite import (
|
| 274 |
+
LarkSuiteDocLoader,
|
| 275 |
+
)
|
| 276 |
+
from langchain_community.document_loaders.llmsherpa import (
|
| 277 |
+
LLMSherpaFileLoader,
|
| 278 |
+
)
|
| 279 |
+
from langchain_community.document_loaders.markdown import (
|
| 280 |
+
UnstructuredMarkdownLoader,
|
| 281 |
+
)
|
| 282 |
+
from langchain_community.document_loaders.mastodon import (
|
| 283 |
+
MastodonTootsLoader,
|
| 284 |
+
)
|
| 285 |
+
from langchain_community.document_loaders.max_compute import (
|
| 286 |
+
MaxComputeLoader,
|
| 287 |
+
)
|
| 288 |
+
from langchain_community.document_loaders.mediawikidump import (
|
| 289 |
+
MWDumpLoader,
|
| 290 |
+
)
|
| 291 |
+
from langchain_community.document_loaders.merge import (
|
| 292 |
+
MergedDataLoader,
|
| 293 |
+
)
|
| 294 |
+
from langchain_community.document_loaders.mhtml import (
|
| 295 |
+
MHTMLLoader,
|
| 296 |
+
)
|
| 297 |
+
from langchain_community.document_loaders.modern_treasury import (
|
| 298 |
+
ModernTreasuryLoader,
|
| 299 |
+
)
|
| 300 |
+
from langchain_community.document_loaders.mongodb import (
|
| 301 |
+
MongodbLoader,
|
| 302 |
+
)
|
| 303 |
+
from langchain_community.document_loaders.needle import (
|
| 304 |
+
NeedleLoader,
|
| 305 |
+
)
|
| 306 |
+
from langchain_community.document_loaders.news import (
|
| 307 |
+
NewsURLLoader,
|
| 308 |
+
)
|
| 309 |
+
from langchain_community.document_loaders.notebook import (
|
| 310 |
+
NotebookLoader,
|
| 311 |
+
)
|
| 312 |
+
from langchain_community.document_loaders.notion import (
|
| 313 |
+
NotionDirectoryLoader,
|
| 314 |
+
)
|
| 315 |
+
from langchain_community.document_loaders.notiondb import (
|
| 316 |
+
NotionDBLoader,
|
| 317 |
+
)
|
| 318 |
+
from langchain_community.document_loaders.obs_directory import (
|
| 319 |
+
OBSDirectoryLoader,
|
| 320 |
+
)
|
| 321 |
+
from langchain_community.document_loaders.obs_file import (
|
| 322 |
+
OBSFileLoader,
|
| 323 |
+
)
|
| 324 |
+
from langchain_community.document_loaders.obsidian import (
|
| 325 |
+
ObsidianLoader,
|
| 326 |
+
)
|
| 327 |
+
from langchain_community.document_loaders.odt import (
|
| 328 |
+
UnstructuredODTLoader,
|
| 329 |
+
)
|
| 330 |
+
from langchain_community.document_loaders.onedrive import (
|
| 331 |
+
OneDriveLoader,
|
| 332 |
+
)
|
| 333 |
+
from langchain_community.document_loaders.onedrive_file import (
|
| 334 |
+
OneDriveFileLoader,
|
| 335 |
+
)
|
| 336 |
+
from langchain_community.document_loaders.open_city_data import (
|
| 337 |
+
OpenCityDataLoader,
|
| 338 |
+
)
|
| 339 |
+
from langchain_community.document_loaders.oracleadb_loader import (
|
| 340 |
+
OracleAutonomousDatabaseLoader,
|
| 341 |
+
)
|
| 342 |
+
from langchain_community.document_loaders.oracleai import (
|
| 343 |
+
OracleDocLoader,
|
| 344 |
+
OracleTextSplitter,
|
| 345 |
+
)
|
| 346 |
+
from langchain_community.document_loaders.org_mode import (
|
| 347 |
+
UnstructuredOrgModeLoader,
|
| 348 |
+
)
|
| 349 |
+
from langchain_community.document_loaders.pdf import (
|
| 350 |
+
AmazonTextractPDFLoader,
|
| 351 |
+
DedocPDFLoader,
|
| 352 |
+
MathpixPDFLoader,
|
| 353 |
+
OnlinePDFLoader,
|
| 354 |
+
PagedPDFSplitter,
|
| 355 |
+
PDFMinerLoader,
|
| 356 |
+
PDFMinerPDFasHTMLLoader,
|
| 357 |
+
PDFPlumberLoader,
|
| 358 |
+
PyMuPDFLoader,
|
| 359 |
+
PyPDFDirectoryLoader,
|
| 360 |
+
PyPDFium2Loader,
|
| 361 |
+
PyPDFLoader,
|
| 362 |
+
UnstructuredPDFLoader,
|
| 363 |
+
)
|
| 364 |
+
from langchain_community.document_loaders.pebblo import (
|
| 365 |
+
PebbloSafeLoader,
|
| 366 |
+
PebbloTextLoader,
|
| 367 |
+
)
|
| 368 |
+
from langchain_community.document_loaders.polars_dataframe import (
|
| 369 |
+
PolarsDataFrameLoader,
|
| 370 |
+
)
|
| 371 |
+
from langchain_community.document_loaders.powerpoint import (
|
| 372 |
+
UnstructuredPowerPointLoader,
|
| 373 |
+
)
|
| 374 |
+
from langchain_community.document_loaders.psychic import (
|
| 375 |
+
PsychicLoader,
|
| 376 |
+
)
|
| 377 |
+
from langchain_community.document_loaders.pubmed import (
|
| 378 |
+
PubMedLoader,
|
| 379 |
+
)
|
| 380 |
+
from langchain_community.document_loaders.pyspark_dataframe import (
|
| 381 |
+
PySparkDataFrameLoader,
|
| 382 |
+
)
|
| 383 |
+
from langchain_community.document_loaders.python import (
|
| 384 |
+
PythonLoader,
|
| 385 |
+
)
|
| 386 |
+
from langchain_community.document_loaders.readthedocs import (
|
| 387 |
+
ReadTheDocsLoader,
|
| 388 |
+
)
|
| 389 |
+
from langchain_community.document_loaders.recursive_url_loader import (
|
| 390 |
+
RecursiveUrlLoader,
|
| 391 |
+
)
|
| 392 |
+
from langchain_community.document_loaders.reddit import (
|
| 393 |
+
RedditPostsLoader,
|
| 394 |
+
)
|
| 395 |
+
from langchain_community.document_loaders.roam import (
|
| 396 |
+
RoamLoader,
|
| 397 |
+
)
|
| 398 |
+
from langchain_community.document_loaders.rocksetdb import (
|
| 399 |
+
RocksetLoader,
|
| 400 |
+
)
|
| 401 |
+
from langchain_community.document_loaders.rss import (
|
| 402 |
+
RSSFeedLoader,
|
| 403 |
+
)
|
| 404 |
+
from langchain_community.document_loaders.rst import (
|
| 405 |
+
UnstructuredRSTLoader,
|
| 406 |
+
)
|
| 407 |
+
from langchain_community.document_loaders.rtf import (
|
| 408 |
+
UnstructuredRTFLoader,
|
| 409 |
+
)
|
| 410 |
+
from langchain_community.document_loaders.s3_directory import (
|
| 411 |
+
S3DirectoryLoader,
|
| 412 |
+
)
|
| 413 |
+
from langchain_community.document_loaders.s3_file import (
|
| 414 |
+
S3FileLoader,
|
| 415 |
+
)
|
| 416 |
+
from langchain_community.document_loaders.scrapfly import (
|
| 417 |
+
ScrapflyLoader,
|
| 418 |
+
)
|
| 419 |
+
from langchain_community.document_loaders.scrapingant import (
|
| 420 |
+
ScrapingAntLoader,
|
| 421 |
+
)
|
| 422 |
+
from langchain_community.document_loaders.sharepoint import (
|
| 423 |
+
SharePointLoader,
|
| 424 |
+
)
|
| 425 |
+
from langchain_community.document_loaders.sitemap import (
|
| 426 |
+
SitemapLoader,
|
| 427 |
+
)
|
| 428 |
+
from langchain_community.document_loaders.slack_directory import (
|
| 429 |
+
SlackDirectoryLoader,
|
| 430 |
+
)
|
| 431 |
+
from langchain_community.document_loaders.snowflake_loader import (
|
| 432 |
+
SnowflakeLoader,
|
| 433 |
+
)
|
| 434 |
+
from langchain_community.document_loaders.spider import (
|
| 435 |
+
SpiderLoader,
|
| 436 |
+
)
|
| 437 |
+
from langchain_community.document_loaders.spreedly import (
|
| 438 |
+
SpreedlyLoader,
|
| 439 |
+
)
|
| 440 |
+
from langchain_community.document_loaders.sql_database import (
|
| 441 |
+
SQLDatabaseLoader,
|
| 442 |
+
)
|
| 443 |
+
from langchain_community.document_loaders.srt import (
|
| 444 |
+
SRTLoader,
|
| 445 |
+
)
|
| 446 |
+
from langchain_community.document_loaders.stripe import (
|
| 447 |
+
StripeLoader,
|
| 448 |
+
)
|
| 449 |
+
from langchain_community.document_loaders.surrealdb import (
|
| 450 |
+
SurrealDBLoader,
|
| 451 |
+
)
|
| 452 |
+
from langchain_community.document_loaders.telegram import (
|
| 453 |
+
TelegramChatApiLoader,
|
| 454 |
+
TelegramChatFileLoader,
|
| 455 |
+
TelegramChatLoader,
|
| 456 |
+
)
|
| 457 |
+
from langchain_community.document_loaders.tencent_cos_directory import (
|
| 458 |
+
TencentCOSDirectoryLoader,
|
| 459 |
+
)
|
| 460 |
+
from langchain_community.document_loaders.tencent_cos_file import (
|
| 461 |
+
TencentCOSFileLoader,
|
| 462 |
+
)
|
| 463 |
+
from langchain_community.document_loaders.tensorflow_datasets import (
|
| 464 |
+
TensorflowDatasetLoader,
|
| 465 |
+
)
|
| 466 |
+
from langchain_community.document_loaders.text import (
|
| 467 |
+
TextLoader,
|
| 468 |
+
)
|
| 469 |
+
from langchain_community.document_loaders.tidb import (
|
| 470 |
+
TiDBLoader,
|
| 471 |
+
)
|
| 472 |
+
from langchain_community.document_loaders.tomarkdown import (
|
| 473 |
+
ToMarkdownLoader,
|
| 474 |
+
)
|
| 475 |
+
from langchain_community.document_loaders.toml import (
|
| 476 |
+
TomlLoader,
|
| 477 |
+
)
|
| 478 |
+
from langchain_community.document_loaders.trello import (
|
| 479 |
+
TrelloLoader,
|
| 480 |
+
)
|
| 481 |
+
from langchain_community.document_loaders.tsv import (
|
| 482 |
+
UnstructuredTSVLoader,
|
| 483 |
+
)
|
| 484 |
+
from langchain_community.document_loaders.twitter import (
|
| 485 |
+
TwitterTweetLoader,
|
| 486 |
+
)
|
| 487 |
+
from langchain_community.document_loaders.unstructured import (
|
| 488 |
+
UnstructuredAPIFileIOLoader,
|
| 489 |
+
UnstructuredAPIFileLoader,
|
| 490 |
+
UnstructuredFileIOLoader,
|
| 491 |
+
UnstructuredFileLoader,
|
| 492 |
+
)
|
| 493 |
+
from langchain_community.document_loaders.url import (
|
| 494 |
+
UnstructuredURLLoader,
|
| 495 |
+
)
|
| 496 |
+
from langchain_community.document_loaders.url_playwright import (
|
| 497 |
+
PlaywrightURLLoader,
|
| 498 |
+
)
|
| 499 |
+
from langchain_community.document_loaders.url_selenium import (
|
| 500 |
+
SeleniumURLLoader,
|
| 501 |
+
)
|
| 502 |
+
from langchain_community.document_loaders.vsdx import (
|
| 503 |
+
VsdxLoader,
|
| 504 |
+
)
|
| 505 |
+
from langchain_community.document_loaders.weather import (
|
| 506 |
+
WeatherDataLoader,
|
| 507 |
+
)
|
| 508 |
+
from langchain_community.document_loaders.web_base import (
|
| 509 |
+
WebBaseLoader,
|
| 510 |
+
)
|
| 511 |
+
from langchain_community.document_loaders.whatsapp_chat import (
|
| 512 |
+
WhatsAppChatLoader,
|
| 513 |
+
)
|
| 514 |
+
from langchain_community.document_loaders.wikipedia import (
|
| 515 |
+
WikipediaLoader,
|
| 516 |
+
)
|
| 517 |
+
from langchain_community.document_loaders.word_document import (
|
| 518 |
+
Docx2txtLoader,
|
| 519 |
+
UnstructuredWordDocumentLoader,
|
| 520 |
+
)
|
| 521 |
+
from langchain_community.document_loaders.xml import (
|
| 522 |
+
UnstructuredXMLLoader,
|
| 523 |
+
)
|
| 524 |
+
from langchain_community.document_loaders.xorbits import (
|
| 525 |
+
XorbitsLoader,
|
| 526 |
+
)
|
| 527 |
+
from langchain_community.document_loaders.youtube import (
|
| 528 |
+
GoogleApiClient,
|
| 529 |
+
GoogleApiYoutubeLoader,
|
| 530 |
+
YoutubeLoader,
|
| 531 |
+
)
|
| 532 |
+
from langchain_community.document_loaders.yuque import (
|
| 533 |
+
YuqueLoader,
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
_module_lookup = {
|
| 538 |
+
"AZLyricsLoader": "langchain_community.document_loaders.azlyrics",
|
| 539 |
+
"AcreomLoader": "langchain_community.document_loaders.acreom",
|
| 540 |
+
"AirbyteCDKLoader": "langchain_community.document_loaders.airbyte",
|
| 541 |
+
"AirbyteGongLoader": "langchain_community.document_loaders.airbyte",
|
| 542 |
+
"AirbyteHubspotLoader": "langchain_community.document_loaders.airbyte",
|
| 543 |
+
"AirbyteJSONLoader": "langchain_community.document_loaders.airbyte_json",
|
| 544 |
+
"AirbyteSalesforceLoader": "langchain_community.document_loaders.airbyte",
|
| 545 |
+
"AirbyteShopifyLoader": "langchain_community.document_loaders.airbyte",
|
| 546 |
+
"AirbyteStripeLoader": "langchain_community.document_loaders.airbyte",
|
| 547 |
+
"AirbyteTypeformLoader": "langchain_community.document_loaders.airbyte",
|
| 548 |
+
"AirbyteZendeskSupportLoader": "langchain_community.document_loaders.airbyte",
|
| 549 |
+
"AirtableLoader": "langchain_community.document_loaders.airtable",
|
| 550 |
+
"AmazonTextractPDFLoader": "langchain_community.document_loaders.pdf",
|
| 551 |
+
"ApifyDatasetLoader": "langchain_community.document_loaders.apify_dataset",
|
| 552 |
+
"ArcGISLoader": "langchain_community.document_loaders.arcgis_loader",
|
| 553 |
+
"ArxivLoader": "langchain_community.document_loaders.arxiv",
|
| 554 |
+
"AssemblyAIAudioLoaderById": "langchain_community.document_loaders.assemblyai",
|
| 555 |
+
"AssemblyAIAudioTranscriptLoader": "langchain_community.document_loaders.assemblyai", # noqa: E501
|
| 556 |
+
"AstraDBLoader": "langchain_community.document_loaders.astradb",
|
| 557 |
+
"AsyncChromiumLoader": "langchain_community.document_loaders.chromium",
|
| 558 |
+
"AsyncHtmlLoader": "langchain_community.document_loaders.async_html",
|
| 559 |
+
"AthenaLoader": "langchain_community.document_loaders.athena",
|
| 560 |
+
"AzureAIDataLoader": "langchain_community.document_loaders.azure_ai_data",
|
| 561 |
+
"AzureAIDocumentIntelligenceLoader": "langchain_community.document_loaders.doc_intelligence", # noqa: E501
|
| 562 |
+
"AzureBlobStorageContainerLoader": "langchain_community.document_loaders.azure_blob_storage_container", # noqa: E501
|
| 563 |
+
"AzureBlobStorageFileLoader": "langchain_community.document_loaders.azure_blob_storage_file", # noqa: E501
|
| 564 |
+
"BSHTMLLoader": "langchain_community.document_loaders.html_bs",
|
| 565 |
+
"BibtexLoader": "langchain_community.document_loaders.bibtex",
|
| 566 |
+
"BigQueryLoader": "langchain_community.document_loaders.bigquery",
|
| 567 |
+
"BiliBiliLoader": "langchain_community.document_loaders.bilibili",
|
| 568 |
+
"BlackboardLoader": "langchain_community.document_loaders.blackboard",
|
| 569 |
+
"Blob": "langchain_community.document_loaders.blob_loaders",
|
| 570 |
+
"BlobLoader": "langchain_community.document_loaders.blob_loaders",
|
| 571 |
+
"BlockchainDocumentLoader": "langchain_community.document_loaders.blockchain",
|
| 572 |
+
"BraveSearchLoader": "langchain_community.document_loaders.brave_search",
|
| 573 |
+
"BrowserbaseLoader": "langchain_community.document_loaders.browserbase",
|
| 574 |
+
"BrowserlessLoader": "langchain_community.document_loaders.browserless",
|
| 575 |
+
"CSVLoader": "langchain_community.document_loaders.csv_loader",
|
| 576 |
+
"CassandraLoader": "langchain_community.document_loaders.cassandra",
|
| 577 |
+
"ChatGPTLoader": "langchain_community.document_loaders.chatgpt",
|
| 578 |
+
"CloudBlobLoader": "langchain_community.document_loaders.blob_loaders",
|
| 579 |
+
"CoNLLULoader": "langchain_community.document_loaders.conllu",
|
| 580 |
+
"CollegeConfidentialLoader": "langchain_community.document_loaders.college_confidential", # noqa: E501
|
| 581 |
+
"ConcurrentLoader": "langchain_community.document_loaders.concurrent",
|
| 582 |
+
"ConfluenceLoader": "langchain_community.document_loaders.confluence",
|
| 583 |
+
"CouchbaseLoader": "langchain_community.document_loaders.couchbase",
|
| 584 |
+
"CubeSemanticLoader": "langchain_community.document_loaders.cube_semantic",
|
| 585 |
+
"DataFrameLoader": "langchain_community.document_loaders.dataframe",
|
| 586 |
+
"DatadogLogsLoader": "langchain_community.document_loaders.datadog_logs",
|
| 587 |
+
"DedocAPIFileLoader": "langchain_community.document_loaders.dedoc",
|
| 588 |
+
"DedocFileLoader": "langchain_community.document_loaders.dedoc",
|
| 589 |
+
"DedocPDFLoader": "langchain_community.document_loaders.pdf",
|
| 590 |
+
"DiffbotLoader": "langchain_community.document_loaders.diffbot",
|
| 591 |
+
"DirectoryLoader": "langchain_community.document_loaders.directory",
|
| 592 |
+
"DiscordChatLoader": "langchain_community.document_loaders.discord",
|
| 593 |
+
"DocugamiLoader": "langchain_community.document_loaders.docugami",
|
| 594 |
+
"DocusaurusLoader": "langchain_community.document_loaders.docusaurus",
|
| 595 |
+
"Docx2txtLoader": "langchain_community.document_loaders.word_document",
|
| 596 |
+
"DropboxLoader": "langchain_community.document_loaders.dropbox",
|
| 597 |
+
"DuckDBLoader": "langchain_community.document_loaders.duckdb_loader",
|
| 598 |
+
"EtherscanLoader": "langchain_community.document_loaders.etherscan",
|
| 599 |
+
"EverNoteLoader": "langchain_community.document_loaders.evernote",
|
| 600 |
+
"FacebookChatLoader": "langchain_community.document_loaders.facebook_chat",
|
| 601 |
+
"FaunaLoader": "langchain_community.document_loaders.fauna",
|
| 602 |
+
"FigmaFileLoader": "langchain_community.document_loaders.figma",
|
| 603 |
+
"FireCrawlLoader": "langchain_community.document_loaders.firecrawl",
|
| 604 |
+
"FileSystemBlobLoader": "langchain_community.document_loaders.blob_loaders",
|
| 605 |
+
"GCSDirectoryLoader": "langchain_community.document_loaders.gcs_directory",
|
| 606 |
+
"GCSFileLoader": "langchain_community.document_loaders.gcs_file",
|
| 607 |
+
"GeoDataFrameLoader": "langchain_community.document_loaders.geodataframe",
|
| 608 |
+
"GitHubIssuesLoader": "langchain_community.document_loaders.github",
|
| 609 |
+
"GitLoader": "langchain_community.document_loaders.git",
|
| 610 |
+
"GitbookLoader": "langchain_community.document_loaders.gitbook",
|
| 611 |
+
"GithubFileLoader": "langchain_community.document_loaders.github",
|
| 612 |
+
"GlueCatalogLoader": "langchain_community.document_loaders.glue_catalog",
|
| 613 |
+
"GoogleApiClient": "langchain_community.document_loaders.youtube",
|
| 614 |
+
"GoogleApiYoutubeLoader": "langchain_community.document_loaders.youtube",
|
| 615 |
+
"GoogleDriveLoader": "langchain_community.document_loaders.googledrive",
|
| 616 |
+
"GoogleSpeechToTextLoader": "langchain_community.document_loaders.google_speech_to_text", # noqa: E501
|
| 617 |
+
"GutenbergLoader": "langchain_community.document_loaders.gutenberg",
|
| 618 |
+
"HNLoader": "langchain_community.document_loaders.hn",
|
| 619 |
+
"HuggingFaceDatasetLoader": "langchain_community.document_loaders.hugging_face_dataset", # noqa: E501
|
| 620 |
+
"HuggingFaceModelLoader": "langchain_community.document_loaders.hugging_face_model",
|
| 621 |
+
"IFixitLoader": "langchain_community.document_loaders.ifixit",
|
| 622 |
+
"IMSDbLoader": "langchain_community.document_loaders.imsdb",
|
| 623 |
+
"ImageCaptionLoader": "langchain_community.document_loaders.image_captions",
|
| 624 |
+
"IuguLoader": "langchain_community.document_loaders.iugu",
|
| 625 |
+
"JSONLoader": "langchain_community.document_loaders.json_loader",
|
| 626 |
+
"JoplinLoader": "langchain_community.document_loaders.joplin",
|
| 627 |
+
"KineticaLoader": "langchain_community.document_loaders.kinetica_loader",
|
| 628 |
+
"LakeFSLoader": "langchain_community.document_loaders.lakefs",
|
| 629 |
+
"LarkSuiteDocLoader": "langchain_community.document_loaders.larksuite",
|
| 630 |
+
"LLMSherpaFileLoader": "langchain_community.document_loaders.llmsherpa",
|
| 631 |
+
"MHTMLLoader": "langchain_community.document_loaders.mhtml",
|
| 632 |
+
"MWDumpLoader": "langchain_community.document_loaders.mediawikidump",
|
| 633 |
+
"MastodonTootsLoader": "langchain_community.document_loaders.mastodon",
|
| 634 |
+
"MathpixPDFLoader": "langchain_community.document_loaders.pdf",
|
| 635 |
+
"MaxComputeLoader": "langchain_community.document_loaders.max_compute",
|
| 636 |
+
"MergedDataLoader": "langchain_community.document_loaders.merge",
|
| 637 |
+
"ModernTreasuryLoader": "langchain_community.document_loaders.modern_treasury",
|
| 638 |
+
"MongodbLoader": "langchain_community.document_loaders.mongodb",
|
| 639 |
+
"NeedleLoader": "langchain_community.document_loaders.needle",
|
| 640 |
+
"NewsURLLoader": "langchain_community.document_loaders.news",
|
| 641 |
+
"NotebookLoader": "langchain_community.document_loaders.notebook",
|
| 642 |
+
"NotionDBLoader": "langchain_community.document_loaders.notiondb",
|
| 643 |
+
"NotionDirectoryLoader": "langchain_community.document_loaders.notion",
|
| 644 |
+
"OBSDirectoryLoader": "langchain_community.document_loaders.obs_directory",
|
| 645 |
+
"OBSFileLoader": "langchain_community.document_loaders.obs_file",
|
| 646 |
+
"ObsidianLoader": "langchain_community.document_loaders.obsidian",
|
| 647 |
+
"OneDriveFileLoader": "langchain_community.document_loaders.onedrive_file",
|
| 648 |
+
"OneDriveLoader": "langchain_community.document_loaders.onedrive",
|
| 649 |
+
"OnlinePDFLoader": "langchain_community.document_loaders.pdf",
|
| 650 |
+
"OpenCityDataLoader": "langchain_community.document_loaders.open_city_data",
|
| 651 |
+
"OracleAutonomousDatabaseLoader": "langchain_community.document_loaders.oracleadb_loader", # noqa: E501
|
| 652 |
+
"OracleDocLoader": "langchain_community.document_loaders.oracleai",
|
| 653 |
+
"OracleTextSplitter": "langchain_community.document_loaders.oracleai",
|
| 654 |
+
"OutlookMessageLoader": "langchain_community.document_loaders.email",
|
| 655 |
+
"PDFMinerLoader": "langchain_community.document_loaders.pdf",
|
| 656 |
+
"PDFMinerPDFasHTMLLoader": "langchain_community.document_loaders.pdf",
|
| 657 |
+
"PDFPlumberLoader": "langchain_community.document_loaders.pdf",
|
| 658 |
+
"PagedPDFSplitter": "langchain_community.document_loaders.pdf",
|
| 659 |
+
"PebbloSafeLoader": "langchain_community.document_loaders.pebblo",
|
| 660 |
+
"PebbloTextLoader": "langchain_community.document_loaders.pebblo",
|
| 661 |
+
"PlaywrightURLLoader": "langchain_community.document_loaders.url_playwright",
|
| 662 |
+
"PolarsDataFrameLoader": "langchain_community.document_loaders.polars_dataframe",
|
| 663 |
+
"PsychicLoader": "langchain_community.document_loaders.psychic",
|
| 664 |
+
"PubMedLoader": "langchain_community.document_loaders.pubmed",
|
| 665 |
+
"PyMuPDFLoader": "langchain_community.document_loaders.pdf",
|
| 666 |
+
"PyPDFDirectoryLoader": "langchain_community.document_loaders.pdf",
|
| 667 |
+
"PyPDFLoader": "langchain_community.document_loaders.pdf",
|
| 668 |
+
"PyPDFium2Loader": "langchain_community.document_loaders.pdf",
|
| 669 |
+
"PySparkDataFrameLoader": "langchain_community.document_loaders.pyspark_dataframe",
|
| 670 |
+
"PythonLoader": "langchain_community.document_loaders.python",
|
| 671 |
+
"RSSFeedLoader": "langchain_community.document_loaders.rss",
|
| 672 |
+
"ReadTheDocsLoader": "langchain_community.document_loaders.readthedocs",
|
| 673 |
+
"RecursiveUrlLoader": "langchain_community.document_loaders.recursive_url_loader",
|
| 674 |
+
"RedditPostsLoader": "langchain_community.document_loaders.reddit",
|
| 675 |
+
"RoamLoader": "langchain_community.document_loaders.roam",
|
| 676 |
+
"RocksetLoader": "langchain_community.document_loaders.rocksetdb",
|
| 677 |
+
"S3DirectoryLoader": "langchain_community.document_loaders.s3_directory",
|
| 678 |
+
"S3FileLoader": "langchain_community.document_loaders.s3_file",
|
| 679 |
+
"ScrapflyLoader": "langchain_community.document_loaders.scrapfly",
|
| 680 |
+
"ScrapingAntLoader": "langchain_community.document_loaders.scrapingant",
|
| 681 |
+
"SQLDatabaseLoader": "langchain_community.document_loaders.sql_database",
|
| 682 |
+
"SRTLoader": "langchain_community.document_loaders.srt",
|
| 683 |
+
"SeleniumURLLoader": "langchain_community.document_loaders.url_selenium",
|
| 684 |
+
"SharePointLoader": "langchain_community.document_loaders.sharepoint",
|
| 685 |
+
"SitemapLoader": "langchain_community.document_loaders.sitemap",
|
| 686 |
+
"SlackDirectoryLoader": "langchain_community.document_loaders.slack_directory",
|
| 687 |
+
"SnowflakeLoader": "langchain_community.document_loaders.snowflake_loader",
|
| 688 |
+
"SpiderLoader": "langchain_community.document_loaders.spider",
|
| 689 |
+
"SpreedlyLoader": "langchain_community.document_loaders.spreedly",
|
| 690 |
+
"StripeLoader": "langchain_community.document_loaders.stripe",
|
| 691 |
+
"SurrealDBLoader": "langchain_community.document_loaders.surrealdb",
|
| 692 |
+
"TelegramChatApiLoader": "langchain_community.document_loaders.telegram",
|
| 693 |
+
"TelegramChatFileLoader": "langchain_community.document_loaders.telegram",
|
| 694 |
+
"TelegramChatLoader": "langchain_community.document_loaders.telegram",
|
| 695 |
+
"TencentCOSDirectoryLoader": "langchain_community.document_loaders.tencent_cos_directory", # noqa: E501
|
| 696 |
+
"TencentCOSFileLoader": "langchain_community.document_loaders.tencent_cos_file",
|
| 697 |
+
"TensorflowDatasetLoader": "langchain_community.document_loaders.tensorflow_datasets", # noqa: E501
|
| 698 |
+
"TextLoader": "langchain_community.document_loaders.text",
|
| 699 |
+
"TiDBLoader": "langchain_community.document_loaders.tidb",
|
| 700 |
+
"ToMarkdownLoader": "langchain_community.document_loaders.tomarkdown",
|
| 701 |
+
"TomlLoader": "langchain_community.document_loaders.toml",
|
| 702 |
+
"TrelloLoader": "langchain_community.document_loaders.trello",
|
| 703 |
+
"TwitterTweetLoader": "langchain_community.document_loaders.twitter",
|
| 704 |
+
"UnstructuredAPIFileIOLoader": "langchain_community.document_loaders.unstructured",
|
| 705 |
+
"UnstructuredAPIFileLoader": "langchain_community.document_loaders.unstructured",
|
| 706 |
+
"UnstructuredCHMLoader": "langchain_community.document_loaders.chm",
|
| 707 |
+
"UnstructuredCSVLoader": "langchain_community.document_loaders.csv_loader",
|
| 708 |
+
"UnstructuredEPubLoader": "langchain_community.document_loaders.epub",
|
| 709 |
+
"UnstructuredEmailLoader": "langchain_community.document_loaders.email",
|
| 710 |
+
"UnstructuredExcelLoader": "langchain_community.document_loaders.excel",
|
| 711 |
+
"UnstructuredFileIOLoader": "langchain_community.document_loaders.unstructured",
|
| 712 |
+
"UnstructuredFileLoader": "langchain_community.document_loaders.unstructured",
|
| 713 |
+
"UnstructuredHTMLLoader": "langchain_community.document_loaders.html",
|
| 714 |
+
"UnstructuredImageLoader": "langchain_community.document_loaders.image",
|
| 715 |
+
"UnstructuredMarkdownLoader": "langchain_community.document_loaders.markdown",
|
| 716 |
+
"UnstructuredODTLoader": "langchain_community.document_loaders.odt",
|
| 717 |
+
"UnstructuredOrgModeLoader": "langchain_community.document_loaders.org_mode",
|
| 718 |
+
"UnstructuredPDFLoader": "langchain_community.document_loaders.pdf",
|
| 719 |
+
"UnstructuredPowerPointLoader": "langchain_community.document_loaders.powerpoint",
|
| 720 |
+
"UnstructuredRSTLoader": "langchain_community.document_loaders.rst",
|
| 721 |
+
"UnstructuredRTFLoader": "langchain_community.document_loaders.rtf",
|
| 722 |
+
"UnstructuredTSVLoader": "langchain_community.document_loaders.tsv",
|
| 723 |
+
"UnstructuredURLLoader": "langchain_community.document_loaders.url",
|
| 724 |
+
"UnstructuredWordDocumentLoader": "langchain_community.document_loaders.word_document", # noqa: E501
|
| 725 |
+
"UnstructuredXMLLoader": "langchain_community.document_loaders.xml",
|
| 726 |
+
"VsdxLoader": "langchain_community.document_loaders.vsdx",
|
| 727 |
+
"WeatherDataLoader": "langchain_community.document_loaders.weather",
|
| 728 |
+
"WebBaseLoader": "langchain_community.document_loaders.web_base",
|
| 729 |
+
"WhatsAppChatLoader": "langchain_community.document_loaders.whatsapp_chat",
|
| 730 |
+
"WikipediaLoader": "langchain_community.document_loaders.wikipedia",
|
| 731 |
+
"XorbitsLoader": "langchain_community.document_loaders.xorbits",
|
| 732 |
+
"YoutubeAudioLoader": "langchain_community.document_loaders.blob_loaders",
|
| 733 |
+
"YoutubeLoader": "langchain_community.document_loaders.youtube",
|
| 734 |
+
"YuqueLoader": "langchain_community.document_loaders.yuque",
|
| 735 |
+
}
|
| 736 |
+
|
| 737 |
+
|
| 738 |
+
def __getattr__(name: str) -> Any:
|
| 739 |
+
if name in _module_lookup:
|
| 740 |
+
module = importlib.import_module(_module_lookup[name])
|
| 741 |
+
return getattr(module, name)
|
| 742 |
+
raise AttributeError(f"module {__name__} has no attribute {name}")
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
__all__ = [
|
| 746 |
+
"AZLyricsLoader",
|
| 747 |
+
"AcreomLoader",
|
| 748 |
+
"AirbyteCDKLoader",
|
| 749 |
+
"AirbyteGongLoader",
|
| 750 |
+
"AirbyteHubspotLoader",
|
| 751 |
+
"AirbyteJSONLoader",
|
| 752 |
+
"AirbyteSalesforceLoader",
|
| 753 |
+
"AirbyteShopifyLoader",
|
| 754 |
+
"AirbyteStripeLoader",
|
| 755 |
+
"AirbyteTypeformLoader",
|
| 756 |
+
"AirbyteZendeskSupportLoader",
|
| 757 |
+
"AirtableLoader",
|
| 758 |
+
"AmazonTextractPDFLoader",
|
| 759 |
+
"ApifyDatasetLoader",
|
| 760 |
+
"ArcGISLoader",
|
| 761 |
+
"ArxivLoader",
|
| 762 |
+
"AssemblyAIAudioLoaderById",
|
| 763 |
+
"AssemblyAIAudioTranscriptLoader",
|
| 764 |
+
"AstraDBLoader",
|
| 765 |
+
"AsyncChromiumLoader",
|
| 766 |
+
"AsyncHtmlLoader",
|
| 767 |
+
"AthenaLoader",
|
| 768 |
+
"AzureAIDataLoader",
|
| 769 |
+
"AzureAIDocumentIntelligenceLoader",
|
| 770 |
+
"AzureBlobStorageContainerLoader",
|
| 771 |
+
"AzureBlobStorageFileLoader",
|
| 772 |
+
"BSHTMLLoader",
|
| 773 |
+
"BibtexLoader",
|
| 774 |
+
"BigQueryLoader",
|
| 775 |
+
"BiliBiliLoader",
|
| 776 |
+
"BlackboardLoader",
|
| 777 |
+
"Blob",
|
| 778 |
+
"BlobLoader",
|
| 779 |
+
"BlockchainDocumentLoader",
|
| 780 |
+
"BraveSearchLoader",
|
| 781 |
+
"BrowserbaseLoader",
|
| 782 |
+
"BrowserlessLoader",
|
| 783 |
+
"CSVLoader",
|
| 784 |
+
"CassandraLoader",
|
| 785 |
+
"ChatGPTLoader",
|
| 786 |
+
"CloudBlobLoader",
|
| 787 |
+
"CoNLLULoader",
|
| 788 |
+
"CollegeConfidentialLoader",
|
| 789 |
+
"ConcurrentLoader",
|
| 790 |
+
"ConfluenceLoader",
|
| 791 |
+
"CouchbaseLoader",
|
| 792 |
+
"CubeSemanticLoader",
|
| 793 |
+
"DataFrameLoader",
|
| 794 |
+
"DatadogLogsLoader",
|
| 795 |
+
"DedocAPIFileLoader",
|
| 796 |
+
"DedocFileLoader",
|
| 797 |
+
"DedocPDFLoader",
|
| 798 |
+
"DiffbotLoader",
|
| 799 |
+
"DirectoryLoader",
|
| 800 |
+
"DiscordChatLoader",
|
| 801 |
+
"DocugamiLoader",
|
| 802 |
+
"DocusaurusLoader",
|
| 803 |
+
"Docx2txtLoader",
|
| 804 |
+
"DropboxLoader",
|
| 805 |
+
"DuckDBLoader",
|
| 806 |
+
"EtherscanLoader",
|
| 807 |
+
"EverNoteLoader",
|
| 808 |
+
"FacebookChatLoader",
|
| 809 |
+
"FaunaLoader",
|
| 810 |
+
"FigmaFileLoader",
|
| 811 |
+
"FireCrawlLoader",
|
| 812 |
+
"FileSystemBlobLoader",
|
| 813 |
+
"GCSDirectoryLoader",
|
| 814 |
+
"GlueCatalogLoader",
|
| 815 |
+
"GCSFileLoader",
|
| 816 |
+
"GeoDataFrameLoader",
|
| 817 |
+
"GitHubIssuesLoader",
|
| 818 |
+
"GitLoader",
|
| 819 |
+
"GitbookLoader",
|
| 820 |
+
"GithubFileLoader",
|
| 821 |
+
"GoogleApiClient",
|
| 822 |
+
"GoogleApiYoutubeLoader",
|
| 823 |
+
"GoogleDriveLoader",
|
| 824 |
+
"GoogleSpeechToTextLoader",
|
| 825 |
+
"GutenbergLoader",
|
| 826 |
+
"HNLoader",
|
| 827 |
+
"HuggingFaceDatasetLoader",
|
| 828 |
+
"HuggingFaceModelLoader",
|
| 829 |
+
"IFixitLoader",
|
| 830 |
+
"ImageCaptionLoader",
|
| 831 |
+
"IMSDbLoader",
|
| 832 |
+
"IuguLoader",
|
| 833 |
+
"JoplinLoader",
|
| 834 |
+
"JSONLoader",
|
| 835 |
+
"KineticaLoader",
|
| 836 |
+
"LakeFSLoader",
|
| 837 |
+
"LarkSuiteDocLoader",
|
| 838 |
+
"LLMSherpaFileLoader",
|
| 839 |
+
"MastodonTootsLoader",
|
| 840 |
+
"MHTMLLoader",
|
| 841 |
+
"MWDumpLoader",
|
| 842 |
+
"MathpixPDFLoader",
|
| 843 |
+
"MaxComputeLoader",
|
| 844 |
+
"MergedDataLoader",
|
| 845 |
+
"ModernTreasuryLoader",
|
| 846 |
+
"MongodbLoader",
|
| 847 |
+
"NeedleLoader",
|
| 848 |
+
"NewsURLLoader",
|
| 849 |
+
"NotebookLoader",
|
| 850 |
+
"NotionDBLoader",
|
| 851 |
+
"NotionDirectoryLoader",
|
| 852 |
+
"OBSDirectoryLoader",
|
| 853 |
+
"OBSFileLoader",
|
| 854 |
+
"ObsidianLoader",
|
| 855 |
+
"OneDriveFileLoader",
|
| 856 |
+
"OneDriveLoader",
|
| 857 |
+
"OnlinePDFLoader",
|
| 858 |
+
"OpenCityDataLoader",
|
| 859 |
+
"OracleAutonomousDatabaseLoader",
|
| 860 |
+
"OracleDocLoader",
|
| 861 |
+
"OracleTextSplitter",
|
| 862 |
+
"OutlookMessageLoader",
|
| 863 |
+
"PDFMinerLoader",
|
| 864 |
+
"PDFMinerPDFasHTMLLoader",
|
| 865 |
+
"PDFPlumberLoader",
|
| 866 |
+
"PagedPDFSplitter",
|
| 867 |
+
"PebbloSafeLoader",
|
| 868 |
+
"PebbloTextLoader",
|
| 869 |
+
"PlaywrightURLLoader",
|
| 870 |
+
"PolarsDataFrameLoader",
|
| 871 |
+
"PsychicLoader",
|
| 872 |
+
"PubMedLoader",
|
| 873 |
+
"PyMuPDFLoader",
|
| 874 |
+
"PyPDFDirectoryLoader",
|
| 875 |
+
"PyPDFLoader",
|
| 876 |
+
"PyPDFium2Loader",
|
| 877 |
+
"PySparkDataFrameLoader",
|
| 878 |
+
"PythonLoader",
|
| 879 |
+
"RSSFeedLoader",
|
| 880 |
+
"ReadTheDocsLoader",
|
| 881 |
+
"RecursiveUrlLoader",
|
| 882 |
+
"RedditPostsLoader",
|
| 883 |
+
"RoamLoader",
|
| 884 |
+
"RocksetLoader",
|
| 885 |
+
"S3DirectoryLoader",
|
| 886 |
+
"S3FileLoader",
|
| 887 |
+
"ScrapflyLoader",
|
| 888 |
+
"ScrapingAntLoader",
|
| 889 |
+
"SQLDatabaseLoader",
|
| 890 |
+
"SRTLoader",
|
| 891 |
+
"SeleniumURLLoader",
|
| 892 |
+
"SharePointLoader",
|
| 893 |
+
"SitemapLoader",
|
| 894 |
+
"SlackDirectoryLoader",
|
| 895 |
+
"SnowflakeLoader",
|
| 896 |
+
"SpiderLoader",
|
| 897 |
+
"SpreedlyLoader",
|
| 898 |
+
"StripeLoader",
|
| 899 |
+
"SurrealDBLoader",
|
| 900 |
+
"TelegramChatApiLoader",
|
| 901 |
+
"TelegramChatFileLoader",
|
| 902 |
+
"TelegramChatLoader",
|
| 903 |
+
"TencentCOSDirectoryLoader",
|
| 904 |
+
"TencentCOSFileLoader",
|
| 905 |
+
"TensorflowDatasetLoader",
|
| 906 |
+
"TextLoader",
|
| 907 |
+
"TiDBLoader",
|
| 908 |
+
"ToMarkdownLoader",
|
| 909 |
+
"TomlLoader",
|
| 910 |
+
"TrelloLoader",
|
| 911 |
+
"TwitterTweetLoader",
|
| 912 |
+
"UnstructuredAPIFileIOLoader",
|
| 913 |
+
"UnstructuredAPIFileLoader",
|
| 914 |
+
"UnstructuredCHMLoader",
|
| 915 |
+
"UnstructuredCSVLoader",
|
| 916 |
+
"UnstructuredEPubLoader",
|
| 917 |
+
"UnstructuredEmailLoader",
|
| 918 |
+
"UnstructuredExcelLoader",
|
| 919 |
+
"UnstructuredFileIOLoader",
|
| 920 |
+
"UnstructuredFileLoader",
|
| 921 |
+
"UnstructuredHTMLLoader",
|
| 922 |
+
"UnstructuredImageLoader",
|
| 923 |
+
"UnstructuredMarkdownLoader",
|
| 924 |
+
"UnstructuredODTLoader",
|
| 925 |
+
"UnstructuredOrgModeLoader",
|
| 926 |
+
"UnstructuredPDFLoader",
|
| 927 |
+
"UnstructuredPowerPointLoader",
|
| 928 |
+
"UnstructuredRSTLoader",
|
| 929 |
+
"UnstructuredRTFLoader",
|
| 930 |
+
"UnstructuredTSVLoader",
|
| 931 |
+
"UnstructuredURLLoader",
|
| 932 |
+
"UnstructuredWordDocumentLoader",
|
| 933 |
+
"UnstructuredXMLLoader",
|
| 934 |
+
"VsdxLoader",
|
| 935 |
+
"WeatherDataLoader",
|
| 936 |
+
"WebBaseLoader",
|
| 937 |
+
"WhatsAppChatLoader",
|
| 938 |
+
"WikipediaLoader",
|
| 939 |
+
"XorbitsLoader",
|
| 940 |
+
"YoutubeAudioLoader",
|
| 941 |
+
"YoutubeLoader",
|
| 942 |
+
"YuqueLoader",
|
| 943 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/pyspark_dataframe.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import logging
|
| 3 |
+
import sys
|
| 4 |
+
from typing import TYPE_CHECKING, Any, Iterator, List, Optional, Tuple
|
| 5 |
+
|
| 6 |
+
from langchain_core.documents import Document
|
| 7 |
+
|
| 8 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__file__)
|
| 11 |
+
|
| 12 |
+
if TYPE_CHECKING:
|
| 13 |
+
from pyspark.sql import SparkSession
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class PySparkDataFrameLoader(BaseLoader):
|
| 17 |
+
"""Load `PySpark` DataFrames."""
|
| 18 |
+
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
spark_session: Optional["SparkSession"] = None,
|
| 22 |
+
df: Optional[Any] = None,
|
| 23 |
+
page_content_column: str = "text",
|
| 24 |
+
fraction_of_memory: float = 0.1,
|
| 25 |
+
):
|
| 26 |
+
"""Initialize with a Spark DataFrame object.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
spark_session: The SparkSession object.
|
| 30 |
+
df: The Spark DataFrame object.
|
| 31 |
+
page_content_column: The name of the column containing the page content.
|
| 32 |
+
Defaults to "text".
|
| 33 |
+
fraction_of_memory: The fraction of memory to use. Defaults to 0.1.
|
| 34 |
+
"""
|
| 35 |
+
try:
|
| 36 |
+
from pyspark.sql import DataFrame, SparkSession
|
| 37 |
+
except ImportError:
|
| 38 |
+
raise ImportError(
|
| 39 |
+
"pyspark is not installed. Please install it with `pip install pyspark`"
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
self.spark = (
|
| 43 |
+
spark_session if spark_session else SparkSession.builder.getOrCreate()
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
if not isinstance(df, DataFrame):
|
| 47 |
+
raise ValueError(
|
| 48 |
+
f"Expected data_frame to be a PySpark DataFrame, got {type(df)}"
|
| 49 |
+
)
|
| 50 |
+
self.df = df
|
| 51 |
+
self.page_content_column = page_content_column
|
| 52 |
+
self.fraction_of_memory = fraction_of_memory
|
| 53 |
+
self.num_rows, self.max_num_rows = self.get_num_rows()
|
| 54 |
+
self.rdd_df = self.df.rdd.map(list)
|
| 55 |
+
self.column_names = self.df.columns
|
| 56 |
+
|
| 57 |
+
def get_num_rows(self) -> Tuple[int, int]:
|
| 58 |
+
"""Gets the number of "feasible" rows for the DataFrame"""
|
| 59 |
+
try:
|
| 60 |
+
import psutil
|
| 61 |
+
except ImportError as e:
|
| 62 |
+
raise ImportError(
|
| 63 |
+
"psutil not installed. Please install it with `pip install psutil`."
|
| 64 |
+
) from e
|
| 65 |
+
row = self.df.limit(1).collect()[0]
|
| 66 |
+
estimated_row_size = sys.getsizeof(row)
|
| 67 |
+
mem_info = psutil.virtual_memory()
|
| 68 |
+
available_memory = mem_info.available
|
| 69 |
+
max_num_rows = int(
|
| 70 |
+
(available_memory / estimated_row_size) * self.fraction_of_memory
|
| 71 |
+
)
|
| 72 |
+
return min(max_num_rows, self.df.count()), max_num_rows
|
| 73 |
+
|
| 74 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 75 |
+
"""A lazy loader for document content."""
|
| 76 |
+
for row in self.rdd_df.toLocalIterator():
|
| 77 |
+
metadata = {self.column_names[i]: row[i] for i in range(len(row))}
|
| 78 |
+
text = metadata[self.page_content_column]
|
| 79 |
+
metadata.pop(self.page_content_column)
|
| 80 |
+
yield Document(page_content=text, metadata=metadata)
|
| 81 |
+
|
| 82 |
+
def load(self) -> List[Document]:
|
| 83 |
+
"""Load from the dataframe."""
|
| 84 |
+
if self.df.count() > self.max_num_rows:
|
| 85 |
+
logger.warning(
|
| 86 |
+
f"The number of DataFrame rows is {self.df.count()}, "
|
| 87 |
+
f"but we will only include the amount "
|
| 88 |
+
f"of rows that can reasonably fit in memory: {self.num_rows}."
|
| 89 |
+
)
|
| 90 |
+
lazy_load_iterator = self.lazy_load()
|
| 91 |
+
return list(itertools.islice(lazy_load_iterator, self.num_rows))
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/python.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tokenize
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Union
|
| 4 |
+
|
| 5 |
+
from langchain_community.document_loaders.text import TextLoader
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class PythonLoader(TextLoader):
|
| 9 |
+
"""Load `Python` files, respecting any non-default encoding if specified."""
|
| 10 |
+
|
| 11 |
+
def __init__(self, file_path: Union[str, Path]):
|
| 12 |
+
"""Initialize with a file path.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
file_path: The path to the file to load.
|
| 16 |
+
"""
|
| 17 |
+
with open(file_path, "rb") as f:
|
| 18 |
+
encoding, _ = tokenize.detect_encoding(f.readline)
|
| 19 |
+
super().__init__(file_path=file_path, encoding=encoding)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/quip.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import re
|
| 3 |
+
import xml.etree.cElementTree # OK: user-must-opt-in
|
| 4 |
+
from io import BytesIO
|
| 5 |
+
from typing import List, Optional, Sequence
|
| 6 |
+
from xml.etree.ElementTree import ElementTree # OK: user-must-opt-in
|
| 7 |
+
|
| 8 |
+
from langchain_core.documents import Document
|
| 9 |
+
|
| 10 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 11 |
+
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
_MAXIMUM_TITLE_LENGTH = 64
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class QuipLoader(BaseLoader):
|
| 18 |
+
"""Load `Quip` pages.
|
| 19 |
+
|
| 20 |
+
Port of https://github.com/quip/quip-api/tree/master/samples/baqup
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
api_url: str,
|
| 26 |
+
access_token: str,
|
| 27 |
+
request_timeout: Optional[int] = 60,
|
| 28 |
+
*,
|
| 29 |
+
allow_dangerous_xml_parsing: bool = False,
|
| 30 |
+
):
|
| 31 |
+
"""
|
| 32 |
+
Args:
|
| 33 |
+
api_url: https://platform.quip.com
|
| 34 |
+
access_token: token of access quip API. Please refer:
|
| 35 |
+
https://quip.com/dev/automation/documentation/current#section/Authentication/Get-Access-to-Quip's-APIs
|
| 36 |
+
request_timeout: timeout of request, default 60s.
|
| 37 |
+
allow_dangerous_xml_parsing: Allow dangerous XML parsing, defaults to False
|
| 38 |
+
"""
|
| 39 |
+
try:
|
| 40 |
+
from quip_api.quip import QuipClient
|
| 41 |
+
except ImportError:
|
| 42 |
+
raise ImportError(
|
| 43 |
+
"`quip_api` package not found, please run `pip install quip_api`"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
self.quip_client = QuipClient(
|
| 47 |
+
access_token=access_token, base_url=api_url, request_timeout=request_timeout
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
if not allow_dangerous_xml_parsing:
|
| 51 |
+
raise ValueError(
|
| 52 |
+
"The quip client uses the built-in XML parser which may cause"
|
| 53 |
+
"security issues when parsing XML data in some cases. "
|
| 54 |
+
"Please see "
|
| 55 |
+
"https://docs.python.org/3/library/xml.html#xml-vulnerabilities "
|
| 56 |
+
"For more information, set `allow_dangerous_xml_parsing` as True "
|
| 57 |
+
"if you are sure that your distribution of the standard library "
|
| 58 |
+
"is not vulnerable to XML vulnerabilities."
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
def load(
|
| 62 |
+
self,
|
| 63 |
+
folder_ids: Optional[List[str]] = None,
|
| 64 |
+
thread_ids: Optional[List[str]] = None,
|
| 65 |
+
max_docs: Optional[int] = 1000,
|
| 66 |
+
include_all_folders: bool = False,
|
| 67 |
+
include_comments: bool = False,
|
| 68 |
+
include_images: bool = False,
|
| 69 |
+
) -> List[Document]:
|
| 70 |
+
"""
|
| 71 |
+
Args:
|
| 72 |
+
:param folder_ids: List of specific folder IDs to load, defaults to None
|
| 73 |
+
:param thread_ids: List of specific thread IDs to load, defaults to None
|
| 74 |
+
:param max_docs: Maximum number of docs to retrieve in total, defaults 1000
|
| 75 |
+
:param include_all_folders: Include all folders that your access_token
|
| 76 |
+
can access, but doesn't include your private folder
|
| 77 |
+
:param include_comments: Include comments, defaults to False
|
| 78 |
+
:param include_images: Include images, defaults to False
|
| 79 |
+
"""
|
| 80 |
+
if not folder_ids and not thread_ids and not include_all_folders:
|
| 81 |
+
raise ValueError(
|
| 82 |
+
"Must specify at least one among `folder_ids`, `thread_ids` "
|
| 83 |
+
"or set `include_all`_folders as True"
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
thread_ids = thread_ids or []
|
| 87 |
+
|
| 88 |
+
if folder_ids:
|
| 89 |
+
for folder_id in folder_ids:
|
| 90 |
+
self.get_thread_ids_by_folder_id(folder_id, 0, thread_ids)
|
| 91 |
+
|
| 92 |
+
if include_all_folders:
|
| 93 |
+
user = self.quip_client.get_authenticated_user()
|
| 94 |
+
if "group_folder_ids" in user:
|
| 95 |
+
self.get_thread_ids_by_folder_id(
|
| 96 |
+
user["group_folder_ids"], 0, thread_ids
|
| 97 |
+
)
|
| 98 |
+
if "shared_folder_ids" in user:
|
| 99 |
+
self.get_thread_ids_by_folder_id(
|
| 100 |
+
user["shared_folder_ids"], 0, thread_ids
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
thread_ids = list(set(thread_ids[:max_docs]))
|
| 104 |
+
return self.process_threads(thread_ids, include_images, include_comments)
|
| 105 |
+
|
| 106 |
+
def get_thread_ids_by_folder_id(
|
| 107 |
+
self, folder_id: str, depth: int, thread_ids: List[str]
|
| 108 |
+
) -> None:
|
| 109 |
+
"""Get thread ids by folder id and update in thread_ids"""
|
| 110 |
+
from quip_api.quip import HTTPError, QuipError
|
| 111 |
+
|
| 112 |
+
try:
|
| 113 |
+
folder = self.quip_client.get_folder(folder_id)
|
| 114 |
+
except QuipError as e:
|
| 115 |
+
if e.code == 403:
|
| 116 |
+
logging.warning(
|
| 117 |
+
f"depth {depth}, Skipped over restricted folder {folder_id}, {e}"
|
| 118 |
+
)
|
| 119 |
+
else:
|
| 120 |
+
logging.warning(
|
| 121 |
+
f"depth {depth}, Skipped over folder {folder_id} "
|
| 122 |
+
f"due to unknown error {e.code}"
|
| 123 |
+
)
|
| 124 |
+
return
|
| 125 |
+
except HTTPError as e:
|
| 126 |
+
logging.warning(
|
| 127 |
+
f"depth {depth}, Skipped over folder {folder_id} "
|
| 128 |
+
f"due to HTTP error {e.code}"
|
| 129 |
+
)
|
| 130 |
+
return
|
| 131 |
+
|
| 132 |
+
title = folder["folder"].get("title", "Folder %s" % folder_id)
|
| 133 |
+
|
| 134 |
+
logging.info(f"depth {depth}, Processing folder {title}")
|
| 135 |
+
for child in folder["children"]:
|
| 136 |
+
if "folder_id" in child:
|
| 137 |
+
self.get_thread_ids_by_folder_id(
|
| 138 |
+
child["folder_id"], depth + 1, thread_ids
|
| 139 |
+
)
|
| 140 |
+
elif "thread_id" in child:
|
| 141 |
+
thread_ids.append(child["thread_id"])
|
| 142 |
+
|
| 143 |
+
def process_threads(
|
| 144 |
+
self, thread_ids: Sequence[str], include_images: bool, include_messages: bool
|
| 145 |
+
) -> List[Document]:
|
| 146 |
+
"""Process a list of thread into a list of documents."""
|
| 147 |
+
docs = []
|
| 148 |
+
for thread_id in thread_ids:
|
| 149 |
+
doc = self.process_thread(thread_id, include_images, include_messages)
|
| 150 |
+
if doc is not None:
|
| 151 |
+
docs.append(doc)
|
| 152 |
+
return docs
|
| 153 |
+
|
| 154 |
+
def process_thread(
|
| 155 |
+
self, thread_id: str, include_images: bool, include_messages: bool
|
| 156 |
+
) -> Optional[Document]:
|
| 157 |
+
thread = self.quip_client.get_thread(thread_id)
|
| 158 |
+
thread_id = thread["thread"]["id"]
|
| 159 |
+
title = thread["thread"]["title"]
|
| 160 |
+
link = thread["thread"]["link"]
|
| 161 |
+
update_ts = thread["thread"]["updated_usec"]
|
| 162 |
+
sanitized_title = QuipLoader._sanitize_title(title)
|
| 163 |
+
|
| 164 |
+
logger.info(
|
| 165 |
+
f"processing thread {thread_id} title {sanitized_title} "
|
| 166 |
+
f"link {link} update_ts {update_ts}"
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
if "html" in thread:
|
| 170 |
+
# Parse the document
|
| 171 |
+
try:
|
| 172 |
+
tree = self.quip_client.parse_document_html(thread["html"])
|
| 173 |
+
except xml.etree.cElementTree.ParseError as e:
|
| 174 |
+
logger.error(f"Error parsing thread {title} {thread_id}, skipping, {e}")
|
| 175 |
+
return None
|
| 176 |
+
|
| 177 |
+
metadata = {
|
| 178 |
+
"title": sanitized_title,
|
| 179 |
+
"update_ts": update_ts,
|
| 180 |
+
"id": thread_id,
|
| 181 |
+
"source": link,
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
# Download each image and replace with the new URL
|
| 185 |
+
text = ""
|
| 186 |
+
if include_images:
|
| 187 |
+
text = self.process_thread_images(tree)
|
| 188 |
+
|
| 189 |
+
if include_messages:
|
| 190 |
+
text = text + "/n" + self.process_thread_messages(thread_id)
|
| 191 |
+
|
| 192 |
+
return Document(
|
| 193 |
+
page_content=thread["html"] + text,
|
| 194 |
+
metadata=metadata,
|
| 195 |
+
)
|
| 196 |
+
return None
|
| 197 |
+
|
| 198 |
+
def process_thread_images(self, tree: ElementTree) -> str:
|
| 199 |
+
text = ""
|
| 200 |
+
|
| 201 |
+
try:
|
| 202 |
+
from PIL import Image
|
| 203 |
+
from pytesseract import pytesseract
|
| 204 |
+
except ImportError:
|
| 205 |
+
raise ImportError(
|
| 206 |
+
"`Pillow or pytesseract` package not found, "
|
| 207 |
+
"please run "
|
| 208 |
+
"`pip install Pillow` or `pip install pytesseract`"
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
for img in tree.iter("img"):
|
| 212 |
+
src = img.get("src")
|
| 213 |
+
if not src or not src.startswith("/blob"):
|
| 214 |
+
continue
|
| 215 |
+
_, _, thread_id, blob_id = src.split("/")
|
| 216 |
+
blob_response = self.quip_client.get_blob(thread_id, blob_id)
|
| 217 |
+
try:
|
| 218 |
+
image = Image.open(BytesIO(blob_response.read()))
|
| 219 |
+
text = text + "\n" + pytesseract.image_to_string(image)
|
| 220 |
+
except OSError as e:
|
| 221 |
+
logger.error(f"failed to convert image to text, {e}")
|
| 222 |
+
raise e
|
| 223 |
+
return text
|
| 224 |
+
|
| 225 |
+
def process_thread_messages(self, thread_id: str) -> str:
|
| 226 |
+
max_created_usec = None
|
| 227 |
+
messages = []
|
| 228 |
+
while True:
|
| 229 |
+
chunk = self.quip_client.get_messages(
|
| 230 |
+
thread_id, max_created_usec=max_created_usec, count=100
|
| 231 |
+
)
|
| 232 |
+
messages.extend(chunk)
|
| 233 |
+
if chunk:
|
| 234 |
+
max_created_usec = chunk[-1]["created_usec"] - 1
|
| 235 |
+
else:
|
| 236 |
+
break
|
| 237 |
+
messages.reverse()
|
| 238 |
+
|
| 239 |
+
texts = [message["text"] for message in messages]
|
| 240 |
+
|
| 241 |
+
return "\n".join(texts)
|
| 242 |
+
|
| 243 |
+
@staticmethod
|
| 244 |
+
def _sanitize_title(title: str) -> str:
|
| 245 |
+
sanitized_title = re.sub(r"\s", " ", title)
|
| 246 |
+
sanitized_title = re.sub(r"(?u)[^- \w.]", "", sanitized_title)
|
| 247 |
+
if len(sanitized_title) > _MAXIMUM_TITLE_LENGTH:
|
| 248 |
+
sanitized_title = sanitized_title[:_MAXIMUM_TITLE_LENGTH]
|
| 249 |
+
return sanitized_title
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/readthedocs.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import TYPE_CHECKING, Any, Iterator, List, Optional, Sequence, Tuple, Union
|
| 5 |
+
|
| 6 |
+
from langchain_core.documents import Document
|
| 7 |
+
|
| 8 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from bs4 import NavigableString
|
| 12 |
+
from bs4.element import Comment, Tag
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ReadTheDocsLoader(BaseLoader):
|
| 16 |
+
"""Load `ReadTheDocs` documentation directory."""
|
| 17 |
+
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
path: Union[str, Path],
|
| 21 |
+
encoding: Optional[str] = None,
|
| 22 |
+
errors: Optional[str] = None,
|
| 23 |
+
custom_html_tag: Optional[Tuple[str, dict]] = None,
|
| 24 |
+
patterns: Sequence[str] = ("*.htm", "*.html"),
|
| 25 |
+
exclude_links_ratio: float = 1.0,
|
| 26 |
+
**kwargs: Optional[Any],
|
| 27 |
+
):
|
| 28 |
+
"""
|
| 29 |
+
Initialize ReadTheDocsLoader
|
| 30 |
+
|
| 31 |
+
The loader loops over all files under `path` and extracts the actual content of
|
| 32 |
+
the files by retrieving main html tags. Default main html tags include
|
| 33 |
+
`<main id="main-content>`, <`div role="main>`, and `<article role="main">`. You
|
| 34 |
+
can also define your own html tags by passing custom_html_tag, e.g.
|
| 35 |
+
`("div", "class=main")`. The loader iterates html tags with the order of
|
| 36 |
+
custom html tags (if exists) and default html tags. If any of the tags is not
|
| 37 |
+
empty, the loop will break and retrieve the content out of that tag.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
path: The location of pulled readthedocs folder.
|
| 41 |
+
encoding: The encoding with which to open the documents.
|
| 42 |
+
errors: Specify how encoding and decoding errors are to be handled—this
|
| 43 |
+
cannot be used in binary mode.
|
| 44 |
+
custom_html_tag: Optional custom html tag to retrieve the content from
|
| 45 |
+
files.
|
| 46 |
+
patterns: The file patterns to load, passed to `glob.rglob`.
|
| 47 |
+
exclude_links_ratio: The ratio of links:content to exclude pages from.
|
| 48 |
+
This is to reduce the frequency at which index pages make their
|
| 49 |
+
way into retrieved results. Recommended: 0.5
|
| 50 |
+
kwargs: named arguments passed to `bs4.BeautifulSoup`.
|
| 51 |
+
"""
|
| 52 |
+
try:
|
| 53 |
+
from bs4 import BeautifulSoup
|
| 54 |
+
except ImportError:
|
| 55 |
+
raise ImportError(
|
| 56 |
+
"Could not import python packages. "
|
| 57 |
+
"Please install it with `pip install beautifulsoup4`. "
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
_ = BeautifulSoup(
|
| 62 |
+
"<html><body>Parser builder library test.</body></html>",
|
| 63 |
+
"html.parser",
|
| 64 |
+
**kwargs,
|
| 65 |
+
)
|
| 66 |
+
except Exception as e:
|
| 67 |
+
raise ValueError("Parsing kwargs do not appear valid") from e
|
| 68 |
+
|
| 69 |
+
self.file_path = Path(path)
|
| 70 |
+
self.encoding = encoding
|
| 71 |
+
self.errors = errors
|
| 72 |
+
self.custom_html_tag = custom_html_tag
|
| 73 |
+
self.patterns = patterns
|
| 74 |
+
self.bs_kwargs = kwargs
|
| 75 |
+
self.exclude_links_ratio = exclude_links_ratio
|
| 76 |
+
|
| 77 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 78 |
+
"""A lazy loader for Documents."""
|
| 79 |
+
for file_pattern in self.patterns:
|
| 80 |
+
for p in self.file_path.rglob(file_pattern):
|
| 81 |
+
if p.is_dir():
|
| 82 |
+
continue
|
| 83 |
+
with open(p, encoding=self.encoding, errors=self.errors) as f:
|
| 84 |
+
text = self._clean_data(f.read())
|
| 85 |
+
yield Document(page_content=text, metadata={"source": str(p)})
|
| 86 |
+
|
| 87 |
+
def _clean_data(self, data: str) -> str:
|
| 88 |
+
from bs4 import BeautifulSoup
|
| 89 |
+
|
| 90 |
+
soup = BeautifulSoup(data, "html.parser", **self.bs_kwargs)
|
| 91 |
+
|
| 92 |
+
# default tags
|
| 93 |
+
html_tags = [
|
| 94 |
+
("div", {"role": "main"}),
|
| 95 |
+
("main", {"id": "main-content"}),
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
if self.custom_html_tag is not None:
|
| 99 |
+
html_tags.append(self.custom_html_tag)
|
| 100 |
+
|
| 101 |
+
element = None
|
| 102 |
+
|
| 103 |
+
# reversed order. check the custom one first
|
| 104 |
+
for tag, attrs in html_tags[::-1]:
|
| 105 |
+
element = soup.find(tag, attrs) # type: ignore[arg-type]
|
| 106 |
+
# if found, break
|
| 107 |
+
if element is not None:
|
| 108 |
+
break
|
| 109 |
+
|
| 110 |
+
if element is not None and _get_link_ratio(element) <= self.exclude_links_ratio:
|
| 111 |
+
text = _get_clean_text(element)
|
| 112 |
+
else:
|
| 113 |
+
text = ""
|
| 114 |
+
# trim empty lines
|
| 115 |
+
return "\n".join([t for t in text.split("\n") if t])
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _get_clean_text(element: Tag) -> str:
|
| 119 |
+
"""Returns cleaned text with newlines preserved and irrelevant elements removed."""
|
| 120 |
+
elements_to_skip = [
|
| 121 |
+
"script",
|
| 122 |
+
"noscript",
|
| 123 |
+
"canvas",
|
| 124 |
+
"meta",
|
| 125 |
+
"svg",
|
| 126 |
+
"map",
|
| 127 |
+
"area",
|
| 128 |
+
"audio",
|
| 129 |
+
"source",
|
| 130 |
+
"track",
|
| 131 |
+
"video",
|
| 132 |
+
"embed",
|
| 133 |
+
"object",
|
| 134 |
+
"param",
|
| 135 |
+
"picture",
|
| 136 |
+
"iframe",
|
| 137 |
+
"frame",
|
| 138 |
+
"frameset",
|
| 139 |
+
"noframes",
|
| 140 |
+
"applet",
|
| 141 |
+
"form",
|
| 142 |
+
"button",
|
| 143 |
+
"select",
|
| 144 |
+
"base",
|
| 145 |
+
"style",
|
| 146 |
+
"img",
|
| 147 |
+
]
|
| 148 |
+
|
| 149 |
+
newline_elements = [
|
| 150 |
+
"p",
|
| 151 |
+
"div",
|
| 152 |
+
"ul",
|
| 153 |
+
"ol",
|
| 154 |
+
"li",
|
| 155 |
+
"h1",
|
| 156 |
+
"h2",
|
| 157 |
+
"h3",
|
| 158 |
+
"h4",
|
| 159 |
+
"h5",
|
| 160 |
+
"h6",
|
| 161 |
+
"pre",
|
| 162 |
+
"table",
|
| 163 |
+
"tr",
|
| 164 |
+
]
|
| 165 |
+
|
| 166 |
+
text = _process_element(element, elements_to_skip, newline_elements)
|
| 167 |
+
return text.strip()
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _get_link_ratio(section: Tag) -> float:
|
| 171 |
+
links = section.find_all("a")
|
| 172 |
+
total_text = "".join(str(s) for s in section.stripped_strings)
|
| 173 |
+
if len(total_text) == 0:
|
| 174 |
+
return 0
|
| 175 |
+
|
| 176 |
+
link_text = "".join(
|
| 177 |
+
str(string.string.strip())
|
| 178 |
+
for link in links
|
| 179 |
+
for string in link.strings
|
| 180 |
+
if string
|
| 181 |
+
)
|
| 182 |
+
return len(link_text) / len(total_text)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _process_element(
|
| 186 |
+
element: Union[Tag, NavigableString, Comment],
|
| 187 |
+
elements_to_skip: List[str],
|
| 188 |
+
newline_elements: List[str],
|
| 189 |
+
) -> str:
|
| 190 |
+
"""
|
| 191 |
+
Traverse through HTML tree recursively to preserve newline and skip
|
| 192 |
+
unwanted (code/binary) elements
|
| 193 |
+
"""
|
| 194 |
+
from bs4 import NavigableString
|
| 195 |
+
from bs4.element import Comment, Tag
|
| 196 |
+
|
| 197 |
+
tag_name = getattr(element, "name", None)
|
| 198 |
+
if isinstance(element, Comment) or tag_name in elements_to_skip:
|
| 199 |
+
return ""
|
| 200 |
+
elif isinstance(element, NavigableString):
|
| 201 |
+
return element
|
| 202 |
+
elif tag_name == "br":
|
| 203 |
+
return "\n"
|
| 204 |
+
elif tag_name in newline_elements:
|
| 205 |
+
return (
|
| 206 |
+
"".join(
|
| 207 |
+
_process_element(child, elements_to_skip, newline_elements)
|
| 208 |
+
for child in element.children
|
| 209 |
+
if isinstance(child, (Tag, NavigableString, Comment))
|
| 210 |
+
)
|
| 211 |
+
+ "\n"
|
| 212 |
+
)
|
| 213 |
+
else:
|
| 214 |
+
return "".join(
|
| 215 |
+
_process_element(child, elements_to_skip, newline_elements)
|
| 216 |
+
for child in element.children
|
| 217 |
+
if isinstance(child, (Tag, NavigableString, Comment))
|
| 218 |
+
)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/recursive_url_loader.py
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import inspect
|
| 5 |
+
import logging
|
| 6 |
+
import re
|
| 7 |
+
from typing import (
|
| 8 |
+
Callable,
|
| 9 |
+
Iterator,
|
| 10 |
+
List,
|
| 11 |
+
Optional,
|
| 12 |
+
Sequence,
|
| 13 |
+
Set,
|
| 14 |
+
Union,
|
| 15 |
+
cast,
|
| 16 |
+
)
|
| 17 |
+
from urllib.parse import urlparse
|
| 18 |
+
|
| 19 |
+
import aiohttp
|
| 20 |
+
import requests
|
| 21 |
+
from langchain_core.documents import Document
|
| 22 |
+
from langchain_core.utils.html import extract_sub_links
|
| 23 |
+
|
| 24 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _metadata_extractor(
|
| 30 |
+
raw_html: str, url: str, response: Union[requests.Response, aiohttp.ClientResponse]
|
| 31 |
+
) -> dict:
|
| 32 |
+
"""Extract metadata from raw html using BeautifulSoup."""
|
| 33 |
+
content_type = getattr(response, "headers").get("Content-Type", "")
|
| 34 |
+
metadata = {"source": url, "content_type": content_type}
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
from bs4 import BeautifulSoup
|
| 38 |
+
except ImportError:
|
| 39 |
+
logger.warning(
|
| 40 |
+
"The bs4 package is required for default metadata extraction. "
|
| 41 |
+
"Please install it with `pip install -U beautifulsoup4`."
|
| 42 |
+
)
|
| 43 |
+
return metadata
|
| 44 |
+
soup = BeautifulSoup(raw_html, "html.parser")
|
| 45 |
+
if title := soup.find("title"):
|
| 46 |
+
metadata["title"] = title.get_text()
|
| 47 |
+
if description := soup.find("meta", attrs={"name": "description"}):
|
| 48 |
+
metadata["description"] = description.get("content", None)
|
| 49 |
+
if html := soup.find("html"):
|
| 50 |
+
metadata["language"] = html.get("lang", None)
|
| 51 |
+
return metadata
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class RecursiveUrlLoader(BaseLoader):
|
| 55 |
+
"""Recursively load all child links from a root URL.
|
| 56 |
+
|
| 57 |
+
**Security Note**:
|
| 58 |
+
This loader is a crawler that will start crawling
|
| 59 |
+
at a given URL and then expand to crawl child links recursively.
|
| 60 |
+
|
| 61 |
+
Web crawlers should generally NOT be deployed with network access
|
| 62 |
+
to any internal servers.
|
| 63 |
+
|
| 64 |
+
Control access to who can submit crawling requests and what network access
|
| 65 |
+
the crawler has.
|
| 66 |
+
|
| 67 |
+
While crawling, the crawler may encounter malicious URLs that would lead to a
|
| 68 |
+
server-side request forgery (SSRF) attack.
|
| 69 |
+
|
| 70 |
+
To mitigate risks, the crawler by default will only load URLs from the same
|
| 71 |
+
domain as the start URL (controlled via prevent_outside named argument).
|
| 72 |
+
|
| 73 |
+
This will mitigate the risk of SSRF attacks, but will not eliminate it.
|
| 74 |
+
|
| 75 |
+
For example, if crawling a host which hosts several sites:
|
| 76 |
+
|
| 77 |
+
https://some_host/alice_site/
|
| 78 |
+
https://some_host/bob_site/
|
| 79 |
+
|
| 80 |
+
A malicious URL on Alice's site could cause the crawler to make a malicious
|
| 81 |
+
GET request to an endpoint on Bob's site. Both sites are hosted on the
|
| 82 |
+
same host, so such a request would not be prevented by default.
|
| 83 |
+
|
| 84 |
+
See https://python.langchain.com/docs/security/
|
| 85 |
+
|
| 86 |
+
Setup:
|
| 87 |
+
|
| 88 |
+
This class has no required additional dependencies. You can optionally install
|
| 89 |
+
``beautifulsoup4`` for richer default metadata extraction:
|
| 90 |
+
|
| 91 |
+
.. code-block:: bash
|
| 92 |
+
|
| 93 |
+
pip install -U beautifulsoup4
|
| 94 |
+
|
| 95 |
+
Instantiate:
|
| 96 |
+
.. code-block:: python
|
| 97 |
+
|
| 98 |
+
from langchain_community.document_loaders import RecursiveUrlLoader
|
| 99 |
+
|
| 100 |
+
loader = RecursiveUrlLoader(
|
| 101 |
+
"https://docs.python.org/3.9/",
|
| 102 |
+
# max_depth=2,
|
| 103 |
+
# use_async=False,
|
| 104 |
+
# extractor=None,
|
| 105 |
+
# metadata_extractor=None,
|
| 106 |
+
# exclude_dirs=(),
|
| 107 |
+
# timeout=10,
|
| 108 |
+
# check_response_status=True,
|
| 109 |
+
# continue_on_failure=True,
|
| 110 |
+
# prevent_outside=True,
|
| 111 |
+
# base_url=None,
|
| 112 |
+
# ...
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
Lazy load:
|
| 116 |
+
.. code-block:: python
|
| 117 |
+
|
| 118 |
+
docs = []
|
| 119 |
+
docs_lazy = loader.lazy_load()
|
| 120 |
+
|
| 121 |
+
# async variant:
|
| 122 |
+
# docs_lazy = await loader.alazy_load()
|
| 123 |
+
|
| 124 |
+
for doc in docs_lazy:
|
| 125 |
+
docs.append(doc)
|
| 126 |
+
print(docs[0].page_content[:100])
|
| 127 |
+
print(docs[0].metadata)
|
| 128 |
+
|
| 129 |
+
.. code-block:: python
|
| 130 |
+
|
| 131 |
+
<!DOCTYPE html>
|
| 132 |
+
|
| 133 |
+
<html xmlns="http://www.w3.org/1999/xhtml">
|
| 134 |
+
<head>
|
| 135 |
+
<meta charset="utf-8" /><
|
| 136 |
+
{'source': 'https://docs.python.org/3.9/', 'content_type': 'text/html', 'title': '3.9.19 Documentation', 'language': None}
|
| 137 |
+
|
| 138 |
+
Async load:
|
| 139 |
+
.. code-block:: python
|
| 140 |
+
|
| 141 |
+
docs = await loader.aload()
|
| 142 |
+
print(docs[0].page_content[:100])
|
| 143 |
+
print(docs[0].metadata)
|
| 144 |
+
|
| 145 |
+
.. code-block:: python
|
| 146 |
+
|
| 147 |
+
<!DOCTYPE html>
|
| 148 |
+
|
| 149 |
+
<html xmlns="http://www.w3.org/1999/xhtml">
|
| 150 |
+
<head>
|
| 151 |
+
<meta charset="utf-8" /><
|
| 152 |
+
{'source': 'https://docs.python.org/3.9/', 'content_type': 'text/html', 'title': '3.9.19 Documentation', 'language': None}
|
| 153 |
+
|
| 154 |
+
Content parsing / extraction:
|
| 155 |
+
By default the loader sets the raw HTML from each link as the Document page
|
| 156 |
+
content. To parse this HTML into a more human/LLM-friendly format you can pass
|
| 157 |
+
in a custom ``extractor`` method:
|
| 158 |
+
|
| 159 |
+
.. code-block:: python
|
| 160 |
+
|
| 161 |
+
# This example uses `beautifulsoup4` and `lxml`
|
| 162 |
+
import re
|
| 163 |
+
from bs4 import BeautifulSoup
|
| 164 |
+
|
| 165 |
+
def bs4_extractor(html: str) -> str:
|
| 166 |
+
soup = BeautifulSoup(html, "lxml")
|
| 167 |
+
return re.sub(r"\\n\\n+", "\\n\\n", soup.text).strip()
|
| 168 |
+
|
| 169 |
+
loader = RecursiveUrlLoader(
|
| 170 |
+
"https://docs.python.org/3.9/",
|
| 171 |
+
extractor=bs4_extractor,
|
| 172 |
+
)
|
| 173 |
+
print(loader.load()[0].page_content[:200])
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
.. code-block:: python
|
| 177 |
+
|
| 178 |
+
3.9.19 Documentation
|
| 179 |
+
|
| 180 |
+
Download
|
| 181 |
+
Download these documents
|
| 182 |
+
Docs by version
|
| 183 |
+
|
| 184 |
+
Python 3.13 (in development)
|
| 185 |
+
Python 3.12 (stable)
|
| 186 |
+
Python 3.11 (security-fixes)
|
| 187 |
+
Python 3.10 (security-fixes)
|
| 188 |
+
Python 3.9 (securit
|
| 189 |
+
|
| 190 |
+
Metadata extraction:
|
| 191 |
+
Similarly to content extraction, you can specify a metadata extraction function
|
| 192 |
+
to customize how Document metadata is extracted from the HTTP response.
|
| 193 |
+
|
| 194 |
+
.. code-block:: python
|
| 195 |
+
|
| 196 |
+
import aiohttp
|
| 197 |
+
import requests
|
| 198 |
+
from typing import Union
|
| 199 |
+
|
| 200 |
+
def simple_metadata_extractor(
|
| 201 |
+
raw_html: str, url: str, response: Union[requests.Response, aiohttp.ClientResponse]
|
| 202 |
+
) -> dict:
|
| 203 |
+
content_type = getattr(response, "headers").get("Content-Type", "")
|
| 204 |
+
return {"source": url, "content_type": content_type}
|
| 205 |
+
|
| 206 |
+
loader = RecursiveUrlLoader(
|
| 207 |
+
"https://docs.python.org/3.9/",
|
| 208 |
+
metadata_extractor=simple_metadata_extractor,
|
| 209 |
+
)
|
| 210 |
+
loader.load()[0].metadata
|
| 211 |
+
|
| 212 |
+
.. code-block:: python
|
| 213 |
+
|
| 214 |
+
{'source': 'https://docs.python.org/3.9/', 'content_type': 'text/html'}
|
| 215 |
+
|
| 216 |
+
Filtering URLs:
|
| 217 |
+
You may not always want to pull every URL from a website. There are four parameters
|
| 218 |
+
that allow us to control what URLs we pull recursively. First, we can set the
|
| 219 |
+
``prevent_outside`` parameter to prevent URLs outside of the ``base_url`` from
|
| 220 |
+
being pulled. Note that the ``base_url`` does not need to be the same as the URL we
|
| 221 |
+
pass in, as shown below. We can also use ``link_regex`` and ``exclude_dirs`` to be
|
| 222 |
+
more specific with the URLs that we select. In this example, we only pull websites
|
| 223 |
+
from the python docs, which contain the string "index" somewhere and are not
|
| 224 |
+
located in the FAQ section of the website.
|
| 225 |
+
|
| 226 |
+
.. code-block:: python
|
| 227 |
+
|
| 228 |
+
loader = RecursiveUrlLoader(
|
| 229 |
+
"https://docs.python.org/3.9/",
|
| 230 |
+
prevent_outside=True,
|
| 231 |
+
base_url="https://docs.python.org",
|
| 232 |
+
link_regex=r'<a\\s+(?:[^>]*?\\s+)?href="([^"]*(?=index)[^"]*)"',
|
| 233 |
+
exclude_dirs=['https://docs.python.org/3.9/faq']
|
| 234 |
+
)
|
| 235 |
+
docs = loader.load()
|
| 236 |
+
|
| 237 |
+
.. code-block:: python
|
| 238 |
+
|
| 239 |
+
['https://docs.python.org/3.9/',
|
| 240 |
+
'https://docs.python.org/3.9/py-modindex.html',
|
| 241 |
+
'https://docs.python.org/3.9/genindex.html',
|
| 242 |
+
'https://docs.python.org/3.9/tutorial/index.html',
|
| 243 |
+
'https://docs.python.org/3.9/using/index.html',
|
| 244 |
+
'https://docs.python.org/3.9/extending/index.html',
|
| 245 |
+
'https://docs.python.org/3.9/installing/index.html',
|
| 246 |
+
'https://docs.python.org/3.9/library/index.html',
|
| 247 |
+
'https://docs.python.org/3.9/c-api/index.html',
|
| 248 |
+
'https://docs.python.org/3.9/howto/index.html',
|
| 249 |
+
'https://docs.python.org/3.9/distributing/index.html',
|
| 250 |
+
'https://docs.python.org/3.9/reference/index.html',
|
| 251 |
+
'https://docs.python.org/3.9/whatsnew/index.html']
|
| 252 |
+
|
| 253 |
+
""" # noqa: E501
|
| 254 |
+
|
| 255 |
+
def __init__(
|
| 256 |
+
self,
|
| 257 |
+
url: str,
|
| 258 |
+
max_depth: Optional[int] = 2,
|
| 259 |
+
use_async: Optional[bool] = None,
|
| 260 |
+
extractor: Optional[Callable[[str], str]] = None,
|
| 261 |
+
metadata_extractor: Optional[_MetadataExtractorType] = None,
|
| 262 |
+
exclude_dirs: Optional[Sequence[str]] = (),
|
| 263 |
+
timeout: Optional[int] = 10,
|
| 264 |
+
prevent_outside: bool = True,
|
| 265 |
+
link_regex: Union[str, re.Pattern, None] = None,
|
| 266 |
+
headers: Optional[dict] = None,
|
| 267 |
+
check_response_status: bool = False,
|
| 268 |
+
continue_on_failure: bool = True,
|
| 269 |
+
*,
|
| 270 |
+
base_url: Optional[str] = None,
|
| 271 |
+
autoset_encoding: bool = True,
|
| 272 |
+
encoding: Optional[str] = None,
|
| 273 |
+
proxies: Optional[dict] = None,
|
| 274 |
+
ssl: bool = True,
|
| 275 |
+
) -> None:
|
| 276 |
+
"""Initialize with URL to crawl and any subdirectories to exclude.
|
| 277 |
+
|
| 278 |
+
Args:
|
| 279 |
+
url: The URL to crawl.
|
| 280 |
+
max_depth: The max depth of the recursive loading.
|
| 281 |
+
use_async: Whether to use asynchronous loading.
|
| 282 |
+
If ``True``, ``lazy_load()`` will not be lazy, but it will still work in
|
| 283 |
+
the expected way, just not lazy.
|
| 284 |
+
extractor: A function to extract document contents from raw HTML.
|
| 285 |
+
When extract function returns an empty string, the document is
|
| 286 |
+
ignored. Default returns the raw HTML.
|
| 287 |
+
metadata_extractor: A function to extract metadata from args: raw HTML, the
|
| 288 |
+
source url, and the requests.Response/aiohttp.ClientResponse object
|
| 289 |
+
(args in that order).
|
| 290 |
+
|
| 291 |
+
Default extractor will attempt to use BeautifulSoup4 to extract the
|
| 292 |
+
title, description and language of the page.
|
| 293 |
+
|
| 294 |
+
..code-block:: python
|
| 295 |
+
|
| 296 |
+
import requests
|
| 297 |
+
import aiohttp
|
| 298 |
+
|
| 299 |
+
def simple_metadata_extractor(
|
| 300 |
+
raw_html: str, url: str, response: Union[requests.Response, aiohttp.ClientResponse]
|
| 301 |
+
) -> dict:
|
| 302 |
+
content_type = getattr(response, "headers").get("Content-Type", "")
|
| 303 |
+
return {"source": url, "content_type": content_type}
|
| 304 |
+
|
| 305 |
+
exclude_dirs: A list of subdirectories to exclude.
|
| 306 |
+
timeout: The timeout for the requests, in the unit of seconds. If ``None``
|
| 307 |
+
then connection will not timeout.
|
| 308 |
+
prevent_outside: If ``True``, prevent loading from urls which are not children
|
| 309 |
+
of the root url.
|
| 310 |
+
link_regex: Regex for extracting sub-links from the raw html of a web page.
|
| 311 |
+
headers: Default request headers to use for all requests.
|
| 312 |
+
check_response_status: If ``True``, check HTTP response status and skip
|
| 313 |
+
URLs with error responses (``400-599``).
|
| 314 |
+
continue_on_failure: If ``True``, continue if getting or parsing a link raises
|
| 315 |
+
an exception. Otherwise, raise the exception.
|
| 316 |
+
base_url: The base url to check for outside links against.
|
| 317 |
+
autoset_encoding: Whether to automatically set the encoding of the response.
|
| 318 |
+
If ``True``, the encoding of the response will be set to the apparent
|
| 319 |
+
encoding, unless the ``encoding`` argument has already been explicitly set.
|
| 320 |
+
encoding: The encoding of the response. If manually set, the encoding will be
|
| 321 |
+
set to given value, regardless of the ``autoset_encoding`` argument.
|
| 322 |
+
proxies: A dictionary mapping protocol names to the proxy URLs to be used for requests.
|
| 323 |
+
This allows the crawler to route its requests through specified proxy servers.
|
| 324 |
+
If ``None``, no proxies will be used and requests will go directly to the target URL.
|
| 325 |
+
|
| 326 |
+
Example usage:
|
| 327 |
+
|
| 328 |
+
..code-block:: python
|
| 329 |
+
|
| 330 |
+
proxies = {
|
| 331 |
+
"http": "http://10.10.1.10:3128",
|
| 332 |
+
"https": "https://10.10.1.10:1080",
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
ssl: Whether to verify SSL certificates during requests.
|
| 336 |
+
By default, SSL certificate verification is enabled (``ssl=True``),
|
| 337 |
+
ensuring secure HTTPS connections. Setting this to ``False`` disables SSL
|
| 338 |
+
certificate verification, which can be useful when crawling internal
|
| 339 |
+
services, development environments, or sites with misconfigured or
|
| 340 |
+
self-signed certificates.
|
| 341 |
+
|
| 342 |
+
**Use with caution:** Disabling SSL verification exposes your crawler to
|
| 343 |
+
man-in-the-middle (MitM) attacks, data tampering, and potential
|
| 344 |
+
interception of sensitive information. This significantly compromises
|
| 345 |
+
the security and integrity of the communication. It should never be
|
| 346 |
+
used in production or when handling sensitive data.
|
| 347 |
+
""" # noqa: E501
|
| 348 |
+
|
| 349 |
+
self.url = url
|
| 350 |
+
self.max_depth = max_depth if max_depth is not None else 2
|
| 351 |
+
self.use_async = use_async if use_async is not None else False
|
| 352 |
+
self.extractor = extractor if extractor is not None else lambda x: x
|
| 353 |
+
self.ssl = ssl
|
| 354 |
+
metadata_extractor = (
|
| 355 |
+
metadata_extractor
|
| 356 |
+
if metadata_extractor is not None
|
| 357 |
+
else _metadata_extractor
|
| 358 |
+
)
|
| 359 |
+
self.autoset_encoding = autoset_encoding
|
| 360 |
+
self.encoding = encoding
|
| 361 |
+
self.metadata_extractor = _wrap_metadata_extractor(metadata_extractor)
|
| 362 |
+
self.exclude_dirs = exclude_dirs if exclude_dirs is not None else ()
|
| 363 |
+
|
| 364 |
+
if any(url.startswith(exclude_dir) for exclude_dir in self.exclude_dirs):
|
| 365 |
+
raise ValueError(
|
| 366 |
+
f"Base url is included in exclude_dirs. Received base_url: {url} and "
|
| 367 |
+
f"exclude_dirs: {self.exclude_dirs}"
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
self.timeout = timeout
|
| 371 |
+
self.prevent_outside = prevent_outside if prevent_outside is not None else True
|
| 372 |
+
self.link_regex = link_regex
|
| 373 |
+
self.headers = headers
|
| 374 |
+
self.check_response_status = check_response_status
|
| 375 |
+
self.continue_on_failure = continue_on_failure
|
| 376 |
+
self.base_url = base_url if base_url is not None else self._parse_base_url(url)
|
| 377 |
+
self.proxies = proxies
|
| 378 |
+
|
| 379 |
+
def _parse_base_url(self, url: str) -> str:
|
| 380 |
+
"""Parse the base URL from the given URL.
|
| 381 |
+
|
| 382 |
+
Args:
|
| 383 |
+
url: The URL to parse.
|
| 384 |
+
|
| 385 |
+
Returns:
|
| 386 |
+
The base URL with scheme and netloc only, ending with a slash.
|
| 387 |
+
"""
|
| 388 |
+
if not url.startswith(("http://", "https://")):
|
| 389 |
+
url = "https://" + url
|
| 390 |
+
parsed_url = urlparse(url)
|
| 391 |
+
return f"{parsed_url.scheme}://{parsed_url.netloc}/"
|
| 392 |
+
|
| 393 |
+
def _get_child_links_recursive(
|
| 394 |
+
self, url: str, visited: Set[str], *, depth: int = 0
|
| 395 |
+
) -> Iterator[Document]:
|
| 396 |
+
"""Recursively get all child links starting with the path of the input URL.
|
| 397 |
+
|
| 398 |
+
Args:
|
| 399 |
+
url: The URL to crawl.
|
| 400 |
+
visited: A set of visited URLs.
|
| 401 |
+
depth: Current depth of recursion. Stop when depth >= max_depth.
|
| 402 |
+
"""
|
| 403 |
+
|
| 404 |
+
if depth >= self.max_depth:
|
| 405 |
+
return
|
| 406 |
+
|
| 407 |
+
# Get all links that can be accessed from the current URL
|
| 408 |
+
visited.add(url)
|
| 409 |
+
try:
|
| 410 |
+
response = requests.get(
|
| 411 |
+
url, timeout=self.timeout, headers=self.headers, proxies=self.proxies
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
if self.encoding is not None:
|
| 415 |
+
response.encoding = self.encoding
|
| 416 |
+
elif self.autoset_encoding:
|
| 417 |
+
response.encoding = response.apparent_encoding
|
| 418 |
+
|
| 419 |
+
if self.check_response_status and 400 <= response.status_code <= 599:
|
| 420 |
+
raise ValueError(f"Received HTTP status {response.status_code}")
|
| 421 |
+
except Exception as e:
|
| 422 |
+
if self.continue_on_failure:
|
| 423 |
+
logger.warning(
|
| 424 |
+
f"Unable to load from {url}. Received error {e} of type "
|
| 425 |
+
f"{e.__class__.__name__}"
|
| 426 |
+
)
|
| 427 |
+
return
|
| 428 |
+
else:
|
| 429 |
+
raise e
|
| 430 |
+
content = self.extractor(response.text)
|
| 431 |
+
if content:
|
| 432 |
+
yield Document(
|
| 433 |
+
page_content=content,
|
| 434 |
+
metadata=self.metadata_extractor(response.text, url, response),
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
# Store the visited links and recursively visit the children
|
| 438 |
+
sub_links = extract_sub_links(
|
| 439 |
+
response.text,
|
| 440 |
+
url,
|
| 441 |
+
base_url=self.base_url,
|
| 442 |
+
pattern=self.link_regex,
|
| 443 |
+
prevent_outside=self.prevent_outside,
|
| 444 |
+
exclude_prefixes=self.exclude_dirs,
|
| 445 |
+
continue_on_failure=self.continue_on_failure,
|
| 446 |
+
)
|
| 447 |
+
for link in sub_links:
|
| 448 |
+
# Check all unvisited links
|
| 449 |
+
if link not in visited:
|
| 450 |
+
yield from self._get_child_links_recursive(
|
| 451 |
+
link, visited, depth=depth + 1
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
async def _async_get_child_links_recursive(
|
| 455 |
+
self,
|
| 456 |
+
url: str,
|
| 457 |
+
visited: Set[str],
|
| 458 |
+
*,
|
| 459 |
+
session: Optional[aiohttp.ClientSession] = None,
|
| 460 |
+
depth: int = 0,
|
| 461 |
+
) -> List[Document]:
|
| 462 |
+
"""Recursively get all child links starting with the path of the input URL.
|
| 463 |
+
|
| 464 |
+
Args:
|
| 465 |
+
url: The URL to crawl.
|
| 466 |
+
visited: A set of visited URLs.
|
| 467 |
+
depth: To reach the current url, how many pages have been visited.
|
| 468 |
+
"""
|
| 469 |
+
if not self.use_async:
|
| 470 |
+
raise ValueError(
|
| 471 |
+
"Async functions forbidden when not initialized with `use_async`"
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
if depth >= self.max_depth:
|
| 475 |
+
return []
|
| 476 |
+
|
| 477 |
+
# Disable SSL verification because websites may have invalid SSL certificates,
|
| 478 |
+
# but won't cause any security issues for us.
|
| 479 |
+
close_session = session is None
|
| 480 |
+
session = (
|
| 481 |
+
session
|
| 482 |
+
if session is not None
|
| 483 |
+
else aiohttp.ClientSession(
|
| 484 |
+
connector=aiohttp.TCPConnector(ssl=self.ssl),
|
| 485 |
+
timeout=aiohttp.ClientTimeout(total=self.timeout),
|
| 486 |
+
headers=self.headers,
|
| 487 |
+
)
|
| 488 |
+
)
|
| 489 |
+
visited.add(url)
|
| 490 |
+
try:
|
| 491 |
+
async with session.get(url) as response:
|
| 492 |
+
text = await response.text()
|
| 493 |
+
if self.check_response_status and 400 <= response.status <= 599:
|
| 494 |
+
raise ValueError(f"Received HTTP status {response.status}")
|
| 495 |
+
except (aiohttp.client_exceptions.InvalidURL, Exception) as e:
|
| 496 |
+
if close_session:
|
| 497 |
+
await session.close()
|
| 498 |
+
if self.continue_on_failure:
|
| 499 |
+
logger.warning(
|
| 500 |
+
f"Unable to load {url}. Received error {e} of type "
|
| 501 |
+
f"{e.__class__.__name__}"
|
| 502 |
+
)
|
| 503 |
+
return []
|
| 504 |
+
else:
|
| 505 |
+
raise e
|
| 506 |
+
results = []
|
| 507 |
+
content = self.extractor(text)
|
| 508 |
+
if content:
|
| 509 |
+
results.append(
|
| 510 |
+
Document(
|
| 511 |
+
page_content=content,
|
| 512 |
+
metadata=self.metadata_extractor(text, url, response),
|
| 513 |
+
)
|
| 514 |
+
)
|
| 515 |
+
if depth < self.max_depth - 1:
|
| 516 |
+
sub_links = extract_sub_links(
|
| 517 |
+
text,
|
| 518 |
+
url,
|
| 519 |
+
base_url=self.base_url,
|
| 520 |
+
pattern=self.link_regex,
|
| 521 |
+
prevent_outside=self.prevent_outside,
|
| 522 |
+
exclude_prefixes=self.exclude_dirs,
|
| 523 |
+
continue_on_failure=self.continue_on_failure,
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
# Recursively call the function to get the children of the children
|
| 527 |
+
sub_tasks = []
|
| 528 |
+
to_visit = set(sub_links).difference(visited)
|
| 529 |
+
for link in to_visit:
|
| 530 |
+
sub_tasks.append(
|
| 531 |
+
self._async_get_child_links_recursive(
|
| 532 |
+
link, visited, session=session, depth=depth + 1
|
| 533 |
+
)
|
| 534 |
+
)
|
| 535 |
+
next_results = await asyncio.gather(*sub_tasks)
|
| 536 |
+
for sub_result in next_results:
|
| 537 |
+
if isinstance(sub_result, Exception) or sub_result is None:
|
| 538 |
+
# We don't want to stop the whole process, so just ignore it
|
| 539 |
+
# Not standard html format or invalid url or 404 may cause this.
|
| 540 |
+
continue
|
| 541 |
+
# locking not fully working, temporary hack to ensure deduplication
|
| 542 |
+
results += [r for r in sub_result if r not in results]
|
| 543 |
+
if close_session:
|
| 544 |
+
await session.close()
|
| 545 |
+
return results
|
| 546 |
+
|
| 547 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 548 |
+
"""Lazy load web pages.
|
| 549 |
+
When use_async is True, this function will not be lazy,
|
| 550 |
+
but it will still work in the expected way, just not lazy."""
|
| 551 |
+
visited: Set[str] = set()
|
| 552 |
+
if self.use_async:
|
| 553 |
+
results = asyncio.run(
|
| 554 |
+
self._async_get_child_links_recursive(self.url, visited)
|
| 555 |
+
)
|
| 556 |
+
return iter(results or [])
|
| 557 |
+
else:
|
| 558 |
+
return self._get_child_links_recursive(self.url, visited)
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
_MetadataExtractorType1 = Callable[[str, str], dict]
|
| 562 |
+
_MetadataExtractorType2 = Callable[
|
| 563 |
+
[str, str, Union[requests.Response, aiohttp.ClientResponse]], dict
|
| 564 |
+
]
|
| 565 |
+
_MetadataExtractorType = Union[_MetadataExtractorType1, _MetadataExtractorType2]
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def _wrap_metadata_extractor(
|
| 569 |
+
metadata_extractor: _MetadataExtractorType,
|
| 570 |
+
) -> _MetadataExtractorType2:
|
| 571 |
+
if len(inspect.signature(metadata_extractor).parameters) == 3:
|
| 572 |
+
return cast(_MetadataExtractorType2, metadata_extractor)
|
| 573 |
+
else:
|
| 574 |
+
|
| 575 |
+
def _metadata_extractor_wrapper(
|
| 576 |
+
raw_html: str,
|
| 577 |
+
url: str,
|
| 578 |
+
response: Union[requests.Response, aiohttp.ClientResponse],
|
| 579 |
+
) -> dict:
|
| 580 |
+
return cast(_MetadataExtractorType1, metadata_extractor)(raw_html, url)
|
| 581 |
+
|
| 582 |
+
return _metadata_extractor_wrapper
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/reddit.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Iterable, List, Optional, Sequence
|
| 4 |
+
|
| 5 |
+
from langchain_core.documents import Document
|
| 6 |
+
|
| 7 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
import praw
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _dependable_praw_import() -> praw:
|
| 14 |
+
try:
|
| 15 |
+
import praw
|
| 16 |
+
except ImportError:
|
| 17 |
+
raise ImportError(
|
| 18 |
+
"praw package not found, please install it with `pip install praw`"
|
| 19 |
+
)
|
| 20 |
+
return praw
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class RedditPostsLoader(BaseLoader):
|
| 24 |
+
"""Load `Reddit` posts.
|
| 25 |
+
|
| 26 |
+
Read posts on a subreddit.
|
| 27 |
+
First, you need to go to
|
| 28 |
+
https://www.reddit.com/prefs/apps/
|
| 29 |
+
and create your application
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(
|
| 33 |
+
self,
|
| 34 |
+
client_id: str,
|
| 35 |
+
client_secret: str,
|
| 36 |
+
user_agent: str,
|
| 37 |
+
search_queries: Sequence[str],
|
| 38 |
+
mode: str,
|
| 39 |
+
categories: Sequence[str] = ["new"],
|
| 40 |
+
number_posts: Optional[int] = 10,
|
| 41 |
+
):
|
| 42 |
+
"""
|
| 43 |
+
Initialize with client_id, client_secret, user_agent, search_queries, mode,
|
| 44 |
+
categories, number_posts.
|
| 45 |
+
Example: https://www.reddit.com/r/learnpython/
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
client_id: Reddit client id.
|
| 49 |
+
client_secret: Reddit client secret.
|
| 50 |
+
user_agent: Reddit user agent.
|
| 51 |
+
search_queries: The search queries.
|
| 52 |
+
mode: The mode.
|
| 53 |
+
categories: The categories. Default: ["new"]
|
| 54 |
+
number_posts: The number of posts. Default: 10
|
| 55 |
+
"""
|
| 56 |
+
self.client_id = client_id
|
| 57 |
+
self.client_secret = client_secret
|
| 58 |
+
self.user_agent = user_agent
|
| 59 |
+
self.search_queries = search_queries
|
| 60 |
+
self.mode = mode
|
| 61 |
+
self.categories = categories
|
| 62 |
+
self.number_posts = number_posts
|
| 63 |
+
|
| 64 |
+
def load(self) -> List[Document]:
|
| 65 |
+
"""Load reddits."""
|
| 66 |
+
praw = _dependable_praw_import()
|
| 67 |
+
|
| 68 |
+
reddit = praw.Reddit(
|
| 69 |
+
client_id=self.client_id,
|
| 70 |
+
client_secret=self.client_secret,
|
| 71 |
+
user_agent=self.user_agent,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
results: List[Document] = []
|
| 75 |
+
|
| 76 |
+
if self.mode == "subreddit":
|
| 77 |
+
for search_query in self.search_queries:
|
| 78 |
+
for category in self.categories:
|
| 79 |
+
docs = self._subreddit_posts_loader(
|
| 80 |
+
search_query=search_query, category=category, reddit=reddit
|
| 81 |
+
)
|
| 82 |
+
results.extend(docs)
|
| 83 |
+
|
| 84 |
+
elif self.mode == "username":
|
| 85 |
+
for search_query in self.search_queries:
|
| 86 |
+
for category in self.categories:
|
| 87 |
+
docs = self._user_posts_loader(
|
| 88 |
+
search_query=search_query, category=category, reddit=reddit
|
| 89 |
+
)
|
| 90 |
+
results.extend(docs)
|
| 91 |
+
|
| 92 |
+
else:
|
| 93 |
+
raise ValueError(
|
| 94 |
+
"mode not correct, please enter 'username' or 'subreddit' as mode"
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
return results
|
| 98 |
+
|
| 99 |
+
def _subreddit_posts_loader(
|
| 100 |
+
self, search_query: str, category: str, reddit: praw.reddit.Reddit
|
| 101 |
+
) -> Iterable[Document]:
|
| 102 |
+
subreddit = reddit.subreddit(search_query)
|
| 103 |
+
method = getattr(subreddit, category)
|
| 104 |
+
cat_posts = method(limit=self.number_posts)
|
| 105 |
+
|
| 106 |
+
"""Format reddit posts into a string."""
|
| 107 |
+
for post in cat_posts:
|
| 108 |
+
metadata = {
|
| 109 |
+
"post_subreddit": post.subreddit_name_prefixed,
|
| 110 |
+
"post_category": category,
|
| 111 |
+
"post_title": post.title,
|
| 112 |
+
"post_score": post.score,
|
| 113 |
+
"post_id": post.id,
|
| 114 |
+
"post_url": post.url,
|
| 115 |
+
"post_author": post.author,
|
| 116 |
+
}
|
| 117 |
+
yield Document(
|
| 118 |
+
page_content=post.selftext,
|
| 119 |
+
metadata=metadata,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
def _user_posts_loader(
|
| 123 |
+
self, search_query: str, category: str, reddit: praw.reddit.Reddit
|
| 124 |
+
) -> Iterable[Document]:
|
| 125 |
+
user = reddit.redditor(search_query)
|
| 126 |
+
method = getattr(user.submissions, category)
|
| 127 |
+
cat_posts = method(limit=self.number_posts)
|
| 128 |
+
|
| 129 |
+
"""Format reddit posts into a string."""
|
| 130 |
+
for post in cat_posts:
|
| 131 |
+
metadata = {
|
| 132 |
+
"post_subreddit": post.subreddit_name_prefixed,
|
| 133 |
+
"post_category": category,
|
| 134 |
+
"post_title": post.title,
|
| 135 |
+
"post_score": post.score,
|
| 136 |
+
"post_id": post.id,
|
| 137 |
+
"post_url": post.url,
|
| 138 |
+
"post_author": post.author,
|
| 139 |
+
}
|
| 140 |
+
yield Document(
|
| 141 |
+
page_content=post.selftext,
|
| 142 |
+
metadata=metadata,
|
| 143 |
+
)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/roam.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from typing import List, Union
|
| 3 |
+
|
| 4 |
+
from langchain_core.documents import Document
|
| 5 |
+
|
| 6 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class RoamLoader(BaseLoader):
|
| 10 |
+
"""Load `Roam` files from a directory."""
|
| 11 |
+
|
| 12 |
+
def __init__(self, path: Union[str, Path]):
|
| 13 |
+
"""Initialize with a path."""
|
| 14 |
+
self.file_path = path
|
| 15 |
+
|
| 16 |
+
def load(self) -> List[Document]:
|
| 17 |
+
"""Load documents."""
|
| 18 |
+
ps = list(Path(self.file_path).glob("**/*.md"))
|
| 19 |
+
docs = []
|
| 20 |
+
for p in ps:
|
| 21 |
+
with open(p) as f:
|
| 22 |
+
text = f.read()
|
| 23 |
+
metadata = {"source": str(p)}
|
| 24 |
+
docs.append(Document(page_content=text, metadata=metadata))
|
| 25 |
+
return docs
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rocksetdb.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Callable, Iterator, List, Optional, Tuple
|
| 2 |
+
|
| 3 |
+
from langchain_core.documents import Document
|
| 4 |
+
|
| 5 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def default_joiner(docs: List[Tuple[str, Any]]) -> str:
|
| 9 |
+
"""Default joiner for content columns."""
|
| 10 |
+
return "\n".join([doc[1] for doc in docs])
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ColumnNotFoundError(Exception):
|
| 14 |
+
"""Column not found error."""
|
| 15 |
+
|
| 16 |
+
def __init__(self, missing_key: str, query: str):
|
| 17 |
+
super().__init__(f'Column "{missing_key}" not selected in query:\n{query}')
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class RocksetLoader(BaseLoader):
|
| 21 |
+
"""Load from a `Rockset` database.
|
| 22 |
+
|
| 23 |
+
To use, you should have the `rockset` python package installed.
|
| 24 |
+
|
| 25 |
+
Example:
|
| 26 |
+
.. code-block:: python
|
| 27 |
+
|
| 28 |
+
# This code will load 3 records from the "langchain_demo"
|
| 29 |
+
# collection as Documents, with the `text` column used as
|
| 30 |
+
# the content
|
| 31 |
+
|
| 32 |
+
from langchain_community.document_loaders import RocksetLoader
|
| 33 |
+
from rockset import RocksetClient, Regions, models
|
| 34 |
+
|
| 35 |
+
loader = RocksetLoader(
|
| 36 |
+
RocksetClient(Regions.usw2a1, "<api key>"),
|
| 37 |
+
models.QueryRequestSql(
|
| 38 |
+
query="select * from langchain_demo limit 3"
|
| 39 |
+
),
|
| 40 |
+
["text"]
|
| 41 |
+
)
|
| 42 |
+
)
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
client: Any,
|
| 48 |
+
query: Any,
|
| 49 |
+
content_keys: List[str],
|
| 50 |
+
metadata_keys: Optional[List[str]] = None,
|
| 51 |
+
content_columns_joiner: Callable[[List[Tuple[str, Any]]], str] = default_joiner,
|
| 52 |
+
):
|
| 53 |
+
"""Initialize with Rockset client.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
client: Rockset client object.
|
| 57 |
+
query: Rockset query object.
|
| 58 |
+
content_keys: The collection columns to be written into the `page_content`
|
| 59 |
+
of the Documents.
|
| 60 |
+
metadata_keys: The collection columns to be written into the `metadata` of
|
| 61 |
+
the Documents. By default, this is all the keys in the document.
|
| 62 |
+
content_columns_joiner: Method that joins content_keys and its values into a
|
| 63 |
+
string. It's method that takes in a List[Tuple[str, Any]]],
|
| 64 |
+
representing a list of tuples of (column name, column value).
|
| 65 |
+
By default, this is a method that joins each column value with a new
|
| 66 |
+
line. This method is only relevant if there are multiple content_keys.
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
from rockset import QueryPaginator, RocksetClient
|
| 70 |
+
from rockset.models import QueryRequestSql
|
| 71 |
+
except ImportError:
|
| 72 |
+
raise ImportError(
|
| 73 |
+
"Could not import rockset client python package. "
|
| 74 |
+
"Please install it with `pip install rockset`."
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
if not isinstance(client, RocksetClient):
|
| 78 |
+
raise ValueError(
|
| 79 |
+
f"client should be an instance of rockset.RocksetClient, "
|
| 80 |
+
f"got {type(client)}"
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
if not isinstance(query, QueryRequestSql):
|
| 84 |
+
raise ValueError(
|
| 85 |
+
f"query should be an instance of rockset.model.QueryRequestSql, "
|
| 86 |
+
f"got {type(query)}"
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
self.client = client
|
| 90 |
+
self.query = query
|
| 91 |
+
self.content_keys = content_keys
|
| 92 |
+
self.content_columns_joiner = content_columns_joiner
|
| 93 |
+
self.metadata_keys = metadata_keys
|
| 94 |
+
self.paginator = QueryPaginator
|
| 95 |
+
self.request_model = QueryRequestSql
|
| 96 |
+
|
| 97 |
+
try:
|
| 98 |
+
self.client.set_application("langchain")
|
| 99 |
+
except AttributeError:
|
| 100 |
+
# ignore
|
| 101 |
+
pass
|
| 102 |
+
|
| 103 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 104 |
+
query_results = self.client.Queries.query(
|
| 105 |
+
sql=self.query
|
| 106 |
+
).results # execute the SQL query
|
| 107 |
+
for doc in query_results: # for each doc in the response
|
| 108 |
+
try:
|
| 109 |
+
yield Document(
|
| 110 |
+
page_content=self.content_columns_joiner(
|
| 111 |
+
[(col, doc[col]) for col in self.content_keys]
|
| 112 |
+
),
|
| 113 |
+
metadata={col: doc[col] for col in self.metadata_keys}
|
| 114 |
+
if self.metadata_keys is not None
|
| 115 |
+
else doc,
|
| 116 |
+
) # try to yield the Document
|
| 117 |
+
except (
|
| 118 |
+
KeyError
|
| 119 |
+
) as e: # either content_columns or metadata_columns is invalid
|
| 120 |
+
raise ColumnNotFoundError(
|
| 121 |
+
e.args[0], self.query
|
| 122 |
+
) # raise that the column isn't in the db schema
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rspace.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import Any, Dict, Iterator, List, Optional, Union
|
| 3 |
+
|
| 4 |
+
from langchain_core.documents import Document
|
| 5 |
+
from langchain_core.utils import get_from_dict_or_env
|
| 6 |
+
|
| 7 |
+
from langchain_community.document_loaders import PyPDFLoader
|
| 8 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class RSpaceLoader(BaseLoader):
|
| 12 |
+
"""Load content from RSpace notebooks, folders, documents or PDF Gallery files.
|
| 13 |
+
|
| 14 |
+
Map RSpace document <-> Langchain Document in 1-1. PDFs are imported using PyPDF.
|
| 15 |
+
|
| 16 |
+
Requirements are rspace_client (`pip install rspace_client`) and PyPDF if importing
|
| 17 |
+
PDF docs (`pip install pypdf`).
|
| 18 |
+
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
def __init__(
|
| 22 |
+
self, global_id: str, api_key: Optional[str] = None, url: Optional[str] = None
|
| 23 |
+
):
|
| 24 |
+
"""api_key: RSpace API key - can also be supplied as environment variable
|
| 25 |
+
'RSPACE_API_KEY'
|
| 26 |
+
url: str
|
| 27 |
+
The URL of your RSpace instance - can also be supplied as environment
|
| 28 |
+
variable 'RSPACE_URL'
|
| 29 |
+
global_id: str
|
| 30 |
+
The global ID of the resource to load,
|
| 31 |
+
e.g. 'SD12344' (a single document); 'GL12345'(A PDF file in the gallery);
|
| 32 |
+
'NB4567' (a notebook); 'FL12244' (a folder)
|
| 33 |
+
"""
|
| 34 |
+
args: Dict[str, Optional[str]] = {
|
| 35 |
+
"api_key": api_key,
|
| 36 |
+
"url": url,
|
| 37 |
+
"global_id": global_id,
|
| 38 |
+
}
|
| 39 |
+
verified_args: Dict[str, str] = RSpaceLoader.validate_environment(args)
|
| 40 |
+
self.api_key = verified_args["api_key"]
|
| 41 |
+
self.url = verified_args["url"]
|
| 42 |
+
self.global_id: str = verified_args["global_id"]
|
| 43 |
+
|
| 44 |
+
@classmethod
|
| 45 |
+
def validate_environment(cls, values: Dict) -> Dict:
|
| 46 |
+
"""Validate that API key and URL exist in environment."""
|
| 47 |
+
values["api_key"] = get_from_dict_or_env(values, "api_key", "RSPACE_API_KEY")
|
| 48 |
+
values["url"] = get_from_dict_or_env(values, "url", "RSPACE_URL")
|
| 49 |
+
if "global_id" not in values or values["global_id"] is None:
|
| 50 |
+
raise ValueError(
|
| 51 |
+
"No value supplied for global_id. Please supply an RSpace global ID"
|
| 52 |
+
)
|
| 53 |
+
return values
|
| 54 |
+
|
| 55 |
+
def _create_rspace_client(self) -> Any:
|
| 56 |
+
"""Create a RSpace client."""
|
| 57 |
+
try:
|
| 58 |
+
from rspace_client.eln import eln, field_content
|
| 59 |
+
|
| 60 |
+
except ImportError:
|
| 61 |
+
raise ImportError("You must run `pip install rspace_client`")
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
eln = eln.ELNClient(self.url, self.api_key)
|
| 65 |
+
eln.get_status()
|
| 66 |
+
|
| 67 |
+
except Exception:
|
| 68 |
+
raise Exception(
|
| 69 |
+
f"Unable to initialize client - is url {self.url} or api key correct?"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
return eln, field_content.FieldContent
|
| 73 |
+
|
| 74 |
+
def _get_doc(self, cli: Any, field_content: Any, d_id: Union[str, int]) -> Document:
|
| 75 |
+
content = ""
|
| 76 |
+
doc = cli.get_document(d_id)
|
| 77 |
+
content += f"<h2>{doc['name']}<h2/>"
|
| 78 |
+
for f in doc["fields"]:
|
| 79 |
+
content += f"{f['name']}\n"
|
| 80 |
+
fc = field_content(f["content"])
|
| 81 |
+
content += fc.get_text()
|
| 82 |
+
content += "\n"
|
| 83 |
+
return Document(
|
| 84 |
+
metadata={"source": f"rspace: {doc['name']}-{doc['globalId']}"},
|
| 85 |
+
page_content=content,
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
def _load_structured_doc(self) -> Iterator[Document]:
|
| 89 |
+
cli, field_content = self._create_rspace_client()
|
| 90 |
+
yield self._get_doc(cli, field_content, self.global_id)
|
| 91 |
+
|
| 92 |
+
def _load_folder_tree(self) -> Iterator[Document]:
|
| 93 |
+
cli, field_content = self._create_rspace_client()
|
| 94 |
+
if self.global_id:
|
| 95 |
+
docs_in_folder = cli.list_folder_tree(
|
| 96 |
+
folder_id=self.global_id[2:], typesToInclude=["document"]
|
| 97 |
+
)
|
| 98 |
+
doc_ids: List[int] = [d["id"] for d in docs_in_folder["records"]]
|
| 99 |
+
for doc_id in doc_ids:
|
| 100 |
+
yield self._get_doc(cli, field_content, doc_id)
|
| 101 |
+
|
| 102 |
+
def _load_pdf(self) -> Iterator[Document]:
|
| 103 |
+
cli, field_content = self._create_rspace_client()
|
| 104 |
+
file_info = cli.get_file_info(self.global_id)
|
| 105 |
+
_, ext = os.path.splitext(file_info["name"])
|
| 106 |
+
if ext.lower() == ".pdf":
|
| 107 |
+
outfile = f"{self.global_id}.pdf"
|
| 108 |
+
cli.download_file(self.global_id, outfile)
|
| 109 |
+
pdf_loader = PyPDFLoader(outfile)
|
| 110 |
+
for pdf in pdf_loader.lazy_load():
|
| 111 |
+
pdf.metadata["rspace_src"] = self.global_id
|
| 112 |
+
yield pdf
|
| 113 |
+
|
| 114 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 115 |
+
if self.global_id and "GL" in self.global_id:
|
| 116 |
+
for d in self._load_pdf():
|
| 117 |
+
yield d
|
| 118 |
+
elif self.global_id and "SD" in self.global_id:
|
| 119 |
+
for d in self._load_structured_doc():
|
| 120 |
+
yield d
|
| 121 |
+
elif self.global_id and self.global_id[0:2] in ["FL", "NB"]:
|
| 122 |
+
for d in self._load_folder_tree():
|
| 123 |
+
yield d
|
| 124 |
+
else:
|
| 125 |
+
raise ValueError("Unknown global ID type")
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rss.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from typing import Any, Iterator, List, Optional, Sequence
|
| 3 |
+
|
| 4 |
+
from langchain_core.documents import Document
|
| 5 |
+
|
| 6 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 7 |
+
from langchain_community.document_loaders.news import NewsURLLoader
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class RSSFeedLoader(BaseLoader):
|
| 13 |
+
"""Load news articles from `RSS` feeds using `Unstructured`.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
urls: URLs for RSS feeds to load. Each articles in the feed is loaded into its own document.
|
| 17 |
+
opml: OPML file to load feed urls from. Only one of urls or opml should be provided. The value
|
| 18 |
+
can be a URL string, or OPML markup contents as byte or string.
|
| 19 |
+
continue_on_failure: If True, continue loading documents even if
|
| 20 |
+
loading fails for a particular URL.
|
| 21 |
+
show_progress_bar: If True, use tqdm to show a loading progress bar. Requires
|
| 22 |
+
tqdm to be installed, ``pip install tqdm``.
|
| 23 |
+
**newsloader_kwargs: Any additional named arguments to pass to
|
| 24 |
+
NewsURLLoader.
|
| 25 |
+
|
| 26 |
+
Example:
|
| 27 |
+
.. code-block:: python
|
| 28 |
+
|
| 29 |
+
from langchain_community.document_loaders import RSSFeedLoader
|
| 30 |
+
|
| 31 |
+
loader = RSSFeedLoader(
|
| 32 |
+
urls=["<url-1>", "<url-2>"],
|
| 33 |
+
)
|
| 34 |
+
docs = loader.load()
|
| 35 |
+
|
| 36 |
+
The loader uses feedparser to parse RSS feeds. The feedparser library is not installed by default so you should
|
| 37 |
+
install it if using this loader:
|
| 38 |
+
https://pythonhosted.org/feedparser/
|
| 39 |
+
|
| 40 |
+
If you use OPML, you should also install listparser:
|
| 41 |
+
https://pythonhosted.org/listparser/
|
| 42 |
+
|
| 43 |
+
Finally, newspaper is used to process each article:
|
| 44 |
+
https://newspaper.readthedocs.io/en/latest/
|
| 45 |
+
""" # noqa: E501
|
| 46 |
+
|
| 47 |
+
def __init__(
|
| 48 |
+
self,
|
| 49 |
+
urls: Optional[Sequence[str]] = None,
|
| 50 |
+
opml: Optional[str] = None,
|
| 51 |
+
continue_on_failure: bool = True,
|
| 52 |
+
show_progress_bar: bool = False,
|
| 53 |
+
**newsloader_kwargs: Any,
|
| 54 |
+
) -> None:
|
| 55 |
+
"""Initialize with urls or OPML."""
|
| 56 |
+
if (urls is None) == (
|
| 57 |
+
opml is None
|
| 58 |
+
): # This is True if both are None or neither is None
|
| 59 |
+
raise ValueError(
|
| 60 |
+
"Provide either the urls or the opml argument, but not both."
|
| 61 |
+
)
|
| 62 |
+
self.urls = urls
|
| 63 |
+
self.opml = opml
|
| 64 |
+
self.continue_on_failure = continue_on_failure
|
| 65 |
+
self.show_progress_bar = show_progress_bar
|
| 66 |
+
self.newsloader_kwargs = newsloader_kwargs
|
| 67 |
+
|
| 68 |
+
def load(self) -> List[Document]:
|
| 69 |
+
iter = self.lazy_load()
|
| 70 |
+
if self.show_progress_bar:
|
| 71 |
+
try:
|
| 72 |
+
from tqdm import tqdm
|
| 73 |
+
except ImportError as e:
|
| 74 |
+
raise ImportError(
|
| 75 |
+
"Package tqdm must be installed if show_progress_bar=True. "
|
| 76 |
+
"Please install with 'pip install tqdm' or set "
|
| 77 |
+
"show_progress_bar=False."
|
| 78 |
+
) from e
|
| 79 |
+
iter = tqdm(iter)
|
| 80 |
+
return list(iter)
|
| 81 |
+
|
| 82 |
+
@property
|
| 83 |
+
def _get_urls(self) -> Sequence[str]:
|
| 84 |
+
if self.urls:
|
| 85 |
+
return self.urls
|
| 86 |
+
try:
|
| 87 |
+
import listparser
|
| 88 |
+
except ImportError as e:
|
| 89 |
+
raise ImportError(
|
| 90 |
+
"Package listparser must be installed if the opml arg is used. "
|
| 91 |
+
"Please install with 'pip install listparser' or use the "
|
| 92 |
+
"urls arg instead."
|
| 93 |
+
) from e
|
| 94 |
+
rss = listparser.parse(self.opml)
|
| 95 |
+
return [feed.url for feed in rss.feeds]
|
| 96 |
+
|
| 97 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 98 |
+
try:
|
| 99 |
+
import feedparser
|
| 100 |
+
except ImportError:
|
| 101 |
+
raise ImportError(
|
| 102 |
+
"feedparser package not found, please install it with "
|
| 103 |
+
"`pip install feedparser`"
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
for url in self._get_urls:
|
| 107 |
+
try:
|
| 108 |
+
feed = feedparser.parse(url)
|
| 109 |
+
if getattr(feed, "bozo", False):
|
| 110 |
+
raise ValueError(
|
| 111 |
+
f"Error fetching {url}, exception: {feed.bozo_exception}"
|
| 112 |
+
)
|
| 113 |
+
except Exception as e:
|
| 114 |
+
if self.continue_on_failure:
|
| 115 |
+
logger.error(f"Error fetching {url}, exception: {e}")
|
| 116 |
+
continue
|
| 117 |
+
else:
|
| 118 |
+
raise e
|
| 119 |
+
try:
|
| 120 |
+
for entry in feed.entries:
|
| 121 |
+
loader = NewsURLLoader(
|
| 122 |
+
urls=[entry.link],
|
| 123 |
+
**self.newsloader_kwargs,
|
| 124 |
+
)
|
| 125 |
+
article = loader.load()[0]
|
| 126 |
+
article.metadata["feed"] = url
|
| 127 |
+
yield article
|
| 128 |
+
except Exception as e:
|
| 129 |
+
if self.continue_on_failure:
|
| 130 |
+
logger.error(f"Error processing entry {entry.link}, exception: {e}")
|
| 131 |
+
continue
|
| 132 |
+
else:
|
| 133 |
+
raise e
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rst.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Loads RST files."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Any, List, Union
|
| 5 |
+
|
| 6 |
+
from langchain_community.document_loaders.unstructured import (
|
| 7 |
+
UnstructuredFileLoader,
|
| 8 |
+
validate_unstructured_version,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class UnstructuredRSTLoader(UnstructuredFileLoader):
|
| 13 |
+
"""Load `RST` files using `Unstructured`.
|
| 14 |
+
|
| 15 |
+
You can run the loader in one of two modes: "single" and "elements".
|
| 16 |
+
If you use "single" mode, the document will be returned as a single
|
| 17 |
+
langchain Document object. If you use "elements" mode, the unstructured
|
| 18 |
+
library will split the document into elements such as Title and NarrativeText.
|
| 19 |
+
You can pass in additional unstructured kwargs after mode to apply
|
| 20 |
+
different unstructured settings.
|
| 21 |
+
|
| 22 |
+
Examples
|
| 23 |
+
--------
|
| 24 |
+
from langchain_community.document_loaders import UnstructuredRSTLoader
|
| 25 |
+
|
| 26 |
+
loader = UnstructuredRSTLoader(
|
| 27 |
+
"example.rst", mode="elements", strategy="fast",
|
| 28 |
+
)
|
| 29 |
+
docs = loader.load()
|
| 30 |
+
|
| 31 |
+
References
|
| 32 |
+
----------
|
| 33 |
+
https://unstructured-io.github.io/unstructured/bricks.html#partition-rst
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
file_path: Union[str, Path],
|
| 39 |
+
mode: str = "single",
|
| 40 |
+
**unstructured_kwargs: Any,
|
| 41 |
+
):
|
| 42 |
+
"""
|
| 43 |
+
Initialize with a file path.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
file_path: The path to the file to load.
|
| 47 |
+
mode: The mode to use for partitioning. See unstructured for details.
|
| 48 |
+
Defaults to "single".
|
| 49 |
+
**unstructured_kwargs: Additional keyword arguments to pass
|
| 50 |
+
to unstructured.
|
| 51 |
+
"""
|
| 52 |
+
file_path = str(file_path)
|
| 53 |
+
validate_unstructured_version(min_unstructured_version="0.7.5")
|
| 54 |
+
super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
|
| 55 |
+
|
| 56 |
+
def _get_elements(self) -> List:
|
| 57 |
+
from unstructured.partition.rst import partition_rst
|
| 58 |
+
|
| 59 |
+
return partition_rst(filename=self.file_path, **self.unstructured_kwargs)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rtf.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Loads rich text files."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Any, List, Union
|
| 5 |
+
|
| 6 |
+
from langchain_community.document_loaders.unstructured import (
|
| 7 |
+
UnstructuredFileLoader,
|
| 8 |
+
validate_unstructured_version,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class UnstructuredRTFLoader(UnstructuredFileLoader):
|
| 13 |
+
"""Load `RTF` files using `Unstructured`.
|
| 14 |
+
|
| 15 |
+
You can run the loader in one of two modes: "single" and "elements".
|
| 16 |
+
If you use "single" mode, the document will be returned as a single
|
| 17 |
+
langchain Document object. If you use "elements" mode, the unstructured
|
| 18 |
+
library will split the document into elements such as Title and NarrativeText.
|
| 19 |
+
You can pass in additional unstructured kwargs after mode to apply
|
| 20 |
+
different unstructured settings.
|
| 21 |
+
|
| 22 |
+
Examples
|
| 23 |
+
--------
|
| 24 |
+
from langchain_community.document_loaders import UnstructuredRTFLoader
|
| 25 |
+
|
| 26 |
+
loader = UnstructuredRTFLoader(
|
| 27 |
+
"example.rtf", mode="elements", strategy="fast",
|
| 28 |
+
)
|
| 29 |
+
docs = loader.load()
|
| 30 |
+
|
| 31 |
+
References
|
| 32 |
+
----------
|
| 33 |
+
https://unstructured-io.github.io/unstructured/bricks.html#partition-rtf
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
file_path: Union[str, Path],
|
| 39 |
+
mode: str = "single",
|
| 40 |
+
**unstructured_kwargs: Any,
|
| 41 |
+
):
|
| 42 |
+
"""
|
| 43 |
+
Initialize with a file path.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
file_path: The path to the file to load.
|
| 47 |
+
mode: The mode to use for partitioning. See unstructured for details.
|
| 48 |
+
Defaults to "single".
|
| 49 |
+
**unstructured_kwargs: Additional keyword arguments to pass
|
| 50 |
+
to unstructured.
|
| 51 |
+
"""
|
| 52 |
+
file_path = str(file_path)
|
| 53 |
+
validate_unstructured_version("0.5.12")
|
| 54 |
+
super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
|
| 55 |
+
|
| 56 |
+
def _get_elements(self) -> List:
|
| 57 |
+
from unstructured.partition.rtf import partition_rtf
|
| 58 |
+
|
| 59 |
+
return partition_rtf(filename=self.file_path, **self.unstructured_kwargs)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/s3_directory.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, List, Optional, Union
|
| 4 |
+
|
| 5 |
+
from langchain_core.documents import Document
|
| 6 |
+
|
| 7 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 8 |
+
from langchain_community.document_loaders.s3_file import S3FileLoader
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
import botocore
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class S3DirectoryLoader(BaseLoader):
|
| 15 |
+
"""Load from `Amazon AWS S3` directory."""
|
| 16 |
+
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
bucket: str,
|
| 20 |
+
prefix: str = "",
|
| 21 |
+
*,
|
| 22 |
+
region_name: Optional[str] = None,
|
| 23 |
+
api_version: Optional[str] = None,
|
| 24 |
+
use_ssl: Optional[bool] = True,
|
| 25 |
+
verify: Union[str, bool, None] = None,
|
| 26 |
+
endpoint_url: Optional[str] = None,
|
| 27 |
+
aws_access_key_id: Optional[str] = None,
|
| 28 |
+
aws_secret_access_key: Optional[str] = None,
|
| 29 |
+
aws_session_token: Optional[str] = None,
|
| 30 |
+
boto_config: Optional[botocore.client.Config] = None,
|
| 31 |
+
):
|
| 32 |
+
"""Initialize with bucket and key name.
|
| 33 |
+
|
| 34 |
+
:param bucket: The name of the S3 bucket.
|
| 35 |
+
:param prefix: The prefix of the S3 key. Defaults to "".
|
| 36 |
+
|
| 37 |
+
:param region_name: The name of the region associated with the client.
|
| 38 |
+
A client is associated with a single region.
|
| 39 |
+
|
| 40 |
+
:param api_version: The API version to use. By default, botocore will
|
| 41 |
+
use the latest API version when creating a client. You only need
|
| 42 |
+
to specify this parameter if you want to use a previous API version
|
| 43 |
+
of the client.
|
| 44 |
+
|
| 45 |
+
:param use_ssl: Whether to use SSL. By default, SSL is used.
|
| 46 |
+
Note that not all services support non-ssl connections.
|
| 47 |
+
|
| 48 |
+
:param verify: Whether to verify SSL certificates.
|
| 49 |
+
By default SSL certificates are verified. You can provide the
|
| 50 |
+
following values:
|
| 51 |
+
|
| 52 |
+
* False - do not validate SSL certificates. SSL will still be
|
| 53 |
+
used (unless use_ssl is False), but SSL certificates
|
| 54 |
+
will not be verified.
|
| 55 |
+
* path/to/cert/bundle.pem - A filename of the CA cert bundle to
|
| 56 |
+
uses. You can specify this argument if you want to use a
|
| 57 |
+
different CA cert bundle than the one used by botocore.
|
| 58 |
+
|
| 59 |
+
:param endpoint_url: The complete URL to use for the constructed
|
| 60 |
+
client. Normally, botocore will automatically construct the
|
| 61 |
+
appropriate URL to use when communicating with a service. You can
|
| 62 |
+
specify a complete URL (including the "http/https" scheme) to
|
| 63 |
+
override this behavior. If this value is provided, then
|
| 64 |
+
``use_ssl`` is ignored.
|
| 65 |
+
|
| 66 |
+
:param aws_access_key_id: The access key to use when creating
|
| 67 |
+
the client. This is entirely optional, and if not provided,
|
| 68 |
+
the credentials configured for the session will automatically
|
| 69 |
+
be used. You only need to provide this argument if you want
|
| 70 |
+
to override the credentials used for this specific client.
|
| 71 |
+
|
| 72 |
+
:param aws_secret_access_key: The secret key to use when creating
|
| 73 |
+
the client. Same semantics as aws_access_key_id above.
|
| 74 |
+
|
| 75 |
+
:param aws_session_token: The session token to use when creating
|
| 76 |
+
the client. Same semantics as aws_access_key_id above.
|
| 77 |
+
|
| 78 |
+
:type boto_config: botocore.client.Config
|
| 79 |
+
:param boto_config: Advanced boto3 client configuration options. If a value
|
| 80 |
+
is specified in the client config, its value will take precedence
|
| 81 |
+
over environment variables and configuration values, but not over
|
| 82 |
+
a value passed explicitly to the method. If a default config
|
| 83 |
+
object is set on the session, the config object used when creating
|
| 84 |
+
the client will be the result of calling ``merge()`` on the
|
| 85 |
+
default config with the config provided to this call.
|
| 86 |
+
"""
|
| 87 |
+
self.bucket = bucket
|
| 88 |
+
self.prefix = prefix
|
| 89 |
+
self.region_name = region_name
|
| 90 |
+
self.api_version = api_version
|
| 91 |
+
self.use_ssl = use_ssl
|
| 92 |
+
self.verify = verify
|
| 93 |
+
self.endpoint_url = endpoint_url
|
| 94 |
+
self.aws_access_key_id = aws_access_key_id
|
| 95 |
+
self.aws_secret_access_key = aws_secret_access_key
|
| 96 |
+
self.aws_session_token = aws_session_token
|
| 97 |
+
self.boto_config = boto_config
|
| 98 |
+
|
| 99 |
+
def load(self) -> List[Document]:
|
| 100 |
+
"""Load documents."""
|
| 101 |
+
try:
|
| 102 |
+
import boto3
|
| 103 |
+
except ImportError:
|
| 104 |
+
raise ImportError(
|
| 105 |
+
"Could not import boto3 python package. "
|
| 106 |
+
"Please install it with `pip install boto3`."
|
| 107 |
+
)
|
| 108 |
+
s3 = boto3.resource(
|
| 109 |
+
"s3",
|
| 110 |
+
region_name=self.region_name,
|
| 111 |
+
api_version=self.api_version,
|
| 112 |
+
use_ssl=self.use_ssl,
|
| 113 |
+
verify=self.verify,
|
| 114 |
+
endpoint_url=self.endpoint_url,
|
| 115 |
+
aws_access_key_id=self.aws_access_key_id,
|
| 116 |
+
aws_secret_access_key=self.aws_secret_access_key,
|
| 117 |
+
aws_session_token=self.aws_session_token,
|
| 118 |
+
config=self.boto_config,
|
| 119 |
+
)
|
| 120 |
+
bucket = s3.Bucket(self.bucket)
|
| 121 |
+
docs = []
|
| 122 |
+
for obj in bucket.objects.filter(Prefix=self.prefix):
|
| 123 |
+
# Skip directories
|
| 124 |
+
if obj.size == 0 and obj.key.endswith("/"):
|
| 125 |
+
continue
|
| 126 |
+
loader = S3FileLoader(
|
| 127 |
+
self.bucket,
|
| 128 |
+
obj.key,
|
| 129 |
+
region_name=self.region_name,
|
| 130 |
+
api_version=self.api_version,
|
| 131 |
+
use_ssl=self.use_ssl,
|
| 132 |
+
verify=self.verify,
|
| 133 |
+
endpoint_url=self.endpoint_url,
|
| 134 |
+
aws_access_key_id=self.aws_access_key_id,
|
| 135 |
+
aws_secret_access_key=self.aws_secret_access_key,
|
| 136 |
+
aws_session_token=self.aws_session_token,
|
| 137 |
+
boto_config=self.boto_config,
|
| 138 |
+
)
|
| 139 |
+
docs.extend(loader.load())
|
| 140 |
+
return docs
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/s3_file.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import tempfile
|
| 5 |
+
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union
|
| 6 |
+
|
| 7 |
+
from langchain_community.document_loaders.unstructured import UnstructuredBaseLoader
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
import botocore
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class S3FileLoader(UnstructuredBaseLoader):
|
| 14 |
+
"""Load from `Amazon AWS S3` file."""
|
| 15 |
+
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
bucket: str,
|
| 19 |
+
key: str,
|
| 20 |
+
*,
|
| 21 |
+
region_name: Optional[str] = None,
|
| 22 |
+
api_version: Optional[str] = None,
|
| 23 |
+
use_ssl: Optional[bool] = True,
|
| 24 |
+
verify: Union[str, bool, None] = None,
|
| 25 |
+
endpoint_url: Optional[str] = None,
|
| 26 |
+
aws_access_key_id: Optional[str] = None,
|
| 27 |
+
aws_secret_access_key: Optional[str] = None,
|
| 28 |
+
aws_session_token: Optional[str] = None,
|
| 29 |
+
boto_config: Optional[botocore.client.Config] = None,
|
| 30 |
+
mode: str = "single",
|
| 31 |
+
post_processors: Optional[List[Callable]] = None,
|
| 32 |
+
**unstructured_kwargs: Any,
|
| 33 |
+
):
|
| 34 |
+
"""Initialize with bucket and key name.
|
| 35 |
+
|
| 36 |
+
:param bucket: The name of the S3 bucket.
|
| 37 |
+
:param key: The key of the S3 object.
|
| 38 |
+
|
| 39 |
+
:param region_name: The name of the region associated with the client.
|
| 40 |
+
A client is associated with a single region.
|
| 41 |
+
|
| 42 |
+
:param api_version: The API version to use. By default, botocore will
|
| 43 |
+
use the latest API version when creating a client. You only need
|
| 44 |
+
to specify this parameter if you want to use a previous API version
|
| 45 |
+
of the client.
|
| 46 |
+
|
| 47 |
+
:param use_ssl: Whether or not to use SSL. By default, SSL is used.
|
| 48 |
+
Note that not all services support non-ssl connections.
|
| 49 |
+
|
| 50 |
+
:param verify: Whether or not to verify SSL certificates.
|
| 51 |
+
By default SSL certificates are verified. You can provide the
|
| 52 |
+
following values:
|
| 53 |
+
|
| 54 |
+
* False - do not validate SSL certificates. SSL will still be
|
| 55 |
+
used (unless use_ssl is False), but SSL certificates
|
| 56 |
+
will not be verified.
|
| 57 |
+
* path/to/cert/bundle.pem - A filename of the CA cert bundle to
|
| 58 |
+
uses. You can specify this argument if you want to use a
|
| 59 |
+
different CA cert bundle than the one used by botocore.
|
| 60 |
+
|
| 61 |
+
:param endpoint_url: The complete URL to use for the constructed
|
| 62 |
+
client. Normally, botocore will automatically construct the
|
| 63 |
+
appropriate URL to use when communicating with a service. You can
|
| 64 |
+
specify a complete URL (including the "http/https" scheme) to
|
| 65 |
+
override this behavior. If this value is provided, then
|
| 66 |
+
``use_ssl`` is ignored.
|
| 67 |
+
|
| 68 |
+
:param aws_access_key_id: The access key to use when creating
|
| 69 |
+
the client. This is entirely optional, and if not provided,
|
| 70 |
+
the credentials configured for the session will automatically
|
| 71 |
+
be used. You only need to provide this argument if you want
|
| 72 |
+
to override the credentials used for this specific client.
|
| 73 |
+
|
| 74 |
+
:param aws_secret_access_key: The secret key to use when creating
|
| 75 |
+
the client. Same semantics as aws_access_key_id above.
|
| 76 |
+
|
| 77 |
+
:param aws_session_token: The session token to use when creating
|
| 78 |
+
the client. Same semantics as aws_access_key_id above.
|
| 79 |
+
|
| 80 |
+
:type boto_config: botocore.client.Config
|
| 81 |
+
:param boto_config: Advanced boto3 client configuration options. If a value
|
| 82 |
+
is specified in the client config, its value will take precedence
|
| 83 |
+
over environment variables and configuration values, but not over
|
| 84 |
+
a value passed explicitly to the method. If a default config
|
| 85 |
+
object is set on the session, the config object used when creating
|
| 86 |
+
the client will be the result of calling ``merge()`` on the
|
| 87 |
+
default config with the config provided to this call.
|
| 88 |
+
:param mode: Mode in which to read the file. Valid options are: single,
|
| 89 |
+
paged and elements.
|
| 90 |
+
:param post_processors: Post processing functions to be applied to
|
| 91 |
+
extracted elements.
|
| 92 |
+
:param **unstructured_kwargs: Arbitrary additional kwargs to pass in when
|
| 93 |
+
calling `partition`
|
| 94 |
+
"""
|
| 95 |
+
super().__init__(mode, post_processors, **unstructured_kwargs)
|
| 96 |
+
self.bucket = bucket
|
| 97 |
+
self.key = key
|
| 98 |
+
self.region_name = region_name
|
| 99 |
+
self.api_version = api_version
|
| 100 |
+
self.use_ssl = use_ssl
|
| 101 |
+
self.verify = verify
|
| 102 |
+
self.endpoint_url = endpoint_url
|
| 103 |
+
self.aws_access_key_id = aws_access_key_id
|
| 104 |
+
self.aws_secret_access_key = aws_secret_access_key
|
| 105 |
+
self.aws_session_token = aws_session_token
|
| 106 |
+
self.boto_config = boto_config
|
| 107 |
+
|
| 108 |
+
def _get_elements(self) -> List:
|
| 109 |
+
"""Get elements."""
|
| 110 |
+
from unstructured.partition.auto import partition
|
| 111 |
+
|
| 112 |
+
try:
|
| 113 |
+
import boto3
|
| 114 |
+
except ImportError:
|
| 115 |
+
raise ImportError(
|
| 116 |
+
"Could not import `boto3` python package. "
|
| 117 |
+
"Please install it with `pip install boto3`."
|
| 118 |
+
)
|
| 119 |
+
s3 = boto3.client(
|
| 120 |
+
"s3",
|
| 121 |
+
region_name=self.region_name,
|
| 122 |
+
api_version=self.api_version,
|
| 123 |
+
use_ssl=self.use_ssl,
|
| 124 |
+
verify=self.verify,
|
| 125 |
+
endpoint_url=self.endpoint_url,
|
| 126 |
+
aws_access_key_id=self.aws_access_key_id,
|
| 127 |
+
aws_secret_access_key=self.aws_secret_access_key,
|
| 128 |
+
aws_session_token=self.aws_session_token,
|
| 129 |
+
config=self.boto_config,
|
| 130 |
+
)
|
| 131 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 132 |
+
file_path = f"{temp_dir}/{self.key}"
|
| 133 |
+
os.makedirs(os.path.dirname(file_path), exist_ok=True)
|
| 134 |
+
s3.download_file(self.bucket, self.key, file_path)
|
| 135 |
+
return partition(filename=file_path, **self.unstructured_kwargs)
|
| 136 |
+
|
| 137 |
+
def _get_metadata(self) -> dict:
|
| 138 |
+
return {"source": f"s3://{self.bucket}/{self.key}"}
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/scrapfly.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Scrapfly Web Reader."""
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Iterator, List, Literal, Optional
|
| 5 |
+
|
| 6 |
+
from langchain_core.document_loaders import BaseLoader
|
| 7 |
+
from langchain_core.documents import Document
|
| 8 |
+
from langchain_core.utils import get_from_env
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__file__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ScrapflyLoader(BaseLoader):
|
| 14 |
+
"""Turn a url to llm accessible markdown with `Scrapfly.io`.
|
| 15 |
+
|
| 16 |
+
For further details, visit: https://scrapfly.io/docs/sdk/python
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
urls: List[str],
|
| 22 |
+
*,
|
| 23 |
+
api_key: Optional[str] = None,
|
| 24 |
+
scrape_format: Literal["markdown", "text"] = "markdown",
|
| 25 |
+
scrape_config: Optional[dict] = None,
|
| 26 |
+
continue_on_failure: bool = True,
|
| 27 |
+
) -> None:
|
| 28 |
+
"""Initialize client.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
urls: List of urls to scrape.
|
| 32 |
+
api_key: The Scrapfly API key. If not specified must have env var
|
| 33 |
+
SCRAPFLY_API_KEY set.
|
| 34 |
+
scrape_format: Scrape result format, one or "markdown" or "text".
|
| 35 |
+
scrape_config: Dictionary of ScrapFly scrape config object.
|
| 36 |
+
continue_on_failure: Whether to continue if scraping a url fails.
|
| 37 |
+
"""
|
| 38 |
+
try:
|
| 39 |
+
from scrapfly import ScrapflyClient
|
| 40 |
+
except ImportError:
|
| 41 |
+
raise ImportError(
|
| 42 |
+
"`scrapfly` package not found, please run `pip install scrapfly-sdk`"
|
| 43 |
+
)
|
| 44 |
+
if not urls:
|
| 45 |
+
raise ValueError("URLs must be provided.")
|
| 46 |
+
api_key = api_key or get_from_env("api_key", "SCRAPFLY_API_KEY")
|
| 47 |
+
self.scrapfly = ScrapflyClient(key=api_key)
|
| 48 |
+
self.urls = urls
|
| 49 |
+
self.scrape_format = scrape_format
|
| 50 |
+
self.scrape_config = scrape_config
|
| 51 |
+
self.continue_on_failure = continue_on_failure
|
| 52 |
+
|
| 53 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 54 |
+
from scrapfly import ScrapeConfig
|
| 55 |
+
|
| 56 |
+
scrape_config = self.scrape_config if self.scrape_config is not None else {}
|
| 57 |
+
for url in self.urls:
|
| 58 |
+
try:
|
| 59 |
+
response = self.scrapfly.scrape(
|
| 60 |
+
ScrapeConfig(url, format=self.scrape_format, **scrape_config)
|
| 61 |
+
)
|
| 62 |
+
yield Document(
|
| 63 |
+
page_content=response.scrape_result["content"],
|
| 64 |
+
metadata={"url": url},
|
| 65 |
+
)
|
| 66 |
+
except Exception as e:
|
| 67 |
+
if self.continue_on_failure:
|
| 68 |
+
logger.error(f"Error fetching data from {url}, exception: {e}")
|
| 69 |
+
else:
|
| 70 |
+
raise e
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/scrapingant.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ScrapingAnt Web Extractor."""
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Iterator, List, Optional
|
| 5 |
+
|
| 6 |
+
from langchain_core.document_loaders import BaseLoader
|
| 7 |
+
from langchain_core.documents import Document
|
| 8 |
+
from langchain_core.utils import get_from_env
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__file__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ScrapingAntLoader(BaseLoader):
|
| 14 |
+
"""Turn an url to LLM accessible markdown with `ScrapingAnt`.
|
| 15 |
+
|
| 16 |
+
For further details, visit: https://docs.scrapingant.com/python-client
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
urls: List[str],
|
| 22 |
+
*,
|
| 23 |
+
api_key: Optional[str] = None,
|
| 24 |
+
scrape_config: Optional[dict] = None,
|
| 25 |
+
continue_on_failure: bool = True,
|
| 26 |
+
) -> None:
|
| 27 |
+
"""Initialize client.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
urls: List of urls to scrape.
|
| 31 |
+
api_key: The ScrapingAnt API key. If not specified must have env var
|
| 32 |
+
SCRAPINGANT_API_KEY set.
|
| 33 |
+
scrape_config: The scraping config from ScrapingAntClient.markdown_request
|
| 34 |
+
continue_on_failure: Whether to continue if scraping an url fails.
|
| 35 |
+
"""
|
| 36 |
+
try:
|
| 37 |
+
from scrapingant_client import ScrapingAntClient
|
| 38 |
+
except ImportError:
|
| 39 |
+
raise ImportError(
|
| 40 |
+
"`scrapingant-client` package not found,"
|
| 41 |
+
" run `pip install scrapingant-client`"
|
| 42 |
+
)
|
| 43 |
+
if not urls:
|
| 44 |
+
raise ValueError("URLs must be provided.")
|
| 45 |
+
api_key = api_key or get_from_env("api_key", "SCRAPINGANT_API_KEY")
|
| 46 |
+
self.client = ScrapingAntClient(token=api_key)
|
| 47 |
+
self.urls = urls
|
| 48 |
+
self.scrape_config = scrape_config
|
| 49 |
+
self.continue_on_failure = continue_on_failure
|
| 50 |
+
|
| 51 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 52 |
+
"""Fetch data from ScrapingAnt."""
|
| 53 |
+
|
| 54 |
+
scrape_config = self.scrape_config if self.scrape_config is not None else {}
|
| 55 |
+
for url in self.urls:
|
| 56 |
+
try:
|
| 57 |
+
result = self.client.markdown_request(url=url, **scrape_config)
|
| 58 |
+
yield Document(
|
| 59 |
+
page_content=result.markdown,
|
| 60 |
+
metadata={"url": result.url},
|
| 61 |
+
)
|
| 62 |
+
except Exception as e:
|
| 63 |
+
if self.continue_on_failure:
|
| 64 |
+
logger.error(f"Error fetching data from {url}, exception: {e}")
|
| 65 |
+
else:
|
| 66 |
+
raise e
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/sharepoint.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Loader that loads data from Sharepoint Document Library"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, Dict, Iterator, List, Optional
|
| 8 |
+
|
| 9 |
+
import requests
|
| 10 |
+
from langchain_core.document_loaders import BaseLoader
|
| 11 |
+
from langchain_core.documents import Document
|
| 12 |
+
from pydantic import Field
|
| 13 |
+
|
| 14 |
+
from langchain_community.document_loaders.base_o365 import (
|
| 15 |
+
O365BaseLoader,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class SharePointLoader(O365BaseLoader, BaseLoader):
|
| 20 |
+
"""Load from `SharePoint`."""
|
| 21 |
+
|
| 22 |
+
document_library_id: str = Field(...)
|
| 23 |
+
""" The ID of the SharePoint document library to load data from."""
|
| 24 |
+
folder_path: Optional[str] = None
|
| 25 |
+
""" The path to the folder to load data from."""
|
| 26 |
+
object_ids: Optional[List[str]] = None
|
| 27 |
+
""" The IDs of the objects to load data from."""
|
| 28 |
+
folder_id: Optional[str] = None
|
| 29 |
+
""" The ID of the folder to load data from."""
|
| 30 |
+
load_auth: Optional[bool] = False
|
| 31 |
+
""" Whether to load authorization identities."""
|
| 32 |
+
token_path: Path = Path.home() / ".credentials" / "o365_token.txt"
|
| 33 |
+
""" The path to the token to make api calls"""
|
| 34 |
+
load_extended_metadata: Optional[bool] = False
|
| 35 |
+
""" Whether to load extended metadata. Size, Owner and full_path."""
|
| 36 |
+
|
| 37 |
+
@property
|
| 38 |
+
def _scopes(self) -> List[str]:
|
| 39 |
+
"""Return required scopes.
|
| 40 |
+
Returns:
|
| 41 |
+
List[str]: A list of required scopes.
|
| 42 |
+
"""
|
| 43 |
+
return ["sharepoint", "basic"]
|
| 44 |
+
|
| 45 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 46 |
+
"""
|
| 47 |
+
Load documents lazily. Use this when working at a large scale.
|
| 48 |
+
Yields:
|
| 49 |
+
Document: A document object representing the parsed blob.
|
| 50 |
+
"""
|
| 51 |
+
try:
|
| 52 |
+
from O365.drive import Drive, Folder
|
| 53 |
+
except ImportError:
|
| 54 |
+
raise ImportError(
|
| 55 |
+
"O365 package not found, please install it with `pip install o365`"
|
| 56 |
+
)
|
| 57 |
+
drive = self._auth().storage().get_drive(self.document_library_id)
|
| 58 |
+
if not isinstance(drive, Drive):
|
| 59 |
+
raise ValueError(f"There isn't a Drive with id {self.document_library_id}.")
|
| 60 |
+
if self.folder_path:
|
| 61 |
+
target_folder = drive.get_item_by_path(self.folder_path)
|
| 62 |
+
if not isinstance(target_folder, Folder):
|
| 63 |
+
raise ValueError(f"There isn't a folder with path {self.folder_path}.")
|
| 64 |
+
for blob in self._load_from_folder(target_folder):
|
| 65 |
+
file_id = str(blob.metadata.get("id"))
|
| 66 |
+
if self.load_auth is True:
|
| 67 |
+
auth_identities = self.authorized_identities(file_id)
|
| 68 |
+
if self.load_extended_metadata is True:
|
| 69 |
+
extended_metadata = self.get_extended_metadata(file_id)
|
| 70 |
+
extended_metadata.update({"source_full_url": target_folder.web_url})
|
| 71 |
+
for parsed_blob in self._blob_parser.lazy_parse(blob):
|
| 72 |
+
if self.load_auth is True:
|
| 73 |
+
parsed_blob.metadata["authorized_identities"] = auth_identities
|
| 74 |
+
if self.load_extended_metadata is True:
|
| 75 |
+
parsed_blob.metadata.update(extended_metadata)
|
| 76 |
+
yield parsed_blob
|
| 77 |
+
if self.folder_id:
|
| 78 |
+
target_folder = drive.get_item(self.folder_id)
|
| 79 |
+
if not isinstance(target_folder, Folder):
|
| 80 |
+
raise ValueError(f"There isn't a folder with path {self.folder_path}.")
|
| 81 |
+
for blob in self._load_from_folder(target_folder):
|
| 82 |
+
file_id = str(blob.metadata.get("id"))
|
| 83 |
+
if self.load_auth is True:
|
| 84 |
+
auth_identities = self.authorized_identities(file_id)
|
| 85 |
+
if self.load_extended_metadata is True:
|
| 86 |
+
extended_metadata = self.get_extended_metadata(file_id)
|
| 87 |
+
extended_metadata.update({"source_full_url": target_folder.web_url})
|
| 88 |
+
for parsed_blob in self._blob_parser.lazy_parse(blob):
|
| 89 |
+
if self.load_auth is True:
|
| 90 |
+
parsed_blob.metadata["authorized_identities"] = auth_identities
|
| 91 |
+
if self.load_extended_metadata is True:
|
| 92 |
+
parsed_blob.metadata.update(extended_metadata)
|
| 93 |
+
yield parsed_blob
|
| 94 |
+
if self.object_ids:
|
| 95 |
+
for blob in self._load_from_object_ids(drive, self.object_ids):
|
| 96 |
+
file_id = str(blob.metadata.get("id"))
|
| 97 |
+
if self.load_auth is True:
|
| 98 |
+
auth_identities = self.authorized_identities(file_id)
|
| 99 |
+
if self.load_extended_metadata is True:
|
| 100 |
+
extended_metadata = self.get_extended_metadata(file_id)
|
| 101 |
+
for parsed_blob in self._blob_parser.lazy_parse(blob):
|
| 102 |
+
if self.load_auth is True:
|
| 103 |
+
parsed_blob.metadata["authorized_identities"] = auth_identities
|
| 104 |
+
if self.load_extended_metadata is True:
|
| 105 |
+
parsed_blob.metadata.update(extended_metadata)
|
| 106 |
+
yield parsed_blob
|
| 107 |
+
|
| 108 |
+
if not (self.folder_path or self.folder_id or self.object_ids):
|
| 109 |
+
target_folder = drive.get_root_folder()
|
| 110 |
+
if not isinstance(target_folder, Folder):
|
| 111 |
+
raise ValueError("Unable to fetch root folder")
|
| 112 |
+
for blob in self._load_from_folder(target_folder):
|
| 113 |
+
file_id = str(blob.metadata.get("id"))
|
| 114 |
+
if self.load_auth is True:
|
| 115 |
+
auth_identities = self.authorized_identities(file_id)
|
| 116 |
+
if self.load_extended_metadata is True:
|
| 117 |
+
extended_metadata = self.get_extended_metadata(file_id)
|
| 118 |
+
for blob_part in self._blob_parser.lazy_parse(blob):
|
| 119 |
+
blob_part.metadata.update(blob.metadata)
|
| 120 |
+
if self.load_auth is True:
|
| 121 |
+
blob_part.metadata["authorized_identities"] = auth_identities
|
| 122 |
+
if self.load_extended_metadata is True:
|
| 123 |
+
blob_part.metadata.update(extended_metadata)
|
| 124 |
+
blob_part.metadata.update(
|
| 125 |
+
{"source_full_url": target_folder.web_url}
|
| 126 |
+
)
|
| 127 |
+
yield blob_part
|
| 128 |
+
|
| 129 |
+
def authorized_identities(self, file_id: str) -> List:
|
| 130 |
+
"""
|
| 131 |
+
Retrieve the access identities (user/group emails) for a given file.
|
| 132 |
+
Args:
|
| 133 |
+
file_id (str): The ID of the file.
|
| 134 |
+
Returns:
|
| 135 |
+
List: A list of group names (email addresses) that have
|
| 136 |
+
access to the file.
|
| 137 |
+
"""
|
| 138 |
+
data = self._fetch_access_token()
|
| 139 |
+
access_token = data.get("access_token")
|
| 140 |
+
url = (
|
| 141 |
+
"https://graph.microsoft.com/v1.0/drives"
|
| 142 |
+
f"/{self.document_library_id}/items/{file_id}/permissions"
|
| 143 |
+
)
|
| 144 |
+
headers = {"Authorization": f"Bearer {access_token}"}
|
| 145 |
+
response = requests.request("GET", url, headers=headers)
|
| 146 |
+
access_list = response.json()
|
| 147 |
+
|
| 148 |
+
group_names = []
|
| 149 |
+
|
| 150 |
+
for access_data in access_list.get("value"):
|
| 151 |
+
if access_data.get("grantedToV2"):
|
| 152 |
+
site_data = (
|
| 153 |
+
(access_data.get("grantedToV2").get("siteUser"))
|
| 154 |
+
or (access_data.get("grantedToV2").get("user"))
|
| 155 |
+
or (access_data.get("grantedToV2").get("group"))
|
| 156 |
+
)
|
| 157 |
+
if site_data:
|
| 158 |
+
email = site_data.get("email")
|
| 159 |
+
if email:
|
| 160 |
+
group_names.append(email)
|
| 161 |
+
return group_names
|
| 162 |
+
|
| 163 |
+
def _fetch_access_token(self) -> Any:
|
| 164 |
+
"""
|
| 165 |
+
Fetch the access token from the token file.
|
| 166 |
+
Returns:
|
| 167 |
+
The access token as a dictionary.
|
| 168 |
+
"""
|
| 169 |
+
with open(self.token_path, encoding="utf-8") as f:
|
| 170 |
+
s = f.read()
|
| 171 |
+
data = json.loads(s)
|
| 172 |
+
return data
|
| 173 |
+
|
| 174 |
+
def get_extended_metadata(self, file_id: str) -> Dict:
|
| 175 |
+
"""
|
| 176 |
+
Retrieve extended metadata for a file in SharePoint.
|
| 177 |
+
As of today, following fields are supported in the extended metadata:
|
| 178 |
+
- size: size of the source file.
|
| 179 |
+
- owner: display name of the owner of the source file.
|
| 180 |
+
- full_path: pretty human readable path of the source file.
|
| 181 |
+
Args:
|
| 182 |
+
file_id (str): The ID of the file.
|
| 183 |
+
Returns:
|
| 184 |
+
`dict` containing the extended metadata of the file, including size, owner,
|
| 185 |
+
and full path.
|
| 186 |
+
"""
|
| 187 |
+
data = self._fetch_access_token()
|
| 188 |
+
access_token = data.get("access_token")
|
| 189 |
+
url = (
|
| 190 |
+
"https://graph.microsoft.com/v1.0/drives/"
|
| 191 |
+
f"{self.document_library_id}/items/{file_id}"
|
| 192 |
+
"?$select=size,createdBy,parentReference,name"
|
| 193 |
+
)
|
| 194 |
+
headers = {"Authorization": f"Bearer {access_token}"}
|
| 195 |
+
response = requests.request("GET", url, headers=headers)
|
| 196 |
+
metadata = response.json()
|
| 197 |
+
staged_metadata = {
|
| 198 |
+
"size": metadata.get("size", 0),
|
| 199 |
+
"owner": metadata.get("createdBy", {})
|
| 200 |
+
.get("user", {})
|
| 201 |
+
.get("displayName", ""),
|
| 202 |
+
"full_path": metadata.get("parentReference", {})
|
| 203 |
+
.get("path", "")
|
| 204 |
+
.split(":")[-1]
|
| 205 |
+
+ "/"
|
| 206 |
+
+ metadata.get("name", ""),
|
| 207 |
+
}
|
| 208 |
+
return staged_metadata
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/sitemap.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import re
|
| 3 |
+
from typing import (
|
| 4 |
+
Any,
|
| 5 |
+
Callable,
|
| 6 |
+
Dict,
|
| 7 |
+
Generator,
|
| 8 |
+
Iterable,
|
| 9 |
+
Iterator,
|
| 10 |
+
List,
|
| 11 |
+
Optional,
|
| 12 |
+
Tuple,
|
| 13 |
+
)
|
| 14 |
+
from urllib.parse import urlparse
|
| 15 |
+
|
| 16 |
+
from langchain_core.documents import Document
|
| 17 |
+
|
| 18 |
+
from langchain_community.document_loaders.web_base import WebBaseLoader
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _default_parsing_function(content: Any) -> str:
|
| 22 |
+
return str(content.get_text())
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _default_meta_function(meta: dict, _content: Any) -> dict:
|
| 26 |
+
return {"source": meta["loc"], **meta}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _batch_block(iterable: Iterable, size: int) -> Generator[List[dict], None, None]:
|
| 30 |
+
it = iter(iterable)
|
| 31 |
+
while item := list(itertools.islice(it, size)):
|
| 32 |
+
yield item
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _extract_scheme_and_domain(url: str) -> Tuple[str, str]:
|
| 36 |
+
"""Extract the scheme + domain from a given URL.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
url (str): The input URL.
|
| 40 |
+
|
| 41 |
+
Returns:
|
| 42 |
+
return a 2-tuple of scheme and domain
|
| 43 |
+
"""
|
| 44 |
+
parsed_uri = urlparse(url)
|
| 45 |
+
return parsed_uri.scheme, parsed_uri.netloc
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class SitemapLoader(WebBaseLoader):
|
| 49 |
+
"""Load a sitemap and its URLs.
|
| 50 |
+
|
| 51 |
+
**Security Note**: This loader can be used to load all URLs specified in a sitemap.
|
| 52 |
+
If a malicious actor gets access to the sitemap, they could force
|
| 53 |
+
the server to load URLs from other domains by modifying the sitemap.
|
| 54 |
+
This could lead to server-side request forgery (SSRF) attacks; e.g.,
|
| 55 |
+
with the attacker forcing the server to load URLs from internal
|
| 56 |
+
service endpoints that are not publicly accessible. While the attacker
|
| 57 |
+
may not immediately gain access to this data, this data could leak
|
| 58 |
+
into downstream systems (e.g., data loader is used to load data for indexing).
|
| 59 |
+
|
| 60 |
+
This loader is a crawler and web crawlers should generally NOT be deployed
|
| 61 |
+
with network access to any internal servers.
|
| 62 |
+
|
| 63 |
+
Control access to who can submit crawling requests and what network access
|
| 64 |
+
the crawler has.
|
| 65 |
+
|
| 66 |
+
By default, the loader will only load URLs from the same domain as the sitemap
|
| 67 |
+
if the site map is not a local file. This can be disabled by setting
|
| 68 |
+
restrict_to_same_domain to False (not recommended).
|
| 69 |
+
|
| 70 |
+
If the site map is a local file, no such risk mitigation is applied by default.
|
| 71 |
+
|
| 72 |
+
Use the filter URLs argument to limit which URLs can be loaded.
|
| 73 |
+
|
| 74 |
+
See https://python.langchain.com/docs/security
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
def __init__(
|
| 78 |
+
self,
|
| 79 |
+
web_path: str,
|
| 80 |
+
filter_urls: Optional[List[str]] = None,
|
| 81 |
+
parsing_function: Optional[Callable] = None,
|
| 82 |
+
blocksize: Optional[int] = None,
|
| 83 |
+
blocknum: int = 0,
|
| 84 |
+
meta_function: Optional[Callable] = None,
|
| 85 |
+
is_local: bool = False,
|
| 86 |
+
continue_on_failure: bool = False,
|
| 87 |
+
restrict_to_same_domain: bool = True,
|
| 88 |
+
max_depth: int = 10,
|
| 89 |
+
**kwargs: Any,
|
| 90 |
+
):
|
| 91 |
+
"""Initialize with webpage path and optional filter URLs.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
web_path: url of the sitemap. can also be a local path
|
| 95 |
+
filter_urls: a list of regexes. If specified, only
|
| 96 |
+
URLS that match one of the filter URLs will be loaded.
|
| 97 |
+
*WARNING* The filter URLs are interpreted as regular expressions.
|
| 98 |
+
Remember to escape special characters if you do not want them to be
|
| 99 |
+
interpreted as regular expression syntax. For example, `.` appears
|
| 100 |
+
frequently in URLs and should be escaped if you want to match a literal
|
| 101 |
+
`.` rather than any character.
|
| 102 |
+
restrict_to_same_domain takes precedence over filter_urls when
|
| 103 |
+
restrict_to_same_domain is True and the sitemap is not a local file.
|
| 104 |
+
parsing_function: Function to parse bs4.Soup output
|
| 105 |
+
blocksize: number of sitemap locations per block
|
| 106 |
+
blocknum: the number of the block that should be loaded - zero indexed.
|
| 107 |
+
Default: 0
|
| 108 |
+
meta_function: Function to parse bs4.Soup output for metadata
|
| 109 |
+
remember when setting this method to also copy metadata["loc"]
|
| 110 |
+
to metadata["source"] if you are using this field
|
| 111 |
+
is_local: whether the sitemap is a local file. Default: False
|
| 112 |
+
continue_on_failure: whether to continue loading the sitemap if an error
|
| 113 |
+
occurs loading a url, emitting a warning instead of raising an
|
| 114 |
+
exception. Setting this to True makes the loader more robust, but also
|
| 115 |
+
may result in missing data. Default: False
|
| 116 |
+
restrict_to_same_domain: whether to restrict loading to URLs to the same
|
| 117 |
+
domain as the sitemap. Attention: This is only applied if the sitemap
|
| 118 |
+
is not a local file!
|
| 119 |
+
max_depth: maximum depth to follow sitemap links. Default: 10
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
if blocksize is not None and blocksize < 1:
|
| 123 |
+
raise ValueError("Sitemap blocksize should be at least 1")
|
| 124 |
+
|
| 125 |
+
if blocknum < 0:
|
| 126 |
+
raise ValueError("Sitemap blocknum can not be lower then 0")
|
| 127 |
+
|
| 128 |
+
try:
|
| 129 |
+
import lxml # noqa:F401
|
| 130 |
+
except ImportError:
|
| 131 |
+
raise ImportError(
|
| 132 |
+
"lxml package not found, please install it with `pip install lxml`"
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
super().__init__(web_paths=[web_path], **kwargs)
|
| 136 |
+
|
| 137 |
+
# Define a list of URL patterns (interpreted as regular expressions) that
|
| 138 |
+
# will be allowed to be loaded.
|
| 139 |
+
# restrict_to_same_domain takes precedence over filter_urls when
|
| 140 |
+
# restrict_to_same_domain is True and the sitemap is not a local file.
|
| 141 |
+
self.allow_url_patterns = filter_urls
|
| 142 |
+
self.restrict_to_same_domain = restrict_to_same_domain
|
| 143 |
+
self.parsing_function = parsing_function or _default_parsing_function
|
| 144 |
+
self.meta_function = meta_function or _default_meta_function
|
| 145 |
+
self.blocksize = blocksize
|
| 146 |
+
self.blocknum = blocknum
|
| 147 |
+
self.is_local = is_local
|
| 148 |
+
self.continue_on_failure = continue_on_failure
|
| 149 |
+
self.max_depth = max_depth
|
| 150 |
+
|
| 151 |
+
def parse_sitemap(self, soup: Any, *, depth: int = 0) -> List[dict]:
|
| 152 |
+
"""Parse sitemap xml and load into a list of dicts.
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
soup: BeautifulSoup object.
|
| 156 |
+
depth: current depth of the sitemap. Default: 0
|
| 157 |
+
|
| 158 |
+
Returns:
|
| 159 |
+
List of dicts.
|
| 160 |
+
"""
|
| 161 |
+
if depth >= self.max_depth:
|
| 162 |
+
return []
|
| 163 |
+
|
| 164 |
+
els: List[Dict] = []
|
| 165 |
+
|
| 166 |
+
for url in soup.find_all("url"):
|
| 167 |
+
loc = url.find("loc")
|
| 168 |
+
if not loc:
|
| 169 |
+
continue
|
| 170 |
+
|
| 171 |
+
# Strip leading and trailing whitespace and newlines
|
| 172 |
+
loc_text = loc.text.strip()
|
| 173 |
+
|
| 174 |
+
if self.restrict_to_same_domain and not self.is_local:
|
| 175 |
+
if _extract_scheme_and_domain(loc_text) != _extract_scheme_and_domain(
|
| 176 |
+
self.web_path
|
| 177 |
+
):
|
| 178 |
+
continue
|
| 179 |
+
|
| 180 |
+
if self.allow_url_patterns and not any(
|
| 181 |
+
re.match(regexp_pattern, loc_text)
|
| 182 |
+
for regexp_pattern in self.allow_url_patterns
|
| 183 |
+
):
|
| 184 |
+
continue
|
| 185 |
+
|
| 186 |
+
els.append(
|
| 187 |
+
{
|
| 188 |
+
tag: prop.text.strip()
|
| 189 |
+
for tag in ["loc", "lastmod", "changefreq", "priority"]
|
| 190 |
+
if (prop := url.find(tag))
|
| 191 |
+
}
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
for sitemap in soup.find_all("sitemap"):
|
| 195 |
+
loc = sitemap.find("loc")
|
| 196 |
+
if not loc:
|
| 197 |
+
continue
|
| 198 |
+
|
| 199 |
+
soup_child = self.scrape_all([loc.text], "xml")[0]
|
| 200 |
+
els.extend(self.parse_sitemap(soup_child, depth=depth + 1))
|
| 201 |
+
return els
|
| 202 |
+
|
| 203 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 204 |
+
"""Load sitemap."""
|
| 205 |
+
if self.is_local:
|
| 206 |
+
try:
|
| 207 |
+
import bs4
|
| 208 |
+
except ImportError:
|
| 209 |
+
raise ImportError(
|
| 210 |
+
"beautifulsoup4 package not found, please install it"
|
| 211 |
+
" with `pip install beautifulsoup4`"
|
| 212 |
+
)
|
| 213 |
+
fp = open(self.web_path)
|
| 214 |
+
soup = bs4.BeautifulSoup(fp, "xml")
|
| 215 |
+
else:
|
| 216 |
+
soup = self._scrape(self.web_path, parser="xml")
|
| 217 |
+
|
| 218 |
+
els = self.parse_sitemap(soup)
|
| 219 |
+
|
| 220 |
+
if self.blocksize is not None:
|
| 221 |
+
elblocks = list(_batch_block(els, self.blocksize))
|
| 222 |
+
blockcount = len(elblocks)
|
| 223 |
+
if blockcount - 1 < self.blocknum:
|
| 224 |
+
raise ValueError(
|
| 225 |
+
"Selected sitemap does not contain enough blocks for given blocknum"
|
| 226 |
+
)
|
| 227 |
+
else:
|
| 228 |
+
els = elblocks[self.blocknum]
|
| 229 |
+
|
| 230 |
+
results = self.scrape_all([el["loc"].strip() for el in els if "loc" in el])
|
| 231 |
+
|
| 232 |
+
for i, result in enumerate(results):
|
| 233 |
+
yield Document(
|
| 234 |
+
page_content=self.parsing_function(result),
|
| 235 |
+
metadata=self.meta_function(els[i], result),
|
| 236 |
+
)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/slack_directory.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import zipfile
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Dict, Iterator, List, Optional, Union
|
| 5 |
+
|
| 6 |
+
from langchain_core.documents import Document
|
| 7 |
+
|
| 8 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SlackDirectoryLoader(BaseLoader):
|
| 12 |
+
"""Load from a `Slack` directory dump."""
|
| 13 |
+
|
| 14 |
+
def __init__(self, zip_path: Union[str, Path], workspace_url: Optional[str] = None):
|
| 15 |
+
"""Initialize the SlackDirectoryLoader.
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
zip_path (str): The path to the Slack directory dump zip file.
|
| 19 |
+
workspace_url (Optional[str]): The Slack workspace URL.
|
| 20 |
+
Including the URL will turn
|
| 21 |
+
sources into links. Defaults to None.
|
| 22 |
+
"""
|
| 23 |
+
self.zip_path = Path(zip_path)
|
| 24 |
+
self.workspace_url = workspace_url
|
| 25 |
+
self.channel_id_map = self._get_channel_id_map(self.zip_path)
|
| 26 |
+
|
| 27 |
+
@staticmethod
|
| 28 |
+
def _get_channel_id_map(zip_path: Path) -> Dict[str, str]:
|
| 29 |
+
"""Get a dictionary mapping channel names to their respective IDs."""
|
| 30 |
+
with zipfile.ZipFile(zip_path, "r") as zip_file:
|
| 31 |
+
try:
|
| 32 |
+
with zip_file.open("channels.json", "r") as f:
|
| 33 |
+
channels = json.load(f)
|
| 34 |
+
return {channel["name"]: channel["id"] for channel in channels}
|
| 35 |
+
except KeyError:
|
| 36 |
+
return {}
|
| 37 |
+
|
| 38 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 39 |
+
"""Load and return documents from the Slack directory dump."""
|
| 40 |
+
with zipfile.ZipFile(self.zip_path, "r") as zip_file:
|
| 41 |
+
for channel_path in zip_file.namelist():
|
| 42 |
+
channel_name = Path(channel_path).parent.name
|
| 43 |
+
if not channel_name:
|
| 44 |
+
continue
|
| 45 |
+
if channel_path.endswith(".json"):
|
| 46 |
+
messages = self._read_json(zip_file, channel_path)
|
| 47 |
+
for message in messages:
|
| 48 |
+
yield self._convert_message_to_document(message, channel_name)
|
| 49 |
+
|
| 50 |
+
def _read_json(self, zip_file: zipfile.ZipFile, file_path: str) -> List[dict]:
|
| 51 |
+
"""Read JSON data from a zip subfile."""
|
| 52 |
+
with zip_file.open(file_path, "r") as f:
|
| 53 |
+
data = json.load(f)
|
| 54 |
+
return data
|
| 55 |
+
|
| 56 |
+
def _convert_message_to_document(
|
| 57 |
+
self, message: dict, channel_name: str
|
| 58 |
+
) -> Document:
|
| 59 |
+
"""
|
| 60 |
+
Convert a message to a Document object.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
message (dict): A message in the form of a dictionary.
|
| 64 |
+
channel_name (str): The name of the channel the message belongs to.
|
| 65 |
+
|
| 66 |
+
Returns:
|
| 67 |
+
Document: A Document object representing the message.
|
| 68 |
+
"""
|
| 69 |
+
text = message.get("text", "")
|
| 70 |
+
metadata = self._get_message_metadata(message, channel_name)
|
| 71 |
+
return Document(
|
| 72 |
+
page_content=text,
|
| 73 |
+
metadata=metadata,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
def _get_message_metadata(self, message: dict, channel_name: str) -> dict:
|
| 77 |
+
"""Create and return metadata for a given message and channel."""
|
| 78 |
+
timestamp = message.get("ts", "")
|
| 79 |
+
user = message.get("user", "")
|
| 80 |
+
source = self._get_message_source(channel_name, user, timestamp)
|
| 81 |
+
return {
|
| 82 |
+
"source": source,
|
| 83 |
+
"channel": channel_name,
|
| 84 |
+
"timestamp": timestamp,
|
| 85 |
+
"user": user,
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
def _get_message_source(self, channel_name: str, user: str, timestamp: str) -> str:
|
| 89 |
+
"""
|
| 90 |
+
Get the message source as a string.
|
| 91 |
+
|
| 92 |
+
Args:
|
| 93 |
+
channel_name (str): The name of the channel the message belongs to.
|
| 94 |
+
user (str): The user ID who sent the message.
|
| 95 |
+
timestamp (str): The timestamp of the message.
|
| 96 |
+
|
| 97 |
+
Returns:
|
| 98 |
+
str: The message source.
|
| 99 |
+
"""
|
| 100 |
+
if self.workspace_url:
|
| 101 |
+
channel_id = self.channel_id_map.get(channel_name, "")
|
| 102 |
+
return (
|
| 103 |
+
f"{self.workspace_url}/archives/{channel_id}"
|
| 104 |
+
+ f"/p{timestamp.replace('.', '')}"
|
| 105 |
+
)
|
| 106 |
+
else:
|
| 107 |
+
return f"{channel_name} - {user} - {timestamp}"
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/snowflake_loader.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any, Dict, Iterator, List, Optional, Tuple
|
| 4 |
+
|
| 5 |
+
from langchain_core.documents import Document
|
| 6 |
+
|
| 7 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class SnowflakeLoader(BaseLoader):
|
| 11 |
+
"""Load from `Snowflake` API.
|
| 12 |
+
|
| 13 |
+
Each document represents one row of the result. The `page_content_columns`
|
| 14 |
+
are written into the `page_content` of the document. The `metadata_columns`
|
| 15 |
+
are written into the `metadata` of the document. By default, all columns
|
| 16 |
+
are written into the `page_content` and none into the `metadata`.
|
| 17 |
+
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def __init__(
|
| 21 |
+
self,
|
| 22 |
+
query: str,
|
| 23 |
+
user: str,
|
| 24 |
+
password: str,
|
| 25 |
+
account: str,
|
| 26 |
+
warehouse: str,
|
| 27 |
+
role: str,
|
| 28 |
+
database: str,
|
| 29 |
+
schema: str,
|
| 30 |
+
parameters: Optional[Dict[str, Any]] = None,
|
| 31 |
+
page_content_columns: Optional[List[str]] = None,
|
| 32 |
+
metadata_columns: Optional[List[str]] = None,
|
| 33 |
+
):
|
| 34 |
+
"""Initialize Snowflake document loader.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
query: The query to run in Snowflake.
|
| 38 |
+
user: Snowflake user.
|
| 39 |
+
password: Snowflake password.
|
| 40 |
+
account: Snowflake account.
|
| 41 |
+
warehouse: Snowflake warehouse.
|
| 42 |
+
role: Snowflake role.
|
| 43 |
+
database: Snowflake database
|
| 44 |
+
schema: Snowflake schema
|
| 45 |
+
parameters: Optional. Parameters to pass to the query.
|
| 46 |
+
page_content_columns: Optional. Columns written to Document `page_content`.
|
| 47 |
+
metadata_columns: Optional. Columns written to Document `metadata`.
|
| 48 |
+
"""
|
| 49 |
+
self.query = query
|
| 50 |
+
self.user = user
|
| 51 |
+
self.password = password
|
| 52 |
+
self.account = account
|
| 53 |
+
self.warehouse = warehouse
|
| 54 |
+
self.role = role
|
| 55 |
+
self.database = database
|
| 56 |
+
self.schema = schema
|
| 57 |
+
self.parameters = parameters
|
| 58 |
+
self.page_content_columns = (
|
| 59 |
+
page_content_columns if page_content_columns is not None else ["*"]
|
| 60 |
+
)
|
| 61 |
+
self.metadata_columns = metadata_columns if metadata_columns is not None else []
|
| 62 |
+
|
| 63 |
+
def _execute_query(self) -> List[Dict[str, Any]]:
|
| 64 |
+
try:
|
| 65 |
+
import snowflake.connector
|
| 66 |
+
except ImportError as ex:
|
| 67 |
+
raise ImportError(
|
| 68 |
+
"Could not import snowflake-connector-python package. "
|
| 69 |
+
"Please install it with `pip install snowflake-connector-python`."
|
| 70 |
+
) from ex
|
| 71 |
+
|
| 72 |
+
conn = snowflake.connector.connect(
|
| 73 |
+
user=self.user,
|
| 74 |
+
password=self.password,
|
| 75 |
+
account=self.account,
|
| 76 |
+
warehouse=self.warehouse,
|
| 77 |
+
role=self.role,
|
| 78 |
+
database=self.database,
|
| 79 |
+
schema=self.schema,
|
| 80 |
+
parameters=self.parameters,
|
| 81 |
+
)
|
| 82 |
+
try:
|
| 83 |
+
cur = conn.cursor()
|
| 84 |
+
cur.execute("USE DATABASE " + self.database)
|
| 85 |
+
cur.execute("USE SCHEMA " + self.schema)
|
| 86 |
+
cur.execute(self.query, self.parameters)
|
| 87 |
+
query_result = cur.fetchall()
|
| 88 |
+
column_names = [column[0] for column in cur.description]
|
| 89 |
+
query_result = [dict(zip(column_names, row)) for row in query_result]
|
| 90 |
+
except Exception as e:
|
| 91 |
+
print(f"An error occurred: {e}") # noqa: T201
|
| 92 |
+
query_result = []
|
| 93 |
+
finally:
|
| 94 |
+
cur.close()
|
| 95 |
+
return query_result
|
| 96 |
+
|
| 97 |
+
def _get_columns(
|
| 98 |
+
self, query_result: List[Dict[str, Any]]
|
| 99 |
+
) -> Tuple[List[str], List[str]]:
|
| 100 |
+
page_content_columns = (
|
| 101 |
+
self.page_content_columns if self.page_content_columns else []
|
| 102 |
+
)
|
| 103 |
+
metadata_columns = self.metadata_columns if self.metadata_columns else []
|
| 104 |
+
if page_content_columns is None and query_result:
|
| 105 |
+
page_content_columns = list(query_result[0].keys())
|
| 106 |
+
if metadata_columns is None:
|
| 107 |
+
metadata_columns = []
|
| 108 |
+
return page_content_columns or [], metadata_columns
|
| 109 |
+
|
| 110 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 111 |
+
query_result = self._execute_query()
|
| 112 |
+
if isinstance(query_result, Exception):
|
| 113 |
+
print(f"An error occurred during the query: {query_result}") # noqa: T201
|
| 114 |
+
return []
|
| 115 |
+
page_content_columns, metadata_columns = self._get_columns(query_result)
|
| 116 |
+
if "*" in page_content_columns:
|
| 117 |
+
page_content_columns = list(query_result[0].keys())
|
| 118 |
+
for row in query_result:
|
| 119 |
+
page_content = "\n".join(
|
| 120 |
+
f"{k}: {v}" for k, v in row.items() if k in page_content_columns
|
| 121 |
+
)
|
| 122 |
+
metadata = {k: v for k, v in row.items() if k in metadata_columns}
|
| 123 |
+
doc = Document(page_content=page_content, metadata=metadata)
|
| 124 |
+
yield doc
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/spider.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Iterator, Literal, Optional
|
| 2 |
+
|
| 3 |
+
from langchain_core.document_loaders import BaseLoader
|
| 4 |
+
from langchain_core.documents import Document
|
| 5 |
+
from langchain_core.utils import get_from_env
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class SpiderLoader(BaseLoader):
|
| 9 |
+
"""Load web pages as Documents using Spider AI.
|
| 10 |
+
|
| 11 |
+
Must have the Python package `spider-client` installed and a Spider API key.
|
| 12 |
+
See https://spider.cloud for more.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
url: str,
|
| 18 |
+
*,
|
| 19 |
+
api_key: Optional[str] = None,
|
| 20 |
+
mode: Literal["scrape", "crawl"] = "scrape",
|
| 21 |
+
params: Optional[dict] = None,
|
| 22 |
+
):
|
| 23 |
+
"""Initialize with API key and URL.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
url: The URL to be processed.
|
| 27 |
+
api_key: The Spider API key. If not specified, will be read from env
|
| 28 |
+
var `SPIDER_API_KEY`.
|
| 29 |
+
mode: The mode to run the loader in. Default is "scrape".
|
| 30 |
+
Options include "scrape" (single page) and "crawl" (with deeper
|
| 31 |
+
crawling following subpages).
|
| 32 |
+
params: Additional parameters for the Spider API.
|
| 33 |
+
"""
|
| 34 |
+
if params is None:
|
| 35 |
+
params = {
|
| 36 |
+
"return_format": "markdown",
|
| 37 |
+
"metadata": True,
|
| 38 |
+
} # Using the metadata param slightly slows down the output
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
from spider import Spider
|
| 42 |
+
except ImportError:
|
| 43 |
+
raise ImportError(
|
| 44 |
+
"`spider` package not found, please run `pip install spider-client`"
|
| 45 |
+
)
|
| 46 |
+
if mode not in ("scrape", "crawl"):
|
| 47 |
+
raise ValueError(
|
| 48 |
+
f"Unrecognized mode '{mode}'. Expected one of 'scrape', 'crawl'."
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# Use the environment variable if the API key isn't provided
|
| 52 |
+
api_key = api_key or get_from_env("api_key", "SPIDER_API_KEY")
|
| 53 |
+
self.spider = Spider(api_key=api_key)
|
| 54 |
+
self.url = url
|
| 55 |
+
self.mode = mode
|
| 56 |
+
self.params = params
|
| 57 |
+
|
| 58 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 59 |
+
"""Load documents based on the specified mode."""
|
| 60 |
+
spider_docs = []
|
| 61 |
+
|
| 62 |
+
if self.mode == "scrape":
|
| 63 |
+
# Scrape a single page
|
| 64 |
+
response = self.spider.scrape_url(self.url, params=self.params)
|
| 65 |
+
if response:
|
| 66 |
+
spider_docs.append(response)
|
| 67 |
+
elif self.mode == "crawl":
|
| 68 |
+
# Crawl multiple pages
|
| 69 |
+
response = self.spider.crawl_url(self.url, params=self.params)
|
| 70 |
+
if response:
|
| 71 |
+
spider_docs.extend(response)
|
| 72 |
+
|
| 73 |
+
for doc in spider_docs:
|
| 74 |
+
if self.mode == "scrape":
|
| 75 |
+
# Ensure page_content is also not None
|
| 76 |
+
page_content = doc[0].get("content", "")
|
| 77 |
+
|
| 78 |
+
# Ensure metadata is also not None
|
| 79 |
+
metadata = doc[0].get("metadata", {})
|
| 80 |
+
|
| 81 |
+
if page_content is not None:
|
| 82 |
+
yield Document(page_content=page_content, metadata=metadata)
|
| 83 |
+
if self.mode == "crawl":
|
| 84 |
+
# Ensure page_content is also not None
|
| 85 |
+
page_content = doc.get("content", "")
|
| 86 |
+
|
| 87 |
+
# Ensure metadata is also not None
|
| 88 |
+
metadata = doc.get("metadata", {})
|
| 89 |
+
|
| 90 |
+
if page_content is not None:
|
| 91 |
+
yield Document(
|
| 92 |
+
page_content=page_content,
|
| 93 |
+
metadata=metadata,
|
| 94 |
+
)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/spreedly.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import urllib.request
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
from langchain_core.documents import Document
|
| 6 |
+
from langchain_core.utils import stringify_dict
|
| 7 |
+
|
| 8 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 9 |
+
|
| 10 |
+
SPREEDLY_ENDPOINTS = {
|
| 11 |
+
"gateways_options": "https://core.spreedly.com/v1/gateways_options.json",
|
| 12 |
+
"gateways": "https://core.spreedly.com/v1/gateways.json",
|
| 13 |
+
"receivers_options": "https://core.spreedly.com/v1/receivers_options.json",
|
| 14 |
+
"receivers": "https://core.spreedly.com/v1/receivers.json",
|
| 15 |
+
"payment_methods": "https://core.spreedly.com/v1/payment_methods.json",
|
| 16 |
+
"certificates": "https://core.spreedly.com/v1/certificates.json",
|
| 17 |
+
"transactions": "https://core.spreedly.com/v1/transactions.json",
|
| 18 |
+
"environments": "https://core.spreedly.com/v1/environments.json",
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class SpreedlyLoader(BaseLoader):
|
| 23 |
+
"""Load from `Spreedly` API."""
|
| 24 |
+
|
| 25 |
+
def __init__(self, access_token: str, resource: str) -> None:
|
| 26 |
+
"""Initialize with an access token and a resource.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
access_token: The access token.
|
| 30 |
+
resource: The resource.
|
| 31 |
+
"""
|
| 32 |
+
self.access_token = access_token
|
| 33 |
+
self.resource = resource
|
| 34 |
+
self.headers = {
|
| 35 |
+
"Authorization": f"Bearer {self.access_token}",
|
| 36 |
+
"Accept": "application/json",
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
def _make_request(self, url: str) -> List[Document]:
|
| 40 |
+
request = urllib.request.Request(url, headers=self.headers)
|
| 41 |
+
|
| 42 |
+
with urllib.request.urlopen(request) as response:
|
| 43 |
+
json_data = json.loads(response.read().decode())
|
| 44 |
+
text = stringify_dict(json_data)
|
| 45 |
+
metadata = {"source": url}
|
| 46 |
+
return [Document(page_content=text, metadata=metadata)]
|
| 47 |
+
|
| 48 |
+
def _get_resource(self) -> List[Document]:
|
| 49 |
+
endpoint = SPREEDLY_ENDPOINTS.get(self.resource)
|
| 50 |
+
if endpoint is None:
|
| 51 |
+
return []
|
| 52 |
+
return self._make_request(endpoint)
|
| 53 |
+
|
| 54 |
+
def load(self) -> List[Document]:
|
| 55 |
+
return self._get_resource()
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/sql_database.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Union
|
| 2 |
+
|
| 3 |
+
from sqlalchemy.engine import RowMapping
|
| 4 |
+
from sqlalchemy.sql.expression import Select
|
| 5 |
+
|
| 6 |
+
from langchain_community.docstore.document import Document
|
| 7 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 8 |
+
from langchain_community.utilities.sql_database import SQLDatabase
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SQLDatabaseLoader(BaseLoader):
|
| 12 |
+
"""
|
| 13 |
+
Load documents by querying database tables supported by SQLAlchemy.
|
| 14 |
+
|
| 15 |
+
For talking to the database, the document loader uses the `SQLDatabase`
|
| 16 |
+
utility from the LangChain integration toolkit.
|
| 17 |
+
|
| 18 |
+
Each document represents one row of the result.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
def __init__(
|
| 22 |
+
self,
|
| 23 |
+
query: Union[str, Select],
|
| 24 |
+
db: SQLDatabase,
|
| 25 |
+
*,
|
| 26 |
+
parameters: Optional[Dict[str, Any]] = None,
|
| 27 |
+
page_content_mapper: Optional[Callable[..., str]] = None,
|
| 28 |
+
metadata_mapper: Optional[Callable[..., Dict[str, Any]]] = None,
|
| 29 |
+
source_columns: Optional[Sequence[str]] = None,
|
| 30 |
+
include_rownum_into_metadata: bool = False,
|
| 31 |
+
include_query_into_metadata: bool = False,
|
| 32 |
+
):
|
| 33 |
+
"""
|
| 34 |
+
Args:
|
| 35 |
+
query: The query to execute.
|
| 36 |
+
db: A LangChain `SQLDatabase`, wrapping an SQLAlchemy engine.
|
| 37 |
+
sqlalchemy_kwargs: More keyword arguments for SQLAlchemy's `create_engine`.
|
| 38 |
+
parameters: Optional. Parameters to pass to the query.
|
| 39 |
+
page_content_mapper: Optional. Function to convert a row into a string
|
| 40 |
+
to use as the `page_content` of the document. By default, the loader
|
| 41 |
+
serializes the whole row into a string, including all columns.
|
| 42 |
+
metadata_mapper: Optional. Function to convert a row into a dictionary
|
| 43 |
+
to use as the `metadata` of the document. By default, no columns are
|
| 44 |
+
selected into the metadata dictionary.
|
| 45 |
+
source_columns: Optional. The names of the columns to use as the `source`
|
| 46 |
+
within the metadata dictionary.
|
| 47 |
+
include_rownum_into_metadata: Optional. Whether to include the row number
|
| 48 |
+
into the metadata dictionary. Default: False.
|
| 49 |
+
include_query_into_metadata: Optional. Whether to include the query
|
| 50 |
+
expression into the metadata dictionary. Default: False.
|
| 51 |
+
"""
|
| 52 |
+
self.query = query
|
| 53 |
+
self.db: SQLDatabase = db
|
| 54 |
+
self.parameters = parameters or {}
|
| 55 |
+
self.page_content_mapper = (
|
| 56 |
+
page_content_mapper or self.page_content_default_mapper
|
| 57 |
+
)
|
| 58 |
+
self.metadata_mapper = metadata_mapper or self.metadata_default_mapper
|
| 59 |
+
self.source_columns = source_columns
|
| 60 |
+
self.include_rownum_into_metadata = include_rownum_into_metadata
|
| 61 |
+
self.include_query_into_metadata = include_query_into_metadata
|
| 62 |
+
|
| 63 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 64 |
+
try:
|
| 65 |
+
import sqlalchemy as sa
|
| 66 |
+
except ImportError:
|
| 67 |
+
raise ImportError(
|
| 68 |
+
"Could not import sqlalchemy python package. "
|
| 69 |
+
"Please install it with `pip install sqlalchemy`."
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
# Querying in `cursor` fetch mode will return an SQLAlchemy `Result` instance.
|
| 73 |
+
result: sa.Result[Any]
|
| 74 |
+
|
| 75 |
+
# Invoke the database query.
|
| 76 |
+
if isinstance(self.query, sa.SelectBase):
|
| 77 |
+
result = self.db._execute( # type: ignore[assignment]
|
| 78 |
+
self.query, fetch="cursor", parameters=self.parameters
|
| 79 |
+
)
|
| 80 |
+
query_sql = str(self.query.compile(bind=self.db._engine))
|
| 81 |
+
elif isinstance(self.query, str):
|
| 82 |
+
result = self.db._execute( # type: ignore[assignment]
|
| 83 |
+
sa.text(self.query), fetch="cursor", parameters=self.parameters
|
| 84 |
+
)
|
| 85 |
+
query_sql = self.query
|
| 86 |
+
else:
|
| 87 |
+
raise TypeError(f"Unable to process query of unknown type: {self.query}")
|
| 88 |
+
|
| 89 |
+
# Iterate database result rows and generate list of documents.
|
| 90 |
+
for i, row in enumerate(result.mappings()):
|
| 91 |
+
page_content = self.page_content_mapper(row)
|
| 92 |
+
metadata = self.metadata_mapper(row)
|
| 93 |
+
|
| 94 |
+
if self.include_rownum_into_metadata:
|
| 95 |
+
metadata["row"] = i
|
| 96 |
+
if self.include_query_into_metadata:
|
| 97 |
+
metadata["query"] = query_sql
|
| 98 |
+
|
| 99 |
+
source_values = []
|
| 100 |
+
for column, value in row.items():
|
| 101 |
+
if self.source_columns and column in self.source_columns:
|
| 102 |
+
source_values.append(value)
|
| 103 |
+
if source_values:
|
| 104 |
+
metadata["source"] = ",".join(source_values)
|
| 105 |
+
|
| 106 |
+
yield Document(page_content=page_content, metadata=metadata)
|
| 107 |
+
|
| 108 |
+
@staticmethod
|
| 109 |
+
def page_content_default_mapper(
|
| 110 |
+
row: RowMapping, column_names: Optional[List[str]] = None
|
| 111 |
+
) -> str:
|
| 112 |
+
"""
|
| 113 |
+
A reasonable default function to convert a record into a "page content" string.
|
| 114 |
+
"""
|
| 115 |
+
if column_names is None:
|
| 116 |
+
column_names = list(row.keys())
|
| 117 |
+
return "\n".join(
|
| 118 |
+
f"{column}: {value}"
|
| 119 |
+
for column, value in row.items()
|
| 120 |
+
if column in column_names
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
@staticmethod
|
| 124 |
+
def metadata_default_mapper(
|
| 125 |
+
row: RowMapping, column_names: Optional[List[str]] = None
|
| 126 |
+
) -> Dict[str, Any]:
|
| 127 |
+
"""
|
| 128 |
+
A reasonable default function to convert a record into a "metadata" dictionary.
|
| 129 |
+
"""
|
| 130 |
+
if column_names is None:
|
| 131 |
+
return {}
|
| 132 |
+
|
| 133 |
+
metadata: Dict[str, Any] = {}
|
| 134 |
+
for column, value in row.items():
|
| 135 |
+
if column in column_names:
|
| 136 |
+
metadata[column] = value
|
| 137 |
+
return metadata
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/srt.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from typing import List, Union
|
| 3 |
+
|
| 4 |
+
from langchain_core.documents import Document
|
| 5 |
+
|
| 6 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class SRTLoader(BaseLoader):
|
| 10 |
+
"""Load `.srt` (subtitle) files."""
|
| 11 |
+
|
| 12 |
+
def __init__(self, file_path: Union[str, Path]):
|
| 13 |
+
"""Initialize with a file path."""
|
| 14 |
+
try:
|
| 15 |
+
import pysrt # noqa:F401
|
| 16 |
+
except ImportError:
|
| 17 |
+
raise ImportError(
|
| 18 |
+
"package `pysrt` not found, please install it with `pip install pysrt`"
|
| 19 |
+
)
|
| 20 |
+
self.file_path = str(file_path)
|
| 21 |
+
|
| 22 |
+
def load(self) -> List[Document]:
|
| 23 |
+
"""Load using pysrt file."""
|
| 24 |
+
import pysrt
|
| 25 |
+
|
| 26 |
+
parsed_info = pysrt.open(self.file_path)
|
| 27 |
+
text = " ".join([t.text for t in parsed_info])
|
| 28 |
+
metadata = {"source": self.file_path}
|
| 29 |
+
return [Document(page_content=text, metadata=metadata)]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/stripe.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import urllib.request
|
| 3 |
+
from typing import List, Optional
|
| 4 |
+
|
| 5 |
+
from langchain_core.documents import Document
|
| 6 |
+
from langchain_core.utils import get_from_env, stringify_dict
|
| 7 |
+
|
| 8 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 9 |
+
|
| 10 |
+
STRIPE_ENDPOINTS = {
|
| 11 |
+
"balance_transactions": "https://api.stripe.com/v1/balance_transactions",
|
| 12 |
+
"charges": "https://api.stripe.com/v1/charges",
|
| 13 |
+
"customers": "https://api.stripe.com/v1/customers",
|
| 14 |
+
"events": "https://api.stripe.com/v1/events",
|
| 15 |
+
"refunds": "https://api.stripe.com/v1/refunds",
|
| 16 |
+
"disputes": "https://api.stripe.com/v1/disputes",
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class StripeLoader(BaseLoader):
|
| 21 |
+
"""Load from `Stripe` API."""
|
| 22 |
+
|
| 23 |
+
def __init__(self, resource: str, access_token: Optional[str] = None) -> None:
|
| 24 |
+
"""Initialize with a resource and an access token.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
resource: The resource.
|
| 28 |
+
access_token: The access token.
|
| 29 |
+
"""
|
| 30 |
+
self.resource = resource
|
| 31 |
+
access_token = access_token or get_from_env(
|
| 32 |
+
"access_token", "STRIPE_ACCESS_TOKEN"
|
| 33 |
+
)
|
| 34 |
+
self.headers = {"Authorization": f"Bearer {access_token}"}
|
| 35 |
+
|
| 36 |
+
def _make_request(self, url: str) -> List[Document]:
|
| 37 |
+
request = urllib.request.Request(url, headers=self.headers)
|
| 38 |
+
|
| 39 |
+
with urllib.request.urlopen(request) as response:
|
| 40 |
+
json_data = json.loads(response.read().decode())
|
| 41 |
+
text = stringify_dict(json_data)
|
| 42 |
+
metadata = {"source": url}
|
| 43 |
+
return [Document(page_content=text, metadata=metadata)]
|
| 44 |
+
|
| 45 |
+
def _get_resource(self) -> List[Document]:
|
| 46 |
+
endpoint = STRIPE_ENDPOINTS.get(self.resource)
|
| 47 |
+
if endpoint is None:
|
| 48 |
+
return []
|
| 49 |
+
return self._make_request(endpoint)
|
| 50 |
+
|
| 51 |
+
def load(self) -> List[Document]:
|
| 52 |
+
return self._get_resource()
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/surrealdb.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Any, Dict, List, Optional
|
| 5 |
+
|
| 6 |
+
from langchain_core.documents import Document
|
| 7 |
+
|
| 8 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class SurrealDBLoader(BaseLoader):
|
| 14 |
+
"""Load SurrealDB documents."""
|
| 15 |
+
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
filter_criteria: Optional[Dict] = None,
|
| 19 |
+
**kwargs: Any,
|
| 20 |
+
) -> None:
|
| 21 |
+
try:
|
| 22 |
+
from surrealdb import Surreal
|
| 23 |
+
except ImportError as e:
|
| 24 |
+
raise ImportError(
|
| 25 |
+
"""Cannot import from surrealdb.
|
| 26 |
+
please install with `pip install surrealdb`."""
|
| 27 |
+
) from e
|
| 28 |
+
|
| 29 |
+
self.dburl = kwargs.pop("dburl", "ws://localhost:8000/rpc")
|
| 30 |
+
|
| 31 |
+
if self.dburl[0:2] == "ws":
|
| 32 |
+
self.sdb = Surreal(self.dburl)
|
| 33 |
+
else:
|
| 34 |
+
raise ValueError("Only websocket connections are supported at this time.")
|
| 35 |
+
|
| 36 |
+
self.filter_criteria = filter_criteria or {}
|
| 37 |
+
|
| 38 |
+
if "table" in self.filter_criteria:
|
| 39 |
+
raise ValueError(
|
| 40 |
+
"key `table` is not a valid criteria for `filter_criteria` argument."
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
self.ns = kwargs.pop("ns", "langchain")
|
| 44 |
+
self.db = kwargs.pop("db", "database")
|
| 45 |
+
self.table = kwargs.pop("table", "documents")
|
| 46 |
+
self.sdb = Surreal(self.dburl)
|
| 47 |
+
self.kwargs = kwargs
|
| 48 |
+
|
| 49 |
+
async def initialize(self) -> None:
|
| 50 |
+
"""
|
| 51 |
+
Initialize connection to surrealdb database
|
| 52 |
+
and authenticate if credentials are provided
|
| 53 |
+
"""
|
| 54 |
+
await self.sdb.connect()
|
| 55 |
+
if "db_user" in self.kwargs and "db_pass" in self.kwargs:
|
| 56 |
+
user = self.kwargs.get("db_user")
|
| 57 |
+
password = self.kwargs.get("db_pass")
|
| 58 |
+
await self.sdb.signin({"user": user, "pass": password})
|
| 59 |
+
|
| 60 |
+
await self.sdb.use(self.ns, self.db)
|
| 61 |
+
|
| 62 |
+
def load(self) -> List[Document]:
|
| 63 |
+
async def _load() -> List[Document]:
|
| 64 |
+
await self.initialize()
|
| 65 |
+
return await self.aload()
|
| 66 |
+
|
| 67 |
+
return asyncio.run(_load())
|
| 68 |
+
|
| 69 |
+
async def aload(self) -> List[Document]:
|
| 70 |
+
"""Load data into Document objects."""
|
| 71 |
+
|
| 72 |
+
query = "SELECT * FROM type::table($table)"
|
| 73 |
+
if self.filter_criteria is not None and len(self.filter_criteria) > 0:
|
| 74 |
+
query += " WHERE "
|
| 75 |
+
for idx, key in enumerate(self.filter_criteria):
|
| 76 |
+
query += f""" {"AND" if idx > 0 else ""} {key} = ${key}"""
|
| 77 |
+
|
| 78 |
+
metadata = {
|
| 79 |
+
"ns": self.ns,
|
| 80 |
+
"db": self.db,
|
| 81 |
+
"table": self.table,
|
| 82 |
+
}
|
| 83 |
+
results = await self.sdb.query(
|
| 84 |
+
query, {"table": self.table, **self.filter_criteria}
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
return [
|
| 88 |
+
(
|
| 89 |
+
Document(
|
| 90 |
+
page_content=json.dumps(result),
|
| 91 |
+
metadata={"id": result["id"], **result["metadata"], **metadata},
|
| 92 |
+
)
|
| 93 |
+
)
|
| 94 |
+
for result in results[0]["result"]
|
| 95 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/telegram.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import TYPE_CHECKING, Dict, List, Optional, Union
|
| 7 |
+
|
| 8 |
+
from langchain_core.documents import Document
|
| 9 |
+
|
| 10 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 11 |
+
|
| 12 |
+
if TYPE_CHECKING:
|
| 13 |
+
import pandas as pd
|
| 14 |
+
from telethon.hints import EntityLike
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def concatenate_rows(row: dict) -> str:
|
| 18 |
+
"""Combine message information in a readable format ready to be used."""
|
| 19 |
+
date = row["date"]
|
| 20 |
+
sender = row["from"]
|
| 21 |
+
text = row["text"]
|
| 22 |
+
return f"{sender} on {date}: {text}\n\n"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class TelegramChatFileLoader(BaseLoader):
|
| 26 |
+
"""Load from `Telegram chat` dump."""
|
| 27 |
+
|
| 28 |
+
def __init__(self, path: Union[str, Path]):
|
| 29 |
+
"""Initialize with a path."""
|
| 30 |
+
self.file_path = path
|
| 31 |
+
|
| 32 |
+
def load(self) -> List[Document]:
|
| 33 |
+
"""Load documents."""
|
| 34 |
+
p = Path(self.file_path)
|
| 35 |
+
|
| 36 |
+
with open(p, encoding="utf8") as f:
|
| 37 |
+
d = json.load(f)
|
| 38 |
+
|
| 39 |
+
text = "".join(
|
| 40 |
+
concatenate_rows(message)
|
| 41 |
+
for message in d["messages"]
|
| 42 |
+
if message["type"] == "message" and isinstance(message["text"], str)
|
| 43 |
+
)
|
| 44 |
+
metadata = {"source": str(p)}
|
| 45 |
+
|
| 46 |
+
return [Document(page_content=text, metadata=metadata)]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def text_to_docs(text: Union[str, List[str]]) -> List[Document]:
|
| 50 |
+
"""Convert a string or list of strings to a list of Documents with metadata."""
|
| 51 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 52 |
+
|
| 53 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
| 54 |
+
chunk_size=800,
|
| 55 |
+
separators=["\n\n", "\n", ".", "!", "?", ",", " ", ""],
|
| 56 |
+
chunk_overlap=20,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
if isinstance(text, str):
|
| 60 |
+
# Take a single string as one page
|
| 61 |
+
text = [text]
|
| 62 |
+
page_docs = [Document(page_content=page) for page in text]
|
| 63 |
+
|
| 64 |
+
# Add page numbers as metadata
|
| 65 |
+
for i, doc in enumerate(page_docs):
|
| 66 |
+
doc.metadata["page"] = i + 1
|
| 67 |
+
|
| 68 |
+
# Split pages into chunks
|
| 69 |
+
doc_chunks = []
|
| 70 |
+
|
| 71 |
+
for doc in page_docs:
|
| 72 |
+
chunks = text_splitter.split_text(doc.page_content)
|
| 73 |
+
for i, chunk in enumerate(chunks):
|
| 74 |
+
doc = Document(
|
| 75 |
+
page_content=chunk, metadata={"page": doc.metadata["page"], "chunk": i}
|
| 76 |
+
)
|
| 77 |
+
# Add sources a metadata
|
| 78 |
+
doc.metadata["source"] = f"{doc.metadata['page']}-{doc.metadata['chunk']}"
|
| 79 |
+
doc_chunks.append(doc)
|
| 80 |
+
return doc_chunks
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class TelegramChatApiLoader(BaseLoader):
|
| 84 |
+
"""Load `Telegram` chat json directory dump."""
|
| 85 |
+
|
| 86 |
+
def __init__(
|
| 87 |
+
self,
|
| 88 |
+
chat_entity: Optional[EntityLike] = None,
|
| 89 |
+
api_id: Optional[int] = None,
|
| 90 |
+
api_hash: Optional[str] = None,
|
| 91 |
+
username: Optional[str] = None,
|
| 92 |
+
file_path: str = "telegram_data.json",
|
| 93 |
+
):
|
| 94 |
+
"""Initialize with API parameters.
|
| 95 |
+
|
| 96 |
+
Args:
|
| 97 |
+
chat_entity: The chat entity to fetch data from.
|
| 98 |
+
api_id: The API ID.
|
| 99 |
+
api_hash: The API hash.
|
| 100 |
+
username: The username.
|
| 101 |
+
file_path: The file path to save the data to. Defaults to
|
| 102 |
+
"telegram_data.json".
|
| 103 |
+
"""
|
| 104 |
+
self.chat_entity = chat_entity
|
| 105 |
+
self.api_id = api_id
|
| 106 |
+
self.api_hash = api_hash
|
| 107 |
+
self.username = username
|
| 108 |
+
self.file_path = file_path
|
| 109 |
+
|
| 110 |
+
async def fetch_data_from_telegram(self) -> None:
|
| 111 |
+
"""Fetch data from Telegram API and save it as a JSON file."""
|
| 112 |
+
from telethon.sync import TelegramClient
|
| 113 |
+
|
| 114 |
+
data = []
|
| 115 |
+
async with TelegramClient(self.username, self.api_id, self.api_hash) as client:
|
| 116 |
+
async for message in client.iter_messages(self.chat_entity):
|
| 117 |
+
is_reply = message.reply_to is not None
|
| 118 |
+
reply_to_id = message.reply_to.reply_to_msg_id if is_reply else None
|
| 119 |
+
data.append(
|
| 120 |
+
{
|
| 121 |
+
"sender_id": message.sender_id,
|
| 122 |
+
"text": message.text,
|
| 123 |
+
"date": message.date.isoformat(),
|
| 124 |
+
"message.id": message.id,
|
| 125 |
+
"is_reply": is_reply,
|
| 126 |
+
"reply_to_id": reply_to_id,
|
| 127 |
+
}
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
with open(self.file_path, "w", encoding="utf-8") as f:
|
| 131 |
+
json.dump(data, f, ensure_ascii=False, indent=4)
|
| 132 |
+
|
| 133 |
+
def _get_message_threads(self, data: pd.DataFrame) -> dict:
|
| 134 |
+
"""Create a dictionary of message threads from the given data.
|
| 135 |
+
|
| 136 |
+
Args:
|
| 137 |
+
data (pd.DataFrame): A DataFrame containing the conversation \
|
| 138 |
+
data with columns:
|
| 139 |
+
- message.sender_id
|
| 140 |
+
- text
|
| 141 |
+
- date
|
| 142 |
+
- message.id
|
| 143 |
+
- is_reply
|
| 144 |
+
- reply_to_id
|
| 145 |
+
|
| 146 |
+
Returns:
|
| 147 |
+
dict: A dictionary where the key is the parent message ID and \
|
| 148 |
+
the value is a list of message IDs in ascending order.
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
def find_replies(parent_id: int, reply_data: pd.DataFrame) -> List[int]:
|
| 152 |
+
"""
|
| 153 |
+
Recursively find all replies to a given parent message ID.
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
parent_id (int): The parent message ID.
|
| 157 |
+
reply_data (pd.DataFrame): A DataFrame containing reply messages.
|
| 158 |
+
|
| 159 |
+
Returns:
|
| 160 |
+
list: A list of message IDs that are replies to the parent message ID.
|
| 161 |
+
"""
|
| 162 |
+
# Find direct replies to the parent message ID
|
| 163 |
+
direct_replies = reply_data[reply_data["reply_to_id"] == parent_id][
|
| 164 |
+
"message.id"
|
| 165 |
+
].tolist()
|
| 166 |
+
|
| 167 |
+
# Recursively find replies to the direct replies
|
| 168 |
+
all_replies = []
|
| 169 |
+
for reply_id in direct_replies:
|
| 170 |
+
all_replies += [reply_id] + find_replies(reply_id, reply_data)
|
| 171 |
+
|
| 172 |
+
return all_replies
|
| 173 |
+
|
| 174 |
+
# Filter out parent messages
|
| 175 |
+
parent_messages = data[~data["is_reply"]]
|
| 176 |
+
|
| 177 |
+
# Filter out reply messages and drop rows with NaN in 'reply_to_id'
|
| 178 |
+
reply_messages = data[data["is_reply"]].dropna(subset=["reply_to_id"])
|
| 179 |
+
|
| 180 |
+
# Convert 'reply_to_id' to integer
|
| 181 |
+
reply_messages["reply_to_id"] = reply_messages["reply_to_id"].astype(int)
|
| 182 |
+
|
| 183 |
+
# Create a dictionary of message threads with parent message IDs as keys and \
|
| 184 |
+
# lists of reply message IDs as values
|
| 185 |
+
message_threads = {
|
| 186 |
+
parent_id: [parent_id] + find_replies(parent_id, reply_messages)
|
| 187 |
+
for parent_id in parent_messages["message.id"]
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
return message_threads
|
| 191 |
+
|
| 192 |
+
def _combine_message_texts(
|
| 193 |
+
self, message_threads: Dict[int, List[int]], data: pd.DataFrame
|
| 194 |
+
) -> str:
|
| 195 |
+
"""
|
| 196 |
+
Combine the message texts for each parent message ID based \
|
| 197 |
+
on the list of message threads.
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
message_threads (dict): A dictionary where the key is the parent message \
|
| 201 |
+
ID and the value is a list of message IDs in ascending order.
|
| 202 |
+
data (pd.DataFrame): A DataFrame containing the conversation data:
|
| 203 |
+
- message.sender_id
|
| 204 |
+
- text
|
| 205 |
+
- date
|
| 206 |
+
- message.id
|
| 207 |
+
- is_reply
|
| 208 |
+
- reply_to_id
|
| 209 |
+
|
| 210 |
+
Returns:
|
| 211 |
+
str: A combined string of message texts sorted by date.
|
| 212 |
+
"""
|
| 213 |
+
combined_text = ""
|
| 214 |
+
|
| 215 |
+
# Iterate through sorted parent message IDs
|
| 216 |
+
for parent_id, message_ids in message_threads.items():
|
| 217 |
+
# Get the message texts for the message IDs and sort them by date
|
| 218 |
+
message_texts = (
|
| 219 |
+
data[data["message.id"].isin(message_ids)]
|
| 220 |
+
.sort_values(by="date")["text"]
|
| 221 |
+
.tolist()
|
| 222 |
+
)
|
| 223 |
+
message_texts = [str(elem) for elem in message_texts]
|
| 224 |
+
|
| 225 |
+
# Combine the message texts
|
| 226 |
+
combined_text += " ".join(message_texts) + ".\n"
|
| 227 |
+
|
| 228 |
+
return combined_text.strip()
|
| 229 |
+
|
| 230 |
+
def load(self) -> List[Document]:
|
| 231 |
+
"""Load documents."""
|
| 232 |
+
|
| 233 |
+
if self.chat_entity is not None:
|
| 234 |
+
try:
|
| 235 |
+
import nest_asyncio
|
| 236 |
+
|
| 237 |
+
nest_asyncio.apply()
|
| 238 |
+
asyncio.run(self.fetch_data_from_telegram())
|
| 239 |
+
except ImportError:
|
| 240 |
+
raise ImportError(
|
| 241 |
+
"""`nest_asyncio` package not found.
|
| 242 |
+
please install with `pip install nest_asyncio`
|
| 243 |
+
"""
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
p = Path(self.file_path)
|
| 247 |
+
|
| 248 |
+
with open(p, encoding="utf8") as f:
|
| 249 |
+
d = json.load(f)
|
| 250 |
+
try:
|
| 251 |
+
import pandas as pd
|
| 252 |
+
except ImportError:
|
| 253 |
+
raise ImportError(
|
| 254 |
+
"""`pandas` package not found.
|
| 255 |
+
please install with `pip install pandas`
|
| 256 |
+
"""
|
| 257 |
+
)
|
| 258 |
+
normalized_messages = pd.json_normalize(d)
|
| 259 |
+
df = pd.DataFrame(normalized_messages)
|
| 260 |
+
|
| 261 |
+
message_threads = self._get_message_threads(df)
|
| 262 |
+
combined_texts = self._combine_message_texts(message_threads, df)
|
| 263 |
+
|
| 264 |
+
return text_to_docs(combined_texts)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
# For backwards compatibility
|
| 268 |
+
TelegramChatLoader = TelegramChatFileLoader
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tencent_cos_directory.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Iterator
|
| 2 |
+
|
| 3 |
+
from langchain_core.documents import Document
|
| 4 |
+
|
| 5 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 6 |
+
from langchain_community.document_loaders.tencent_cos_file import TencentCOSFileLoader
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TencentCOSDirectoryLoader(BaseLoader):
|
| 10 |
+
"""Load from `Tencent Cloud COS` directory."""
|
| 11 |
+
|
| 12 |
+
def __init__(self, conf: Any, bucket: str, prefix: str = ""):
|
| 13 |
+
"""Initialize with COS config, bucket and prefix.
|
| 14 |
+
:param conf(CosConfig): COS config.
|
| 15 |
+
:param bucket(str): COS bucket.
|
| 16 |
+
:param prefix(str): prefix.
|
| 17 |
+
"""
|
| 18 |
+
self.conf = conf
|
| 19 |
+
self.bucket = bucket
|
| 20 |
+
self.prefix = prefix
|
| 21 |
+
|
| 22 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 23 |
+
"""Load documents."""
|
| 24 |
+
try:
|
| 25 |
+
from qcloud_cos import CosS3Client
|
| 26 |
+
except ImportError:
|
| 27 |
+
raise ImportError(
|
| 28 |
+
"Could not import cos-python-sdk-v5 python package. "
|
| 29 |
+
"Please install it with `pip install cos-python-sdk-v5`."
|
| 30 |
+
)
|
| 31 |
+
client = CosS3Client(self.conf)
|
| 32 |
+
contents = []
|
| 33 |
+
marker = ""
|
| 34 |
+
while True:
|
| 35 |
+
response = client.list_objects(
|
| 36 |
+
Bucket=self.bucket, Prefix=self.prefix, Marker=marker, MaxKeys=1000
|
| 37 |
+
)
|
| 38 |
+
if "Contents" in response:
|
| 39 |
+
contents.extend(response["Contents"])
|
| 40 |
+
if response["IsTruncated"] == "false":
|
| 41 |
+
break
|
| 42 |
+
marker = response["NextMarker"]
|
| 43 |
+
for content in contents:
|
| 44 |
+
if content["Key"].endswith("/"):
|
| 45 |
+
continue
|
| 46 |
+
loader = TencentCOSFileLoader(self.conf, self.bucket, content["Key"])
|
| 47 |
+
yield loader.load()[0]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tencent_cos_file.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
from typing import Any, Iterator
|
| 4 |
+
|
| 5 |
+
from langchain_core.documents import Document
|
| 6 |
+
|
| 7 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 8 |
+
from langchain_community.document_loaders.unstructured import UnstructuredFileLoader
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TencentCOSFileLoader(BaseLoader):
|
| 12 |
+
"""Load from `Tencent Cloud COS` file."""
|
| 13 |
+
|
| 14 |
+
def __init__(self, conf: Any, bucket: str, key: str):
|
| 15 |
+
"""Initialize with COS config, bucket and key name.
|
| 16 |
+
:param conf(CosConfig): COS config.
|
| 17 |
+
:param bucket(str): COS bucket.
|
| 18 |
+
:param key(str): COS file key.
|
| 19 |
+
"""
|
| 20 |
+
self.conf = conf
|
| 21 |
+
self.bucket = bucket
|
| 22 |
+
self.key = key
|
| 23 |
+
|
| 24 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 25 |
+
"""Load documents."""
|
| 26 |
+
try:
|
| 27 |
+
from qcloud_cos import CosS3Client
|
| 28 |
+
except ImportError:
|
| 29 |
+
raise ImportError(
|
| 30 |
+
"Could not import cos-python-sdk-v5 python package. "
|
| 31 |
+
"Please install it with `pip install cos-python-sdk-v5`."
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
# initialize a client
|
| 35 |
+
client = CosS3Client(self.conf)
|
| 36 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 37 |
+
file_path = f"{temp_dir}/{self.bucket}/{self.key}"
|
| 38 |
+
os.makedirs(os.path.dirname(file_path), exist_ok=True)
|
| 39 |
+
# Download the file to a destination
|
| 40 |
+
client.download_file(
|
| 41 |
+
Bucket=self.bucket, Key=self.key, DestFilePath=file_path
|
| 42 |
+
)
|
| 43 |
+
loader = UnstructuredFileLoader(file_path)
|
| 44 |
+
# UnstructuredFileLoader not implement lazy_load yet
|
| 45 |
+
return iter(loader.load())
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tensorflow_datasets.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable, Dict, Iterator, Optional
|
| 2 |
+
|
| 3 |
+
from langchain_core.documents import Document
|
| 4 |
+
|
| 5 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 6 |
+
from langchain_community.utilities.tensorflow_datasets import TensorflowDatasets
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TensorflowDatasetLoader(BaseLoader):
|
| 10 |
+
"""Load from `TensorFlow Dataset`.
|
| 11 |
+
|
| 12 |
+
Attributes:
|
| 13 |
+
dataset_name: the name of the dataset to load
|
| 14 |
+
split_name: the name of the split to load.
|
| 15 |
+
load_max_docs: a limit to the number of loaded documents. Defaults to 100.
|
| 16 |
+
sample_to_document_function: a function that converts a dataset sample
|
| 17 |
+
into a Document
|
| 18 |
+
|
| 19 |
+
Example:
|
| 20 |
+
.. code-block:: python
|
| 21 |
+
|
| 22 |
+
from langchain_community.document_loaders import TensorflowDatasetLoader
|
| 23 |
+
|
| 24 |
+
def mlqaen_example_to_document(example: dict) -> Document:
|
| 25 |
+
return Document(
|
| 26 |
+
page_content=decode_to_str(example["context"]),
|
| 27 |
+
metadata={
|
| 28 |
+
"id": decode_to_str(example["id"]),
|
| 29 |
+
"title": decode_to_str(example["title"]),
|
| 30 |
+
"question": decode_to_str(example["question"]),
|
| 31 |
+
"answer": decode_to_str(example["answers"]["text"][0]),
|
| 32 |
+
},
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
tsds_client = TensorflowDatasetLoader(
|
| 36 |
+
dataset_name="mlqa/en",
|
| 37 |
+
split_name="test",
|
| 38 |
+
load_max_docs=100,
|
| 39 |
+
sample_to_document_function=mlqaen_example_to_document,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
dataset_name: str,
|
| 47 |
+
split_name: str,
|
| 48 |
+
load_max_docs: Optional[int] = 100,
|
| 49 |
+
sample_to_document_function: Optional[Callable[[Dict], Document]] = None,
|
| 50 |
+
):
|
| 51 |
+
"""Initialize the TensorflowDatasetLoader.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
dataset_name: the name of the dataset to load
|
| 55 |
+
split_name: the name of the split to load.
|
| 56 |
+
load_max_docs: a limit to the number of loaded documents. Defaults to 100.
|
| 57 |
+
sample_to_document_function: a function that converts a dataset sample
|
| 58 |
+
into a Document.
|
| 59 |
+
"""
|
| 60 |
+
self.dataset_name: str = dataset_name
|
| 61 |
+
self.split_name: str = split_name
|
| 62 |
+
self.load_max_docs = load_max_docs
|
| 63 |
+
"""The maximum number of documents to load."""
|
| 64 |
+
self.sample_to_document_function: Optional[Callable[[Dict], Document]] = (
|
| 65 |
+
sample_to_document_function
|
| 66 |
+
)
|
| 67 |
+
"""Custom function that transform a dataset sample into a Document."""
|
| 68 |
+
|
| 69 |
+
self._tfds_client = TensorflowDatasets( # type: ignore[call-arg]
|
| 70 |
+
dataset_name=self.dataset_name,
|
| 71 |
+
split_name=self.split_name,
|
| 72 |
+
load_max_docs=self.load_max_docs, # type: ignore[arg-type]
|
| 73 |
+
sample_to_document_function=self.sample_to_document_function,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 77 |
+
yield from self._tfds_client.lazy_load()
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/text.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Iterator, Optional, Union
|
| 4 |
+
|
| 5 |
+
from langchain_core.documents import Document
|
| 6 |
+
|
| 7 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 8 |
+
from langchain_community.document_loaders.helpers import detect_file_encodings
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TextLoader(BaseLoader):
|
| 14 |
+
"""Load text file.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
file_path: Path to the file to load.
|
| 19 |
+
|
| 20 |
+
encoding: File encoding to use. If `None`, the file will be loaded
|
| 21 |
+
with the default system encoding.
|
| 22 |
+
|
| 23 |
+
autodetect_encoding: Whether to try to autodetect the file encoding
|
| 24 |
+
if the specified encoding fails.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
file_path: Union[str, Path],
|
| 30 |
+
encoding: Optional[str] = None,
|
| 31 |
+
autodetect_encoding: bool = False,
|
| 32 |
+
):
|
| 33 |
+
"""Initialize with file path."""
|
| 34 |
+
self.file_path = file_path
|
| 35 |
+
self.encoding = encoding
|
| 36 |
+
self.autodetect_encoding = autodetect_encoding
|
| 37 |
+
|
| 38 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 39 |
+
"""Load from file path."""
|
| 40 |
+
text = ""
|
| 41 |
+
try:
|
| 42 |
+
with open(self.file_path, encoding=self.encoding) as f:
|
| 43 |
+
text = f.read()
|
| 44 |
+
except UnicodeDecodeError as e:
|
| 45 |
+
if self.autodetect_encoding:
|
| 46 |
+
detected_encodings = detect_file_encodings(self.file_path)
|
| 47 |
+
for encoding in detected_encodings:
|
| 48 |
+
logger.debug(f"Trying encoding: {encoding.encoding}")
|
| 49 |
+
try:
|
| 50 |
+
with open(self.file_path, encoding=encoding.encoding) as f:
|
| 51 |
+
text = f.read()
|
| 52 |
+
break
|
| 53 |
+
except UnicodeDecodeError:
|
| 54 |
+
continue
|
| 55 |
+
else:
|
| 56 |
+
raise RuntimeError(f"Error loading {self.file_path}") from e
|
| 57 |
+
except Exception as e:
|
| 58 |
+
raise RuntimeError(f"Error loading {self.file_path}") from e
|
| 59 |
+
|
| 60 |
+
metadata = {"source": str(self.file_path)}
|
| 61 |
+
yield Document(page_content=text, metadata=metadata)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tidb.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, Iterator, List, Optional
|
| 2 |
+
|
| 3 |
+
from langchain_core.documents import Document
|
| 4 |
+
|
| 5 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TiDBLoader(BaseLoader):
|
| 9 |
+
"""Load documents from TiDB."""
|
| 10 |
+
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
connection_string: str,
|
| 14 |
+
query: str,
|
| 15 |
+
page_content_columns: Optional[List[str]] = None,
|
| 16 |
+
metadata_columns: Optional[List[str]] = None,
|
| 17 |
+
engine_args: Optional[Dict[str, Any]] = None,
|
| 18 |
+
) -> None:
|
| 19 |
+
"""Initialize TiDB document loader.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
connection_string (str): The connection string for the TiDB database,
|
| 23 |
+
format: "mysql+pymysql://root@127.0.0.1:4000/test".
|
| 24 |
+
query: The query to run in TiDB.
|
| 25 |
+
page_content_columns: Optional. Columns written to Document `page_content`,
|
| 26 |
+
default(None) to all columns.
|
| 27 |
+
metadata_columns: Optional. Columns written to Document `metadata`,
|
| 28 |
+
default(None) to no columns.
|
| 29 |
+
engine_args: Optional. Additional arguments to pass to sqlalchemy engine.
|
| 30 |
+
"""
|
| 31 |
+
self.connection_string = connection_string
|
| 32 |
+
self.query = query
|
| 33 |
+
self.page_content_columns = page_content_columns
|
| 34 |
+
self.metadata_columns = metadata_columns if metadata_columns is not None else []
|
| 35 |
+
self.engine_args = engine_args
|
| 36 |
+
|
| 37 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 38 |
+
"""Lazy load TiDB data into document objects."""
|
| 39 |
+
|
| 40 |
+
from sqlalchemy import create_engine
|
| 41 |
+
from sqlalchemy.engine import Engine
|
| 42 |
+
from sqlalchemy.sql import text
|
| 43 |
+
|
| 44 |
+
# use sqlalchemy to create db connection
|
| 45 |
+
engine: Engine = create_engine(
|
| 46 |
+
self.connection_string, **(self.engine_args or {})
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# execute query
|
| 50 |
+
with engine.connect() as conn:
|
| 51 |
+
result = conn.execute(text(self.query))
|
| 52 |
+
|
| 53 |
+
# convert result to Document objects
|
| 54 |
+
column_names = list(result.keys())
|
| 55 |
+
for row in result:
|
| 56 |
+
# convert row to dict{column:value}
|
| 57 |
+
row_data = {
|
| 58 |
+
column_names[index]: value for index, value in enumerate(row)
|
| 59 |
+
}
|
| 60 |
+
page_content = "\n".join(
|
| 61 |
+
f"{k}: {v}"
|
| 62 |
+
for k, v in row_data.items()
|
| 63 |
+
if self.page_content_columns is None
|
| 64 |
+
or k in self.page_content_columns
|
| 65 |
+
)
|
| 66 |
+
metadata = {col: row_data[col] for col in self.metadata_columns}
|
| 67 |
+
yield Document(page_content=page_content, metadata=metadata)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tomarkdown.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Iterator
|
| 4 |
+
|
| 5 |
+
import requests
|
| 6 |
+
from langchain_core.documents import Document
|
| 7 |
+
|
| 8 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ToMarkdownLoader(BaseLoader):
|
| 12 |
+
"""Load `HTML` using `2markdown API`."""
|
| 13 |
+
|
| 14 |
+
def __init__(self, url: str, api_key: str):
|
| 15 |
+
"""Initialize with url and api key."""
|
| 16 |
+
self.url = url
|
| 17 |
+
self.api_key = api_key
|
| 18 |
+
|
| 19 |
+
def lazy_load(
|
| 20 |
+
self,
|
| 21 |
+
) -> Iterator[Document]:
|
| 22 |
+
"""Lazily load the file."""
|
| 23 |
+
response = requests.post(
|
| 24 |
+
"https://api.2markdown.com/v1/url2md",
|
| 25 |
+
headers={"X-Api-Key": self.api_key},
|
| 26 |
+
json={"url": self.url},
|
| 27 |
+
)
|
| 28 |
+
text = response.json()["article"]
|
| 29 |
+
metadata = {"source": self.url}
|
| 30 |
+
yield Document(page_content=text, metadata=metadata)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/toml.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Iterator, Union
|
| 4 |
+
|
| 5 |
+
from langchain_core.documents import Document
|
| 6 |
+
|
| 7 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TomlLoader(BaseLoader):
|
| 11 |
+
"""Load `TOML` files.
|
| 12 |
+
|
| 13 |
+
It can load a single source file or several files in a single
|
| 14 |
+
directory.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(self, source: Union[str, Path]):
|
| 18 |
+
"""Initialize the TomlLoader with a source file or directory."""
|
| 19 |
+
self.source = Path(source)
|
| 20 |
+
|
| 21 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 22 |
+
"""Lazily load the TOML documents from the source file or directory."""
|
| 23 |
+
import tomli
|
| 24 |
+
|
| 25 |
+
if self.source.is_file() and self.source.suffix == ".toml":
|
| 26 |
+
files = [self.source]
|
| 27 |
+
elif self.source.is_dir():
|
| 28 |
+
files = list(self.source.glob("**/*.toml"))
|
| 29 |
+
else:
|
| 30 |
+
raise ValueError("Invalid source path or file type")
|
| 31 |
+
|
| 32 |
+
for file_path in files:
|
| 33 |
+
with file_path.open("r", encoding="utf-8") as file:
|
| 34 |
+
content = file.read()
|
| 35 |
+
try:
|
| 36 |
+
data = tomli.loads(content)
|
| 37 |
+
doc = Document(
|
| 38 |
+
page_content=json.dumps(data),
|
| 39 |
+
metadata={"source": str(file_path)},
|
| 40 |
+
)
|
| 41 |
+
yield doc
|
| 42 |
+
except tomli.TOMLDecodeError as e:
|
| 43 |
+
print(f"Error parsing TOML file {file_path}: {e}") # noqa: T201
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/trello.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Any, Iterator, Literal, Optional, Tuple
|
| 4 |
+
|
| 5 |
+
from langchain_core.documents import Document
|
| 6 |
+
from langchain_core.utils import get_from_env
|
| 7 |
+
|
| 8 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from trello import Board, Card, TrelloClient
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TrelloLoader(BaseLoader):
|
| 15 |
+
"""Load cards from a `Trello` board."""
|
| 16 |
+
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
client: TrelloClient,
|
| 20 |
+
board_name: str,
|
| 21 |
+
*,
|
| 22 |
+
include_card_name: bool = True,
|
| 23 |
+
include_comments: bool = True,
|
| 24 |
+
include_checklist: bool = True,
|
| 25 |
+
card_filter: Literal["closed", "open", "all"] = "all",
|
| 26 |
+
extra_metadata: Tuple[str, ...] = ("due_date", "labels", "list", "closed"),
|
| 27 |
+
):
|
| 28 |
+
"""Initialize Trello loader.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
client: Trello API client.
|
| 32 |
+
board_name: The name of the Trello board.
|
| 33 |
+
include_card_name: Whether to include the name of the card in the document.
|
| 34 |
+
include_comments: Whether to include the comments on the card in the
|
| 35 |
+
document.
|
| 36 |
+
include_checklist: Whether to include the checklist on the card in the
|
| 37 |
+
document.
|
| 38 |
+
card_filter: Filter on card status. Valid values are "closed", "open",
|
| 39 |
+
"all".
|
| 40 |
+
extra_metadata: List of additional metadata fields to include as document
|
| 41 |
+
metadata.Valid values are "due_date", "labels", "list", "closed".
|
| 42 |
+
|
| 43 |
+
"""
|
| 44 |
+
self.client = client
|
| 45 |
+
self.board_name = board_name
|
| 46 |
+
self.include_card_name = include_card_name
|
| 47 |
+
self.include_comments = include_comments
|
| 48 |
+
self.include_checklist = include_checklist
|
| 49 |
+
self.extra_metadata = extra_metadata
|
| 50 |
+
self.card_filter = card_filter
|
| 51 |
+
|
| 52 |
+
@classmethod
|
| 53 |
+
def from_credentials(
|
| 54 |
+
cls,
|
| 55 |
+
board_name: str,
|
| 56 |
+
*,
|
| 57 |
+
api_key: Optional[str] = None,
|
| 58 |
+
token: Optional[str] = None,
|
| 59 |
+
**kwargs: Any,
|
| 60 |
+
) -> TrelloLoader:
|
| 61 |
+
"""Convenience constructor that builds TrelloClient init param for you.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
board_name: The name of the Trello board.
|
| 65 |
+
api_key: Trello API key. Can also be specified as environment variable
|
| 66 |
+
TRELLO_API_KEY.
|
| 67 |
+
token: Trello token. Can also be specified as environment variable
|
| 68 |
+
TRELLO_TOKEN.
|
| 69 |
+
include_card_name: Whether to include the name of the card in the document.
|
| 70 |
+
include_comments: Whether to include the comments on the card in the
|
| 71 |
+
document.
|
| 72 |
+
include_checklist: Whether to include the checklist on the card in the
|
| 73 |
+
document.
|
| 74 |
+
card_filter: Filter on card status. Valid values are "closed", "open",
|
| 75 |
+
"all".
|
| 76 |
+
extra_metadata: List of additional metadata fields to include as document
|
| 77 |
+
metadata.Valid values are "due_date", "labels", "list", "closed".
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
try:
|
| 81 |
+
from trello import TrelloClient
|
| 82 |
+
except ImportError as ex:
|
| 83 |
+
raise ImportError(
|
| 84 |
+
"Could not import trello python package. "
|
| 85 |
+
"Please install it with `pip install py-trello`."
|
| 86 |
+
) from ex
|
| 87 |
+
api_key = api_key or get_from_env("api_key", "TRELLO_API_KEY")
|
| 88 |
+
token = token or get_from_env("token", "TRELLO_TOKEN")
|
| 89 |
+
client = TrelloClient(api_key=api_key, token=token)
|
| 90 |
+
return cls(client, board_name, **kwargs)
|
| 91 |
+
|
| 92 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 93 |
+
"""Loads all cards from the specified Trello board.
|
| 94 |
+
|
| 95 |
+
You can filter the cards, metadata and text included by using the optional
|
| 96 |
+
parameters.
|
| 97 |
+
|
| 98 |
+
Returns:
|
| 99 |
+
A list of documents, one for each card in the board.
|
| 100 |
+
"""
|
| 101 |
+
try:
|
| 102 |
+
from bs4 import BeautifulSoup # noqa: F401
|
| 103 |
+
except ImportError as ex:
|
| 104 |
+
raise ImportError(
|
| 105 |
+
"`beautifulsoup4` package not found, please run"
|
| 106 |
+
" `pip install beautifulsoup4`"
|
| 107 |
+
) from ex
|
| 108 |
+
|
| 109 |
+
board = self._get_board()
|
| 110 |
+
# Create a dictionary with the list IDs as keys and the list names as values
|
| 111 |
+
list_dict = {list_item.id: list_item.name for list_item in board.list_lists()}
|
| 112 |
+
# Get Cards on the board
|
| 113 |
+
cards = board.get_cards(card_filter=self.card_filter)
|
| 114 |
+
for card in cards:
|
| 115 |
+
yield self._card_to_doc(card, list_dict)
|
| 116 |
+
|
| 117 |
+
def _get_board(self) -> Board:
|
| 118 |
+
# Find the first board with a matching name
|
| 119 |
+
board = next(
|
| 120 |
+
(b for b in self.client.list_boards() if b.name == self.board_name), None
|
| 121 |
+
)
|
| 122 |
+
if not board:
|
| 123 |
+
raise ValueError(f"Board `{self.board_name}` not found.")
|
| 124 |
+
return board
|
| 125 |
+
|
| 126 |
+
def _card_to_doc(self, card: Card, list_dict: dict) -> Document:
|
| 127 |
+
from bs4 import BeautifulSoup
|
| 128 |
+
|
| 129 |
+
text_content = ""
|
| 130 |
+
if self.include_card_name:
|
| 131 |
+
text_content = card.name + "\n"
|
| 132 |
+
if card.description.strip():
|
| 133 |
+
text_content += BeautifulSoup(card.description, "lxml").get_text()
|
| 134 |
+
if self.include_checklist:
|
| 135 |
+
# Get all the checklist items on the card
|
| 136 |
+
for checklist in card.checklists:
|
| 137 |
+
if checklist.items:
|
| 138 |
+
items = [
|
| 139 |
+
f"{item['name']}:{item['state']}" for item in checklist.items
|
| 140 |
+
]
|
| 141 |
+
text_content += f"\n{checklist.name}\n" + "\n".join(items)
|
| 142 |
+
|
| 143 |
+
if self.include_comments:
|
| 144 |
+
# Get all the comments on the card
|
| 145 |
+
comments = [
|
| 146 |
+
BeautifulSoup(comment["data"]["text"], "lxml").get_text()
|
| 147 |
+
for comment in card.comments
|
| 148 |
+
]
|
| 149 |
+
text_content += "Comments:" + "\n".join(comments)
|
| 150 |
+
|
| 151 |
+
# Default metadata fields
|
| 152 |
+
metadata = {
|
| 153 |
+
"title": card.name,
|
| 154 |
+
"id": card.id,
|
| 155 |
+
"url": card.url,
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
# Extra metadata fields. Card object is not subscriptable.
|
| 159 |
+
if "labels" in self.extra_metadata:
|
| 160 |
+
metadata["labels"] = [label.name for label in card.labels]
|
| 161 |
+
if "list" in self.extra_metadata:
|
| 162 |
+
if card.list_id in list_dict:
|
| 163 |
+
metadata["list"] = list_dict[card.list_id]
|
| 164 |
+
if "closed" in self.extra_metadata:
|
| 165 |
+
metadata["closed"] = card.closed
|
| 166 |
+
if "due_date" in self.extra_metadata:
|
| 167 |
+
metadata["due_date"] = card.due_date
|
| 168 |
+
|
| 169 |
+
return Document(page_content=text_content, metadata=metadata)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tsv.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from typing import Any, List, Union
|
| 3 |
+
|
| 4 |
+
from langchain_community.document_loaders.unstructured import (
|
| 5 |
+
UnstructuredFileLoader,
|
| 6 |
+
validate_unstructured_version,
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class UnstructuredTSVLoader(UnstructuredFileLoader):
|
| 11 |
+
"""Load `TSV` files using `Unstructured`.
|
| 12 |
+
|
| 13 |
+
Like other
|
| 14 |
+
Unstructured loaders, UnstructuredTSVLoader can be used in both
|
| 15 |
+
"single" and "elements" mode. If you use the loader in "elements"
|
| 16 |
+
mode, the TSV file will be a single Unstructured Table element.
|
| 17 |
+
If you use the loader in "elements" mode, an HTML representation
|
| 18 |
+
of the table will be available in the "text_as_html" key in the
|
| 19 |
+
document metadata.
|
| 20 |
+
|
| 21 |
+
Examples
|
| 22 |
+
--------
|
| 23 |
+
from langchain_community.document_loaders.tsv import UnstructuredTSVLoader
|
| 24 |
+
|
| 25 |
+
loader = UnstructuredTSVLoader("stanley-cups.tsv", mode="elements")
|
| 26 |
+
docs = loader.load()
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
file_path: Union[str, Path],
|
| 32 |
+
mode: str = "single",
|
| 33 |
+
**unstructured_kwargs: Any,
|
| 34 |
+
):
|
| 35 |
+
file_path = str(file_path)
|
| 36 |
+
validate_unstructured_version(min_unstructured_version="0.7.6")
|
| 37 |
+
super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
|
| 38 |
+
|
| 39 |
+
def _get_elements(self) -> List:
|
| 40 |
+
from unstructured.partition.tsv import partition_tsv
|
| 41 |
+
|
| 42 |
+
return partition_tsv(filename=self.file_path, **self.unstructured_kwargs)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/twitter.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence, Union
|
| 4 |
+
|
| 5 |
+
from langchain_core.documents import Document
|
| 6 |
+
|
| 7 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
import tweepy
|
| 11 |
+
from tweepy import OAuth2BearerHandler, OAuthHandler
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _dependable_tweepy_import() -> tweepy:
|
| 15 |
+
try:
|
| 16 |
+
import tweepy
|
| 17 |
+
except ImportError:
|
| 18 |
+
raise ImportError(
|
| 19 |
+
"tweepy package not found, please install it with `pip install tweepy`"
|
| 20 |
+
)
|
| 21 |
+
return tweepy
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class TwitterTweetLoader(BaseLoader):
|
| 25 |
+
"""Load `Twitter` tweets.
|
| 26 |
+
|
| 27 |
+
Read tweets of the user's Twitter handle.
|
| 28 |
+
|
| 29 |
+
First you need to go to
|
| 30 |
+
`https://developer.twitter.com/en/docs/twitter-api
|
| 31 |
+
/getting-started/getting-access-to-the-twitter-api`
|
| 32 |
+
to get your token. And create a v2 version of the app.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
auth_handler: Union[OAuthHandler, OAuth2BearerHandler],
|
| 38 |
+
twitter_users: Sequence[str],
|
| 39 |
+
number_tweets: Optional[int] = 100,
|
| 40 |
+
):
|
| 41 |
+
self.auth = auth_handler
|
| 42 |
+
self.twitter_users = twitter_users
|
| 43 |
+
self.number_tweets = number_tweets
|
| 44 |
+
|
| 45 |
+
def load(self) -> List[Document]:
|
| 46 |
+
"""Load tweets."""
|
| 47 |
+
tweepy = _dependable_tweepy_import()
|
| 48 |
+
api = tweepy.API(self.auth, parser=tweepy.parsers.JSONParser())
|
| 49 |
+
|
| 50 |
+
results: List[Document] = []
|
| 51 |
+
for username in self.twitter_users:
|
| 52 |
+
tweets = api.user_timeline(screen_name=username, count=self.number_tweets)
|
| 53 |
+
user = api.get_user(screen_name=username)
|
| 54 |
+
docs = self._format_tweets(tweets, user)
|
| 55 |
+
results.extend(docs)
|
| 56 |
+
return results
|
| 57 |
+
|
| 58 |
+
def _format_tweets(
|
| 59 |
+
self, tweets: List[Dict[str, Any]], user_info: dict
|
| 60 |
+
) -> Iterable[Document]:
|
| 61 |
+
"""Format tweets into a string."""
|
| 62 |
+
for tweet in tweets:
|
| 63 |
+
metadata = {
|
| 64 |
+
"created_at": tweet["created_at"],
|
| 65 |
+
"user_info": user_info,
|
| 66 |
+
}
|
| 67 |
+
yield Document(
|
| 68 |
+
page_content=tweet["text"],
|
| 69 |
+
metadata=metadata,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
@classmethod
|
| 73 |
+
def from_bearer_token(
|
| 74 |
+
cls,
|
| 75 |
+
oauth2_bearer_token: str,
|
| 76 |
+
twitter_users: Sequence[str],
|
| 77 |
+
number_tweets: Optional[int] = 100,
|
| 78 |
+
) -> TwitterTweetLoader:
|
| 79 |
+
"""Create a TwitterTweetLoader from OAuth2 bearer token."""
|
| 80 |
+
tweepy = _dependable_tweepy_import()
|
| 81 |
+
auth = tweepy.OAuth2BearerHandler(oauth2_bearer_token)
|
| 82 |
+
return cls(
|
| 83 |
+
auth_handler=auth,
|
| 84 |
+
twitter_users=twitter_users,
|
| 85 |
+
number_tweets=number_tweets,
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
@classmethod
|
| 89 |
+
def from_secrets(
|
| 90 |
+
cls,
|
| 91 |
+
access_token: str,
|
| 92 |
+
access_token_secret: str,
|
| 93 |
+
consumer_key: str,
|
| 94 |
+
consumer_secret: str,
|
| 95 |
+
twitter_users: Sequence[str],
|
| 96 |
+
number_tweets: Optional[int] = 100,
|
| 97 |
+
) -> TwitterTweetLoader:
|
| 98 |
+
"""Create a TwitterTweetLoader from access tokens and secrets."""
|
| 99 |
+
tweepy = _dependable_tweepy_import()
|
| 100 |
+
auth = tweepy.OAuthHandler(
|
| 101 |
+
access_token=access_token,
|
| 102 |
+
access_token_secret=access_token_secret,
|
| 103 |
+
consumer_key=consumer_key,
|
| 104 |
+
consumer_secret=consumer_secret,
|
| 105 |
+
)
|
| 106 |
+
return cls(
|
| 107 |
+
auth_handler=auth,
|
| 108 |
+
twitter_users=twitter_users,
|
| 109 |
+
number_tweets=number_tweets,
|
| 110 |
+
)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/unstructured.py
ADDED
|
@@ -0,0 +1,509 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Loader that uses unstructured to load files."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
from abc import ABC, abstractmethod
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import IO, Any, Callable, Iterator, List, Optional, Sequence, Union
|
| 10 |
+
|
| 11 |
+
from langchain_core._api.deprecation import deprecated
|
| 12 |
+
from langchain_core.documents import Document
|
| 13 |
+
from typing_extensions import TypeAlias
|
| 14 |
+
|
| 15 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 16 |
+
|
| 17 |
+
Element: TypeAlias = Any
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger(__file__)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def satisfies_min_unstructured_version(min_version: str) -> bool:
|
| 23 |
+
"""Check if the installed `Unstructured` version exceeds the minimum version
|
| 24 |
+
for the feature in question."""
|
| 25 |
+
from unstructured.__version__ import __version__ as __unstructured_version__
|
| 26 |
+
|
| 27 |
+
min_version_tuple = tuple([int(x) for x in min_version.split(".")])
|
| 28 |
+
|
| 29 |
+
# NOTE(MthwRobinson) - enables the loader to work when you're using pre-release
|
| 30 |
+
# versions of unstructured like 0.4.17-dev1
|
| 31 |
+
_unstructured_version = __unstructured_version__.split("-")[0]
|
| 32 |
+
unstructured_version_tuple = tuple(
|
| 33 |
+
[int(x) for x in _unstructured_version.split(".")]
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
return unstructured_version_tuple >= min_version_tuple
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def validate_unstructured_version(min_unstructured_version: str) -> None:
|
| 40 |
+
"""Raise an error if the `Unstructured` version does not exceed the
|
| 41 |
+
specified minimum."""
|
| 42 |
+
if not satisfies_min_unstructured_version(min_unstructured_version):
|
| 43 |
+
raise ValueError(
|
| 44 |
+
f"unstructured>={min_unstructured_version} is required in this loader."
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class UnstructuredBaseLoader(BaseLoader, ABC):
|
| 49 |
+
"""Base Loader that uses `Unstructured`."""
|
| 50 |
+
|
| 51 |
+
def __init__(
|
| 52 |
+
self,
|
| 53 |
+
mode: str = "single", # deprecated
|
| 54 |
+
post_processors: Optional[List[Callable[[str], str]]] = None,
|
| 55 |
+
**unstructured_kwargs: Any,
|
| 56 |
+
):
|
| 57 |
+
"""Initialize with file path."""
|
| 58 |
+
try:
|
| 59 |
+
import unstructured # noqa:F401
|
| 60 |
+
except ImportError:
|
| 61 |
+
raise ImportError(
|
| 62 |
+
"unstructured package not found, please install it with "
|
| 63 |
+
"`pip install unstructured`"
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
# `single` - elements are combined into one (default)
|
| 67 |
+
# `elements` - maintain individual elements
|
| 68 |
+
# `paged` - elements are combined by page
|
| 69 |
+
_valid_modes = {"single", "elements", "paged"}
|
| 70 |
+
if mode not in _valid_modes:
|
| 71 |
+
raise ValueError(
|
| 72 |
+
f"Got {mode} for `mode`, but should be one of `{_valid_modes}`"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
if not satisfies_min_unstructured_version("0.5.4"):
|
| 76 |
+
if "strategy" in unstructured_kwargs:
|
| 77 |
+
unstructured_kwargs.pop("strategy")
|
| 78 |
+
|
| 79 |
+
self._check_if_both_mode_and_chunking_strategy_are_by_page(
|
| 80 |
+
mode, unstructured_kwargs
|
| 81 |
+
)
|
| 82 |
+
self.mode = mode
|
| 83 |
+
self.unstructured_kwargs = unstructured_kwargs
|
| 84 |
+
self.post_processors = post_processors or []
|
| 85 |
+
|
| 86 |
+
@abstractmethod
|
| 87 |
+
def _get_elements(self) -> List[Element]:
|
| 88 |
+
"""Get elements."""
|
| 89 |
+
|
| 90 |
+
@abstractmethod
|
| 91 |
+
def _get_metadata(self) -> dict[str, Any]:
|
| 92 |
+
"""Get file_path metadata if available."""
|
| 93 |
+
|
| 94 |
+
def _post_process_elements(self, elements: List[Element]) -> List[Element]:
|
| 95 |
+
"""Apply post processing functions to extracted unstructured elements.
|
| 96 |
+
|
| 97 |
+
Post processing functions are str -> str callables passed
|
| 98 |
+
in using the post_processors kwarg when the loader is instantiated.
|
| 99 |
+
"""
|
| 100 |
+
for element in elements:
|
| 101 |
+
for post_processor in self.post_processors:
|
| 102 |
+
element.apply(post_processor)
|
| 103 |
+
return elements
|
| 104 |
+
|
| 105 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 106 |
+
"""Load file."""
|
| 107 |
+
elements = self._get_elements()
|
| 108 |
+
self._post_process_elements(elements)
|
| 109 |
+
if self.mode == "elements":
|
| 110 |
+
for element in elements:
|
| 111 |
+
metadata = self._get_metadata()
|
| 112 |
+
# NOTE(MthwRobinson) - the attribute check is for backward compatibility
|
| 113 |
+
# with unstructured<0.4.9. The metadata attributed was added in 0.4.9.
|
| 114 |
+
if hasattr(element, "metadata"):
|
| 115 |
+
metadata.update(element.metadata.to_dict())
|
| 116 |
+
if hasattr(element, "category"):
|
| 117 |
+
metadata["category"] = element.category
|
| 118 |
+
if element.to_dict().get("element_id"):
|
| 119 |
+
metadata["element_id"] = element.to_dict().get("element_id")
|
| 120 |
+
yield Document(page_content=str(element), metadata=metadata)
|
| 121 |
+
elif self.mode == "paged":
|
| 122 |
+
logger.warning(
|
| 123 |
+
"`mode='paged'` is deprecated in favor of the 'by_page' chunking"
|
| 124 |
+
" strategy. Learn more about chunking here:"
|
| 125 |
+
" https://docs.unstructured.io/open-source/core-functionality/chunking"
|
| 126 |
+
)
|
| 127 |
+
text_dict: dict[int, str] = {}
|
| 128 |
+
meta_dict: dict[int, dict[str, Any]] = {}
|
| 129 |
+
|
| 130 |
+
for element in elements:
|
| 131 |
+
metadata = self._get_metadata()
|
| 132 |
+
if hasattr(element, "metadata"):
|
| 133 |
+
metadata.update(element.metadata.to_dict())
|
| 134 |
+
page_number = metadata.get("page_number", 1)
|
| 135 |
+
|
| 136 |
+
# Check if this page_number already exists in text_dict
|
| 137 |
+
if page_number not in text_dict:
|
| 138 |
+
# If not, create new entry with initial text and metadata
|
| 139 |
+
text_dict[page_number] = str(element) + "\n\n"
|
| 140 |
+
meta_dict[page_number] = metadata
|
| 141 |
+
else:
|
| 142 |
+
# If exists, append to text and update the metadata
|
| 143 |
+
text_dict[page_number] += str(element) + "\n\n"
|
| 144 |
+
meta_dict[page_number].update(metadata)
|
| 145 |
+
|
| 146 |
+
# Convert the dict to a list of Document objects
|
| 147 |
+
for key in text_dict.keys():
|
| 148 |
+
yield Document(page_content=text_dict[key], metadata=meta_dict[key])
|
| 149 |
+
elif self.mode == "single":
|
| 150 |
+
metadata = self._get_metadata()
|
| 151 |
+
text = "\n\n".join([str(el) for el in elements])
|
| 152 |
+
yield Document(page_content=text, metadata=metadata)
|
| 153 |
+
else:
|
| 154 |
+
raise ValueError(f"mode of {self.mode} not supported.")
|
| 155 |
+
|
| 156 |
+
def _check_if_both_mode_and_chunking_strategy_are_by_page(
|
| 157 |
+
self, mode: str, unstructured_kwargs: dict[str, Any]
|
| 158 |
+
) -> None:
|
| 159 |
+
if (
|
| 160 |
+
mode == "paged"
|
| 161 |
+
and unstructured_kwargs.get("chunking_strategy") == "by_page"
|
| 162 |
+
):
|
| 163 |
+
raise ValueError(
|
| 164 |
+
"Only one of `chunking_strategy='by_page'` or `mode='paged'` may be"
|
| 165 |
+
" set. `chunking_strategy` is preferred."
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@deprecated(
|
| 170 |
+
since="0.2.8",
|
| 171 |
+
removal="1.0",
|
| 172 |
+
alternative_import="langchain_unstructured.UnstructuredLoader",
|
| 173 |
+
)
|
| 174 |
+
class UnstructuredFileLoader(UnstructuredBaseLoader):
|
| 175 |
+
"""Load files using `Unstructured`.
|
| 176 |
+
|
| 177 |
+
The file loader uses the unstructured partition function and will automatically
|
| 178 |
+
detect the file type. You can run the loader in different modes: "single",
|
| 179 |
+
"elements", and "paged". The default "single" mode will return a single langchain
|
| 180 |
+
Document object. If you use "elements" mode, the unstructured library will split
|
| 181 |
+
the document into elements such as Title and NarrativeText and return those as
|
| 182 |
+
individual langchain Document objects. In addition to these post-processing modes
|
| 183 |
+
(which are specific to the LangChain Loaders), Unstructured has its own "chunking"
|
| 184 |
+
parameters for post-processing elements into more useful chunks for uses cases such
|
| 185 |
+
as Retrieval Augmented Generation (RAG). You can pass in additional unstructured
|
| 186 |
+
kwargs to configure different unstructured settings.
|
| 187 |
+
|
| 188 |
+
Examples
|
| 189 |
+
--------
|
| 190 |
+
from langchain_community.document_loaders import UnstructuredFileLoader
|
| 191 |
+
|
| 192 |
+
loader = UnstructuredFileLoader(
|
| 193 |
+
"example.pdf", mode="elements", strategy="fast",
|
| 194 |
+
)
|
| 195 |
+
docs = loader.load()
|
| 196 |
+
|
| 197 |
+
References
|
| 198 |
+
----------
|
| 199 |
+
https://docs.unstructured.io/open-source/core-functionality/partitioning
|
| 200 |
+
https://docs.unstructured.io/open-source/core-functionality/chunking
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
def __init__(
|
| 204 |
+
self,
|
| 205 |
+
file_path: Union[str, List[str], Path, List[Path]],
|
| 206 |
+
*,
|
| 207 |
+
mode: str = "single",
|
| 208 |
+
**unstructured_kwargs: Any,
|
| 209 |
+
):
|
| 210 |
+
"""Initialize with file path."""
|
| 211 |
+
self.file_path = file_path
|
| 212 |
+
|
| 213 |
+
super().__init__(mode=mode, **unstructured_kwargs)
|
| 214 |
+
|
| 215 |
+
def _get_elements(self) -> List[Element]:
|
| 216 |
+
from unstructured.partition.auto import partition
|
| 217 |
+
|
| 218 |
+
if isinstance(self.file_path, list):
|
| 219 |
+
elements: List[Element] = []
|
| 220 |
+
for file in self.file_path:
|
| 221 |
+
if isinstance(file, Path):
|
| 222 |
+
file = str(file)
|
| 223 |
+
elements.extend(partition(filename=file, **self.unstructured_kwargs))
|
| 224 |
+
return elements
|
| 225 |
+
else:
|
| 226 |
+
if isinstance(self.file_path, Path):
|
| 227 |
+
self.file_path = str(self.file_path)
|
| 228 |
+
return partition(filename=self.file_path, **self.unstructured_kwargs)
|
| 229 |
+
|
| 230 |
+
def _get_metadata(self) -> dict[str, Any]:
|
| 231 |
+
return {"source": self.file_path}
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def get_elements_from_api(
|
| 235 |
+
file_path: Union[str, List[str], Path, List[Path], None] = None,
|
| 236 |
+
file: Union[IO[bytes], Sequence[IO[bytes]], None] = None,
|
| 237 |
+
api_url: str = "https://api.unstructuredapp.io/general/v0/general",
|
| 238 |
+
api_key: str = "",
|
| 239 |
+
**unstructured_kwargs: Any,
|
| 240 |
+
) -> List[Element]:
|
| 241 |
+
"""Retrieve a list of elements from the `Unstructured API`."""
|
| 242 |
+
if is_list := isinstance(file_path, list):
|
| 243 |
+
file_path = [str(path) for path in file_path]
|
| 244 |
+
if isinstance(file, Sequence) or is_list:
|
| 245 |
+
from unstructured.partition.api import partition_multiple_via_api
|
| 246 |
+
|
| 247 |
+
_doc_elements = partition_multiple_via_api(
|
| 248 |
+
filenames=file_path,
|
| 249 |
+
files=file,
|
| 250 |
+
api_key=api_key,
|
| 251 |
+
api_url=api_url,
|
| 252 |
+
**unstructured_kwargs,
|
| 253 |
+
)
|
| 254 |
+
elements = []
|
| 255 |
+
for _elements in _doc_elements:
|
| 256 |
+
elements.extend(_elements)
|
| 257 |
+
return elements
|
| 258 |
+
else:
|
| 259 |
+
from unstructured.partition.api import partition_via_api
|
| 260 |
+
|
| 261 |
+
return partition_via_api(
|
| 262 |
+
filename=str(file_path) if file_path is not None else None,
|
| 263 |
+
file=file,
|
| 264 |
+
api_key=api_key,
|
| 265 |
+
api_url=api_url,
|
| 266 |
+
**unstructured_kwargs,
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
@deprecated(
|
| 271 |
+
since="0.2.8",
|
| 272 |
+
removal="1.0",
|
| 273 |
+
alternative_import="langchain_unstructured.UnstructuredLoader",
|
| 274 |
+
)
|
| 275 |
+
class UnstructuredAPIFileLoader(UnstructuredBaseLoader):
|
| 276 |
+
"""Load files using `Unstructured` API.
|
| 277 |
+
|
| 278 |
+
By default, the loader makes a call to the hosted Unstructured API. If you are
|
| 279 |
+
running the unstructured API locally, you can change the API rule by passing in the
|
| 280 |
+
url parameter when you initialize the loader. The hosted Unstructured API requires
|
| 281 |
+
an API key. See the links below to learn more about our API offerings and get an
|
| 282 |
+
API key.
|
| 283 |
+
|
| 284 |
+
You can run the loader in different modes: "single", "elements", and "paged". The
|
| 285 |
+
default "single" mode will return a single langchain Document object. If you use
|
| 286 |
+
"elements" mode, the unstructured library will split the document into elements such
|
| 287 |
+
as Title and NarrativeText and return those as individual langchain Document
|
| 288 |
+
objects. In addition to these post-processing modes (which are specific to the
|
| 289 |
+
LangChain Loaders), Unstructured has its own "chunking" parameters for
|
| 290 |
+
post-processing elements into more useful chunks for uses cases such as Retrieval
|
| 291 |
+
Augmented Generation (RAG). You can pass in additional unstructured kwargs to
|
| 292 |
+
configure different unstructured settings.
|
| 293 |
+
|
| 294 |
+
Examples
|
| 295 |
+
```python
|
| 296 |
+
from langchain_community.document_loaders import UnstructuredAPIFileLoader
|
| 297 |
+
|
| 298 |
+
loader = UnstructuredAPIFileLoader(
|
| 299 |
+
"example.pdf", mode="elements", strategy="fast", api_key="MY_API_KEY",
|
| 300 |
+
)
|
| 301 |
+
docs = loader.load()
|
| 302 |
+
|
| 303 |
+
References
|
| 304 |
+
----------
|
| 305 |
+
https://docs.unstructured.io/api-reference/api-services/sdk
|
| 306 |
+
https://docs.unstructured.io/api-reference/api-services/overview
|
| 307 |
+
https://docs.unstructured.io/open-source/core-functionality/partitioning
|
| 308 |
+
https://docs.unstructured.io/open-source/core-functionality/chunking
|
| 309 |
+
"""
|
| 310 |
+
|
| 311 |
+
def __init__(
|
| 312 |
+
self,
|
| 313 |
+
file_path: Union[str, List[str]],
|
| 314 |
+
*,
|
| 315 |
+
mode: str = "single",
|
| 316 |
+
url: str = "https://api.unstructuredapp.io/general/v0/general",
|
| 317 |
+
api_key: str = "",
|
| 318 |
+
**unstructured_kwargs: Any,
|
| 319 |
+
):
|
| 320 |
+
"""Initialize with file path."""
|
| 321 |
+
validate_unstructured_version(min_unstructured_version="0.10.15")
|
| 322 |
+
|
| 323 |
+
self.file_path = file_path
|
| 324 |
+
self.url = url
|
| 325 |
+
self.api_key = os.getenv("UNSTRUCTURED_API_KEY") or api_key
|
| 326 |
+
|
| 327 |
+
super().__init__(mode=mode, **unstructured_kwargs)
|
| 328 |
+
|
| 329 |
+
def _get_metadata(self) -> dict[str, Any]:
|
| 330 |
+
return {"source": self.file_path}
|
| 331 |
+
|
| 332 |
+
def _get_elements(self) -> List[Element]:
|
| 333 |
+
return get_elements_from_api(
|
| 334 |
+
file_path=self.file_path,
|
| 335 |
+
api_key=self.api_key,
|
| 336 |
+
api_url=self.url,
|
| 337 |
+
**self.unstructured_kwargs,
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
def _post_process_elements(self, elements: List[Element]) -> List[Element]:
|
| 341 |
+
"""Apply post processing functions to extracted unstructured elements.
|
| 342 |
+
|
| 343 |
+
Post processing functions are str -> str callables passed
|
| 344 |
+
in using the post_processors kwarg when the loader is instantiated.
|
| 345 |
+
"""
|
| 346 |
+
for element in elements:
|
| 347 |
+
for post_processor in self.post_processors:
|
| 348 |
+
element.apply(post_processor)
|
| 349 |
+
return elements
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
@deprecated(
|
| 353 |
+
since="0.2.8",
|
| 354 |
+
removal="1.0",
|
| 355 |
+
alternative_import="langchain_unstructured.UnstructuredLoader",
|
| 356 |
+
)
|
| 357 |
+
class UnstructuredFileIOLoader(UnstructuredBaseLoader):
|
| 358 |
+
"""Load file-like objects opened in read mode using `Unstructured`.
|
| 359 |
+
|
| 360 |
+
The file loader uses the unstructured partition function and will automatically
|
| 361 |
+
detect the file type. You can run the loader in different modes: "single",
|
| 362 |
+
"elements", and "paged". The default "single" mode will return a single langchain
|
| 363 |
+
Document object. If you use "elements" mode, the unstructured library will split
|
| 364 |
+
the document into elements such as Title and NarrativeText and return those as
|
| 365 |
+
individual langchain Document objects. In addition to these post-processing modes
|
| 366 |
+
(which are specific to the LangChain Loaders), Unstructured has its own "chunking"
|
| 367 |
+
parameters for post-processing elements into more useful chunks for uses cases
|
| 368 |
+
such as Retrieval Augmented Generation (RAG). You can pass in additional
|
| 369 |
+
unstructured kwargs to configure different unstructured settings.
|
| 370 |
+
|
| 371 |
+
Examples
|
| 372 |
+
--------
|
| 373 |
+
from langchain_community.document_loaders import UnstructuredFileIOLoader
|
| 374 |
+
|
| 375 |
+
with open("example.pdf", "rb") as f:
|
| 376 |
+
loader = UnstructuredFileIOLoader(
|
| 377 |
+
f, mode="elements", strategy="fast",
|
| 378 |
+
)
|
| 379 |
+
docs = loader.load()
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
References
|
| 383 |
+
----------
|
| 384 |
+
https://docs.unstructured.io/open-source/core-functionality/partitioning
|
| 385 |
+
https://docs.unstructured.io/open-source/core-functionality/chunking
|
| 386 |
+
"""
|
| 387 |
+
|
| 388 |
+
def __init__(
|
| 389 |
+
self,
|
| 390 |
+
file: IO[bytes],
|
| 391 |
+
*,
|
| 392 |
+
mode: str = "single",
|
| 393 |
+
**unstructured_kwargs: Any,
|
| 394 |
+
):
|
| 395 |
+
"""Initialize with file path."""
|
| 396 |
+
self.file = file
|
| 397 |
+
super().__init__(mode=mode, **unstructured_kwargs)
|
| 398 |
+
|
| 399 |
+
def _get_elements(self) -> List[Element]:
|
| 400 |
+
from unstructured.partition.auto import partition
|
| 401 |
+
|
| 402 |
+
return partition(file=self.file, **self.unstructured_kwargs)
|
| 403 |
+
|
| 404 |
+
def _get_metadata(self) -> dict[str, Any]:
|
| 405 |
+
return {}
|
| 406 |
+
|
| 407 |
+
def _post_process_elements(self, elements: List[Element]) -> List[Element]:
|
| 408 |
+
"""Apply post processing functions to extracted unstructured elements.
|
| 409 |
+
|
| 410 |
+
Post processing functions are str -> str callables passed
|
| 411 |
+
in using the post_processors kwarg when the loader is instantiated.
|
| 412 |
+
"""
|
| 413 |
+
for element in elements:
|
| 414 |
+
for post_processor in self.post_processors:
|
| 415 |
+
element.apply(post_processor)
|
| 416 |
+
return elements
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
@deprecated(
|
| 420 |
+
since="0.2.8",
|
| 421 |
+
removal="1.0",
|
| 422 |
+
alternative_import="langchain_unstructured.UnstructuredLoader",
|
| 423 |
+
)
|
| 424 |
+
class UnstructuredAPIFileIOLoader(UnstructuredBaseLoader):
|
| 425 |
+
"""Send file-like objects with `unstructured-client` sdk to the Unstructured API.
|
| 426 |
+
|
| 427 |
+
By default, the loader makes a call to the hosted Unstructured API. If you are
|
| 428 |
+
running the unstructured API locally, you can change the API rule by passing in the
|
| 429 |
+
url parameter when you initialize the loader. The hosted Unstructured API requires
|
| 430 |
+
an API key. See the links below to learn more about our API offerings and get an
|
| 431 |
+
API key.
|
| 432 |
+
|
| 433 |
+
You can run the loader in different modes: "single", "elements", and "paged". The
|
| 434 |
+
default "single" mode will return a single langchain Document object. If you use
|
| 435 |
+
"elements" mode, the unstructured library will split the document into elements
|
| 436 |
+
such as Title and NarrativeText and return those as individual langchain Document
|
| 437 |
+
objects. In addition to these post-processing modes (which are specific to the
|
| 438 |
+
LangChain Loaders), Unstructured has its own "chunking" parameters for
|
| 439 |
+
post-processing elements into more useful chunks for uses cases such as Retrieval
|
| 440 |
+
Augmented Generation (RAG). You can pass in additional unstructured kwargs to
|
| 441 |
+
configure different unstructured settings.
|
| 442 |
+
|
| 443 |
+
Examples
|
| 444 |
+
--------
|
| 445 |
+
from langchain_community.document_loaders import UnstructuredAPIFileLoader
|
| 446 |
+
|
| 447 |
+
with open("example.pdf", "rb") as f:
|
| 448 |
+
loader = UnstructuredAPIFileIOLoader(
|
| 449 |
+
f, mode="elements", strategy="fast", api_key="MY_API_KEY",
|
| 450 |
+
)
|
| 451 |
+
docs = loader.load()
|
| 452 |
+
|
| 453 |
+
References
|
| 454 |
+
----------
|
| 455 |
+
https://docs.unstructured.io/api-reference/api-services/sdk
|
| 456 |
+
https://docs.unstructured.io/api-reference/api-services/overview
|
| 457 |
+
https://docs.unstructured.io/open-source/core-functionality/partitioning
|
| 458 |
+
https://docs.unstructured.io/open-source/core-functionality/chunking
|
| 459 |
+
"""
|
| 460 |
+
|
| 461 |
+
def __init__(
|
| 462 |
+
self,
|
| 463 |
+
file: Union[IO[bytes], Sequence[IO[bytes]]],
|
| 464 |
+
*,
|
| 465 |
+
mode: str = "single",
|
| 466 |
+
url: str = "https://api.unstructuredapp.io/general/v0/general",
|
| 467 |
+
api_key: str = "",
|
| 468 |
+
**unstructured_kwargs: Any,
|
| 469 |
+
):
|
| 470 |
+
"""Initialize with file path."""
|
| 471 |
+
|
| 472 |
+
if isinstance(file, Sequence):
|
| 473 |
+
validate_unstructured_version(min_unstructured_version="0.6.3")
|
| 474 |
+
validate_unstructured_version(min_unstructured_version="0.6.2")
|
| 475 |
+
|
| 476 |
+
self.file = file
|
| 477 |
+
self.url = url
|
| 478 |
+
self.api_key = os.getenv("UNSTRUCTURED_API_KEY") or api_key
|
| 479 |
+
|
| 480 |
+
super().__init__(mode=mode, **unstructured_kwargs)
|
| 481 |
+
|
| 482 |
+
def _get_elements(self) -> List[Element]:
|
| 483 |
+
if self.unstructured_kwargs.get("metadata_filename"):
|
| 484 |
+
return get_elements_from_api(
|
| 485 |
+
file=self.file,
|
| 486 |
+
file_path=self.unstructured_kwargs.pop("metadata_filename"),
|
| 487 |
+
api_key=self.api_key,
|
| 488 |
+
api_url=self.url,
|
| 489 |
+
**self.unstructured_kwargs,
|
| 490 |
+
)
|
| 491 |
+
else:
|
| 492 |
+
raise ValueError(
|
| 493 |
+
"If partitioning a file via api,"
|
| 494 |
+
" metadata_filename must be specified as well.",
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
def _get_metadata(self) -> dict[str, Any]:
|
| 498 |
+
return {}
|
| 499 |
+
|
| 500 |
+
def _post_process_elements(self, elements: List[Element]) -> List[Element]:
|
| 501 |
+
"""Apply post processing functions to extracted unstructured elements.
|
| 502 |
+
|
| 503 |
+
Post processing functions are str -> str callables passed
|
| 504 |
+
in using the post_processors kwarg when the loader is instantiated.
|
| 505 |
+
"""
|
| 506 |
+
for element in elements:
|
| 507 |
+
for post_processor in self.post_processors:
|
| 508 |
+
element.apply(post_processor)
|
| 509 |
+
return elements
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/url.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Loader that uses unstructured to load HTML files."""
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Any, List
|
| 5 |
+
|
| 6 |
+
from langchain_core.documents import Document
|
| 7 |
+
|
| 8 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class UnstructuredURLLoader(BaseLoader):
|
| 14 |
+
"""Load files from remote URLs using `Unstructured`.
|
| 15 |
+
|
| 16 |
+
Use the unstructured partition function to detect the MIME type
|
| 17 |
+
and route the file to the appropriate partitioner.
|
| 18 |
+
|
| 19 |
+
You can run the loader in one of two modes: "single" and "elements".
|
| 20 |
+
If you use "single" mode, the document will be returned as a single
|
| 21 |
+
langchain Document object. If you use "elements" mode, the unstructured
|
| 22 |
+
library will split the document into elements such as Title and NarrativeText.
|
| 23 |
+
You can pass in additional unstructured kwargs after mode to apply
|
| 24 |
+
different unstructured settings.
|
| 25 |
+
|
| 26 |
+
Examples
|
| 27 |
+
--------
|
| 28 |
+
from langchain_community.document_loaders import UnstructuredURLLoader
|
| 29 |
+
|
| 30 |
+
loader = UnstructuredURLLoader(
|
| 31 |
+
urls=["<url-1>", "<url-2>"], mode="elements", strategy="fast",
|
| 32 |
+
)
|
| 33 |
+
docs = loader.load()
|
| 34 |
+
|
| 35 |
+
References
|
| 36 |
+
----------
|
| 37 |
+
https://unstructured-io.github.io/unstructured/bricks.html#partition
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
urls: List[str],
|
| 43 |
+
continue_on_failure: bool = True,
|
| 44 |
+
mode: str = "single",
|
| 45 |
+
show_progress_bar: bool = False,
|
| 46 |
+
**unstructured_kwargs: Any,
|
| 47 |
+
):
|
| 48 |
+
"""Initialize with file path."""
|
| 49 |
+
try:
|
| 50 |
+
import unstructured # noqa:F401
|
| 51 |
+
from unstructured.__version__ import __version__ as __unstructured_version__
|
| 52 |
+
|
| 53 |
+
self.__version = __unstructured_version__
|
| 54 |
+
except ImportError:
|
| 55 |
+
raise ImportError(
|
| 56 |
+
"unstructured package not found, please install it with "
|
| 57 |
+
"`pip install unstructured`"
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
self._validate_mode(mode)
|
| 61 |
+
self.mode = mode
|
| 62 |
+
|
| 63 |
+
headers = unstructured_kwargs.pop("headers", {})
|
| 64 |
+
if len(headers.keys()) != 0:
|
| 65 |
+
warn_about_headers = False
|
| 66 |
+
if self.__is_non_html_available():
|
| 67 |
+
warn_about_headers = not self.__is_headers_available_for_non_html()
|
| 68 |
+
else:
|
| 69 |
+
warn_about_headers = not self.__is_headers_available_for_html()
|
| 70 |
+
|
| 71 |
+
if warn_about_headers:
|
| 72 |
+
logger.warning(
|
| 73 |
+
"You are using an old version of unstructured. "
|
| 74 |
+
"The headers parameter is ignored"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
self.urls = urls
|
| 78 |
+
self.continue_on_failure = continue_on_failure
|
| 79 |
+
self.headers = headers
|
| 80 |
+
self.unstructured_kwargs = unstructured_kwargs
|
| 81 |
+
self.show_progress_bar = show_progress_bar
|
| 82 |
+
|
| 83 |
+
def _validate_mode(self, mode: str) -> None:
|
| 84 |
+
_valid_modes = {"single", "elements"}
|
| 85 |
+
if mode not in _valid_modes:
|
| 86 |
+
raise ValueError(
|
| 87 |
+
f"Got {mode} for `mode`, but should be one of `{_valid_modes}`"
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
def __is_headers_available_for_html(self) -> bool:
|
| 91 |
+
_unstructured_version = self.__version.split("-")[0]
|
| 92 |
+
unstructured_version = tuple([int(x) for x in _unstructured_version.split(".")])
|
| 93 |
+
|
| 94 |
+
return unstructured_version >= (0, 5, 7)
|
| 95 |
+
|
| 96 |
+
def __is_headers_available_for_non_html(self) -> bool:
|
| 97 |
+
_unstructured_version = self.__version.split("-")[0]
|
| 98 |
+
unstructured_version = tuple([int(x) for x in _unstructured_version.split(".")])
|
| 99 |
+
|
| 100 |
+
return unstructured_version >= (0, 5, 13)
|
| 101 |
+
|
| 102 |
+
def __is_non_html_available(self) -> bool:
|
| 103 |
+
_unstructured_version = self.__version.split("-")[0]
|
| 104 |
+
unstructured_version = tuple([int(x) for x in _unstructured_version.split(".")])
|
| 105 |
+
|
| 106 |
+
return unstructured_version >= (0, 5, 12)
|
| 107 |
+
|
| 108 |
+
def load(self) -> List[Document]:
|
| 109 |
+
"""Load file."""
|
| 110 |
+
from unstructured.partition.auto import partition
|
| 111 |
+
from unstructured.partition.html import partition_html
|
| 112 |
+
|
| 113 |
+
docs: List[Document] = list()
|
| 114 |
+
if self.show_progress_bar:
|
| 115 |
+
try:
|
| 116 |
+
from tqdm import tqdm
|
| 117 |
+
except ImportError as e:
|
| 118 |
+
raise ImportError(
|
| 119 |
+
"Package tqdm must be installed if show_progress_bar=True. "
|
| 120 |
+
"Please install with 'pip install tqdm' or set "
|
| 121 |
+
"show_progress_bar=False."
|
| 122 |
+
) from e
|
| 123 |
+
|
| 124 |
+
urls = tqdm(self.urls)
|
| 125 |
+
else:
|
| 126 |
+
urls = self.urls
|
| 127 |
+
|
| 128 |
+
for url in urls:
|
| 129 |
+
try:
|
| 130 |
+
if self.__is_non_html_available():
|
| 131 |
+
if self.__is_headers_available_for_non_html():
|
| 132 |
+
elements = partition(
|
| 133 |
+
url=url, headers=self.headers, **self.unstructured_kwargs
|
| 134 |
+
)
|
| 135 |
+
else:
|
| 136 |
+
elements = partition(url=url, **self.unstructured_kwargs)
|
| 137 |
+
else:
|
| 138 |
+
if self.__is_headers_available_for_html():
|
| 139 |
+
elements = partition_html(
|
| 140 |
+
url=url, headers=self.headers, **self.unstructured_kwargs
|
| 141 |
+
)
|
| 142 |
+
else:
|
| 143 |
+
elements = partition_html(url=url, **self.unstructured_kwargs)
|
| 144 |
+
except Exception as e:
|
| 145 |
+
if self.continue_on_failure:
|
| 146 |
+
logger.error(f"Error fetching or processing {url}, exception: {e}")
|
| 147 |
+
continue
|
| 148 |
+
else:
|
| 149 |
+
raise e
|
| 150 |
+
|
| 151 |
+
if self.mode == "single":
|
| 152 |
+
text = "\n\n".join([str(el) for el in elements])
|
| 153 |
+
metadata = {"source": url}
|
| 154 |
+
docs.append(Document(page_content=text, metadata=metadata))
|
| 155 |
+
elif self.mode == "elements":
|
| 156 |
+
for element in elements:
|
| 157 |
+
metadata = element.metadata.to_dict()
|
| 158 |
+
metadata["category"] = element.category
|
| 159 |
+
docs.append(Document(page_content=str(element), metadata=metadata))
|
| 160 |
+
|
| 161 |
+
return docs
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/url_playwright.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Loader that uses Playwright to load a page, then uses unstructured to parse html."""
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
from abc import ABC, abstractmethod
|
| 6 |
+
from typing import TYPE_CHECKING, AsyncIterator, Dict, Iterator, List, Optional, Union
|
| 7 |
+
|
| 8 |
+
from langchain_core.documents import Document
|
| 9 |
+
|
| 10 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 11 |
+
|
| 12 |
+
if TYPE_CHECKING:
|
| 13 |
+
from playwright.async_api import Browser as AsyncBrowser
|
| 14 |
+
from playwright.async_api import Page as AsyncPage
|
| 15 |
+
from playwright.async_api import Response as AsyncResponse
|
| 16 |
+
from playwright.sync_api import Browser, Page, Response
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class PlaywrightEvaluator(ABC):
|
| 23 |
+
"""Abstract base class for all evaluators.
|
| 24 |
+
|
| 25 |
+
Each evaluator should take a page, a browser instance, and a response
|
| 26 |
+
object, process the page as necessary, and return the resulting text.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
@abstractmethod
|
| 30 |
+
def evaluate(self, page: "Page", browser: "Browser", response: "Response") -> str:
|
| 31 |
+
"""Synchronously process the page and return the resulting text.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
page: The page to process.
|
| 35 |
+
browser: The browser instance.
|
| 36 |
+
response: The response from page.goto().
|
| 37 |
+
|
| 38 |
+
Returns:
|
| 39 |
+
text: The text content of the page.
|
| 40 |
+
"""
|
| 41 |
+
pass
|
| 42 |
+
|
| 43 |
+
@abstractmethod
|
| 44 |
+
async def evaluate_async(
|
| 45 |
+
self, page: "AsyncPage", browser: "AsyncBrowser", response: "AsyncResponse"
|
| 46 |
+
) -> str:
|
| 47 |
+
"""Asynchronously process the page and return the resulting text.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
page: The page to process.
|
| 51 |
+
browser: The browser instance.
|
| 52 |
+
response: The response from page.goto().
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
text: The text content of the page.
|
| 56 |
+
"""
|
| 57 |
+
pass
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class UnstructuredHtmlEvaluator(PlaywrightEvaluator):
|
| 61 |
+
"""Evaluate the page HTML content using the `unstructured` library."""
|
| 62 |
+
|
| 63 |
+
def __init__(self, remove_selectors: Optional[List[str]] = None):
|
| 64 |
+
"""Initialize UnstructuredHtmlEvaluator."""
|
| 65 |
+
try:
|
| 66 |
+
import unstructured # noqa:F401
|
| 67 |
+
except ImportError:
|
| 68 |
+
raise ImportError(
|
| 69 |
+
"unstructured package not found, please install it with "
|
| 70 |
+
"`pip install unstructured`"
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
self.remove_selectors = remove_selectors
|
| 74 |
+
|
| 75 |
+
def evaluate(self, page: "Page", browser: "Browser", response: "Response") -> str:
|
| 76 |
+
"""Synchronously process the HTML content of the page."""
|
| 77 |
+
from unstructured.partition.html import partition_html
|
| 78 |
+
|
| 79 |
+
for selector in self.remove_selectors or []:
|
| 80 |
+
elements = page.locator(selector).all()
|
| 81 |
+
for element in elements:
|
| 82 |
+
if element.is_visible():
|
| 83 |
+
element.evaluate("element => element.remove()")
|
| 84 |
+
|
| 85 |
+
page_source = page.content()
|
| 86 |
+
elements = partition_html(text=page_source)
|
| 87 |
+
return "\n\n".join([str(el) for el in elements])
|
| 88 |
+
|
| 89 |
+
async def evaluate_async(
|
| 90 |
+
self, page: "AsyncPage", browser: "AsyncBrowser", response: "AsyncResponse"
|
| 91 |
+
) -> str:
|
| 92 |
+
"""Asynchronously process the HTML content of the page."""
|
| 93 |
+
from unstructured.partition.html import partition_html
|
| 94 |
+
|
| 95 |
+
for selector in self.remove_selectors or []:
|
| 96 |
+
elements = await page.locator(selector).all()
|
| 97 |
+
for element in elements:
|
| 98 |
+
if await element.is_visible():
|
| 99 |
+
await element.evaluate("element => element.remove()")
|
| 100 |
+
|
| 101 |
+
page_source = await page.content()
|
| 102 |
+
elements = partition_html(text=page_source)
|
| 103 |
+
return "\n\n".join([str(el) for el in elements])
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class PlaywrightURLLoader(BaseLoader):
|
| 107 |
+
"""Load `HTML` pages with `Playwright` and parse with `Unstructured`.
|
| 108 |
+
|
| 109 |
+
This is useful for loading pages that require javascript to render.
|
| 110 |
+
|
| 111 |
+
Attributes:
|
| 112 |
+
urls (List[str]): List of URLs to load.
|
| 113 |
+
continue_on_failure (bool): If True, continue loading other URLs on failure.
|
| 114 |
+
headless (bool): If True, the browser will run in headless mode.
|
| 115 |
+
proxy (Optional[Dict[str, str]]): If set, the browser will access URLs
|
| 116 |
+
through the specified proxy.
|
| 117 |
+
browser_session (Optional[Union[str, os.PathLike[str]]]): Path to a file with
|
| 118 |
+
browser session data that can be used to restore the browser session.
|
| 119 |
+
|
| 120 |
+
Example:
|
| 121 |
+
.. code-block:: python
|
| 122 |
+
|
| 123 |
+
from langchain_community.document_loaders import PlaywrightURLLoader
|
| 124 |
+
|
| 125 |
+
urls = ["https://api.ipify.org/?format=json",]
|
| 126 |
+
proxy={
|
| 127 |
+
"server": "https://xx.xx.xx:15818", # https://<host>:<port>
|
| 128 |
+
"username": "username",
|
| 129 |
+
"password": "password"
|
| 130 |
+
}
|
| 131 |
+
loader = PlaywrightURLLoader(urls, proxy=proxy)
|
| 132 |
+
data = loader.load()
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
def __init__(
|
| 136 |
+
self,
|
| 137 |
+
urls: List[str],
|
| 138 |
+
continue_on_failure: bool = True,
|
| 139 |
+
headless: bool = True,
|
| 140 |
+
remove_selectors: Optional[List[str]] = None,
|
| 141 |
+
evaluator: Optional[PlaywrightEvaluator] = None,
|
| 142 |
+
proxy: Optional[Dict[str, str]] = None,
|
| 143 |
+
browser_session: Optional[Union[str, os.PathLike[str]]] = None,
|
| 144 |
+
):
|
| 145 |
+
"""Load a list of URLs using Playwright."""
|
| 146 |
+
try:
|
| 147 |
+
import playwright # noqa:F401
|
| 148 |
+
except ImportError:
|
| 149 |
+
raise ImportError(
|
| 150 |
+
"playwright package not found, please install it with "
|
| 151 |
+
"`pip install playwright`"
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
self.urls = urls
|
| 155 |
+
self.continue_on_failure = continue_on_failure
|
| 156 |
+
self.headless = headless
|
| 157 |
+
self.proxy = proxy
|
| 158 |
+
self.browser_session = browser_session
|
| 159 |
+
|
| 160 |
+
if remove_selectors and evaluator:
|
| 161 |
+
raise ValueError(
|
| 162 |
+
"`remove_selectors` and `evaluator` cannot be both not None"
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
# Use the provided evaluator, if any, otherwise, use the default.
|
| 166 |
+
self.evaluator = evaluator or UnstructuredHtmlEvaluator(remove_selectors)
|
| 167 |
+
|
| 168 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 169 |
+
"""Load the specified URLs using Playwright and create Document instances.
|
| 170 |
+
|
| 171 |
+
Returns:
|
| 172 |
+
A list of Document instances with loaded content.
|
| 173 |
+
"""
|
| 174 |
+
from playwright.sync_api import sync_playwright
|
| 175 |
+
|
| 176 |
+
with sync_playwright() as p:
|
| 177 |
+
browser = p.chromium.launch(headless=self.headless, proxy=self.proxy)
|
| 178 |
+
context = None
|
| 179 |
+
|
| 180 |
+
if self.browser_session:
|
| 181 |
+
if os.path.exists(self.browser_session):
|
| 182 |
+
context = browser.new_context(storage_state=self.browser_session)
|
| 183 |
+
else:
|
| 184 |
+
logger.warning(f"Session file not found: {self.browser_session}")
|
| 185 |
+
|
| 186 |
+
if context is None:
|
| 187 |
+
context = browser.new_context()
|
| 188 |
+
|
| 189 |
+
for url in self.urls:
|
| 190 |
+
try:
|
| 191 |
+
page = context.new_page()
|
| 192 |
+
response = page.goto(url)
|
| 193 |
+
if response is None:
|
| 194 |
+
raise ValueError(f"page.goto() returned None for url {url}")
|
| 195 |
+
|
| 196 |
+
page.wait_for_load_state("load")
|
| 197 |
+
|
| 198 |
+
text = self.evaluator.evaluate(page, browser, response)
|
| 199 |
+
page.close()
|
| 200 |
+
metadata = {"source": url}
|
| 201 |
+
yield Document(page_content=text, metadata=metadata)
|
| 202 |
+
except Exception as e:
|
| 203 |
+
if self.continue_on_failure:
|
| 204 |
+
logger.error(
|
| 205 |
+
f"Error fetching or processing {url}, exception: {e}"
|
| 206 |
+
)
|
| 207 |
+
else:
|
| 208 |
+
raise e
|
| 209 |
+
browser.close()
|
| 210 |
+
|
| 211 |
+
async def aload(self) -> List[Document]:
|
| 212 |
+
"""Load the specified URLs with Playwright and create Documents asynchronously.
|
| 213 |
+
Use this function when in a jupyter notebook environment.
|
| 214 |
+
|
| 215 |
+
Returns:
|
| 216 |
+
A list of Document instances with loaded content.
|
| 217 |
+
"""
|
| 218 |
+
return [doc async for doc in self.alazy_load()]
|
| 219 |
+
|
| 220 |
+
async def alazy_load(self) -> AsyncIterator[Document]:
|
| 221 |
+
"""Load the specified URLs with Playwright and create Documents asynchronously.
|
| 222 |
+
Use this function when in a jupyter notebook environment.
|
| 223 |
+
|
| 224 |
+
Returns:
|
| 225 |
+
A list of Document instances with loaded content.
|
| 226 |
+
"""
|
| 227 |
+
from playwright.async_api import async_playwright
|
| 228 |
+
|
| 229 |
+
async with async_playwright() as p:
|
| 230 |
+
browser = await p.chromium.launch(headless=self.headless, proxy=self.proxy)
|
| 231 |
+
context = None
|
| 232 |
+
|
| 233 |
+
if self.browser_session:
|
| 234 |
+
if os.path.exists(self.browser_session):
|
| 235 |
+
context = await browser.new_context(
|
| 236 |
+
storage_state=self.browser_session
|
| 237 |
+
)
|
| 238 |
+
else:
|
| 239 |
+
logger.warning(f"Session file not found: {self.browser_session}")
|
| 240 |
+
|
| 241 |
+
if context is None:
|
| 242 |
+
context = await browser.new_context()
|
| 243 |
+
|
| 244 |
+
for url in self.urls:
|
| 245 |
+
try:
|
| 246 |
+
page = await context.new_page()
|
| 247 |
+
response = await page.goto(url)
|
| 248 |
+
if response is None:
|
| 249 |
+
raise ValueError(f"page.goto() returned None for url {url}")
|
| 250 |
+
|
| 251 |
+
await page.wait_for_load_state("load")
|
| 252 |
+
|
| 253 |
+
text = await self.evaluator.evaluate_async(page, browser, response)
|
| 254 |
+
await page.close()
|
| 255 |
+
metadata = {"source": url}
|
| 256 |
+
yield Document(page_content=text, metadata=metadata)
|
| 257 |
+
except Exception as e:
|
| 258 |
+
if self.continue_on_failure:
|
| 259 |
+
logger.error(
|
| 260 |
+
f"Error fetching or processing {url}, exception: {e}"
|
| 261 |
+
)
|
| 262 |
+
else:
|
| 263 |
+
raise e
|
| 264 |
+
await browser.close()
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/url_selenium.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Loader that uses Selenium to load a page, then uses unstructured to load the html."""
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from typing import TYPE_CHECKING, List, Literal, Optional, Union
|
| 5 |
+
|
| 6 |
+
if TYPE_CHECKING:
|
| 7 |
+
from selenium.webdriver import Chrome, Firefox
|
| 8 |
+
|
| 9 |
+
from langchain_core.documents import Document
|
| 10 |
+
|
| 11 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class SeleniumURLLoader(BaseLoader):
|
| 17 |
+
"""Load `HTML` pages with `Selenium` and parse with `Unstructured`.
|
| 18 |
+
|
| 19 |
+
This is useful for loading pages that require javascript to render.
|
| 20 |
+
|
| 21 |
+
Attributes:
|
| 22 |
+
urls (List[str]): List of URLs to load.
|
| 23 |
+
continue_on_failure (bool): If True, continue loading other URLs on failure.
|
| 24 |
+
browser (str): The browser to use, either 'chrome' or 'firefox'.
|
| 25 |
+
binary_location (Optional[str]): The location of the browser binary.
|
| 26 |
+
executable_path (Optional[str]): The path to the browser executable.
|
| 27 |
+
headless (bool): If True, the browser will run in headless mode.
|
| 28 |
+
arguments [List[str]]: List of arguments to pass to the browser.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
urls: List[str],
|
| 34 |
+
continue_on_failure: bool = True,
|
| 35 |
+
browser: Literal["chrome", "firefox"] = "chrome",
|
| 36 |
+
binary_location: Optional[str] = None,
|
| 37 |
+
executable_path: Optional[str] = None,
|
| 38 |
+
headless: bool = True,
|
| 39 |
+
arguments: List[str] = [],
|
| 40 |
+
):
|
| 41 |
+
"""Load a list of URLs using Selenium and unstructured."""
|
| 42 |
+
try:
|
| 43 |
+
import selenium # noqa:F401
|
| 44 |
+
except ImportError:
|
| 45 |
+
raise ImportError(
|
| 46 |
+
"selenium package not found, please install it with "
|
| 47 |
+
"`pip install selenium`"
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
import unstructured # noqa:F401
|
| 52 |
+
except ImportError:
|
| 53 |
+
raise ImportError(
|
| 54 |
+
"unstructured package not found, please install it with "
|
| 55 |
+
"`pip install unstructured`"
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
self.urls = urls
|
| 59 |
+
self.continue_on_failure = continue_on_failure
|
| 60 |
+
self.browser = browser
|
| 61 |
+
self.binary_location = binary_location
|
| 62 |
+
self.executable_path = executable_path
|
| 63 |
+
self.headless = headless
|
| 64 |
+
self.arguments = arguments
|
| 65 |
+
|
| 66 |
+
def _get_driver(self) -> Union["Chrome", "Firefox"]:
|
| 67 |
+
"""Create and return a WebDriver instance based on the specified browser.
|
| 68 |
+
|
| 69 |
+
Raises:
|
| 70 |
+
ValueError: If an invalid browser is specified.
|
| 71 |
+
|
| 72 |
+
Returns:
|
| 73 |
+
Union[Chrome, Firefox]: A WebDriver instance for the specified browser.
|
| 74 |
+
"""
|
| 75 |
+
if self.browser.lower() == "chrome":
|
| 76 |
+
from selenium.webdriver import Chrome
|
| 77 |
+
from selenium.webdriver.chrome.options import Options as ChromeOptions
|
| 78 |
+
from selenium.webdriver.chrome.service import Service
|
| 79 |
+
|
| 80 |
+
chrome_options = ChromeOptions()
|
| 81 |
+
|
| 82 |
+
for arg in self.arguments:
|
| 83 |
+
chrome_options.add_argument(arg)
|
| 84 |
+
|
| 85 |
+
if self.headless:
|
| 86 |
+
chrome_options.add_argument("--headless")
|
| 87 |
+
chrome_options.add_argument("--no-sandbox")
|
| 88 |
+
if self.binary_location is not None:
|
| 89 |
+
chrome_options.binary_location = self.binary_location
|
| 90 |
+
if self.executable_path is None:
|
| 91 |
+
return Chrome(options=chrome_options)
|
| 92 |
+
return Chrome(
|
| 93 |
+
options=chrome_options,
|
| 94 |
+
service=Service(executable_path=self.executable_path),
|
| 95 |
+
)
|
| 96 |
+
elif self.browser.lower() == "firefox":
|
| 97 |
+
from selenium.webdriver import Firefox
|
| 98 |
+
from selenium.webdriver.firefox.options import Options as FirefoxOptions
|
| 99 |
+
from selenium.webdriver.firefox.service import Service
|
| 100 |
+
|
| 101 |
+
firefox_options = FirefoxOptions()
|
| 102 |
+
|
| 103 |
+
for arg in self.arguments:
|
| 104 |
+
firefox_options.add_argument(arg)
|
| 105 |
+
|
| 106 |
+
if self.headless:
|
| 107 |
+
firefox_options.add_argument("--headless")
|
| 108 |
+
if self.binary_location is not None:
|
| 109 |
+
firefox_options.binary_location = self.binary_location
|
| 110 |
+
if self.executable_path is None:
|
| 111 |
+
return Firefox(options=firefox_options)
|
| 112 |
+
return Firefox(
|
| 113 |
+
options=firefox_options,
|
| 114 |
+
service=Service(executable_path=self.executable_path),
|
| 115 |
+
)
|
| 116 |
+
else:
|
| 117 |
+
raise ValueError("Invalid browser specified. Use 'chrome' or 'firefox'.")
|
| 118 |
+
|
| 119 |
+
def _build_metadata(self, url: str, driver: Union["Chrome", "Firefox"]) -> dict:
|
| 120 |
+
from selenium.common.exceptions import NoSuchElementException
|
| 121 |
+
from selenium.webdriver.common.by import By
|
| 122 |
+
|
| 123 |
+
"""Build metadata based on the contents of the webpage"""
|
| 124 |
+
metadata = {
|
| 125 |
+
"source": url,
|
| 126 |
+
"title": "No title found.",
|
| 127 |
+
"description": "No description found.",
|
| 128 |
+
"language": "No language found.",
|
| 129 |
+
}
|
| 130 |
+
if title := driver.title:
|
| 131 |
+
metadata["title"] = title
|
| 132 |
+
try:
|
| 133 |
+
if description := driver.find_element(
|
| 134 |
+
By.XPATH, '//meta[@name="description"]'
|
| 135 |
+
):
|
| 136 |
+
metadata["description"] = (
|
| 137 |
+
description.get_attribute("content") or "No description found."
|
| 138 |
+
)
|
| 139 |
+
except NoSuchElementException:
|
| 140 |
+
pass
|
| 141 |
+
try:
|
| 142 |
+
if html_tag := driver.find_element(By.TAG_NAME, "html"):
|
| 143 |
+
metadata["language"] = (
|
| 144 |
+
html_tag.get_attribute("lang") or "No language found."
|
| 145 |
+
)
|
| 146 |
+
except NoSuchElementException:
|
| 147 |
+
pass
|
| 148 |
+
return metadata
|
| 149 |
+
|
| 150 |
+
def load(self) -> List[Document]:
|
| 151 |
+
"""Load the specified URLs using Selenium and create Document instances.
|
| 152 |
+
|
| 153 |
+
Returns:
|
| 154 |
+
List[Document]: A list of Document instances with loaded content.
|
| 155 |
+
"""
|
| 156 |
+
from unstructured.partition.html import partition_html
|
| 157 |
+
|
| 158 |
+
docs: List[Document] = list()
|
| 159 |
+
driver = self._get_driver()
|
| 160 |
+
|
| 161 |
+
for url in self.urls:
|
| 162 |
+
try:
|
| 163 |
+
driver.get(url)
|
| 164 |
+
page_content = driver.page_source
|
| 165 |
+
elements = partition_html(text=page_content)
|
| 166 |
+
text = "\n\n".join([str(el) for el in elements])
|
| 167 |
+
metadata = self._build_metadata(url, driver)
|
| 168 |
+
docs.append(Document(page_content=text, metadata=metadata))
|
| 169 |
+
except Exception as e:
|
| 170 |
+
if self.continue_on_failure:
|
| 171 |
+
logger.error(f"Error fetching or processing {url}, exception: {e}")
|
| 172 |
+
else:
|
| 173 |
+
raise e
|
| 174 |
+
|
| 175 |
+
driver.quit()
|
| 176 |
+
return docs
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/vsdx.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
from abc import ABC
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import List, Union
|
| 6 |
+
from urllib.parse import urlparse
|
| 7 |
+
|
| 8 |
+
import requests
|
| 9 |
+
|
| 10 |
+
from langchain_community.docstore.document import Document
|
| 11 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 12 |
+
from langchain_community.document_loaders.blob_loaders import Blob
|
| 13 |
+
from langchain_community.document_loaders.parsers import VsdxParser
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class VsdxLoader(BaseLoader, ABC):
|
| 17 |
+
def __init__(self, file_path: Union[str, Path]):
|
| 18 |
+
"""Initialize with file path."""
|
| 19 |
+
self.file_path = str(file_path)
|
| 20 |
+
if "~" in self.file_path:
|
| 21 |
+
self.file_path = os.path.expanduser(self.file_path)
|
| 22 |
+
|
| 23 |
+
# If the file is a web path, download it to a temporary file, and use that
|
| 24 |
+
if not os.path.isfile(self.file_path) and self._is_valid_url(self.file_path):
|
| 25 |
+
r = requests.get(self.file_path)
|
| 26 |
+
|
| 27 |
+
if r.status_code != 200:
|
| 28 |
+
raise ValueError(
|
| 29 |
+
"Check the url of your file; returned status code %s"
|
| 30 |
+
% r.status_code
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
self.web_path = self.file_path
|
| 34 |
+
self.temp_file = tempfile.NamedTemporaryFile()
|
| 35 |
+
self.temp_file.write(r.content)
|
| 36 |
+
self.file_path = self.temp_file.name
|
| 37 |
+
elif not os.path.isfile(self.file_path):
|
| 38 |
+
raise ValueError("File path %s is not a valid file or url" % self.file_path)
|
| 39 |
+
|
| 40 |
+
self.parser = VsdxParser()
|
| 41 |
+
|
| 42 |
+
def __del__(self) -> None:
|
| 43 |
+
if hasattr(self, "temp_file"):
|
| 44 |
+
self.temp_file.close()
|
| 45 |
+
|
| 46 |
+
@staticmethod
|
| 47 |
+
def _is_valid_url(url: str) -> bool:
|
| 48 |
+
"""Check if the url is valid."""
|
| 49 |
+
parsed = urlparse(url)
|
| 50 |
+
return bool(parsed.netloc) and bool(parsed.scheme)
|
| 51 |
+
|
| 52 |
+
def load(self) -> List[Document]:
|
| 53 |
+
blob = Blob.from_path(self.file_path)
|
| 54 |
+
return list(self.parser.parse(blob))
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/weather.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Simple reader that reads weather data from OpenWeatherMap API"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from typing import Iterator, Optional, Sequence
|
| 7 |
+
|
| 8 |
+
from langchain_core.documents import Document
|
| 9 |
+
|
| 10 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 11 |
+
from langchain_community.utilities.openweathermap import OpenWeatherMapAPIWrapper
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class WeatherDataLoader(BaseLoader):
|
| 15 |
+
"""Load weather data with `Open Weather Map` API.
|
| 16 |
+
|
| 17 |
+
Reads the forecast & current weather of any location using OpenWeatherMap's free
|
| 18 |
+
API. Checkout 'https://openweathermap.org/appid' for more on how to generate a free
|
| 19 |
+
OpenWeatherMap API.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
client: OpenWeatherMapAPIWrapper,
|
| 25 |
+
places: Sequence[str],
|
| 26 |
+
) -> None:
|
| 27 |
+
"""Initialize with parameters."""
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.client = client
|
| 30 |
+
self.places = places
|
| 31 |
+
|
| 32 |
+
@classmethod
|
| 33 |
+
def from_params(
|
| 34 |
+
cls, places: Sequence[str], *, openweathermap_api_key: Optional[str] = None
|
| 35 |
+
) -> WeatherDataLoader:
|
| 36 |
+
client = OpenWeatherMapAPIWrapper(openweathermap_api_key=openweathermap_api_key)
|
| 37 |
+
return cls(client, places)
|
| 38 |
+
|
| 39 |
+
def lazy_load(
|
| 40 |
+
self,
|
| 41 |
+
) -> Iterator[Document]:
|
| 42 |
+
"""Lazily load weather data for the given locations."""
|
| 43 |
+
for place in self.places:
|
| 44 |
+
metadata = {"queried_at": datetime.now()}
|
| 45 |
+
content = self.client.run(place)
|
| 46 |
+
yield Document(page_content=content, metadata=metadata)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/web_base.py
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Web base loader class."""
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import logging
|
| 5 |
+
import warnings
|
| 6 |
+
from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Sequence, Union
|
| 7 |
+
|
| 8 |
+
import aiohttp
|
| 9 |
+
import requests
|
| 10 |
+
from langchain_core._api import deprecated
|
| 11 |
+
from langchain_core.documents import Document
|
| 12 |
+
|
| 13 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 14 |
+
from langchain_community.utils.user_agent import get_user_agent
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
default_header_template = {
|
| 19 |
+
"User-Agent": get_user_agent(),
|
| 20 |
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*"
|
| 21 |
+
";q=0.8",
|
| 22 |
+
"Accept-Language": "en-US,en;q=0.5",
|
| 23 |
+
"Referer": "https://www.google.com/",
|
| 24 |
+
"DNT": "1",
|
| 25 |
+
"Connection": "keep-alive",
|
| 26 |
+
"Upgrade-Insecure-Requests": "1",
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _build_metadata(soup: Any, url: str) -> dict:
|
| 31 |
+
"""Build metadata from BeautifulSoup output."""
|
| 32 |
+
metadata = {"source": url}
|
| 33 |
+
if title := soup.find("title"):
|
| 34 |
+
metadata["title"] = title.get_text()
|
| 35 |
+
if description := soup.find("meta", attrs={"name": "description"}):
|
| 36 |
+
metadata["description"] = description.get("content", "No description found.")
|
| 37 |
+
if html := soup.find("html"):
|
| 38 |
+
metadata["language"] = html.get("lang", "No language found.")
|
| 39 |
+
return metadata
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class WebBaseLoader(BaseLoader):
|
| 43 |
+
"""
|
| 44 |
+
WebBaseLoader document loader integration
|
| 45 |
+
|
| 46 |
+
Setup:
|
| 47 |
+
Install ``langchain_community``.
|
| 48 |
+
|
| 49 |
+
.. code-block:: bash
|
| 50 |
+
|
| 51 |
+
pip install -U langchain_community
|
| 52 |
+
|
| 53 |
+
Instantiate:
|
| 54 |
+
.. code-block:: python
|
| 55 |
+
|
| 56 |
+
from langchain_community.document_loaders import WebBaseLoader
|
| 57 |
+
|
| 58 |
+
loader = WebBaseLoader(
|
| 59 |
+
web_path = "https://www.espn.com/"
|
| 60 |
+
# header_template = None,
|
| 61 |
+
# verify_ssl = True,
|
| 62 |
+
# proxies = None,
|
| 63 |
+
# continue_on_failure = False,
|
| 64 |
+
# autoset_encoding = True,
|
| 65 |
+
# encoding = None,
|
| 66 |
+
# web_paths = (),
|
| 67 |
+
# requests_per_second = 2,
|
| 68 |
+
# default_parser = "html.parser",
|
| 69 |
+
# requests_kwargs = None,
|
| 70 |
+
# raise_for_status = False,
|
| 71 |
+
# bs_get_text_kwargs = None,
|
| 72 |
+
# bs_kwargs = None,
|
| 73 |
+
# session = None,
|
| 74 |
+
# show_progress = True,
|
| 75 |
+
# trust_env = False,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
Lazy load:
|
| 79 |
+
.. code-block:: python
|
| 80 |
+
|
| 81 |
+
docs = []
|
| 82 |
+
for doc in loader.lazy_load():
|
| 83 |
+
docs.append(doc)
|
| 84 |
+
print(docs[0].page_content[:100])
|
| 85 |
+
print(docs[0].metadata)
|
| 86 |
+
|
| 87 |
+
.. code-block:: python
|
| 88 |
+
|
| 89 |
+
ESPN - Serving Sports Fans. Anytime. Anywhere.
|
| 90 |
+
|
| 91 |
+
{'source': 'https://www.espn.com/', 'title': 'ESPN - Serving Sports Fans. Anytime. Anywhere.', 'description': 'Visit ESPN for live scores, highlights and sports news. Stream exclusive games on ESPN+ and play fantasy sports.', 'language': 'en'}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
Async load:
|
| 95 |
+
.. code-block:: python
|
| 96 |
+
|
| 97 |
+
docs = []
|
| 98 |
+
async for doc in loader.alazy_load():
|
| 99 |
+
docs.append(doc)
|
| 100 |
+
print(docs[0].page_content[:100])
|
| 101 |
+
print(docs[0].metadata)
|
| 102 |
+
|
| 103 |
+
.. code-block:: python
|
| 104 |
+
|
| 105 |
+
ESPN - Serving Sports Fans. Anytime. Anywhere.
|
| 106 |
+
|
| 107 |
+
{'source': 'https://www.espn.com/', 'title': 'ESPN - Serving Sports Fans. Anytime. Anywhere.', 'description': 'Visit ESPN for live scores, highlights and sports news. Stream exclusive games on ESPN+ and play fantasy sports.', 'language': 'en'}
|
| 108 |
+
|
| 109 |
+
.. versionchanged:: 0.3.14
|
| 110 |
+
|
| 111 |
+
Deprecated ``aload`` (which was not async) and implemented a native async
|
| 112 |
+
``alazy_load``. Expand below for more details.
|
| 113 |
+
|
| 114 |
+
.. dropdown:: How to update ``aload``
|
| 115 |
+
|
| 116 |
+
Instead of using ``aload``, you can use ``load`` for synchronous loading or
|
| 117 |
+
``alazy_load`` for asynchronous lazy loading.
|
| 118 |
+
|
| 119 |
+
Example using ``load`` (synchronous):
|
| 120 |
+
|
| 121 |
+
.. code-block:: python
|
| 122 |
+
|
| 123 |
+
docs: List[Document] = loader.load()
|
| 124 |
+
|
| 125 |
+
Example using ``alazy_load`` (asynchronous):
|
| 126 |
+
|
| 127 |
+
.. code-block:: python
|
| 128 |
+
|
| 129 |
+
docs: List[Document] = []
|
| 130 |
+
async for doc in loader.alazy_load():
|
| 131 |
+
docs.append(doc)
|
| 132 |
+
|
| 133 |
+
This is in preparation for accommodating an asynchronous ``aload`` in the
|
| 134 |
+
future:
|
| 135 |
+
|
| 136 |
+
.. code-block:: python
|
| 137 |
+
|
| 138 |
+
docs: List[Document] = await loader.aload()
|
| 139 |
+
|
| 140 |
+
""" # noqa: E501
|
| 141 |
+
|
| 142 |
+
def __init__(
|
| 143 |
+
self,
|
| 144 |
+
web_path: Union[str, Sequence[str]] = "",
|
| 145 |
+
header_template: Optional[dict] = None,
|
| 146 |
+
verify_ssl: bool = True,
|
| 147 |
+
proxies: Optional[dict] = None,
|
| 148 |
+
continue_on_failure: bool = False,
|
| 149 |
+
autoset_encoding: bool = True,
|
| 150 |
+
encoding: Optional[str] = None,
|
| 151 |
+
web_paths: Sequence[str] = (),
|
| 152 |
+
requests_per_second: int = 2,
|
| 153 |
+
default_parser: str = "html.parser",
|
| 154 |
+
requests_kwargs: Optional[Dict[str, Any]] = None,
|
| 155 |
+
raise_for_status: bool = False,
|
| 156 |
+
bs_get_text_kwargs: Optional[Dict[str, Any]] = None,
|
| 157 |
+
bs_kwargs: Optional[Dict[str, Any]] = None,
|
| 158 |
+
session: Any = None,
|
| 159 |
+
*,
|
| 160 |
+
show_progress: bool = True,
|
| 161 |
+
trust_env: bool = False,
|
| 162 |
+
) -> None:
|
| 163 |
+
"""Initialize loader.
|
| 164 |
+
|
| 165 |
+
Args:
|
| 166 |
+
web_paths: Web paths to load from.
|
| 167 |
+
requests_per_second: Max number of concurrent requests to make.
|
| 168 |
+
default_parser: Default parser to use for BeautifulSoup.
|
| 169 |
+
requests_kwargs: kwargs for requests
|
| 170 |
+
raise_for_status: Raise an exception if http status code denotes an error.
|
| 171 |
+
bs_get_text_kwargs: kwargs for beatifulsoup4 get_text
|
| 172 |
+
bs_kwargs: kwargs for beatifulsoup4 web page parsing
|
| 173 |
+
show_progress: Show progress bar when loading pages.
|
| 174 |
+
trust_env: set to True if using proxy to make web requests, for example
|
| 175 |
+
using http(s)_proxy environment variables. Defaults to False.
|
| 176 |
+
"""
|
| 177 |
+
# web_path kept for backwards-compatibility.
|
| 178 |
+
if web_path and web_paths:
|
| 179 |
+
raise ValueError(
|
| 180 |
+
"Received web_path and web_paths. Only one can be specified. "
|
| 181 |
+
"web_path is deprecated, web_paths should be used."
|
| 182 |
+
)
|
| 183 |
+
if web_paths:
|
| 184 |
+
self.web_paths = list(web_paths)
|
| 185 |
+
elif isinstance(web_path, str):
|
| 186 |
+
self.web_paths = [web_path]
|
| 187 |
+
elif isinstance(web_path, Sequence):
|
| 188 |
+
self.web_paths = list(web_path)
|
| 189 |
+
else:
|
| 190 |
+
raise TypeError(
|
| 191 |
+
f"web_path must be str or Sequence[str] got ({type(web_path)}) or"
|
| 192 |
+
f" web_paths must be Sequence[str] got ({type(web_paths)})"
|
| 193 |
+
)
|
| 194 |
+
self.requests_per_second = requests_per_second
|
| 195 |
+
self.default_parser = default_parser
|
| 196 |
+
self.requests_kwargs = requests_kwargs or {}
|
| 197 |
+
self.raise_for_status = raise_for_status
|
| 198 |
+
self.show_progress = show_progress
|
| 199 |
+
self.bs_get_text_kwargs = bs_get_text_kwargs or {}
|
| 200 |
+
self.bs_kwargs = bs_kwargs or {}
|
| 201 |
+
if session:
|
| 202 |
+
self.session = session
|
| 203 |
+
else:
|
| 204 |
+
session = requests.Session()
|
| 205 |
+
header_template = header_template or default_header_template.copy()
|
| 206 |
+
if not header_template.get("User-Agent"):
|
| 207 |
+
try:
|
| 208 |
+
from fake_useragent import UserAgent
|
| 209 |
+
|
| 210 |
+
header_template["User-Agent"] = UserAgent().random
|
| 211 |
+
except ImportError:
|
| 212 |
+
logger.info(
|
| 213 |
+
"fake_useragent not found, using default user agent."
|
| 214 |
+
"To get a realistic header for requests, "
|
| 215 |
+
"`pip install fake_useragent`."
|
| 216 |
+
)
|
| 217 |
+
session.headers = dict(header_template)
|
| 218 |
+
session.verify = verify_ssl
|
| 219 |
+
if proxies:
|
| 220 |
+
session.proxies.update(proxies)
|
| 221 |
+
self.session = session
|
| 222 |
+
self.continue_on_failure = continue_on_failure
|
| 223 |
+
self.autoset_encoding = autoset_encoding
|
| 224 |
+
self.encoding = encoding
|
| 225 |
+
self.trust_env = trust_env
|
| 226 |
+
|
| 227 |
+
@property
|
| 228 |
+
def web_path(self) -> str:
|
| 229 |
+
if len(self.web_paths) > 1:
|
| 230 |
+
raise ValueError("Multiple webpaths found.")
|
| 231 |
+
return self.web_paths[0]
|
| 232 |
+
|
| 233 |
+
async def _fetch(
|
| 234 |
+
self, url: str, retries: int = 3, cooldown: int = 2, backoff: float = 1.5
|
| 235 |
+
) -> str:
|
| 236 |
+
async with aiohttp.ClientSession(trust_env=self.trust_env) as session:
|
| 237 |
+
for i in range(retries):
|
| 238 |
+
try:
|
| 239 |
+
kwargs: Dict = dict(
|
| 240 |
+
headers=self.session.headers,
|
| 241 |
+
cookies=self.session.cookies.get_dict(),
|
| 242 |
+
)
|
| 243 |
+
if not self.session.verify:
|
| 244 |
+
kwargs["ssl"] = False
|
| 245 |
+
|
| 246 |
+
async with session.get(
|
| 247 |
+
url, **(self.requests_kwargs | kwargs)
|
| 248 |
+
) as response:
|
| 249 |
+
if self.raise_for_status:
|
| 250 |
+
response.raise_for_status()
|
| 251 |
+
return await response.text()
|
| 252 |
+
except aiohttp.ClientConnectionError as e:
|
| 253 |
+
if i == retries - 1:
|
| 254 |
+
raise
|
| 255 |
+
else:
|
| 256 |
+
logger.warning(
|
| 257 |
+
f"Error fetching {url} with attempt "
|
| 258 |
+
f"{i + 1}/{retries}: {e}. Retrying..."
|
| 259 |
+
)
|
| 260 |
+
await asyncio.sleep(cooldown * backoff**i)
|
| 261 |
+
raise ValueError("retry count exceeded")
|
| 262 |
+
|
| 263 |
+
async def _fetch_with_rate_limit(
|
| 264 |
+
self, url: str, semaphore: asyncio.Semaphore
|
| 265 |
+
) -> str:
|
| 266 |
+
async with semaphore:
|
| 267 |
+
try:
|
| 268 |
+
return await self._fetch(url)
|
| 269 |
+
except Exception as e:
|
| 270 |
+
if self.continue_on_failure:
|
| 271 |
+
logger.warning(
|
| 272 |
+
f"Error fetching {url}, skipping due to"
|
| 273 |
+
f" continue_on_failure=True"
|
| 274 |
+
)
|
| 275 |
+
return ""
|
| 276 |
+
logger.exception(
|
| 277 |
+
f"Error fetching {url} and aborting, use continue_on_failure=True "
|
| 278 |
+
"to continue loading urls after encountering an error."
|
| 279 |
+
)
|
| 280 |
+
raise e
|
| 281 |
+
|
| 282 |
+
async def fetch_all(self, urls: List[str]) -> Any:
|
| 283 |
+
"""Fetch all urls concurrently with rate limiting."""
|
| 284 |
+
semaphore = asyncio.Semaphore(self.requests_per_second)
|
| 285 |
+
tasks = []
|
| 286 |
+
for url in urls:
|
| 287 |
+
task = asyncio.ensure_future(self._fetch_with_rate_limit(url, semaphore))
|
| 288 |
+
tasks.append(task)
|
| 289 |
+
try:
|
| 290 |
+
if self.show_progress:
|
| 291 |
+
from tqdm.asyncio import tqdm_asyncio
|
| 292 |
+
|
| 293 |
+
return await tqdm_asyncio.gather(
|
| 294 |
+
*tasks, desc="Fetching pages", ascii=True, mininterval=1
|
| 295 |
+
)
|
| 296 |
+
else:
|
| 297 |
+
return await asyncio.gather(*tasks)
|
| 298 |
+
except ImportError:
|
| 299 |
+
warnings.warn("For better logging of progress, `pip install tqdm`")
|
| 300 |
+
return await asyncio.gather(*tasks)
|
| 301 |
+
|
| 302 |
+
@staticmethod
|
| 303 |
+
def _check_parser(parser: str) -> None:
|
| 304 |
+
"""Check that parser is valid for bs4."""
|
| 305 |
+
valid_parsers = ["html.parser", "lxml", "xml", "lxml-xml", "html5lib"]
|
| 306 |
+
if parser not in valid_parsers:
|
| 307 |
+
raise ValueError(
|
| 308 |
+
"`parser` must be one of " + ", ".join(valid_parsers) + "."
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
def _unpack_fetch_results(
|
| 312 |
+
self, results: Any, urls: List[str], parser: Union[str, None] = None
|
| 313 |
+
) -> List[Any]:
|
| 314 |
+
"""Unpack fetch results into BeautifulSoup objects."""
|
| 315 |
+
from bs4 import BeautifulSoup
|
| 316 |
+
|
| 317 |
+
final_results = []
|
| 318 |
+
for i, result in enumerate(results):
|
| 319 |
+
url = urls[i]
|
| 320 |
+
if parser is None:
|
| 321 |
+
if url.endswith(".xml"):
|
| 322 |
+
parser = "xml"
|
| 323 |
+
else:
|
| 324 |
+
parser = self.default_parser
|
| 325 |
+
self._check_parser(parser)
|
| 326 |
+
final_results.append(BeautifulSoup(result, parser, **self.bs_kwargs))
|
| 327 |
+
return final_results
|
| 328 |
+
|
| 329 |
+
def scrape_all(self, urls: List[str], parser: Union[str, None] = None) -> List[Any]:
|
| 330 |
+
"""Fetch all urls, then return soups for all results."""
|
| 331 |
+
results = asyncio.run(self.fetch_all(urls))
|
| 332 |
+
return self._unpack_fetch_results(results, urls, parser=parser)
|
| 333 |
+
|
| 334 |
+
async def ascrape_all(
|
| 335 |
+
self, urls: List[str], parser: Union[str, None] = None
|
| 336 |
+
) -> List[Any]:
|
| 337 |
+
"""Async fetch all urls, then return soups for all results."""
|
| 338 |
+
results = await self.fetch_all(urls)
|
| 339 |
+
return self._unpack_fetch_results(results, urls, parser=parser)
|
| 340 |
+
|
| 341 |
+
def _scrape(
|
| 342 |
+
self,
|
| 343 |
+
url: str,
|
| 344 |
+
parser: Union[str, None] = None,
|
| 345 |
+
bs_kwargs: Optional[dict] = None,
|
| 346 |
+
) -> Any:
|
| 347 |
+
from bs4 import BeautifulSoup
|
| 348 |
+
|
| 349 |
+
if parser is None:
|
| 350 |
+
if url.endswith(".xml"):
|
| 351 |
+
parser = "xml"
|
| 352 |
+
else:
|
| 353 |
+
parser = self.default_parser
|
| 354 |
+
|
| 355 |
+
self._check_parser(parser)
|
| 356 |
+
|
| 357 |
+
html_doc = self.session.get(url, **self.requests_kwargs)
|
| 358 |
+
if self.raise_for_status:
|
| 359 |
+
html_doc.raise_for_status()
|
| 360 |
+
|
| 361 |
+
if self.encoding is not None:
|
| 362 |
+
html_doc.encoding = self.encoding
|
| 363 |
+
elif self.autoset_encoding:
|
| 364 |
+
html_doc.encoding = html_doc.apparent_encoding
|
| 365 |
+
return BeautifulSoup(html_doc.text, parser, **(bs_kwargs or {}))
|
| 366 |
+
|
| 367 |
+
def scrape(self, parser: Union[str, None] = None) -> Any:
|
| 368 |
+
"""Scrape data from webpage and return it in BeautifulSoup format."""
|
| 369 |
+
|
| 370 |
+
return self._scrape(self.web_path, parser=parser, bs_kwargs=self.bs_kwargs)
|
| 371 |
+
|
| 372 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 373 |
+
"""Lazy load text from the url(s) in web_path."""
|
| 374 |
+
for path in self.web_paths:
|
| 375 |
+
soup = self._scrape(path, bs_kwargs=self.bs_kwargs)
|
| 376 |
+
text = soup.get_text(**self.bs_get_text_kwargs)
|
| 377 |
+
metadata = _build_metadata(soup, path)
|
| 378 |
+
yield Document(page_content=text, metadata=metadata)
|
| 379 |
+
|
| 380 |
+
async def alazy_load(self) -> AsyncIterator[Document]:
|
| 381 |
+
"""Async lazy load text from the url(s) in web_path."""
|
| 382 |
+
results = await self.ascrape_all(self.web_paths)
|
| 383 |
+
for path, soup in zip(self.web_paths, results):
|
| 384 |
+
text = soup.get_text(**self.bs_get_text_kwargs)
|
| 385 |
+
metadata = _build_metadata(soup, path)
|
| 386 |
+
yield Document(page_content=text, metadata=metadata)
|
| 387 |
+
|
| 388 |
+
@deprecated(
|
| 389 |
+
since="0.3.14",
|
| 390 |
+
removal="1.0",
|
| 391 |
+
message=(
|
| 392 |
+
"See API reference for updated usage: "
|
| 393 |
+
"https://python.langchain.com/api_reference/community/document_loaders/langchain_community.document_loaders.web_base.WebBaseLoader.html" # noqa: E501
|
| 394 |
+
),
|
| 395 |
+
)
|
| 396 |
+
def aload(self) -> List[Document]: # type: ignore[override]
|
| 397 |
+
"""Load text from the urls in web_path async into Documents."""
|
| 398 |
+
|
| 399 |
+
results = self.scrape_all(self.web_paths)
|
| 400 |
+
docs = []
|
| 401 |
+
for path, soup in zip(self.web_paths, results):
|
| 402 |
+
text = soup.get_text(**self.bs_get_text_kwargs)
|
| 403 |
+
metadata = _build_metadata(soup, path)
|
| 404 |
+
docs.append(Document(page_content=text, metadata=metadata))
|
| 405 |
+
|
| 406 |
+
return docs
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/whatsapp_chat.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Iterator
|
| 4 |
+
|
| 5 |
+
from langchain_core.documents import Document
|
| 6 |
+
|
| 7 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def concatenate_rows(date: str, sender: str, text: str) -> str:
|
| 11 |
+
"""Combine message information in a readable format ready to be used."""
|
| 12 |
+
return f"{sender} on {date}: {text}\n\n"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class WhatsAppChatLoader(BaseLoader):
|
| 16 |
+
"""Load `WhatsApp` messages text file."""
|
| 17 |
+
|
| 18 |
+
def __init__(self, path: str):
|
| 19 |
+
"""Initialize with path."""
|
| 20 |
+
self.file_path = path
|
| 21 |
+
|
| 22 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 23 |
+
p = Path(self.file_path)
|
| 24 |
+
text_content = ""
|
| 25 |
+
|
| 26 |
+
with open(p, encoding="utf8") as f:
|
| 27 |
+
lines = f.readlines()
|
| 28 |
+
|
| 29 |
+
message_line_regex = r"""
|
| 30 |
+
\[?
|
| 31 |
+
(
|
| 32 |
+
\d{1,4}
|
| 33 |
+
[\/.]
|
| 34 |
+
\d{1,2}
|
| 35 |
+
[\/.]
|
| 36 |
+
\d{1,4}
|
| 37 |
+
,\s
|
| 38 |
+
\d{1,2}
|
| 39 |
+
:\d{2}
|
| 40 |
+
(?:
|
| 41 |
+
:\d{2}
|
| 42 |
+
)?
|
| 43 |
+
(?:[\s_](?:AM|PM))?
|
| 44 |
+
)
|
| 45 |
+
\]?
|
| 46 |
+
[\s-]*
|
| 47 |
+
([~\w\s]+)
|
| 48 |
+
[:]+
|
| 49 |
+
\s
|
| 50 |
+
(.+)
|
| 51 |
+
"""
|
| 52 |
+
ignore_lines = ["This message was deleted", "<Media omitted>"]
|
| 53 |
+
for line in lines:
|
| 54 |
+
result = re.match(
|
| 55 |
+
message_line_regex, line.strip(), flags=re.VERBOSE | re.IGNORECASE
|
| 56 |
+
)
|
| 57 |
+
if result:
|
| 58 |
+
date, sender, text = result.groups()
|
| 59 |
+
if text not in ignore_lines:
|
| 60 |
+
text_content += concatenate_rows(date, sender, text)
|
| 61 |
+
|
| 62 |
+
metadata = {"source": str(p)}
|
| 63 |
+
|
| 64 |
+
yield Document(page_content=text_content, metadata=metadata)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/wikipedia.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Iterator, Optional
|
| 2 |
+
|
| 3 |
+
from langchain_core.documents import Document
|
| 4 |
+
|
| 5 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 6 |
+
from langchain_community.utilities.wikipedia import WikipediaAPIWrapper
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class WikipediaLoader(BaseLoader):
|
| 10 |
+
"""Load from `Wikipedia`.
|
| 11 |
+
|
| 12 |
+
The hard limit on the length of the query is 300 for now.
|
| 13 |
+
|
| 14 |
+
Each wiki page represents one Document.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
query: str,
|
| 20 |
+
lang: str = "en",
|
| 21 |
+
load_max_docs: Optional[int] = 25,
|
| 22 |
+
load_all_available_meta: Optional[bool] = False,
|
| 23 |
+
doc_content_chars_max: Optional[int] = 4000,
|
| 24 |
+
):
|
| 25 |
+
"""
|
| 26 |
+
Initializes a new instance of the WikipediaLoader class.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
query (str): The query string to search on Wikipedia.
|
| 30 |
+
lang (str, optional): The language code for the Wikipedia language edition.
|
| 31 |
+
Defaults to "en".
|
| 32 |
+
load_max_docs (int, optional): The maximum number of documents to load.
|
| 33 |
+
Defaults to 100.
|
| 34 |
+
load_all_available_meta (bool, optional): Indicates whether to load all
|
| 35 |
+
available metadata for each document. Defaults to False.
|
| 36 |
+
doc_content_chars_max (int, optional): The maximum number of characters
|
| 37 |
+
for the document content. Defaults to 4000.
|
| 38 |
+
"""
|
| 39 |
+
self.query = query
|
| 40 |
+
self.lang = lang
|
| 41 |
+
self.load_max_docs = load_max_docs
|
| 42 |
+
self.load_all_available_meta = load_all_available_meta
|
| 43 |
+
self.doc_content_chars_max = doc_content_chars_max
|
| 44 |
+
|
| 45 |
+
def lazy_load(self) -> Iterator[Document]:
|
| 46 |
+
"""
|
| 47 |
+
Loads the query result from Wikipedia into a list of `Document` objects.
|
| 48 |
+
|
| 49 |
+
Returns:
|
| 50 |
+
A list of `Document` objects representing the loaded
|
| 51 |
+
Wikipedia pages.
|
| 52 |
+
"""
|
| 53 |
+
client = WikipediaAPIWrapper( # type: ignore[call-arg]
|
| 54 |
+
lang=self.lang,
|
| 55 |
+
top_k_results=self.load_max_docs, # type: ignore[arg-type]
|
| 56 |
+
load_all_available_meta=self.load_all_available_meta, # type: ignore[arg-type]
|
| 57 |
+
doc_content_chars_max=self.doc_content_chars_max, # type: ignore[arg-type]
|
| 58 |
+
)
|
| 59 |
+
yield from client.load(self.query)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/word_document.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Loads word documents."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import tempfile
|
| 5 |
+
from abc import ABC
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, List, Union
|
| 8 |
+
from urllib.parse import urlparse
|
| 9 |
+
|
| 10 |
+
import requests
|
| 11 |
+
from langchain_core.documents import Document
|
| 12 |
+
|
| 13 |
+
from langchain_community.document_loaders.base import BaseLoader
|
| 14 |
+
from langchain_community.document_loaders.unstructured import (
|
| 15 |
+
UnstructuredFileLoader,
|
| 16 |
+
validate_unstructured_version,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Docx2txtLoader(BaseLoader, ABC):
|
| 21 |
+
"""Load `DOCX` file using `docx2txt` and chunks at character level.
|
| 22 |
+
|
| 23 |
+
Defaults to check for local file, but if the file is a web path, it will download it
|
| 24 |
+
to a temporary file, and use that, then clean up the temporary file after completion
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self, file_path: Union[str, Path]):
|
| 28 |
+
"""Initialize with file path."""
|
| 29 |
+
self.file_path = str(file_path)
|
| 30 |
+
self.original_file_path = self.file_path
|
| 31 |
+
if "~" in self.file_path:
|
| 32 |
+
self.file_path = os.path.expanduser(self.file_path)
|
| 33 |
+
|
| 34 |
+
# If the file is a web path, download it to a temporary file, and use that
|
| 35 |
+
if not os.path.isfile(self.file_path) and self._is_valid_url(self.file_path):
|
| 36 |
+
r = requests.get(self.file_path)
|
| 37 |
+
|
| 38 |
+
if r.status_code != 200:
|
| 39 |
+
raise ValueError(
|
| 40 |
+
"Check the url of your file; returned status code %s"
|
| 41 |
+
% r.status_code
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
self.web_path = self.file_path
|
| 45 |
+
self.temp_file = tempfile.NamedTemporaryFile()
|
| 46 |
+
self.temp_file.write(r.content)
|
| 47 |
+
self.file_path = self.temp_file.name
|
| 48 |
+
elif not os.path.isfile(self.file_path):
|
| 49 |
+
raise ValueError("File path %s is not a valid file or url" % self.file_path)
|
| 50 |
+
|
| 51 |
+
def __del__(self) -> None:
|
| 52 |
+
if hasattr(self, "temp_file"):
|
| 53 |
+
self.temp_file.close()
|
| 54 |
+
|
| 55 |
+
def load(self) -> List[Document]:
|
| 56 |
+
"""Load given path as single page."""
|
| 57 |
+
import docx2txt
|
| 58 |
+
|
| 59 |
+
return [
|
| 60 |
+
Document(
|
| 61 |
+
page_content=docx2txt.process(self.file_path),
|
| 62 |
+
metadata={"source": self.original_file_path},
|
| 63 |
+
)
|
| 64 |
+
]
|
| 65 |
+
|
| 66 |
+
@staticmethod
|
| 67 |
+
def _is_valid_url(url: str) -> bool:
|
| 68 |
+
"""Check if the url is valid."""
|
| 69 |
+
parsed = urlparse(url)
|
| 70 |
+
return bool(parsed.netloc) and bool(parsed.scheme)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class UnstructuredWordDocumentLoader(UnstructuredFileLoader):
|
| 74 |
+
"""Load `Microsoft Word` file using `Unstructured`.
|
| 75 |
+
|
| 76 |
+
Works with both .docx and .doc files.
|
| 77 |
+
You can run the loader in one of two modes: "single" and "elements".
|
| 78 |
+
If you use "single" mode, the document will be returned as a single
|
| 79 |
+
langchain Document object. If you use "elements" mode, the unstructured
|
| 80 |
+
library will split the document into elements such as Title and NarrativeText.
|
| 81 |
+
You can pass in additional unstructured kwargs after mode to apply
|
| 82 |
+
different unstructured settings.
|
| 83 |
+
|
| 84 |
+
Examples
|
| 85 |
+
--------
|
| 86 |
+
from langchain_community.document_loaders import UnstructuredWordDocumentLoader
|
| 87 |
+
|
| 88 |
+
loader = UnstructuredWordDocumentLoader(
|
| 89 |
+
"example.docx", mode="elements", strategy="fast",
|
| 90 |
+
)
|
| 91 |
+
docs = loader.load()
|
| 92 |
+
|
| 93 |
+
References
|
| 94 |
+
----------
|
| 95 |
+
https://unstructured-io.github.io/unstructured/bricks.html#partition-docx
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
def __init__(
|
| 99 |
+
self,
|
| 100 |
+
file_path: Union[str, Path],
|
| 101 |
+
mode: str = "single",
|
| 102 |
+
**unstructured_kwargs: Any,
|
| 103 |
+
):
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
Args:
|
| 107 |
+
file_path: The path to the Word file to load.
|
| 108 |
+
mode: The mode to use when loading the file. Can be one of "single",
|
| 109 |
+
"multi", or "all". Default is "single".
|
| 110 |
+
**unstructured_kwargs: Any kwargs to pass to the unstructured.
|
| 111 |
+
"""
|
| 112 |
+
file_path = str(file_path)
|
| 113 |
+
super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
|
| 114 |
+
|
| 115 |
+
def _get_elements(self) -> List:
|
| 116 |
+
from unstructured.file_utils.filetype import FileType, detect_filetype
|
| 117 |
+
|
| 118 |
+
# NOTE(MthwRobinson) - magic will raise an import error if the libmagic
|
| 119 |
+
# system dependency isn't installed. If it's not installed, we'll just
|
| 120 |
+
# check the file extension
|
| 121 |
+
try:
|
| 122 |
+
import magic # noqa: F401
|
| 123 |
+
|
| 124 |
+
is_doc = detect_filetype(self.file_path) == FileType.DOC
|
| 125 |
+
except ImportError:
|
| 126 |
+
_, extension = os.path.splitext(str(self.file_path))
|
| 127 |
+
is_doc = extension == ".doc"
|
| 128 |
+
|
| 129 |
+
if is_doc:
|
| 130 |
+
validate_unstructured_version("0.4.11")
|
| 131 |
+
|
| 132 |
+
if is_doc:
|
| 133 |
+
from unstructured.partition.doc import partition_doc
|
| 134 |
+
|
| 135 |
+
return partition_doc(filename=self.file_path, **self.unstructured_kwargs)
|
| 136 |
+
else:
|
| 137 |
+
from unstructured.partition.docx import partition_docx
|
| 138 |
+
|
| 139 |
+
return partition_docx(filename=self.file_path, **self.unstructured_kwargs)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/xml.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Loads Microsoft Excel files."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Any, List, Union
|
| 5 |
+
|
| 6 |
+
from langchain_community.document_loaders.unstructured import (
|
| 7 |
+
UnstructuredFileLoader,
|
| 8 |
+
validate_unstructured_version,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class UnstructuredXMLLoader(UnstructuredFileLoader):
|
| 13 |
+
"""Load `XML` file using `Unstructured`.
|
| 14 |
+
|
| 15 |
+
You can run the loader in one of two modes: "single" and "elements".
|
| 16 |
+
If you use "single" mode, the document will be returned as a single
|
| 17 |
+
langchain Document object. If you use "elements" mode, the unstructured
|
| 18 |
+
library will split the document into elements such as Title and NarrativeText.
|
| 19 |
+
You can pass in additional unstructured kwargs after mode to apply
|
| 20 |
+
different unstructured settings.
|
| 21 |
+
|
| 22 |
+
Examples
|
| 23 |
+
--------
|
| 24 |
+
from langchain_community.document_loaders import UnstructuredXMLLoader
|
| 25 |
+
|
| 26 |
+
loader = UnstructuredXMLLoader(
|
| 27 |
+
"example.xml", mode="elements", strategy="fast",
|
| 28 |
+
)
|
| 29 |
+
docs = loader.load()
|
| 30 |
+
|
| 31 |
+
References
|
| 32 |
+
----------
|
| 33 |
+
https://unstructured-io.github.io/unstructured/bricks.html#partition-xml
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
file_path: Union[str, Path],
|
| 39 |
+
mode: str = "single",
|
| 40 |
+
**unstructured_kwargs: Any,
|
| 41 |
+
):
|
| 42 |
+
file_path = str(file_path)
|
| 43 |
+
validate_unstructured_version(min_unstructured_version="0.6.7")
|
| 44 |
+
super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
|
| 45 |
+
|
| 46 |
+
def _get_elements(self) -> List:
|
| 47 |
+
from unstructured.partition.xml import partition_xml
|
| 48 |
+
|
| 49 |
+
return partition_xml(filename=self.file_path, **self.unstructured_kwargs)
|