id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
21edf055ea62-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 = []
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
21edf055ea62-2 | api_hash: The API hash.
username: The username.
file_path: The file path to save the data to. Defaults to
"telegram_data.json".
"""
self.chat_entity = chat_entity
self.api_id = api_id
self.api_hash = api_hash
self.username = username
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
21edf055ea62-3 | Returns:
dict: A dictionary where the key is the parent message ID and \
the value is a list of message IDs in ascending order.
"""
def find_replies(parent_id: int, reply_data: pd.DataFrame) -> List[int]:
"""
Recursively find all replies to a given par... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
21edf055ea62-4 | }
return message_threads
def _combine_message_texts(
self, message_threads: Dict[int, List[int]], data: pd.DataFrame
) -> str:
"""
Combine the message texts for each parent message ID based \
on the list of message threads.
Args:
message_threads (d... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
21edf055ea62-5 | """
)
p = Path(self.file_path)
with open(p, encoding="utf8") as f:
d = json.load(f)
try:
import pandas as pd
except ImportError:
raise ImportError(
"""`pandas` package not found.
please install with `pip... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
9a86553edf1d-0 | Source code for langchain.document_loaders.apify_dataset
from typing import Any, Callable, Dict, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.pydantic_v1 import BaseModel, root_validator
[docs]class ApifyDatasetLoader(BaseLoader, BaseModel):... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/apify_dataset.html |
9a86553edf1d-1 | dictionary (an Apify dataset item) and converts it to an instance
of the Document class.
"""
super().__init__(
dataset_id=dataset_id, dataset_mapping_function=dataset_mapping_function
)
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/apify_dataset.html |
b2301f82470c-0 | Source code for langchain.document_loaders.larksuite
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 LarkSuiteDocLoader(BaseLoader):
"""Load from `LarkSuite` (`FeiShu`)."""
[d... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/larksuite.html |
b2301f82470c-1 | f"{api_url_prefix}/{self.document_id}/raw_content"
)
text = raw_content_json["data"]["content"]
metadata = {
"document_id": self.document_id,
"revision_id": metadata_json["data"]["document"]["revision_id"],
"title": metadata_json["data"]["document"]["title"],
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/larksuite.html |
9c54ab426776-0 | Source code for langchain.document_loaders.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.
It loads data from either main page results or the comments p... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hn.html |
9c54ab426776-1 | ranking = lineItem.select_one("span[class='rank']").text
link = lineItem.find("span", {"class": "titleline"}).find("a").get("href")
title = lineItem.find("span", {"class": "titleline"}).text.strip()
metadata = {
"source": self.web_path,
"title": title,... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hn.html |
c2d668c554a8-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):
"""Load from `... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html |
c2d668c554a8-1 | self.query = query
self.user = user
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 = (
pag... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html |
c2d668c554a8-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html |
d0fbdd4ff4cd-0 | Source code for langchain.document_loaders.html
from typing import List
from langchain.document_loaders.unstructured import UnstructuredFileLoader
[docs]class UnstructuredHTMLLoader(UnstructuredFileLoader):
"""Load `HTML` files using `Unstructured`.
You can run the loader in one of two modes: "single" and "elem... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/html.html |
460300f1d497-0 | Source code for langchain.document_loaders.obs_directory
# coding:utf-8
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.obs_file import OBSFileLoader
[docs]class OBSDirectoryLoader(BaseLoader):
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obs_directory.html |
460300f1d497-1 | Note:
Before using this class, make sure you have registered with OBS and have the necessary credentials. The `ak`, `sk`, and `endpoint` values are mandatory unless `get_token_from_ecs` is True or the bucket policy is public read. `token` is required when using temporary credentials.
Example:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obs_directory.html |
460300f1d497-2 | )
if resp.status < 300:
for content in resp.body.contents:
loader = OBSFileLoader(self.bucket, content.key, client=self.client)
docs.extend(loader.load())
if resp.body.is_truncated is True:
mark = resp.body.next_mark... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obs_directory.html |
f2b48409902d-0 | Source code for langchain.document_loaders.image_captions
from io import BytesIO
from typing import Any, List, Tuple, Union
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class ImageCaptionLoader(BaseLoader):
"""Load image captions.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html |
f2b48409902d-1 | "`pip install transformers`."
)
processor = BlipProcessor.from_pretrained(self.blip_processor)
model = BlipForConditionalGeneration.from_pretrained(self.blip_model)
results = []
for image in self.images:
caption, metadata = self._get_captions_and_metadata(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html |
f2b48409902d-2 | if isinstance(image_source, bytes):
metadata: dict = {"image_source": "Image bytes provided"}
else:
metadata = {"image_path": image_source}
return caption, metadata | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html |
b289f6ee5b3d-0 | Source code for langchain.document_loaders.baiducloud_bos_file
import logging
import os
import tempfile
from typing import Any, Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.unstructured import UnstructuredFileLoade... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/baiducloud_bos_file.html |
b289f6ee5b3d-1 | client.get_object_to_file(self.bucket, self.key, file_path)
try:
loader = UnstructuredFileLoader(file_path)
documents = loader.load()
return iter(documents)
except Exception as ex:
logger.error(f"load document error = {ex}")
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/baiducloud_bos_file.html |
ed4b8cefffab-0 | Source code for langchain.document_loaders.figma
import json
import urllib.request
from typing import Any, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utils import stringify_dict
[docs]class FigmaFileLoader(BaseLoader):
"""Load `Figma` ... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/figma.html |
f85710b32147-0 | Source code for langchain.document_loaders.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):
"""Load `GitBook` data.
1.... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html |
f85710b32147-1 | self.base_url = self.base_url[:-1]
if load_all_paths:
# set web_path to the sitemap if we want to crawl all paths
web_page = f"{self.base_url}/sitemap.xml"
super().__init__(web_paths=(web_page,), continue_on_failure=continue_on_failure)
self.load_all_paths = load_all_path... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html |
f85710b32147-2 | return Document(page_content=content, metadata=metadata)
def _get_paths(self, soup: Any) -> List[str]:
"""Fetch all relative paths in the navbar."""
return [urlparse(loc.text).path for loc in soup.find_all("loc")] | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html |
ede3c2ffc6f5-0 | Source code for langchain.document_loaders.html_bs
import logging
from typing import Dict, List, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = logging.getLogger(__name__)
[docs]class BSHTMLLoader(BaseLoader):
"""Load `HTML` files and parse the... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html |
ede3c2ffc6f5-1 | with open(self.file_path, "r", encoding=self.open_encoding) as f:
soup = BeautifulSoup(f, **self.bs_kwargs)
text = soup.get_text(self.get_text_separator)
if soup.title:
title = str(soup.title.string)
else:
title = ""
metadata: Dict[str, Union[str, None... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html |
4217136fd77b-0 | Source code for langchain.document_loaders.dataframe
from typing import Any, Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class BaseDataFrameLoader(BaseLoader):
[docs] def __init__(self, data_frame: Any, *, page_content_column: str = "te... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/dataframe.html |
4217136fd77b-1 | if not isinstance(data_frame, pd.DataFrame):
raise ValueError(
f"Expected data_frame to be a pd.DataFrame, got {type(data_frame)}"
)
super().__init__(data_frame, page_content_column=page_content_column) | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/dataframe.html |
76797d9b0cbf-0 | Source code for langchain.document_loaders.onedrive_file
from __future__ import annotations
import tempfile
from typing import TYPE_CHECKING, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.unstructured import UnstructuredFileL... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive_file.html |
c6bde6f244ef-0 | Source code for langchain.document_loaders.sitemap
import itertools
import re
from typing import Any, Callable, Generator, Iterable, List, Optional, Tuple
from urllib.parse import urlparse
from langchain.document_loaders.web_base import WebBaseLoader
from langchain.schema import Document
def _default_parsing_function(c... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html |
c6bde6f244ef-1 | into downstream systems (e.g., data loader is used to load data for indexing).
This loader is a crawler and web crawlers should generally NOT be deployed
with network access to any internal servers.
Control access to who can submit crawling requests and what network access
the crawler ha... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html |
c6bde6f244ef-2 | interpreted as regular expression syntax. For example, `.` appears
frequently in URLs and should be escaped if you want to match a literal
`.` rather than any character.
restrict_to_same_domain takes precedence over filter_urls when
restrict_to_same_domain... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html |
c6bde6f244ef-3 | )
super().__init__(web_paths=[web_path], **kwargs)
# Define a list of URL patterns (interpreted as regular expressions) that
# will be allowed to be loaded.
# restrict_to_same_domain takes precedence over filter_urls when
# restrict_to_same_domain is True and the sitemap is not a... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html |
c6bde6f244ef-4 | if (prop := url.find(tag))
}
)
for sitemap in soup.find_all("sitemap"):
loc = sitemap.find("loc")
if not loc:
continue
soup_child = self.scrape_all([loc.text], "xml")[0]
els.extend(self.parse_sitemap(soup_child))
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html |
627c314e34dc-0 | Source code for langchain.document_loaders.tencent_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.tencent_cos_file import TencentCOSFileLoader
[docs]class TencentCOSDirectoryLoad... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tencent_cos_directory.html |
627c314e34dc-1 | if content["Key"].endswith("/"):
continue
loader = TencentCOSFileLoader(self.conf, self.bucket, content["Key"])
yield loader.load()[0] | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tencent_cos_directory.html |
165adbf572ac-0 | Source code for langchain.document_loaders.reddit
from __future__ import annotations
from typing import TYPE_CHECKING, Iterable, List, Optional, Sequence
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE_CHECKING:
import praw
def _dependable_praw_import(... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/reddit.html |
165adbf572ac-1 | self.user_agent = user_agent
self.search_queries = search_queries
self.mode = mode
self.categories = categories
self.number_posts = number_posts
[docs] def load(self) -> List[Document]:
"""Load reddits."""
praw = _dependable_praw_import()
reddit = praw.Reddit(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/reddit.html |
165adbf572ac-2 | "post_category": category,
"post_title": post.title,
"post_score": post.score,
"post_id": post.id,
"post_url": post.url,
"post_author": post.author,
}
yield Document(
page_content=post.selftext,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/reddit.html |
dac9f474d297-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"""
[docs] def __init__(self, loaders: List... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/merge.html |
094af0c289aa-0 | Source code for langchain.document_loaders.azlyrics
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class AZLyricsLoader(WebBaseLoader):
"""Load `AZLyrics` webpages."""
[docs] def load(self) -> List[Document]:
""... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/azlyrics.html |
8abbde1a4046-0 | Source code for langchain.document_loaders.odt
from typing import Any, List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
validate_unstructured_version,
)
[docs]class UnstructuredODTLoader(UnstructuredFileLoader):
"""Load `OpenOffice ODT` files using `Unstructured`.
You c... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/odt.html |
8abbde1a4046-1 | super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
def _get_elements(self) -> List:
from unstructured.partition.odt import partition_odt
return partition_odt(filename=self.file_path, **self.unstructured_kwargs) | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/odt.html |
8ecc17f2b944-0 | Source code for langchain.document_loaders.notion
from pathlib import Path
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class NotionDirectoryLoader(BaseLoader):
"""Load `Notion directory` dump."""
[docs] def __init__(self, p... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notion.html |
5e0cc3c2f122-0 | Source code for langchain.document_loaders.recursive_url_loader
from __future__ import annotations
import asyncio
import logging
import re
from typing import (
TYPE_CHECKING,
Callable,
Iterator,
List,
Optional,
Sequence,
Set,
Union,
)
import requests
from langchain.docstore.document impo... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html |
5e0cc3c2f122-1 | Control access to who can submit crawling requests and what network access
the crawler has.
While crawling, the crawler may encounter malicious URLs that would lead to a
server-side request forgery (SSRF) attack.
To mitigate risks, the crawler by default will only load URLs from the same... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html |
5e0cc3c2f122-2 | max_depth: The max depth of the recursive loading.
use_async: Whether to use asynchronous loading.
If True, this function will not be lazy, but it will still work in the
expected way, just not lazy.
extractor: A function to extract document contents from raw html.... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html |
5e0cc3c2f122-3 | f"exclude_dirs: {self.exclude_dirs}"
)
self.timeout = timeout
self.prevent_outside = prevent_outside if prevent_outside is not None else True
self.link_regex = link_regex
self._lock = asyncio.Lock() if self.use_async else None
self.headers = headers
self.check... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html |
5e0cc3c2f122-4 | url,
base_url=self.url,
pattern=self.link_regex,
prevent_outside=self.prevent_outside,
exclude_prefixes=self.exclude_dirs,
)
for link in sub_links:
# Check all unvisited links
if link not in visited:
yield from self.... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html |
5e0cc3c2f122-5 | visited.add(url)
try:
async with session.get(url) as response:
text = await response.text()
if self.check_response_status and 400 <= response.status <= 599:
raise ValueError(f"Received HTTP status {response.status}")
except (aiohttp.client_... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html |
5e0cc3c2f122-6 | # We don't want to stop the whole process, so just ignore it
# Not standard html format or invalid url or 404 may cause this.
continue
# locking not fully working, temporary hack to ensure deduplication
results += [r for r in sub_result if r not in... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html |
136556e804c1-0 | Source code for langchain.document_loaders.modern_treasury
import json
import urllib.request
from base64 import b64encode
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utils import get_from_env, stringify_value
MO... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/modern_treasury.html |
136556e804c1-1 | resource: str,
organization_id: Optional[str] = None,
api_key: Optional[str] = None,
) -> None:
"""
Args:
resource: The Modern Treasury resource to load.
organization_id: The Modern Treasury organization ID. It can also be
specified via the envi... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/modern_treasury.html |
e0c5b8799757-0 | Source code for langchain.document_loaders.blob_loaders.schema
"""Schema for Blobs and Blob Loaders.
The goal is to facilitate decoupling of content loading from content parsing code.
In addition, content loading code should provide a lazy loading interface by default.
"""
from __future__ import annotations
import cont... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html |
e0c5b8799757-1 | return str(self.path) if self.path else None
@root_validator(pre=True)
def check_blob_is_valid(cls, values: Mapping[str, Any]) -> Mapping[str, Any]:
"""Verify that either data or path is provided."""
if "data" not in values and "path" not in values:
raise ValueError("Either data or p... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html |
e0c5b8799757-2 | yield f
else:
raise NotImplementedError(f"Unable to convert blob {self}")
[docs] @classmethod
def from_path(
cls,
path: PathLike,
*,
encoding: str = "utf-8",
mime_type: Optional[str] = None,
guess_type: bool = True,
) -> Blob:
"""Loa... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html |
e0c5b8799757-3 | mime_type: if provided, will be set as the mime-type of the data
path: if provided, will be set as the source from which the data came
Returns:
Blob instance
"""
return cls(data=data, mimetype=mime_type, encoding=encoding, path=path)
def __repr__(self) -> str:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html |
39ae4090a20a-0 | Source code for langchain.document_loaders.blob_loaders.file_system
"""Use to load blobs from the local file system."""
from pathlib import Path
from typing import Callable, Iterable, Iterator, Optional, Sequence, TypeVar, Union
from langchain.document_loaders.blob_loaders.schema import Blob, BlobLoader
T = TypeVar("T"... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html |
39ae4090a20a-1 | *,
glob: str = "**/[!.]*",
exclude: Sequence[str] = (),
suffixes: Optional[Sequence[str]] = None,
show_progress: bool = False,
) -> None:
"""Initialize with a path to directory and how to glob over it.
Args:
path: Path to directory to load from
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html |
39ae4090a20a-2 | elif isinstance(path, str):
_path = Path(path)
else:
raise TypeError(f"Expected str or Path, got {type(path)}")
self.path = _path.expanduser() # Expand user to handle ~
self.glob = glob
self.suffixes = set(suffixes or [])
self.show_progress = show_progres... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html |
3989c6dccfee-0 | Source code for langchain.document_loaders.blob_loaders.youtube_audio
from typing import Iterable, List
from langchain.document_loaders.blob_loaders import FileSystemBlobLoader
from langchain.document_loaders.blob_loaders.schema import Blob, BlobLoader
[docs]class YoutubeAudioLoader(BlobLoader):
"""Load YouTube url... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/youtube_audio.html |
f7255c39df3d-0 | Source code for langchain.document_loaders.parsers.msword
from typing import Iterator
from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.blob_loaders import Blob
from langchain.schema import Document
[docs]class MsWordParser(BaseBlobParser):
"""Parse the Microsoft Word docume... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/msword.html |
44b317e6acee-0 | Source code for langchain.document_loaders.parsers.txt
"""Module for parsing text files.."""
from typing import Iterator
from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.blob_loaders import Blob
from langchain.schema import Document
[docs]class TextParser(BaseBlobParser):
"... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/txt.html |
78df72f7297f-0 | Source code for langchain.document_loaders.parsers.pdf
"""Module contains common parsers for PDFs."""
from __future__ import annotations
import warnings
from typing import (
TYPE_CHECKING,
Any,
Iterable,
Iterator,
Mapping,
Optional,
Sequence,
Union,
)
from urllib.parse import urlparse
im... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
78df72f7297f-1 | except ImportError:
raise ImportError(
"`rapidocr-onnxruntime` package not found, please install it with "
"`pip install rapidocr-onnxruntime`"
)
ocr = RapidOCR()
text = ""
for img in images:
result, _ = ocr(img)
if result:
result = [text[1... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
78df72f7297f-2 | images = []
for obj in xObject:
if xObject[obj]["/Subtype"] == "/Image":
if xObject[obj]["/Filter"][1:] in _PDF_FILTER_WITHOUT_LOSS:
height, width = xObject[obj]["/Height"], xObject[obj]["/Width"]
images.append(
np.fromb... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
78df72f7297f-3 | yield Document(page_content=text, metadata=metadata)
else:
from pdfminer.pdfpage import PDFPage
pages = PDFPage.get_pages(pdf_file_obj)
for i, _ in enumerate(pages):
text = extract_text(pdf_file_obj, page_numbers=[i])
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
78df72f7297f-4 | """Extract images from page and get the text with RapidOCR."""
import pdfminer
def get_image(layout_object: Any) -> Any:
if isinstance(layout_object, pdfminer.layout.LTImage):
return layout_object
if isinstance(layout_object, pdfminer.layout.LTContainer):
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
78df72f7297f-5 | import fitz
with blob.as_bytes_io() as file_path:
doc = fitz.open(file_path) # open document
yield from [
Document(
page_content=page.get_text(**self.text_kwargs)
+ self._extract_images_from_page(doc, page),
met... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
78df72f7297f-6 | try:
import pypdfium2 # noqa:F401
except ImportError:
raise ImportError(
"pypdfium2 package not found, please install it with"
" `pip install pypdfium2`"
)
self.extract_images = extract_images
[docs] def lazy_parse(self, blob: Blob)... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
78df72f7297f-7 | [docs]class PDFPlumberParser(BaseBlobParser):
"""Parse `PDF` with `PDFPlumber`."""
[docs] def __init__(
self,
text_kwargs: Optional[Mapping[str, Any]] = None,
dedupe: bool = False,
extract_images: bool = False,
) -> None:
"""Initialize the parser.
Args:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
78df72f7297f-8 | """Process the page content based on dedupe."""
if self.dedupe:
return page.dedupe_chars().extract_text(**self.text_kwargs)
return page.extract_text(**self.text_kwargs)
def _extract_images_from_page(self, page: pdfplumber.page.Page) -> str:
"""Extract images from page and get the... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
78df72f7297f-9 | requirements.
Besides the AWS configuration, it is very similar to the other PDF
loaders, while also supporting JPEG, PNG and TIFF and non-native
PDF formats.
```python
from langchain.document_loaders import AmazonTextractPDFLoader
loader=AmazonTextractPDFLoader("example_data/alejandro_rosalez_s... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
78df72f7297f-10 | import textractor.entities.document as textractor
self.tc = tc
self.textractor = textractor
if textract_features is not None:
self.textract_features = [
tc.Textract_Features(f) for f in textract_features
]
else:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
78df72f7297f-11 | input_document=str(blob.path),
features=self.textract_features,
boto3_textract_client=self.boto3_textract_client,
)
else:
textract_response_json = self.tc.call_textract(
input_document=blob.as_bytes(),
features=self.textract... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
78df72f7297f-12 | """Lazily parse the blob."""
with blob.as_bytes_io() as file_obj:
poller = self.client.begin_analyze_document(self.model, file_obj)
result = poller.result()
docs = self._generate_docs(blob, result)
yield from docs | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
0f22622efe89-0 | Source code for langchain.document_loaders.parsers.generic
"""Code for generic / auxiliary parsers.
This module contains some logic to help assemble more sophisticated parsers.
"""
from typing import Iterator, Mapping, Optional
from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.b... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/generic.html |
0f22622efe89-1 | """
self.handlers = handlers
self.fallback_parser = fallback_parser
[docs] def lazy_parse(self, blob: Blob) -> Iterator[Document]:
"""Load documents from a blob."""
mimetype = blob.mimetype
if mimetype is None:
raise ValueError(f"{blob} does not have a mimetype.")
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/generic.html |
fb2dcee2baf9-0 | Source code for langchain.document_loaders.parsers.registry
"""Module includes a registry of default parser configurations."""
from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.parsers.generic import MimeTypeBasedParser
from langchain.document_loaders.parsers.msword import MsWor... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/registry.html |
e74c1c95fafc-0 | Source code for langchain.document_loaders.parsers.grobid
import logging
from typing import Dict, Iterator, List, Union
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.blob_loaders import Blob
logger = logging.ge... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/grobid.html |
e74c1c95fafc-1 | chunks = []
for section in sections:
sect = section.find("head")
if sect is not None:
for i, paragraph in enumerate(section.find_all("p")):
chunk_bboxes = []
paragraph_text = []
for i, sentence in enumerate(parag... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/grobid.html |
e74c1c95fafc-2 | "pages": (fpage, lpage),
}
chunks.append(paragraph_dict)
yield from [
Document(
page_content=chunk["text"],
metadata=dict(
{
"text": str(chunk["text"]),
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/grobid.html |
e74c1c95fafc-3 | xml_data = None
if xml_data is None:
return iter([])
else:
return self.process_xml(file_path, xml_data, self.segment_sentences) | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/grobid.html |
a270471d2920-0 | Source code for langchain.document_loaders.parsers.audio
import logging
import time
from typing import Dict, Iterator, Optional, Tuple
from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.blob_loaders import Blob
from langchain.schema import Document
logger = logging.getLogger(__na... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html |
a270471d2920-1 | # Audio chunk
chunk = audio[i : i + chunk_duration_ms]
file_obj = io.BytesIO(chunk.export(format="mp3").read())
if blob.source is not None:
file_obj.name = blob.source + f"_part_{split_number}.mp3"
else:
file_obj.name = f"part_{split_number... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html |
a270471d2920-2 | forced_decoder_ids = WhisperProcessor.get_decoder_prompt_ids(language="french",
task="transcribe")
forced_decoder_ids = WhisperProcessor.get_decoder_prompt_ids(language="french",
task="translate")
"""
[docs] def __init__(
self,
device: str = "0",
lang_model: Opti... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html |
a270471d2920-3 | # check GPU memory and select automatically the model
mem = torch.cuda.get_device_properties(self.device).total_memory / (
1024**2
)
if mem < 5000:
rec_model = "openai/whisper-base"
elif mem < 7000:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html |
a270471d2920-4 | from pydub import AudioSegment
except ImportError:
raise ImportError(
"pydub package not found, please install it with `pip install pydub`"
)
try:
import librosa
except ImportError:
raise ImportError(
"librosa packag... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html |
a270471d2920-5 | Defaults to automatic language recognition.
Either `api_key` or `iam_token` must be provided, but not both.
"""
if (api_key is None) == (iam_token is None):
raise ValueError(
"Either 'api_key' or 'iam_token' must be provided, but not both."
)
self.... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html |
a270471d2920-6 | page_content=res.normalized_text,
metadata={"source": blob.source},
) | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html |
2b17500a51c9-0 | Source code for langchain.document_loaders.parsers.docai
"""Module contains a PDF parser based on Document AI from Google Cloud.
You need to install two libraries to use this parser:
pip install google-cloud-documentai
pip install google-cloud-documentai-toolbox
"""
import logging
import re
import time
from dataclasses... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html |
2b17500a51c9-1 | gcs_output_path: a path on Google Cloud Storage to store parsing results
processor_name: full resource name of a Document AI processor or processor
version
You should provide either a client or location (and then a client
would be instantiated).
"""
if boo... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html |
2b17500a51c9-2 | client_info=get_client_info(module="document-ai"),
)
[docs] def lazy_parse(self, blob: Blob) -> Iterator[Document]:
"""Parses a blob lazily.
Args:
blobs: a Blob to parse
This is a long-running operation. A recommended way is to batch
documents together and ... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html |
2b17500a51c9-3 | Document as WrappedDocument,
)
except ImportError as exc:
raise ImportError(
"documentai_toolbox package not found, please install it with"
" `pip install google-cloud-documentai-toolbox`"
) from exc
ocr_config = (
OcrConfig... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html |
2b17500a51c9-4 | Args:
blobs: a list of blobs to parse.
gcs_output_path: a path on Google Cloud Storage to store parsing results.
timeout_sec: a timeout to wait for Document AI to complete, in seconds.
check_in_interval_sec: an interval to wait until next check
whether par... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html |
2b17500a51c9-5 | yield from self.parse_from_results(results)
[docs] def parse_from_results(
self, results: List[DocAIParsingResults]
) -> Iterator[Document]:
try:
from google.cloud.documentai_toolbox.utilities.gcs_utilities import (
split_gcs_uri,
)
from google.... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html |
2b17500a51c9-6 | for name in operation_names
]
[docs] def is_running(self, operations: List["Operation"]) -> bool:
return any(not op.done() for op in operations)
[docs] def docai_parse(
self,
blobs: Sequence[Blob],
*,
gcs_output_path: Optional[str] = None,
processor_name: Op... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.