id stringlengths 14 16 | text stringlengths 29 2.73k | source stringlengths 49 117 |
|---|---|---|
15423f9eb833-3 | if self.example_selector:
raise ValueError("Saving an example selector is not currently supported")
return super().dict(**kwargs)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 29, 2023. | https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
34b6294458a2-0 | Source code for langchain.prompts.chat
"""Chat prompt template."""
from __future__ import annotations
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Callable, List, Sequence, Tuple, Type, TypeVar, Union
from pydantic import BaseModel, Field
from langchain.memory.buffer import get_b... | https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
34b6294458a2-1 | def input_variables(self) -> List[str]:
"""Input variables for this prompt template."""
return [self.variable_name]
MessagePromptTemplateT = TypeVar(
"MessagePromptTemplateT", bound="BaseStringMessagePromptTemplate"
)
class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
prompt:... | https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
34b6294458a2-2 | def format(self, **kwargs: Any) -> BaseMessage:
text = self.prompt.format(**kwargs)
return HumanMessage(content=text, additional_kwargs=self.additional_kwargs)
class AIMessagePromptTemplate(BaseStringMessagePromptTemplate):
def format(self, **kwargs: Any) -> BaseMessage:
text = self.prompt.f... | https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
34b6294458a2-3 | def from_template(cls, template: str, **kwargs: Any) -> ChatPromptTemplate:
prompt_template = PromptTemplate.from_template(template, **kwargs)
message = HumanMessagePromptTemplate(prompt=prompt_template)
return cls.from_messages([message])
@classmethod
def from_role_strings(
cls,... | https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
34b6294458a2-4 | if isinstance(message_template, BaseMessage):
result.extend([message_template])
elif isinstance(message_template, BaseMessagePromptTemplate):
rel_params = {
k: v
for k, v in kwargs.items()
if k in message_template.in... | https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
e5f183b6c7aa-0 | Source code for langchain.prompts.example_selector.semantic_similarity
"""Example selector that selects examples based on SemanticSimilarity."""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Type
from pydantic import BaseModel, Extra
from langchain.embeddings.base import Embeddings
fr... | https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
e5f183b6c7aa-1 | return ids[0]
[docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
"""Select which examples to use based on semantic similarity."""
# Get the docs with the highest similarity.
if self.input_keys:
input_variables = {key: input_variables[key] for key in s... | https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
e5f183b6c7aa-2 | instead of all variables.
vectorstore_cls_kwargs: optional kwargs containing url for vector store
Returns:
The ExampleSelector instantiated, backed by a vector store.
"""
if input_keys:
string_examples = [
" ".join(sorted_values({k: eg[k] for k... | https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
e5f183b6c7aa-3 | examples = [dict(e.metadata) for e in example_docs]
# If example keys are provided, filter examples to those keys.
if self.example_keys:
examples = [{k: eg[k] for k in self.example_keys} for eg in examples]
return examples
[docs] @classmethod
def from_examples(
cls,
... | https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
e5f183b6c7aa-4 | string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs
)
return cls(vectorstore=vectorstore, k=k, fetch_k=fetch_k, input_keys=input_keys)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 29, 2023. | https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
991f082948ec-0 | Source code for langchain.prompts.example_selector.length_based
"""Select examples based on length."""
import re
from typing import Callable, Dict, List
from pydantic import BaseModel, validator
from langchain.prompts.example_selector.base import BaseExampleSelector
from langchain.prompts.prompt import PromptTemplate
d... | https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html |
991f082948ec-1 | get_text_length = values["get_text_length"]
string_examples = [example_prompt.format(**eg) for eg in values["examples"]]
return [get_text_length(eg) for eg in string_examples]
[docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
"""Select which examples to use base... | https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html |
4131eb9a1678-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 |
6f3ca3d9cce0-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 |
6f3ca3d9cce0-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 |
13cbe1e5f82d-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 |
13cbe1e5f82d-1 | self,
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_k... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/modern_treasury.html |
1ccde144cfed-0 | Source code for langchain.document_loaders.bigquery
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class BigQueryLoader(BaseLoader):
"""Loads a query result from BigQuery into a list of documents.
Each document repr... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html |
1ccde144cfed-1 | metadata_columns = []
for row in query_result:
page_content = "\n".join(
f"{k}: {v}" for k, v in row.items() if k in page_content_columns
)
metadata = {k: v for k, v in row.items() if k in metadata_columns}
doc = Document(page_content=page_content,... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html |
b5dcf3155993-0 | Source code for langchain.document_loaders.readthedocs
"""Loader that loads ReadTheDocs documentation directory dump."""
from pathlib import Path
from typing import Any, List, Optional, Tuple, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class ReadT... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/readthedocs.html |
b5dcf3155993-1 | try:
from bs4 import BeautifulSoup
except ImportError:
raise ImportError(
"Could not import python packages. "
"Please install it with `pip install beautifulsoup4`. "
)
try:
_ = BeautifulSoup(
"<html><body>Pa... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/readthedocs.html |
b5dcf3155993-2 | if text is not None:
break
if text is not None:
text = text.get_text()
else:
text = ""
# trim empty lines
return "\n".join([t for t in text.split("\n") if t])
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on M... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/readthedocs.html |
ca9be01d498b-0 | Source code for langchain.document_loaders.chatgpt
"""Load conversations from ChatGPT data export"""
import datetime
import json
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def concatenate_rows(message: dict, title: str) -> str:
if ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html |
ca9be01d498b-1 | documents.append(Document(page_content=text, metadata=metadata))
return documents
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 29, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html |
758e417f80d6-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 |
758e417f80d6-1 | return partition_pptx(filename=self.file_path, **self.unstructured_kwargs)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 29, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html |
5ed58cfc8c1b-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 |
fd43a3fdfe13-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/python.html |
f35648828b9b-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/azure_blob_storage_file.html |
43ceffc1d4d8-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 |
43ceffc1d4d8-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 |
13dbc5233e1d-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 |
13dbc5233e1d-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 May 29, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html |
b81c9ceefc2e-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 |
16101013f978-0 | Source code for langchain.document_loaders.srt
"""Loader for .srt (subtitle) files."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class SRTLoader(BaseLoader):
"""Loader for .srt (subtitle) files."""
def __init__(self, fil... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/srt.html |
8c29cc68128d-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html |
8c29cc68128d-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html |
8c29cc68128d-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html |
69245b19c97e-0 | Source code for langchain.document_loaders.notion
"""Loader that loads Notion directory dump."""
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):
"""Loader that load... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notion.html |
850d49002ba3-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html |
850d49002ba3-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html |
850d49002ba3-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html |
850d49002ba3-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html |
217863fdadaf-0 | Source code for langchain.document_loaders.reddit
"""Reddit document loader."""
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 pra... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/reddit.html |
217863fdadaf-1 | if self.mode == "subreddit":
for search_query in self.search_queries:
for category in self.categories:
docs = self._subreddit_posts_loader(
search_query=search_query, category=category, reddit=reddit
)
result... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/reddit.html |
217863fdadaf-2 | method = getattr(user.submissions, category)
cat_posts = method(limit=self.number_posts)
"""Format reddit posts into a string."""
for post in cat_posts:
metadata = {
"post_subreddit": post.subreddit_name_prefixed,
"post_category": category,
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/reddit.html |
4b59101a742f-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 |
4b59101a742f-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 |
75f1c6aec473-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/mastodon.html |
75f1c6aec473-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/mastodon.html |
80a2000c3a60-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html |
80a2000c3a60-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html |
80a2000c3a60-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,
)
By ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html |
51c2b901c3b8-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_directory.html |
7f335368b8de-0 | Source code for langchain.document_loaders.html
"""Loader that uses unstructured to load HTML files."""
from typing import List
from langchain.document_loaders.unstructured import UnstructuredFileLoader
[docs]class UnstructuredHTMLLoader(UnstructuredFileLoader):
"""Loader that uses unstructured to load HTML files."... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/html.html |
56643671e5ad-0 | Source code for langchain.document_loaders.confluence
"""Load Data from a Confluence Space"""
import logging
from io import BytesIO
from typing import Any, Callable, List, Optional, Union
from tenacity import (
before_sleep_log,
retry,
stop_after_attempt,
wait_exponential,
)
from langchain.docstore.docu... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
56643671e5ad-1 | :param url: _description_
:type url: str
:param api_key: _description_, defaults to None
:type api_key: str, optional
:param username: _description_, defaults to None
:type username: str, optional
:param oauth2: _description_, defaults to {}
:type oauth2: dict, optional
:param cloud: _de... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
56643671e5ad-2 | if errors:
raise ValueError(f"Error(s) while validating input: {errors}")
self.base_url = url
self.number_of_retries = number_of_retries
self.min_retry_seconds = min_retry_seconds
self.max_retry_seconds = max_retry_seconds
try:
from atlassian import Conflu... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
56643671e5ad-3 | "`username` and provide a value for `oauth2`"
)
if oauth2 and oauth2.keys() != [
"access_token",
"access_token_secret",
"consumer_key",
"key_cert",
]:
errors.append(
"You have either ommited require keys or added ext... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
56643671e5ad-4 | :type include_restricted_content: bool, optional
:param include_archived_content: Whether to include archived content,
defaults to False
:type include_archived_content: bool, optional
:param include_attachments: defaults to False
:type include_att... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
56643671e5ad-5 | )
ids_by_label = [page["id"] for page in pages]
if page_ids:
page_ids = list(set(page_ids + ids_by_label))
else:
page_ids = list(set(ids_by_label))
if cql:
pages = self.paginate_request(
self.confluence.cql,
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
56643671e5ad-6 | Unfortunately, due to page size, sometimes the Confluence API
doesn't match the limit value. If `limit` is >100 confluence
seems to cap the response to 100. Also, due to the Atlassian Python
package, we don't get the "next" values from the "_links" key because
they only return the value... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
56643671e5ad-7 | break
docs.extend(batch)
return docs[:max_pages]
[docs] def is_public_page(self, page: dict) -> bool:
"""Check if a page is publicly accessible."""
restrictions = self.confluence.get_all_restrictions_for_content(page["id"])
return (
page["status"] == "current"
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
56643671e5ad-8 | ).get_text() + "".join(attachment_texts)
if include_comments:
comments = self.confluence.get_page_comments(
page["id"], expand="body.view.value", depth="all"
)["results"]
comment_texts = [
BeautifulSoup(comment["body"]["view"]["value"], "lxml")... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
56643671e5ad-9 | elif (
media_type == "application/vnd.openxmlformats-officedocument"
".wordprocessingml.document"
):
text = title + self.process_doc(absolute_url)
elif media_type == "application/vnd.ms-excel":
text = title + self.process_xls(absolu... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
56643671e5ad-10 | "`pytesseract` or `Pillow` package not found, "
"please run `pip install pytesseract Pillow`"
)
response = self.confluence.request(path=link, absolute=True)
text = ""
if (
response.status_code != 200
or response.content == b""
or re... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
56643671e5ad-11 | ):
return text
workbook = xlrd.open_workbook(file_contents=response.content)
for sheet in workbook.sheets():
text += f"{sheet.name}:\n"
for row in range(sheet.nrows):
for col in range(sheet.ncols):
text += f"{sheet.cell_value(row, c... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
c5472a290520-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 |
c5472a290520-1 | channel_name = Path(channel_path).parent.name
if not channel_name:
continue
if channel_path.endswith(".json"):
messages = self._read_json(zip_file, channel_path)
for message in messages:
document = self._... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/slack_directory.html |
c5472a290520-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 |
5f46ffcb5068-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 |
5f46ffcb5068-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 |
feccf45d49db-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 |
fb50eafb5b39-0 | Source code for langchain.document_loaders.email
"""Loader that loads email files."""
import os
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
satisfies_... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/email.html |
fb50eafb5b39-1 | "`pip install extract_msg`"
)
[docs] def load(self) -> List[Document]:
"""Load data into document objects."""
import extract_msg
msg = extract_msg.Message(self.file_path)
return [
Document(
page_content=msg.body,
metadata={
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/email.html |
27214b4af607-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 |
27214b4af607-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 |
27214b4af607-2 | }
)
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))
return els
[docs] def load(self) -> Lis... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html |
2053953aac84-0 | Source code for langchain.document_loaders.word_document
"""Loader that loads word documents."""
import os
import tempfile
from abc import ABC
from typing import List
from urllib.parse import urlparse
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html |
2053953aac84-1 | if hasattr(self, "temp_file"):
self.temp_file.close()
[docs] def load(self) -> List[Document]:
"""Load given path as single page."""
import docx2txt
return [
Document(
page_content=docx2txt.process(self.file_path),
metadata={"source": se... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html |
2053953aac84-2 | "Please upgrade the unstructured package and try again."
)
if is_doc:
from unstructured.partition.doc import partition_doc
return partition_doc(filename=self.file_path, **self.unstructured_kwargs)
else:
from unstructured.partition.docx import partition_doc... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html |
70918c64c863-0 | Source code for langchain.document_loaders.dataframe
"""Load from Dataframe object"""
from typing import Any, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class DataFrameLoader(BaseLoader):
"""Load Pandas DataFrames."""
def __init__(self, dat... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/dataframe.html |
b896f84820fd-0 | Source code for langchain.document_loaders.web_base
"""Web base loader class."""
import asyncio
import logging
import warnings
from typing import Any, List, Optional, Union
import aiohttp
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = log... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
b896f84820fd-1 | ):
"""Initialize with webpage path."""
# TODO: Deprecate web_path in favor of web_paths, and remove this
# left like this because there are a number of loaders that expect single
# urls
if isinstance(web_path, str):
self.web_paths = [web_path]
elif isinstance(... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
b896f84820fd-2 | return await response.text()
except aiohttp.ClientConnectionError as e:
if i == retries - 1:
raise
else:
logger.warning(
f"Error fetching {url} with attempt "
f... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
b896f84820fd-3 | )
[docs] def scrape_all(self, urls: List[str], parser: Union[str, None] = None) -> List[Any]:
"""Fetch all urls, then return soups for all results."""
from bs4 import BeautifulSoup
results = asyncio.run(self.fetch_all(urls))
final_results = []
for i, result in enumerate(result... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
b896f84820fd-4 | docs.append(Document(page_content=text, metadata=metadata))
return docs
[docs] def aload(self) -> List[Document]:
"""Load text from the urls in web_path async into Documents."""
results = self.scrape_all(self.web_paths)
docs = []
for i in range(len(results)):
soup ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
977e258c785f-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 |
2adee9b509bd-0 | Source code for langchain.document_loaders.onedrive
"""Loader that loads data from OneDrive"""
from __future__ import annotations
import logging
import os
import tempfile
from enum import Enum
from pathlib import Path
from typing import TYPE_CHECKING, Dict, List, Optional, Type, Union
from pydantic import BaseModel, Ba... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive.html |
2adee9b509bd-1 | mime_types_mapping[
file_type.value
] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" # noqa: E501
elif file_type.value == "pdf":
mime_types_mapping[file_type.value] = "application/pdf"
return mime_types_mapping
[docs]c... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive.html |
2adee9b509bd-2 | )
account = Account(
credentials=(
self.settings.client_id,
self.settings.client_secret.get_secret_value(),
),
scopes=SCOPES,
token_backend=token_backend,
**{"raise_http_errors": False},
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive.html |
2adee9b509bd-3 | Args:
folder (Type[Folder]): The folder object to load the documents from.
Returns:
List[Document]: A list of Document objects representing
the loaded documents.
"""
docs = []
file_types = _SupportedFileTypes(file_types=["doc", "docx", "pdf"])
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive.html |
2adee9b509bd-4 | file = drive.get_item(object_id)
if not file:
logging.warning(
"There isn't a file with "
f"object_id {object_id} in drive {drive}."
)
continue
if file.is_file:
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive.html |
8b261ee1679e-0 | Source code for langchain.document_loaders.directory
"""Loading logic for loading documents from a directory."""
import concurrent
import logging
from pathlib import Path
from typing import Any, List, Optional, Type, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import Base... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html |
8b261ee1679e-1 | self.loader_kwargs = loader_kwargs
self.silent_errors = silent_errors
self.recursive = recursive
self.show_progress = show_progress
self.use_multithreading = use_multithreading
self.max_concurrency = max_concurrency
[docs] def load_file(
self, item: Path, path: Path, d... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html |
8b261ee1679e-2 | logger.warning(e)
else:
raise e
if self.use_multithreading:
with concurrent.futures.ThreadPoolExecutor(
max_workers=self.max_concurrency
) as executor:
executor.map(lambda i: self.load_file(i, p, docs, pbar), items)
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html |
e2e8f050b07b-0 | Source code for langchain.document_loaders.html_bs
"""Loader that uses bs4 to load HTML files, enriching metadata with page title."""
import logging
from typing import Dict, List, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = logging.getLogger(__n... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html |
e2e8f050b07b-1 | title = ""
metadata: Dict[str, Union[str, None]] = {
"source": self.file_path,
"title": title,
}
return [Document(page_content=text, metadata=metadata)]
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 29, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html |
221e3b9989fe-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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.