id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
e39fff581ace-0
Source code for langchain.embeddings.self_hosted """Running custom embedding models on self-hosted remote hardware.""" from typing import Any, Callable, List from pydantic import Extra from langchain.embeddings.base import Embeddings from langchain.llms import SelfHostedPipeline def _embed_documents(pipeline: Any, *arg...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
e39fff581ace-1
model_load_fn=get_pipeline, hardware=gpu model_reqs=["./", "torch", "transformers"], ) Example passing in a pipeline path: .. code-block:: python from langchain.embeddings import SelfHostedHFEmbeddings import runhouse as rh from...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
e39fff581ace-2
[docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using a HuggingFace transformer model. Args: text: The text to embed. Returns: Embeddings for the text. """ text = text.replace("\n", " ") embeddings = self.clie...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
d49ec90c0f3f-0
Source code for langchain.embeddings.minimax """Wrapper around MiniMax APIs.""" from __future__ import annotations import logging from typing import Any, Callable, Dict, List, Optional import requests from pydantic import BaseModel, Extra, root_validator from tenacity import ( before_sleep_log, retry, stop_...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
d49ec90c0f3f-1
the constructor. Example: .. code-block:: python from langchain.embeddings import MiniMaxEmbeddings embeddings = MiniMaxEmbeddings() query_text = "This is a test query." query_result = embeddings.embed_query(query_text) document_text = "This is a t...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
d49ec90c0f3f-2
self, texts: List[str], embed_type: str, ) -> List[List[float]]: payload = { "model": self.model, "type": embed_type, "texts": texts, } # HTTP headers for authorization headers = { "Authorization": f"Bearer {self.minimax...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
d49ec90c0f3f-3
) return embeddings[0] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
c81b90f88854-0
Source code for langchain.embeddings.openai """Wrapper around OpenAI embedding models.""" from __future__ import annotations import logging from typing import ( Any, Callable, Dict, List, Literal, Optional, Sequence, Set, Tuple, Union, ) import numpy as np from pydantic import Ba...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
c81b90f88854-1
"""Use tenacity to retry the embedding call.""" retry_decorator = _create_retry_decorator(embeddings) @retry_decorator def _embed_with_retry(**kwargs: Any) -> Any: return embeddings.client.create(**kwargs) return _embed_with_retry(**kwargs) [docs]class OpenAIEmbeddings(BaseModel, Embeddings): ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
c81b90f88854-2
embeddings = OpenAIEmbeddings( deployment="your-embeddings-deployment-name", model="your-embeddings-model-name", openai_api_base="https://your-endpoint.openai.azure.com/", openai_api_type="azure", ) text = "This is a test query." ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
c81b90f88854-3
extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" values["openai_api_key"] = get_from_dict_or_env( values, "openai_api_key", "OPENAI_API_KEY" ) values["open...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
c81b90f88854-4
) return values @property def _invocation_params(self) -> Dict: openai_args = { "engine": self.deployment, "request_timeout": self.request_timeout, "headers": self.headers, "api_key": self.openai_api_key, "organization": self.openai_org...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
c81b90f88854-5
for i, text in enumerate(texts): if self.model.endswith("001"): # See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500 # replace newlines, which can negatively affect performance. text = text.replace("\n", " ") token = en...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
c81b90f88854-6
)[ "data" ][0]["embedding"] else: average = np.average(_result, axis=0, weights=num_tokens_in_batch[i]) embeddings[i] = (average / np.linalg.norm(average)).tolist() return embeddings def _embedding_func(self, text: str, *, engine: s...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
c81b90f88854-7
return self._get_len_safe_embeddings(texts, engine=self.deployment) [docs] def embed_query(self, text: str) -> List[float]: """Call out to OpenAI's embedding endpoint for embedding query text. Args: text: The text to embed. Returns: Embedding for the text. """ ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
4d6dc72553be-0
Source code for langchain.embeddings.mosaicml """Wrapper around MosaicML APIs.""" from typing import Any, Dict, List, Mapping, Optional, Tuple import requests from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env [docs]cla...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
4d6dc72553be-1
"""Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" mosaicml_api_token = get_from_dict_or_env( values, "mosaicml_api_tok...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
4d6dc72553be-2
f"Error raised by inference API: {parsed_response['error']}" ) if "data" not in parsed_response: raise ValueError( f"Error raised by inference API, no key data: {parsed_response}" ) embeddings = parsed_response["data"] e...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
f28621e5e35c-0
Source code for langchain.embeddings.sagemaker_endpoint """Wrapper around Sagemaker InvokeEndpoint API.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.llms.sagemaker_endpoint import ContentHandlerBase ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
f28621e5e35c-1
credentials_profile_name=credentials_profile_name ) """ client: Any #: :meta private: endpoint_name: str = "" """The name of the endpoint from the deployed Sagemaker model. Must be unique within an AWS Region.""" region_name: str = "" """The aws region where the Sagemaker model ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
f28621e5e35c-2
""" # noqa: E501 model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" endpoint_kwargs: Optional[Dict] = None """Optional attributes passed to the invoke_endpoint function. See `boto3`_. docs for more info. .. _boto3: <https://boto3.amazonaws.com/v1/documentation/ap...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
f28621e5e35c-3
# replace newlines, which can negatively affect performance. texts = list(map(lambda x: x.replace("\n", " "), texts)) _model_kwargs = self.model_kwargs or {} _endpoint_kwargs = self.endpoint_kwargs or {} body = self.content_handler.transform_input(texts, _model_kwargs) content_ty...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
f28621e5e35c-4
"""Compute query embeddings using a SageMaker inference endpoint. Args: text: The text to embed. Returns: Embeddings for the text. """ return self._embedding_func([text])[0] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Ju...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
eaf6e26ef177-0
Source code for langchain.document_loaders.sitemap """Loader that fetches a sitemap and loads those URLs.""" import itertools import re from typing import Any, Callable, Generator, Iterable, List, Optional from langchain.document_loaders.web_base import WebBaseLoader from langchain.schema import Document def _default_p...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html
eaf6e26ef177-1
meta_function: Function to parse bs4.Soup output for metadata remember when setting this method to also copy metadata["loc"] to metadata["source"] if you are using this field is_local: whether the sitemap is a local file """ if blocksize is not None and blocks...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html
eaf6e26ef177-2
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)) ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html
6138d69df50f-0
Source code for langchain.document_loaders.image """Loader that loads image files.""" from typing import List from langchain.document_loaders.unstructured import UnstructuredFileLoader [docs]class UnstructuredImageLoader(UnstructuredFileLoader): """Loader that uses unstructured to load image files, such as PNGs and...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/image.html
df3c2a58ad24-0
Source code for langchain.document_loaders.modern_treasury """Loader that fetches data from 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 lan...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/modern_treasury.html
df3c2a58ad24-1
resource: str, organization_id: Optional[str] = None, api_key: Optional[str] = None, ) -> None: self.resource = resource organization_id = organization_id or get_from_env( "organization_id", "MODERN_TREASURY_ORGANIZATION_ID" ) api_key = api_key or get_from...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/modern_treasury.html
0f79fd7fa21a-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/odt.html
848403781281-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/slack_directory.html
848403781281-1
if not channel_name: continue if channel_path.endswith(".json"): messages = self._read_json(zip_file, channel_path) for message in messages: document = self._convert_message_to_document( messa...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/slack_directory.html
848403781281-2
"timestamp": timestamp, "user": user, } def _get_message_source(self, channel_name: str, user: str, timestamp: str) -> str: """ Get the message source as a string. Args: channel_name (str): The name of the channel the message belongs to. user (str)...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/slack_directory.html
48bf3cfd44ae-0
Source code for langchain.document_loaders.max_compute from __future__ import annotations from typing import Any, Iterator, List, Optional, Sequence from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.utilities.max_compute import MaxComputeAPIWrapper [d...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/max_compute.html
48bf3cfd44ae-1
given parameters. Args: query: SQL query to execute. endpoint: MaxCompute endpoint. project: A project is a basic organizational unit of MaxCompute, which is similar to a database. access_id: MaxCompute access ID. Should be passed in directly or se...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/max_compute.html
29670375e236-0
Source code for langchain.document_loaders.toml import json from pathlib import Path from typing import Iterator, List, Union from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class TomlLoader(BaseLoader): """ A TOML document loader that inherits from ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/toml.html
29670375e236-1
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/toml.html
c5c5d132028a-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/epub.html
3eaba7880439-0
Source code for langchain.document_loaders.xml """Loader that loads Microsoft Excel files.""" from typing import Any, List from langchain.document_loaders.unstructured import ( UnstructuredFileLoader, validate_unstructured_version, ) [docs]class UnstructuredXMLLoader(UnstructuredFileLoader): """Loader that ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/xml.html
5dd27cd67ba1-0
Source code for langchain.document_loaders.notiondb """Notion DB loader for langchain""" from typing import Any, Dict, List, Optional import requests from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader NOTION_BASE_URL = "https://api.notion.com/v1" DATABASE_URL = NOTIO...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html
5dd27cd67ba1-1
Returns: List[Document]: List of documents. """ page_ids = self._retrieve_page_ids() return list(self.load_page(page_id) for page_id in page_ids) def _retrieve_page_ids( self, query_dict: Dict[str, Any] = {"page_size": 100} ) -> List[str]: """Get all the pages...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html
5dd27cd67ba1-2
[item["name"] for item in prop_data["multi_select"]] if prop_data["multi_select"] else [] ) elif prop_type == "url": value = prop_data["url"] else: value = None metadata[prop_name.lower()] = value...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html
5dd27cd67ba1-3
) -> Any: res = requests.request( method, url, headers=self.headers, json=query_dict, timeout=self.request_timeout_sec, ) res.raise_for_status() return res.json() By Harrison Chase © Copyright 2023, Harrison Chase. ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html
7672107d393e-0
Source code for langchain.document_loaders.diffbot """Loader that uses Diffbot to load webpages in text format.""" import logging from typing import Any, List import requests from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader logger = logging.getLogger(__name__) [doc...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/diffbot.html
7672107d393e-1
text = data["objects"][0]["text"] if "objects" in data else "" metadata = {"source": url} docs.append(Document(page_content=text, metadata=metadata)) except Exception as e: if self.continue_on_failure: logger.error(f"Error fetching or proce...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/diffbot.html
caedc7bd3cf2-0
Source code for langchain.document_loaders.git import os from typing import Callable, List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class GitLoader(BaseLoader): """Loads files from a Git repository into a list of documents. Repositor...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/git.html
caedc7bd3cf2-1
else: repo = Repo(self.repo_path) repo.git.checkout(self.branch) docs: List[Document] = [] for item in repo.tree().traverse(): if not isinstance(item, Blob): continue file_path = os.path.join(self.repo_path, item.path) ignored_f...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/git.html
bb937521acca-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html
bb937521acca-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html
4c02ba3c14cb-0
Source code for langchain.document_loaders.weather """Simple reader that reads weather data from OpenWeatherMap API""" from __future__ import annotations from datetime import datetime from typing import Iterator, List, Optional, Sequence from langchain.docstore.document import Document from langchain.document_loaders.b...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/weather.html
4c02ba3c14cb-1
return list(self.lazy_load()) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/weather.html
93920e4b1a96-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html
93920e4b1a96-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html
6dc3135f9bac-0
Source code for langchain.document_loaders.fauna from typing import Iterator, List, Optional, Sequence from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class FaunaLoader(BaseLoader): """ Attributes: query (str): The FQL query string to execute...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/fauna.html
6dc3135f9bac-1
page_content = "" for key, value in document_dict.items(): if key == self.page_content_field: page_content = value document: Document = Document( page_content=page_content, metadata={"id": result.id, "ts"...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/fauna.html
16d971fe4631-0
Source code for langchain.document_loaders.text import logging from typing import List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.helpers import detect_file_encodings logger = logging.getLogger(__name__) [docs]class T...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html
16d971fe4631-1
except Exception as e: raise RuntimeError(f"Error loading {self.file_path}") from e metadata = {"source": self.file_path} return [Document(page_content=text, metadata=metadata)] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html
bc9622e975f5-0
Source code for langchain.document_loaders.apify_dataset """Logic for loading documents from Apify datasets.""" from typing import Any, Callable, Dict, List from pydantic import BaseModel, root_validator from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/apify_dataset.html
bc9622e975f5-1
) return values [docs] def load(self) -> List[Document]: """Load documents.""" dataset_items = self.apify_client.dataset(self.dataset_id).list_items().items return list(map(self.dataset_mapping_function, dataset_items)) By Harrison Chase © Copyright 2023, Harrison Chase. ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/apify_dataset.html
170a12b28bed-0
Source code for langchain.document_loaders.stripe """Loader that fetches data from Stripe""" import json import urllib.request 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_dic...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/stripe.html
170a12b28bed-1
if endpoint is None: return [] return self._make_request(endpoint) [docs] def load(self) -> List[Document]: return self._get_resource() By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/stripe.html
8dd1a45e48e6-0
Source code for langchain.document_loaders.airbyte_json """Loader that loads local airbyte json files.""" import json from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.utils import stringify_dict [docs]class AirbyteJSONLoader(B...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte_json.html
33e8c73efc98-0
Source code for langchain.document_loaders.blackboard """Loader that loads all documents from a blackboard course.""" import contextlib import re from pathlib import Path from typing import Any, List, Optional, Tuple from urllib.parse import unquote from langchain.docstore.document import Document from langchain.docume...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
33e8c73efc98-1
): """Initialize with blackboard course url. The BbRouter cookie is required for most blackboard courses. Args: blackboard_course_url: Blackboard course url. bbrouter: BbRouter cookie. load_all_recursively: If True, load all documents recursively. ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
33e8c73efc98-2
"""Load data into document objects. Returns: List of documents. """ if self.load_all_recursively: soup_info = self.scrape() self.folder_path = self._get_folder_path(soup_info) relative_paths = self._get_paths(soup_info) documents = [] ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
33e8c73efc98-3
# Get the folder path folder_path = Path(".") / course_name_clean return str(folder_path) def _get_documents(self, soup: Any) -> List[Document]: """Fetch content from page and return Documents. Args: soup: BeautifulSoup4 soup object. Returns: List of d...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
33e8c73efc98-4
Path(self.folder_path).mkdir(parents=True, exist_ok=True) # Download all attachments for attachment in attachments: self.download(attachment) def _load_documents(self) -> List[Document]: """Load all documents in the folder. Returns: List of documents. ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
33e8c73efc98-5
"""Parse the filename from a url. Args: url: Url to parse the filename from. Returns: The filename. """ if (url_path := Path(url)) and url_path.suffix == ".pdf": return url_path.name else: return self._parse_filename_from_url(url) ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
33e8c73efc98-6
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
bc36f5400b5c-0
Source code for langchain.document_loaders.url """Loader that uses unstructured to load HTML files.""" import logging from typing import Any, List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader logger = logging.getLogger(__name__) [docs]class UnstructuredURLLoade...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html
bc36f5400b5c-1
def _validate_mode(self, mode: str) -> None: _valid_modes = {"single", "elements"} if mode not in _valid_modes: raise ValueError( f"Got {mode} for `mode`, but should be one of `{_valid_modes}`" ) def __is_headers_available_for_html(self) -> bool: _unst...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html
bc36f5400b5c-2
elements = partition(url=url, **self.unstructured_kwargs) else: if self.__is_headers_available_for_html(): elements = partition_html( url=url, headers=self.headers, **self.unstructured_kwargs ) ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html
44a25d988b52-0
Source code for langchain.document_loaders.gutenberg """Loader that loads .txt web files.""" from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class GutenbergLoader(BaseLoader): """Loader that uses urllib to load .txt web files.""" ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/gutenberg.html
5f451bb58bca-0
Source code for langchain.document_loaders.json_loader """Loader that loads data from JSON.""" import json from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Union from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class JSONLoader...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/json_loader.html
5f451bb58bca-1
""" try: import jq # noqa:F401 except ImportError: raise ImportError( "jq package not found, please install it with `pip install jq`" ) self.file_path = Path(file_path).resolve() self._jq_schema = jq.compile(jq_schema) self._co...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/json_loader.html
5f451bb58bca-2
else: content = sample if self._text_content and not isinstance(content, str): raise ValueError( f"Expected page_content is string, got {type(content)} instead. \ Set `text_content=False` if the desired input for \ `page_content` is...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/json_loader.html
97d16573aaaa-0
Source code for langchain.document_loaders.pdf """Loader that loads PDF files.""" import json import logging import os import tempfile import time from abc import ABC from io import StringIO from pathlib import Path from typing import Any, Iterator, List, Mapping, Optional from urllib.parse import urlparse import reque...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
97d16573aaaa-1
if not os.path.isfile(self.file_path) and self._is_valid_url(self.file_path): r = requests.get(self.file_path) if r.status_code != 200: raise ValueError( "Check the url of your file; returned status code %s" % r.status_code ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
97d16573aaaa-2
try: import pypdf # noqa:F401 except ImportError: raise ImportError( "pypdf package not found, please install it with " "`pip install pypdf`" ) self.parser = PyPDFParser() super().__init__(file_path) [docs] def load(self) -> List[Document]:...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
97d16573aaaa-3
silent_errors: bool = False, load_hidden: bool = False, recursive: bool = False, ): self.path = path self.glob = glob self.load_hidden = load_hidden self.recursive = recursive self.silent_errors = silent_errors @staticmethod def _is_visible(path: Path)...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
97d16573aaaa-4
[docs] def load(self) -> List[Document]: """Eagerly load the content.""" return list(self.lazy_load()) [docs] def lazy_load( self, ) -> Iterator[Document]: """Lazily lod documents.""" blob = Blob.from_path(self.file_path) yield from self.parser.parse(blob) [docs...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
97d16573aaaa-5
def __init__(self, file_path: str) -> None: """Initialize with file path.""" try: import fitz # noqa:F401 except ImportError: raise ImportError( "`PyMuPDF` package not found, please install it with " "`pip install pymupdf`" ) ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
97d16573aaaa-6
@property def headers(self) -> dict: return {"app_id": self.mathpix_api_id, "app_key": self.mathpix_api_key} @property def url(self) -> str: return "https://api.mathpix.com/v3/pdf" @property def data(self) -> dict: options = {"conversion_formats": {self.processed_file_format:...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
97d16573aaaa-7
self.wait_for_processing(pdf_id) url = f"{self.url}/{pdf_id}.{self.processed_file_format}" response = requests.get(url, headers=self.headers) return response.content.decode("utf-8") [docs] def clean_pdf(self, contents: str) -> str: contents = "\n".join( [line for line in c...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
97d16573aaaa-8
"`pip install pdfplumber`" ) super().__init__(file_path) self.text_kwargs = text_kwargs or {} [docs] def load(self) -> List[Document]: """Load file.""" parser = PDFPlumberParser(text_kwargs=self.text_kwargs) blob = Blob.from_path(self.file_path) return pars...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
9ad56175bd25-0
Source code for langchain.document_loaders.s3_directory """Loading logic for loading documents from an s3 directory.""" from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.s3_file import S3FileLoader [docs]class ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_directory.html
bef5daff10f9-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/wikipedia.html
dc118a08c82f-0
Source code for langchain.document_loaders.hugging_face_dataset """Loader that loads HuggingFace datasets.""" from typing import Iterator, List, Mapping, Optional, Sequence, Union from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class HuggingFaceDatasetLoader...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html
dc118a08c82f-1
self.page_content_column = page_content_column self.name = name self.data_dir = data_dir self.data_files = data_files self.cache_dir = cache_dir self.keep_in_memory = keep_in_memory self.save_infos = save_infos self.use_auth_token = use_auth_token self.num...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html
5c4b21ff844e-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html
5c4b21ff844e-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html
30135ae4794f-0
Source code for langchain.document_loaders.onedrive_file from __future__ import annotations import tempfile from typing import TYPE_CHECKING, List from pydantic import BaseModel, Field from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive_file.html
11d69320d52a-0
Source code for langchain.document_loaders.obsidian """Loader that loads Obsidian directory dump.""" import re from pathlib import Path from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class ObsidianLoader(BaseLoader): """Loader th...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/obsidian.html
11d69320d52a-1
ps = list(Path(self.file_path).glob("**/*.md")) docs = [] for p in ps: with open(p, encoding=self.encoding) as f: text = f.read() front_matter = self._parse_front_matter(text) text = self._remove_front_matter(text) metadata = { ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/obsidian.html
a6b6fd42cec9-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/hn.html
a6b6fd42cec9-1
title = lineItem.find("span", {"class": "titleline"}).text.strip() metadata = { "source": self.web_path, "title": title, "link": link, "ranking": ranking, } documents.append( Document( ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/hn.html
a4aa4b3426c5-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html
a4aa4b3426c5-1
return partition_pptx(filename=self.file_path, **self.unstructured_kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html
cfa0069873a2-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html
cfa0069873a2-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html