id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 53 121 |
|---|---|---|
8539d34acb87-0 | Source code for langchain.document_loaders.mastodon
"""Mastodon document loader."""
from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mastodon.html |
8539d34acb87-1 | access_token = access_token or os.environ.get("MASTODON_ACCESS_TOKEN")
self.api = mastodon.Mastodon(
access_token=access_token, api_base_url=api_base_url
)
self.mastodon_accounts = mastodon_accounts
self.number_toots = number_toots
self.exclude_replies = exclude_repli... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mastodon.html |
3695ff764293-0 | Source code for langchain.document_loaders.discord
"""Load from Discord chat dump"""
from __future__ import annotations
from typing import TYPE_CHECKING, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE_CHECKING:
import pandas as pd
[docs]class Dis... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/discord.html |
0a8d5b622bcb-0 | Source code for langchain.document_loaders.merge
from typing import Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class MergedDataLoader(BaseLoader):
"""Merge documents from a list of loaders"""
def __init__(self, loaders: List):
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/merge.html |
c8b7ed7e32a7-0 | Source code for langchain.document_loaders.s3_file
"""Loading logic for loading documents from an s3 file."""
import os
import tempfile
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.unstructured import Unst... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_file.html |
5c96e92624a1-0 | Source code for langchain.document_loaders.epub
"""Loader that loads EPub files."""
from typing import List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
satisfies_min_unstructured_version,
)
[docs]class UnstructuredEPubLoader(UnstructuredFileLoader):
"""Loader that uses unst... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/epub.html |
a1e46b49cee4-0 | Source code for langchain.document_loaders.duckdb_loader
from typing import Dict, List, Optional, cast
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class DuckDBLoader(BaseLoader):
"""Loads a query result from DuckDB into a list of documents.
Each ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/duckdb_loader.html |
a1e46b49cee4-1 | results = query_result.fetchall()
description = cast(list, query_result.description)
field_names = [c[0] for c in description]
if self.page_content_columns is None:
page_content_columns = field_names
else:
page_content_columns = self.page_c... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/duckdb_loader.html |
54127f2a91ee-0 | Source code for langchain.document_loaders.notebook
"""Loader that loads .ipynb notebook files."""
import json
from pathlib import Path
from typing import Any, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def concatenate_cells(
cell: dict, include_outp... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
54127f2a91ee-1 | return f"'{cell_type}' cell: '{source}'\n\n"
return ""
def remove_newlines(x: Any) -> Any:
"""Remove recursively newlines, no matter the data structure they are stored in."""
import pandas as pd
if isinstance(x, str):
return x.replace("\n", "")
elif isinstance(x, list):
return [remov... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
54127f2a91ee-2 | if self.remove_newline:
filtered_data = filtered_data.applymap(remove_newlines)
text = filtered_data.apply(
lambda x: concatenate_cells(
x, self.include_outputs, self.max_output_length, self.traceback
),
axis=1,
).str.cat(sep=" ")
m... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
630f0805cbd0-0 | Source code for langchain.document_loaders.odt
"""Loader that loads Open Office ODT files."""
from typing import Any, List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
validate_unstructured_version,
)
[docs]class UnstructuredODTLoader(UnstructuredFileLoader):
"""Loader that ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/odt.html |
1860c0beb4fe-0 | Source code for langchain.document_loaders.googledrive
"""Loader that loads data from Google Drive."""
# Prerequisites:
# 1. Create a Google Cloud project
# 2. Enable the Google Drive API:
# https://console.cloud.google.com/flows/enableapi?apiid=drive.googleapis.com
# 3. Authorize credentials for desktop app:
# htt... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
1860c0beb4fe-1 | # results in pydantic validation errors
file_loader_cls: Any = None
file_loader_kwargs: Dict["str", Any] = {}
@root_validator
def validate_inputs(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Validate that either folder_id or document_ids is set, but not both."""
if values.get("fold... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
1860c0beb4fe-2 | if file_type not in allowed_types:
raise ValueError(
f"Given file type {file_type} is not supported. "
f"Supported values are: {short_names}; and "
f"their full-form names: {full_names}"
)
# repla... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
1860c0beb4fe-3 | )
if self.token_path.exists():
creds = Credentials.from_authorized_user_file(str(self.token_path), SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
elif "GOOGLE_APPLICATION_CREDENTIAL... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
1860c0beb4fe-4 | metadata = {
"source": (
f"https://docs.google.com/spreadsheets/d/{id}/"
f"edit?gid={sheet['properties']['sheetId']}"
),
"title": f"{spreadsheet['properties']['title']} - {sheet_name}",
"row":... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
1860c0beb4fe-5 | text = fh.getvalue().decode("utf-8")
metadata = {
"source": f"https://docs.google.com/document/d/{id}/edit",
"title": f"{file.get('name')}",
}
return Document(page_content=text, metadata=metadata)
def _load_documents_from_folder(
self, folder_id: str, *, file_... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
1860c0beb4fe-6 | else:
pass
return returns
def _fetch_files_recursive(
self, service: Any, folder_id: str
) -> List[Dict[str, Union[str, List[str]]]]:
"""Fetch all files and subfolders recursively."""
results = (
service.files()
.list(
q=f"'... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
1860c0beb4fe-7 | file = service.files().get(fileId=id, supportsAllDrives=True).execute()
request = service.files().get_media(fileId=id)
fh = BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
if self... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
1860c0beb4fe-8 | )
elif self.document_ids:
return self._load_documents_from_ids()
else:
return self._load_file_from_ids() | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
af2a152dde91-0 | Source code for langchain.document_loaders.azure_blob_storage_file
"""Loading logic for loading documents from an Azure Blob Storage file."""
import os
import tempfile
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/azure_blob_storage_file.html |
8a6b52298574-0 | Source code for langchain.document_loaders.twitter
"""Twitter document loader."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE_CHEC... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html |
8a6b52298574-1 | user = api.get_user(screen_name=username)
docs = self._format_tweets(tweets, user)
results.extend(docs)
return results
def _format_tweets(
self, tweets: List[Dict[str, Any]], user_info: dict
) -> Iterable[Document]:
"""Format tweets into a string."""
for t... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html |
8a6b52298574-2 | access_token=access_token,
access_token_secret=access_token_secret,
consumer_key=consumer_key,
consumer_secret=consumer_secret,
)
return cls(
auth_handler=auth,
twitter_users=twitter_users,
number_tweets=number_tweets,
) | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html |
5afc3dd9a2a6-0 | Source code for langchain.document_loaders.hn
"""Loader that loads HN."""
from typing import Any, List
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class HNLoader(WebBaseLoader):
"""Load Hacker News data from either main page results or the com... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hn.html |
5afc3dd9a2a6-1 | title = lineItem.find("span", {"class": "titleline"}).text.strip()
metadata = {
"source": self.web_path,
"title": title,
"link": link,
"ranking": ranking,
}
documents.append(
Document(
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hn.html |
e60cb40b45e7-0 | Source code for langchain.document_loaders.gitbook
"""Loader that loads GitBook."""
from typing import Any, List, Optional
from urllib.parse import urljoin, urlparse
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class GitbookLoader(WebBaseLoader):
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html |
e60cb40b45e7-1 | [docs] def load(self) -> List[Document]:
"""Fetch text from one single GitBook page."""
if self.load_all_paths:
soup_info = self.scrape()
relative_paths = self._get_paths(soup_info)
documents = []
for path in relative_paths:
url = urljoi... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html |
38fc27d84aed-0 | Source code for langchain.document_loaders.college_confidential
"""Loader that loads College Confidential."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class CollegeConfidentialLoader(WebBaseLoader):
"""Loader that lo... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/college_confidential.html |
ce609b5da8f9-0 | Source code for langchain.document_loaders.powerpoint
"""Loader that loads powerpoint files."""
import os
from typing import List
from langchain.document_loaders.unstructured import UnstructuredFileLoader
[docs]class UnstructuredPowerPointLoader(UnstructuredFileLoader):
"""Loader that uses unstructured to load powe... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html |
dc7e82c61027-0 | Source code for langchain.document_loaders.larksuite
"""Loader that loads LarkSuite (FeiShu) document json dump."""
import json
import urllib.request
from typing import Any, Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class LarkSuiteDocLoa... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/larksuite.html |
dc7e82c61027-1 | metadata = {
"document_id": self.document_id,
"revision_id": metadata_json["data"]["document"]["revision_id"],
"title": metadata_json["data"]["document"]["title"],
}
yield Document(page_content=text, metadata=metadata)
[docs] def load(self) -> List[Document]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/larksuite.html |
485e2f7c79d7-0 | Source code for langchain.document_loaders.url_playwright
"""Loader that uses Playwright to load a page, then uses unstructured to load the html.
"""
import logging
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = logging.... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html |
485e2f7c79d7-1 | [docs] def load(self) -> List[Document]:
"""Load the specified URLs using Playwright and create Document instances.
Returns:
List[Document]: A list of Document instances with loaded content.
"""
from playwright.sync_api import sync_playwright
from unstructured.part... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html |
24bf9b80f9ef-0 | Source code for langchain.document_loaders.joplin
import json
import urllib
from datetime import datetime
from typing import Iterator, List, Optional
from langchain.document_loaders.base import BaseLoader
from langchain.schema import Document
from langchain.utils import get_from_env
LINK_NOTE_TEMPLATE = "joplin://x-cal... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/joplin.html |
24bf9b80f9ef-1 | )
self._get_tag_url = (
f"{base_url}/notes/{{id}}/tags?token={access_token}&fields=title"
)
def _get_notes(self) -> Iterator[Document]:
has_more = True
page = 1
while has_more:
req_note = urllib.request.Request(self._get_note_url.format(page=page))
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/joplin.html |
24bf9b80f9ef-2 | def _convert_date(self, date: int) -> str:
return datetime.fromtimestamp(date / 1000).strftime("%Y-%m-%d %H:%M:%S")
[docs] def lazy_load(self) -> Iterator[Document]:
yield from self._get_notes()
[docs] def load(self) -> List[Document]:
return list(self.lazy_load()) | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/joplin.html |
efef29343e55-0 | Source code for langchain.document_loaders.gcs_directory
"""Loading logic for loading documents from an GCS directory."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.gcs_file import GCSFileLoader
[docs]cl... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_directory.html |
6afd381084fb-0 | Source code for langchain.document_loaders.azure_blob_storage_container
"""Loading logic for loading documents from an Azure Blob Storage container."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.azure_blob_storage_file import (
AzureBlobStorageFileLoader... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/azure_blob_storage_container.html |
308c0f8acdfe-0 | Source code for langchain.document_loaders.url_selenium
"""Loader that uses Selenium to load a page, then uses unstructured to load the html.
"""
import logging
from typing import TYPE_CHECKING, List, Literal, Optional, Union
if TYPE_CHECKING:
from selenium.webdriver import Chrome, Firefox
from langchain.docstore.d... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html |
308c0f8acdfe-1 | raise ImportError(
"selenium package not found, please install it with "
"`pip install selenium`"
)
try:
import unstructured # noqa:F401
except ImportError:
raise ImportError(
"unstructured package not found, please ins... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html |
308c0f8acdfe-2 | for arg in self.arguments:
firefox_options.add_argument(arg)
if self.headless:
firefox_options.add_argument("--headless")
if self.binary_location is not None:
firefox_options.binary_location = self.binary_location
if self.executable_pat... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html |
760393548905-0 | Source code for langchain.document_loaders.snowflake_loader
from __future__ import annotations
from typing import Any, Dict, Iterator, List, Optional, Tuple
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class SnowflakeLoader(BaseLoader):
"""Loads a que... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html |
760393548905-1 | self.password = password
self.account = account
self.warehouse = warehouse
self.role = role
self.database = database
self.schema = schema
self.parameters = parameters
self.page_content_columns = (
page_content_columns if page_content_columns is not Non... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html |
760393548905-2 | ) -> Tuple[List[str], List[str]]:
page_content_columns = (
self.page_content_columns if self.page_content_columns else []
)
metadata_columns = self.metadata_columns if self.metadata_columns else []
if page_content_columns is None and query_result:
page_content_col... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html |
b024813683f9-0 | Source code for langchain.document_loaders.image_captions
"""
Loader that loads image captions
By default, the loader utilizes the pre-trained BLIP image captioning model.
https://huggingface.co/Salesforce/blip-image-captioning-base
"""
from typing import Any, List, Tuple, Union
import requests
from langchain.docstore.... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html |
b024813683f9-1 | model=model, processor=processor, path_image=path_image
)
doc = Document(page_content=caption, metadata=metadata)
results.append(doc)
return results
def _get_captions_and_metadata(
self, model: Any, processor: Any, path_image: str
) -> Tuple[str, dict]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html |
dc35463239d4-0 | Source code for langchain.document_loaders.wikipedia
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utilities.wikipedia import WikipediaAPIWrapper
[docs]class WikipediaLoader(BaseLoader):
"""Loads a query resul... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/wikipedia.html |
dc35463239d4-1 | Loads the query result from Wikipedia into a list of Documents.
Returns:
List[Document]: A list of Document objects representing the loaded
Wikipedia pages.
"""
client = WikipediaAPIWrapper(
lang=self.lang,
top_k_results=self.load_max_docs,
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/wikipedia.html |
fe3ca6d7fd80-0 | Source code for langchain.document_loaders.ifixit
"""Loader that loads iFixit data."""
from typing import List, Optional
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.web_base import WebBaseLoader
IFIXIT_BASE_URL =... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html |
fe3ca6d7fd80-1 | """Teardowns are just guides by a different name"""
self.page_type = pieces[0] if pieces[0] != "Teardown" else "Guide"
if self.page_type == "Guide" or self.page_type == "Answers":
self.id = pieces[2]
else:
self.id = pieces[1]
self.web_path = web_path
[docs] def... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html |
fe3ca6d7fd80-2 | self, url_override: Optional[str] = None
) -> List[Document]:
loader = WebBaseLoader(self.web_path if url_override is None else url_override)
soup = loader.scrape()
output = []
title = soup.find("h1", "post-title").text
output.append("# " + title)
output.append(soup.s... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html |
fe3ca6d7fd80-3 | data = res.json()
text = "\n".join(
[
data[key]
for key in ["title", "description", "contents_raw"]
if key in data
]
).strip()
metadata = {"source": self.web_path, "title": data["title"]}
documents.append(Document(pa... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html |
fe3ca6d7fd80-4 | else:
for part in data["parts"]:
doc_parts.append("\n - " + part["text"])
for row in data["steps"]:
doc_parts.append(
"\n\n## "
+ (
row["title"]
if row["title"] != ""
else "Step {}... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html |
65a931f3a15d-0 | Source code for langchain.document_loaders.docugami
"""Loader that loads processed documents from Docugami."""
import io
import logging
import os
import re
from pathlib import Path
from typing import Any, Dict, List, Mapping, Optional, Sequence, Union
import requests
from pydantic import BaseModel, root_validator
from ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
65a931f3a15d-1 | if values.get("file_paths") and values.get("docset_id"):
raise ValueError("Cannot specify both file_paths and remote API docset_id")
if not values.get("file_paths") and not values.get("docset_id"):
raise ValueError("Must specify either file_paths or remote API docset_id")
if valu... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
65a931f3a15d-2 | ancestor_chain = chunk.xpath("ancestor-or-self::*")
return "/" + "/".join(_xpath_qname_for_chunk(x) for x in ancestor_chain)
def _structure_value(node: Any) -> str:
"""Get the structure value for a node."""
structure = (
"table"
if node.tag == ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
65a931f3a15d-3 | """Create a Document from a node and text."""
metadata = {
XPATH_KEY: _xpath_for_chunk(node),
DOCUMENT_ID_KEY: document["id"],
DOCUMENT_NAME_KEY: document["name"],
STRUCTURE_KEY: node.attrib.get("structure", ""),
TAG_KEY: re.sub... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
65a931f3a15d-4 | while url:
response = requests.get(
url,
headers={"Authorization": f"Bearer {self.access_token}"},
)
if response.ok:
data = response.json()
all_documents.extend(data["documents"])
url = data.get("next", N... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
65a931f3a15d-5 | data={},
)
if response.ok:
data = response.json()
all_artifacts.extend(data["artifacts"])
url = data.get("next", None)
else:
raise Exception(
f"Failed to download {url} (status: {response.status_code}... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
65a931f3a15d-6 | per_file_metadata[doc_id] = metadata
else:
raise Exception(
f"Failed to download {artifact_url}/content "
+ "(status: {response.status_code})"
)
return per_file_metadata
def _load_chunks_for_document(
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
65a931f3a15d-7 | for project in _project_details:
metadata = self._metadata_for_project(project)
combined_project_metadata.update(metadata)
for doc in _document_details:
doc_metadata = combined_project_metadata.get(doc["id"])
chunks += self._load_chunks... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
16cfd5c24a18-0 | Source code for langchain.document_loaders.unstructured
"""Loader that uses unstructured to load files."""
import collections
from abc import ABC, abstractmethod
from typing import IO, Any, Dict, List, Sequence, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoade... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html |
16cfd5c24a18-1 | import unstructured # noqa:F401
except ImportError:
raise ValueError(
"unstructured package not found, please install it with "
"`pip install unstructured`"
)
_valid_modes = {"single", "elements", "paged"}
if mode not in _valid_modes:
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html |
16cfd5c24a18-2 | for idx, element in enumerate(elements):
metadata = self._get_metadata()
if hasattr(element, "metadata"):
metadata.update(element.metadata.to_dict())
page_number = metadata.get("page_number", 1)
# Check if this page_number already exist... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html |
16cfd5c24a18-3 | def _get_elements(self) -> List:
from unstructured.partition.auto import partition
return partition(filename=self.file_path, **self.unstructured_kwargs)
def _get_metadata(self) -> dict:
return {"source": self.file_path}
def get_elements_from_api(
file_path: Union[str, List[str], None] = ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html |
16cfd5c24a18-4 | url: str = "https://api.unstructured.io/general/v0/general",
api_key: str = "",
**unstructured_kwargs: Any,
):
"""Initialize with file path."""
if isinstance(file_path, str):
validate_unstructured_version(min_unstructured_version="0.6.2")
else:
validat... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html |
16cfd5c24a18-5 | def __init__(
self,
file: Union[IO, Sequence[IO]],
mode: str = "single",
url: str = "https://api.unstructured.io/general/v0/general",
api_key: str = "",
**unstructured_kwargs: Any,
):
"""Initialize with file path."""
if isinstance(file, collections.abc... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html |
2a599c5d7dfe-0 | Source code for langchain.document_loaders.telegram
"""Loader that loads Telegram chat json dump."""
from __future__ import annotations
import asyncio
import json
from pathlib import Path
from typing import TYPE_CHECKING, Dict, List, Optional, Union
from langchain.docstore.document import Document
from langchain.docume... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
2a599c5d7dfe-1 | if isinstance(text, str):
# Take a single string as one page
text = [text]
page_docs = [Document(page_content=page) for page in text]
# Add page numbers as metadata
for i, doc in enumerate(page_docs):
doc.metadata["page"] = i + 1
# Split pages into chunks
doc_chunks = []
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
2a599c5d7dfe-2 | [docs] async def fetch_data_from_telegram(self) -> None:
"""Fetch data from Telegram API and save it as a JSON file."""
from telethon.sync import TelegramClient
data = []
async with TelegramClient(self.username, self.api_id, self.api_hash) as client:
async for message in c... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
2a599c5d7dfe-3 | Args:
parent_id (int): The parent message ID.
reply_data (pd.DataFrame): A DataFrame containing reply messages.
Returns:
list: A list of message IDs that are replies to the parent message ID.
"""
# Find direct replies to the parent mess... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
2a599c5d7dfe-4 | message_threads (dict): A dictionary where the key is the parent message \
ID and the value is a list of message IDs in ascending order.
data (pd.DataFrame): A DataFrame containing the conversation data:
- message.sender_id
- text
- date
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
2a599c5d7dfe-5 | please install with `pip install pandas`
"""
)
normalized_messages = pd.json_normalize(d)
df = pd.DataFrame(normalized_messages)
message_threads = self._get_message_threads(df)
combined_texts = self._combine_message_texts(message_threads, df)
return te... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
5e73f9d512a4-0 | Source code for langchain.document_loaders.rtf
"""Loader that loads rich text files."""
from typing import Any, List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
satisfies_min_unstructured_version,
)
[docs]class UnstructuredRTFLoader(UnstructuredFileLoader):
"""Loader that u... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rtf.html |
b7da31fdc536-0 | Source code for langchain.document_loaders.bibtex
import logging
import re
from pathlib import Path
from typing import Any, Iterator, List, Mapping, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utilities.bibtex import BibtexparserWrapper... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html |
b7da31fdc536-1 | import fitz
parent_dir = Path(self.file_path).parent
# regex is useful for Zotero flavor bibtex files
file_names = self.file_regex.findall(entry.get("file", ""))
if not file_names:
return None
texts: List[str] = []
for file_name in file_names:
try:... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html |
b7da31fdc536-2 | yield doc
[docs] def load(self) -> List[Document]:
"""Load bibtex file documents from the given bibtex file path.
See https://bibtexparser.readthedocs.io/en/master/
Args:
file_path: the path to the bibtex file
Returns:
a list of documents with the document.page... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html |
06612c512db4-0 | Source code for langchain.document_loaders.python
import tokenize
from langchain.document_loaders.text import TextLoader
[docs]class PythonLoader(TextLoader):
"""
Load Python files, respecting any non-default encoding if specified.
"""
def __init__(self, file_path: str):
with open(file_path, "rb... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/python.html |
3f15ecf22015-0 | Source code for langchain.document_loaders.imsdb
"""Loader that loads IMSDb."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class IMSDbLoader(WebBaseLoader):
"""Loader that loads IMSDb webpages."""
[docs] def load(se... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/imsdb.html |
7d3cb91d935c-0 | Source code for langchain.document_loaders.bigquery
from __future__ import annotations
from typing import TYPE_CHECKING, List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE_CHECKING:
from google.auth.credentials import Credentials
[docs]clas... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html |
7d3cb91d935c-1 | self.project = project
self.page_content_columns = page_content_columns
self.metadata_columns = metadata_columns
self.credentials = credentials
[docs] def load(self) -> List[Document]:
try:
from google.cloud import bigquery
except ImportError as ex:
rai... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html |
ba36a4e23717-0 | Source code for langchain.document_loaders.tencent_cos_directory
"""Loading logic for loading documents from Tencent Cloud COS directory."""
from typing import Any, Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.tenc... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tencent_cos_directory.html |
ba36a4e23717-1 | for content in contents:
if content["Key"].endswith("/"):
continue
loader = TencentCOSFileLoader(self.conf, self.bucket, content["Key"])
yield loader.load()[0] | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tencent_cos_directory.html |
3ad17e6d40bf-0 | Source code for langchain.document_loaders.tomarkdown
"""Loader that loads HTML to markdown using 2markdown."""
from __future__ import annotations
from typing import Iterator, List
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class ToMarkd... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tomarkdown.html |
e7cf4b61b7aa-0 | Source code for langchain.document_loaders.org_mode
"""Loader that loads Org-Mode files."""
from typing import Any, List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
validate_unstructured_version,
)
[docs]class UnstructuredOrgModeLoader(UnstructuredFileLoader):
"""Loader tha... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/org_mode.html |
74eb798febbf-0 | Source code for langchain.document_loaders.embaas
import base64
import warnings
from typing import Any, Dict, Iterator, List, Optional
import requests
from pydantic import BaseModel, root_validator, validator
from typing_extensions import NotRequired, TypedDict
from langchain.docstore.document import Document
from lang... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
74eb798febbf-1 | """The instruction to pass to the Embaas document extraction API."""
class EmbaasDocumentExtractionPayload(EmbaasDocumentExtractionParameters):
"""Payload for the Embaas document extraction API."""
bytes: str
"""The base64 encoded bytes of the document to extract text from."""
class BaseEmbaasLoader(BaseMod... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
74eb798febbf-2 | # Custom api parameters (create embeddings automatically)
from langchain.document_loaders.embaas import EmbaasBlobLoader
loader = EmbaasBlobLoader(
params={
"should_embed": True,
"model": "e5-large-v2",
"chunk_size": 256... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
74eb798febbf-3 | payload["mime_type"] = blob.mimetype
return payload
def _handle_request(
self, payload: EmbaasDocumentExtractionPayload
) -> List[Document]:
"""Sends a request to the embaas API and handles the response."""
headers = {
"Authorization": f"Bearer {self.embaas_api_key}",... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
74eb798febbf-4 | it as a named parameter to the constructor.
Example:
.. code-block:: python
# Default parsing
from langchain.document_loaders.embaas import EmbaasLoader
loader = EmbaasLoader(file_path="example.mp3")
documents = loader.load()
# Custom api parameter... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
74eb798febbf-5 | yield from self.blob_loader.lazy_parse(blob=blob)
[docs] def load(self) -> List[Document]:
return list(self.lazy_load())
[docs] def load_and_split(
self, text_splitter: Optional[TextSplitter] = None
) -> List[Document]:
if self.params.get("should_embed", False):
warnings.wa... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
7097efc4139a-0 | Source code for langchain.document_loaders.csv_loader
import csv
from typing import Any, Dict, List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
validate_unstructure... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html |
7097efc4139a-1 | with open(self.file_path, newline="", encoding=self.encoding) as csvfile:
csv_reader = csv.DictReader(csvfile, **self.csv_args) # type: ignore
for i, row in enumerate(csv_reader):
content = "\n".join(f"{k.strip()}: {v.strip()}" for k, v in row.items())
try:
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html |
b89247e3945e-0 | Source code for langchain.document_loaders.evernote
"""Load documents from Evernote.
https://gist.github.com/foxmask/7b29c43a161e001ff04afdb2f181e31c
"""
import hashlib
import logging
from base64 import b64decode
from time import strptime
from typing import Any, Dict, Iterator, List, Optional
from langchain.docstore.do... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html |
b89247e3945e-1 | self.file_path = file_path
self.load_single_document = load_single_document
[docs] def load(self) -> List[Document]:
"""Load documents from EverNote export file."""
documents = [
Document(
page_content=note["content"],
metadata={
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html |
b89247e3945e-2 | rsc_dict["hash"] = hashlib.md5(rsc_dict[elem.tag]).hexdigest()
else:
rsc_dict[elem.tag] = elem.text
return rsc_dict
@staticmethod
def _parse_note(note: List, prefix: Optional[str] = None) -> dict:
note_dict: Dict[str, Any] = {}
resources = []
def add_p... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html |
b89247e3945e-3 | # Without huge_tree set to True, parser may complain about huge text node
# Try to recover, because there may be " ", which will cause
# "XMLSyntaxError: Entity 'nbsp' not defined"
try:
from lxml import etree
except ImportError as e:
logging.error(
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html |
70dec4aad125-0 | Source code for langchain.document_loaders.slack_directory
"""Loader for documents from a Slack export."""
import json
import zipfile
from pathlib import Path
from typing import Dict, List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class Slack... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/slack_directory.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.