id stringlengths 14 16 | text stringlengths 4 1.28k | source stringlengths 54 121 |
|---|---|---|
01c3490947ed-5 | title = kg.get("title")
entity_type = kg.get("type")
if entity_type:
snippets.append(f"{title}: {entity_type}.")
description = kg.get("description")
if description:
snippets.append(description)
for attribute, value in kg.get("at... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
01c3490947ed-6 | return " ".join(self._parse_snippets(results))
def _google_serper_api_results(
self, search_term: str, search_type: str = "search", **kwargs: Any
) -> dict:
headers = {
"X-API-KEY": self.serper_api_key or "",
"Content-Type": "application/json",
}
params = ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
01c3490947ed-7 | self, search_term: str, search_type: str = "search", **kwargs: Any
) -> dict:
headers = {
"X-API-KEY": self.serper_api_key or "",
"Content-Type": "application/json",
}
url = f"https://google.serper.dev/{search_type}"
params = {
"q": search_term,
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
01c3490947ed-8 | ) as response:
search_results = await response.json()
return search_results | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
e4266e2db2dd-0 | Source code for langchain.utilities.twilio
"""Util that calls Twilio."""
from typing import Any, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class TwilioAPIWrapper(BaseModel):
"""Messaging Client using Twilio.
To use, you should hav... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html |
e4266e2db2dd-1 | from_number="+10123456789"
)
twilio.run('test', '+12484345508')
"""
client: Any #: :meta private:
account_sid: Optional[str] = None
"""Twilio account string identifier."""
auth_token: Optional[str] = None
"""Twilio auth token."""
from_number: Optional[str] = None
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html |
e4266e2db2dd-2 | [short codes](https://www.twilio.com/docs/sms/api/short-code) purchased from
Twilio also work here. You cannot, for example, spoof messages from a private
cell phone number. If you are using `messaging_service_sid`, this parameter
must be empty.
""" # noqa: E501
class Config:
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html |
e4266e2db2dd-3 | )
account_sid = get_from_dict_or_env(values, "account_sid", "TWILIO_ACCOUNT_SID")
auth_token = get_from_dict_or_env(values, "auth_token", "TWILIO_AUTH_TOKEN")
values["from_number"] = get_from_dict_or_env(
values, "from_number", "TWILIO_FROM_NUMBER"
)
values["client"] ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html |
e4266e2db2dd-4 | SMS/MMS or
[Channel user address](https://www.twilio.com/docs/sms/channels#channel-addresses)
for other 3rd-party channels.
""" # noqa: E501
message = self.client.messages.create(to, from_=self.from_number, body=body)
return message.sid | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html |
e6ada77f723d-0 | Source code for langchain.utilities.google_places_api
"""Chain that calls Google Places API.
"""
import logging
from typing import Any, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class GooglePlacesAPIWrapper(BaseModel):
"""Wrapper arou... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html |
e6ada77f723d-1 | from langchain import GooglePlacesAPIWrapper
gplaceapi = GooglePlacesAPIWrapper()
"""
gplaces_api_key: Optional[str] = None
google_map_client: Any #: :meta private:
top_k_results: Optional[int] = None
class Config:
"""Configuration for this pydantic object."""
extra = Ex... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html |
e6ada77f723d-2 | except ImportError:
raise ImportError(
"Could not import googlemaps python package. "
"Please install it with `pip install googlemaps`."
)
return values
[docs] def run(self, query: str) -> str:
"""Run Places search and get k number of places tha... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html |
e6ada77f723d-3 | if details is not None:
places.append(details)
return "\n".join([f"{i+1}. {item}" for i, item in enumerate(places)])
[docs] def fetch_place_details(self, place_id: str) -> Optional[str]:
try:
place_details = self.google_map_client.place(place_id)
formatted_deta... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html |
e6ada77f723d-4 | )
phone_number = place_details.get("result", {}).get(
"formatted_phone_number", "Unknown"
)
website = place_details.get("result", {}).get("website", "Unknown")
formatted_details = (
f"{name}\nAddress: {address}\n"
f"Phone: {... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html |
95b939988cd9-0 | Source code for langchain.document_loaders.tomarkdown
"""Loader that loads HTML to markdown using 2markdown."""
from __future__ import annotations
from typing import Iterator, List
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class ToMarkd... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tomarkdown.html |
95b939988cd9-1 | json={"url": self.url},
)
text = response.json()["article"]
metadata = {"source": self.url}
yield Document(page_content=text, metadata=metadata)
[docs] def load(self) -> List[Document]:
"""Load file."""
return list(self.lazy_load()) | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tomarkdown.html |
f786ea6c747d-0 | Source code for langchain.document_loaders.conllu
"""Load CoNLL-U files."""
import csv
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class CoNLLULoader(BaseLoader):
"""Load CoNLL-U files."""
def __init__(self, file_path: str... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/conllu.html |
f786ea6c747d-1 | text = ""
for i, line in enumerate(lines):
# Do not add a space after a punctuation mark or at the end of the sentence
if line[9] == "SpaceAfter=No" or i == len(lines) - 1:
text += line[1]
else:
text += line[1] + " "
metadata = {"source... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/conllu.html |
98a3d832c7a5-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://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/toml.html |
98a3d832c7a5-1 | """Lazily load the TOML documents from the source file or directory."""
import tomli
if self.source.is_file() and self.source.suffix == ".toml":
files = [self.source]
elif self.source.is_dir():
files = list(self.source.glob("**/*.toml"))
else:
raise Va... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/toml.html |
e8b2e872d147-0 | Source code for langchain.document_loaders.url_playwright
"""Loader that uses Playwright to load a page, then uses unstructured to load the html.
"""
import logging
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = logging.... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html |
e8b2e872d147-1 | urls: List[str],
continue_on_failure: bool = True,
headless: bool = True,
remove_selectors: Optional[List[str]] = None,
):
"""Load a list of URLs using Playwright and unstructured."""
try:
import playwright # noqa:F401
except ImportError:
rais... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html |
e8b2e872d147-2 | self.remove_selectors = remove_selectors
[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_... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html |
e8b2e872d147-3 | page_source = page.content()
elements = partition_html(text=page_source)
text = "\n\n".join([str(el) for el in elements])
metadata = {"source": url}
docs.append(Document(page_content=text, metadata=metadata))
except Exceptio... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html |
3c25eef7318d-0 | Source code for langchain.document_loaders.gcs_directory
"""Loading logic for loading documents from an GCS directory."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.gcs_file import GCSFileLoader
[docs]cl... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_directory.html |
3c25eef7318d-1 | "Please install it with `pip install google-cloud-storage`."
)
client = storage.Client(project=self.project_name)
docs = []
for blob in client.list_blobs(self.bucket, prefix=self.prefix):
# we shall just skip directories since GCSFileLoader creates
# intermedi... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_directory.html |
0192d70ecef4-0 | Source code for langchain.document_loaders.joplin
import json
import urllib
from datetime import datetime
from typing import Iterator, List, Optional
from langchain.document_loaders.base import BaseLoader
from langchain.schema import Document
from langchain.utils import get_from_env
LINK_NOTE_TEMPLATE = "joplin://x-cal... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/joplin.html |
0192d70ecef4-1 | https://joplinapp.org/clipper/
"""
def __init__(
self,
access_token: Optional[str] = None,
port: int = 41184,
host: str = "localhost",
) -> None:
access_token = access_token or get_from_env(
"access_token", "JOPLIN_ACCESS_TOKEN"
)
base_url ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/joplin.html |
0192d70ecef4-2 | self._get_tag_url = (
f"{base_url}/notes/{{id}}/tags?token={access_token}&fields=title"
)
def _get_notes(self) -> Iterator[Document]:
has_more = True
page = 1
while has_more:
req_note = urllib.request.Request(self._get_note_url.format(page=page))
w... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/joplin.html |
0192d70ecef4-3 | "updated_time": self._convert_date(note["updated_time"]),
}
yield Document(page_content=note["body"], metadata=metadata)
has_more = json_data["has_more"]
page += 1
def _get_folder(self, folder_id: str) -> str:
req_folder = urllib.reques... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/joplin.html |
0192d70ecef4-4 | def _convert_date(self, date: int) -> str:
return datetime.fromtimestamp(date / 1000).strftime("%Y-%m-%d %H:%M:%S")
[docs] def lazy_load(self) -> Iterator[Document]:
yield from self._get_notes()
[docs] def load(self) -> List[Document]:
return list(self.lazy_load()) | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/joplin.html |
1e9e18ce742a-0 | Source code for langchain.document_loaders.powerpoint
"""Loader that loads powerpoint files."""
import os
from typing import List
from langchain.document_loaders.unstructured import UnstructuredFileLoader
[docs]class UnstructuredPowerPointLoader(UnstructuredFileLoader):
"""Loader that uses unstructured to load powe... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html |
1e9e18ce742a-1 | try:
import magic # noqa: F401
is_ppt = detect_filetype(self.file_path) == FileType.PPT
except ImportError:
_, extension = os.path.splitext(str(self.file_path))
is_ppt = extension == ".ppt"
if is_ppt and unstructured_version < (0, 4, 11):
rais... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html |
1e9e18ce742a-2 | return partition_pptx(filename=self.file_path, **self.unstructured_kwargs) | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html |
20bc1fb39b90-0 | Source code for langchain.document_loaders.snowflake_loader
from __future__ import annotations
from typing import Any, Dict, Iterator, List, Optional, Tuple
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class SnowflakeLoader(BaseLoader):
"""Loads a que... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html |
20bc1fb39b90-1 | warehouse: str,
role: str,
database: str,
schema: str,
parameters: Optional[Dict[str, Any]] = None,
page_content_columns: Optional[List[str]] = None,
metadata_columns: Optional[List[str]] = None,
):
"""Initialize Snowflake document loader.
Args:
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html |
20bc1fb39b90-2 | self.password = password
self.account = account
self.warehouse = warehouse
self.role = role
self.database = database
self.schema = schema
self.parameters = parameters
self.page_content_columns = (
page_content_columns if page_content_columns is not Non... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html |
20bc1fb39b90-3 | warehouse=self.warehouse,
role=self.role,
database=self.database,
schema=self.schema,
parameters=self.parameters,
)
try:
cur = conn.cursor()
cur.execute("USE DATABASE " + self.database)
cur.execute("USE SCHEMA " + self.s... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html |
20bc1fb39b90-4 | 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_columns = list(query_result[0].keys())
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html |
20bc1fb39b90-5 | 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, metadata=metadata)
yield doc
[docs] def load(self) ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html |
9f537ee0a880-0 | Source code for langchain.document_loaders.rtf
"""Loader that loads rich text files."""
from typing import Any, List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
satisfies_min_unstructured_version,
)
[docs]class UnstructuredRTFLoader(UnstructuredFileLoader):
"""Loader that u... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rtf.html |
9f537ee0a880-1 | def _get_elements(self) -> List:
from unstructured.partition.rtf import partition_rtf
return partition_rtf(filename=self.file_path, **self.unstructured_kwargs) | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rtf.html |
1521c4124d32-0 | Source code for langchain.document_loaders.notebook
"""Loader that loads .ipynb notebook files."""
import json
from pathlib import Path
from typing import Any, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def concatenate_cells(
cell: dict, include_outp... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
1521c4124d32-1 | return (
f"'{cell_type}' cell: '{source}'\n, gives error '{error_name}',"
f" with description '{error_value}'\n"
f"and traceback '{traceback}'\n\n"
)
else:
return (
f"'{cell_type}' cell: '{source}... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
1521c4124d32-2 | )
else:
return f"'{cell_type}' cell: '{source}'\n\n"
return ""
def remove_newlines(x: Any) -> Any:
"""Remove recursively newlines, no matter the data structure they are stored in."""
import pandas as pd
if isinstance(x, str):
return x.replace("\n", "")
elif isinstance(x, list):
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
1521c4124d32-3 | remove_newline: bool = False,
traceback: bool = False,
):
"""Initialize with path."""
self.file_path = path
self.include_outputs = include_outputs
self.max_output_length = max_output_length
self.remove_newline = remove_newline
self.traceback = traceback
[docs]... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
1521c4124d32-4 | filtered_data = data[["cell_type", "source", "outputs"]]
if self.remove_newline:
filtered_data = filtered_data.applymap(remove_newlines)
text = filtered_data.apply(
lambda x: concatenate_cells(
x, self.include_outputs, self.max_output_length, self.traceback
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
5f6e80dab79a-0 | Source code for langchain.document_loaders.gitbook
"""Loader that loads GitBook."""
from typing import Any, List, Optional
from urllib.parse import urljoin, urlparse
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class GitbookLoader(WebBaseLoader):
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html |
5f6e80dab79a-1 | relative paths are discovered.
load_all_paths: If set to True, all relative paths in the navbar
are loaded instead of only `web_page`.
base_url: If `load_all_paths` is True, the relative paths are
appended to this base url. Defaults to `web_page` if not set.
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html |
5f6e80dab79a-2 | """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 = urljoin(self.base_url, path)
print(f"Fetch... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html |
5f6e80dab79a-3 | page_content_raw = soup.find(self.content_selector)
if not page_content_raw:
return None
content = page_content_raw.get_text(separator="\n").strip()
title_if_exists = page_content_raw.find("h1")
title = title_if_exists.text if title_if_exists else ""
metadata = {"sour... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html |
695acccc8d2b-0 | Source code for langchain.document_loaders.web_base
"""Web base loader class."""
import asyncio
import logging
import warnings
from typing import Any, Dict, Iterator, List, Optional, Union
import aiohttp
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoa... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
695acccc8d2b-1 | }
def _build_metadata(soup: Any, url: str) -> dict:
"""Build metadata from BeautifulSoup output."""
metadata = {"source": url}
if title := soup.find("title"):
metadata["title"] = title.get_text()
if description := soup.find("meta", attrs={"name": "description"}):
metadata["description"] ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
695acccc8d2b-2 | """Default parser to use for BeautifulSoup."""
requests_kwargs: Dict[str, Any] = {}
"""kwargs for requests"""
bs_get_text_kwargs: Dict[str, Any] = {}
"""kwargs for beatifulsoup4 get_text"""
def __init__(
self,
web_path: Union[str, List[str]],
header_template: Optional[dict] =... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
695acccc8d2b-3 | try:
import bs4 # noqa:F401
except ImportError:
raise ValueError(
"bs4 package not found, please install it with " "`pip install bs4`"
)
# Choose to verify
self.verify = verify
headers = header_template or default_header_template
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
695acccc8d2b-4 | raise ValueError("Multiple webpaths found.")
return self.web_paths[0]
async def _fetch(
self, url: str, retries: int = 3, cooldown: int = 2, backoff: float = 1.5
) -> str:
# For SiteMap SSL verification
if not self.requests_kwargs.get("verify", True):
connector = aioh... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
695acccc8d2b-5 | else:
logger.warning(
f"Error fetching {url} with attempt "
f"{i + 1}/{retries}: {e}. Retrying..."
)
await asyncio.sleep(cooldown * backoff**i)
raise ValueError("retry count exceeded")... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
695acccc8d2b-6 | tasks.append(task)
try:
from tqdm.asyncio import tqdm_asyncio
return await tqdm_asyncio.gather(
*tasks, desc="Fetching pages", ascii=True, mininterval=1
)
except ImportError:
warnings.warn("For better logging of progress, `pip install tqdm`... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
695acccc8d2b-7 | )
[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://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
695acccc8d2b-8 | parser = "xml"
else:
parser = self.default_parser
self._check_parser(parser)
html_doc = self.session.get(url, verify=self.verify, **self.requests_kwargs)
html_doc.encoding = html_doc.apparent_encoding
return BeautifulSoup(html_doc.text, parser)
[docs] def s... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
695acccc8d2b-9 | metadata = _build_metadata(soup, path)
yield Document(page_content=text, metadata=metadata)
[docs] def load(self) -> List[Document]:
"""Load text from the url(s) in web_path."""
return list(self.lazy_load())
[docs] def aload(self) -> List[Document]:
"""Load text from the urls i... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
45a8374392ab-0 | Source code for langchain.document_loaders.bilibili
import json
import re
import warnings
from typing import List, Tuple
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class BiliBiliLoader(BaseLoader):
"""Loader that loads bilibili trans... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bilibili.html |
45a8374392ab-1 | results.append(doc)
return results
def _get_bilibili_subs_and_info(self, url: str) -> Tuple[str, dict]:
try:
from bilibili_api import sync, video
except ImportError:
raise ValueError(
"requests package not found, please install it with "
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bilibili.html |
45a8374392ab-2 | else:
raise ValueError(f"{url} is not bilibili url.")
video_info = sync(v.get_info())
video_info.update({"url": url})
# Get subtitle url
subtitle = video_info.pop("subtitle")
sub_list = subtitle["list"]
if sub_list:
sub_url = sub_list[0]["subti... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bilibili.html |
45a8374392ab-3 | else:
raw_transcript = ""
warnings.warn(
f"""
No subtitles found for video: {url}.
Return Empty transcript.
"""
)
return raw_transcript, video_info | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bilibili.html |
f09273b5b5da-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://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/diffbot.html |
f09273b5b5da-1 | def _get_diffbot_data(self, url: str) -> Any:
"""Get Diffbot file from Diffbot REST API."""
# TODO: Add support for other Diffbot APIs
diffbot_url = self._diffbot_api_url("article")
params = {
"token": self.api_token,
"url": url,
}
response = reque... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/diffbot.html |
f09273b5b5da-2 | 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://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/diffbot.html |
bfc2d89b905f-0 | Source code for langchain.document_loaders.csv_loader
import csv
from typing import Any, Dict, List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
validate_unstructure... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html |
bfc2d89b905f-1 | The source of each document will then be set to the value of the column
with the name specified in `source_column`.
Output Example:
.. code-block:: txt
column1: value1
column2: value2
column3: value3
"""
def __init__(
self,
file_path: str,
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html |
bfc2d89b905f-2 | csv_reader = csv.DictReader(csvfile, **self.csv_args) # type: ignore
for i, row in enumerate(csv_reader):
content = "\n".join(f"{k.strip()}: {v.strip()}" for k, v in row.items())
try:
source = (
row[self.source_column]
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html |
bfc2d89b905f-3 | def __init__(
self, file_path: str, mode: str = "single", **unstructured_kwargs: Any
):
validate_unstructured_version(min_unstructured_version="0.6.8")
super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
def _get_elements(self) -> List:
from unstructured.parti... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html |
111ccdc2854c-0 | Source code for langchain.document_loaders.dataframe
"""Load from Dataframe object"""
from typing import Any, Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class DataFrameLoader(BaseLoader):
"""Load Pandas DataFrames."""
def __init__... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/dataframe.html |
111ccdc2854c-1 | text = row[self.page_content_column]
metadata = row.to_dict()
metadata.pop(self.page_content_column)
yield Document(page_content=text, metadata=metadata)
[docs] def load(self) -> List[Document]:
"""Load full dataframe."""
return list(self.lazy_load()) | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/dataframe.html |
e4aca5325405-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://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html |
e4aca5325405-1 | [docs]class DirectoryLoader(BaseLoader):
"""Loading logic for loading documents from a directory."""
def __init__(
self,
path: str,
glob: str = "**/[!.]*",
silent_errors: bool = False,
load_hidden: bool = False,
loader_cls: FILE_LOADER_TYPE = UnstructuredFileLoade... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html |
e4aca5325405-2 | self.loader_cls = loader_cls
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(
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html |
e4aca5325405-3 | pbar.update(1)
[docs] def load(self) -> List[Document]:
"""Load documents."""
p = Path(self.path)
if not p.exists():
raise FileNotFoundError(f"Directory not found: '{self.path}'")
if not p.is_dir():
raise ValueError(f"Expected directory, got file: '{self.path}'... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html |
e4aca5325405-4 | if self.silent_errors:
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: se... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html |
a5d91b60b9af-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://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive_file.html |
a5d91b60b9af-1 | loader = UnstructuredFileLoader(file_path)
return loader.load() | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive_file.html |
73798d967652-0 | Source code for langchain.document_loaders.googledrive
"""Loader that loads data from Google Drive."""
# Prerequisites:
# 1. Create a Google Cloud project
# 2. Enable the Google Drive API:
# https://console.cloud.google.com/flows/enableapi?apiid=drive.googleapis.com
# 3. Authorize credentials for desktop app:
# htt... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
73798d967652-1 | SCOPES = ["https://www.googleapis.com/auth/drive.readonly"]
[docs]class GoogleDriveLoader(BaseLoader, BaseModel):
"""Loader that loads Google Docs from Google Drive."""
service_account_key: Path = Path.home() / ".credentials" / "keys.json"
credentials_path: Path = Path.home() / ".credentials" / "credentials... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
73798d967652-2 | file_loader_cls: Any = None
file_loader_kwargs: Dict["str", Any] = {}
@root_validator
def validate_inputs(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Validate that either folder_id or document_ids is set, but not both."""
if values.get("folder_id") and (
values.get("docume... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
73798d967652-3 | if file_types:
if values.get("document_ids") or values.get("file_ids"):
raise ValueError(
"file_types can only be given when folder_id is given,"
" (not when document_ids or file_ids are given)."
)
type_mapping = {
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
73798d967652-4 | raise ValueError(
f"Given file type {file_type} is not supported. "
f"Supported values are: {short_names}; and "
f"their full-form names: {full_names}"
)
# replace short-form file types by full-form file types
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
73798d967652-5 | """Load credentials."""
# Adapted from https://developers.google.com/drive/api/v3/quickstart/python
try:
from google.auth import default
from google.auth.transport.requests import Request
from google.oauth2 import service_account
from google.oauth2.credent... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
73798d967652-6 | if self.token_path.exists():
creds = Credentials.from_authorized_user_file(str(self.token_path), SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
elif "GOOGLE_APPLICATION_CREDENTIALS" not in ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
73798d967652-7 | """Load a sheet and all tabs from an ID."""
from googleapiclient.discovery import build
creds = self._load_credentials()
sheets_service = build("sheets", "v4", credentials=creds)
spreadsheet = sheets_service.spreadsheets().get(spreadsheetId=id).execute()
sheets = spreadsheet.get(... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
73798d967652-8 | "source": (
f"https://docs.google.com/spreadsheets/d/{id}/"
f"edit?gid={sheet['properties']['sheetId']}"
),
"title": f"{spreadsheet['properties']['title']} - {sheet_name}",
"row": i,
}
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
73798d967652-9 | from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseDownload
creds = self._load_credentials()
service = build("drive", "v3", credentials=creds)
file = service.files().get(fileId=id, supportsAllDrives=True).execute()
request = service.files().e... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
73798d967652-10 | metadata = {
"source": f"https://docs.google.com/document/d/{id}/edit",
"title": f"{file.get('name')}",
}
return Document(page_content=text, metadata=metadata)
def _load_documents_from_folder(
self, folder_id: str, *, file_types: Optional[Sequence[str]] = None
) -... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
73798d967652-11 | else:
_files = files
returns = []
for file in _files:
if file["trashed"] and not self.load_trashed_files:
continue
elif file["mimeType"] == "application/vnd.google-apps.document":
returns.append(self._load_document_from_id(file["id"])) ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
73798d967652-12 | ) -> List[Dict[str, Union[str, List[str]]]]:
"""Fetch all files and subfolders recursively."""
results = (
service.files()
.list(
q=f"'{folder_id}' in parents",
pageSize=1000,
includeItemsFromAllDrives=True,
supports... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
73798d967652-13 | returns.append(file)
return returns
def _load_documents_from_ids(self) -> List[Document]:
"""Load documents from a list of IDs."""
if not self.document_ids:
raise ValueError("document_ids must be set")
return [self._load_document_from_id(doc_id) for doc_id in self.documen... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
73798d967652-14 | fh = BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
if self.file_loader_cls is not None:
fh.seek(0)
loader = self.file_loader_cls(file=fh, **self.file_loader_kwargs)
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
73798d967652-15 | "page": i,
},
)
for i, page in enumerate(pdf_reader.pages)
]
def _load_file_from_ids(self) -> List[Document]:
"""Load files from a list of IDs."""
if not self.file_ids:
raise ValueError("file_ids must be set")
docs =... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
4afedefaee6e-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://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte_json.html |
4afedefaee6e-1 | return [Document(page_content=text, metadata=metadata)] | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte_json.html |
371a0de63670-0 | Source code for langchain.document_loaders.image_captions
"""
Loader that loads image captions
By default, the loader utilizes the pre-trained BLIP image captioning model.
https://huggingface.co/Salesforce/blip-image-captioning-base
"""
from typing import Any, List, Tuple, Union
import requests
from langchain.docstore.... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.