langchain-importly 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- langchain_importly-0.1.0/.gitignore +6 -0
- langchain_importly-0.1.0/LICENSE +21 -0
- langchain_importly-0.1.0/PKG-INFO +87 -0
- langchain_importly-0.1.0/README.md +62 -0
- langchain_importly-0.1.0/langchain_importly/__init__.py +12 -0
- langchain_importly-0.1.0/langchain_importly/document_loaders.py +271 -0
- langchain_importly-0.1.0/langchain_importly/py.typed +0 -0
- langchain_importly-0.1.0/pyproject.toml +42 -0
- langchain_importly-0.1.0/tests/conftest.py +5 -0
- langchain_importly-0.1.0/tests/integration_tests/test_live.py +25 -0
- langchain_importly-0.1.0/tests/unit_tests/test_document_loaders.py +139 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Importly
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: langchain-importly
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: LangChain document loader for video and audio links (YouTube, TikTok, podcasts and more) via the Importly API. Works from servers where downloads get blocked.
|
|
5
|
+
Project-URL: Homepage, https://www.importly.io/?utm_source=langchain&utm_medium=package&utm_campaign=guerrilla-2026-11
|
|
6
|
+
Project-URL: Documentation, https://www.importly.io/docs?utm_source=langchain&utm_medium=package&utm_campaign=guerrilla-2026-11
|
|
7
|
+
Project-URL: Repository, https://github.com/importly-io/importly-integrations/tree/main/python/langchain-importly
|
|
8
|
+
Project-URL: Issues, https://github.com/importly-io/importly-integrations/issues
|
|
9
|
+
Author-email: Importly <support@importly.io>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: audio,document-loader,langchain,podcast,rag,transcript,video,youtube
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: <4.0,>=3.10
|
|
19
|
+
Requires-Dist: importly<0.2,>=0.1.0
|
|
20
|
+
Requires-Dist: langchain-core<2.0,>=0.3.0
|
|
21
|
+
Provides-Extra: test
|
|
22
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
|
|
23
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# langchain-importly
|
|
27
|
+
|
|
28
|
+
A LangChain document loader for video and audio links. Give it links from YouTube, TikTok, X, Instagram, a podcast or 1,000+ other sites, and get transcript `Document`s with the title, duration, source URL and per-chunk timestamps.
|
|
29
|
+
|
|
30
|
+
It runs on the [Importly API](https://www.importly.io/?utm_source=langchain&utm_medium=package&utm_campaign=guerrilla-2026-11), so it keeps working once your app is deployed: from servers, serverless functions, Hugging Face Spaces and agent sandboxes, where video sites usually block downloads. Free to try, no card required.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install -U langchain-importly
|
|
36
|
+
export IMPORTLY_API_KEY=... # https://www.importly.io/login?mode=signup&utm_source=langchain&utm_medium=package&utm_campaign=guerrilla-2026-11
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Use
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from langchain_importly import ImportlyLoader
|
|
43
|
+
|
|
44
|
+
loader = ImportlyLoader(
|
|
45
|
+
[
|
|
46
|
+
"https://www.youtube.com/watch?v=jNQXAC9IVRw",
|
|
47
|
+
"https://www.tiktok.com/@scout2015/video/6718335390845095173",
|
|
48
|
+
],
|
|
49
|
+
transcript_format="chunks", # "text" (default), "chunks" or "segments"
|
|
50
|
+
chunk_size_seconds=60,
|
|
51
|
+
)
|
|
52
|
+
docs = loader.load() # or: await loader.aload(), loader.lazy_load()
|
|
53
|
+
|
|
54
|
+
docs[0].metadata
|
|
55
|
+
# {'source': 'https://www.youtube.com/watch?v=jNQXAC9IVRw', 'url': '...', 'job_id': '...',
|
|
56
|
+
# 'language': 'en', 'transcript_source': 'platform_captions', 'duration': 19.0,
|
|
57
|
+
# 'title': 'Me at the zoo', 'thumbnail': '...', 'chunk_index': 0,
|
|
58
|
+
# 'start_seconds': 1.2, 'end_seconds': 14.367, 'start_timestamp': '00:00:01', 'end_timestamp': '00:00:14'}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Then split, embed and store them like any other documents. With `"chunks"`, every piece keeps its start and end time, so your app can cite or link to the moment an answer came from.
|
|
62
|
+
|
|
63
|
+
## Options
|
|
64
|
+
|
|
65
|
+
| Option | Default | What it does |
|
|
66
|
+
| --- | --- | --- |
|
|
67
|
+
| `transcript_format` | `"text"` | One Document per link, per ~`chunk_size_seconds` window, or per caption segment |
|
|
68
|
+
| `chunk_size_seconds` | `120` | Window length for `"chunks"` (segments are never split) |
|
|
69
|
+
| `language` | captions' default | Two-letter code, e.g. `"es"` |
|
|
70
|
+
| `provider` | `None` | `"importly"` turns on speech-to-text for media without captions (billed per minute) |
|
|
71
|
+
| `max_cost_dollars` | `None` | Cap per link for speech-to-text |
|
|
72
|
+
| `include_metadata` | `True` | Adds `title` and `thumbnail` (one extra $0.003 call per link) |
|
|
73
|
+
| `continue_on_failure` | `False` | Log and skip links that fail (private, removed, no captions) instead of raising |
|
|
74
|
+
| `max_concurrency` | `4` | Links processed at once in `aload` / `alazy_load` |
|
|
75
|
+
| `api_key` | `IMPORTLY_API_KEY` | |
|
|
76
|
+
|
|
77
|
+
By default transcripts come from the media's captions ($0.003 per link). For media without captions, the loader raises `importly.TranscriptionProviderRequiredError` with a price quote; set `provider="importly"` to transcribe the audio instead.
|
|
78
|
+
|
|
79
|
+
Need the file or full metadata too? The same key works with the [`importly`](https://pypi.org/project/importly/) SDK: `Importly().import_media(url)` returns a download link.
|
|
80
|
+
|
|
81
|
+
## Links
|
|
82
|
+
|
|
83
|
+
- [Importly docs](https://www.importly.io/docs?utm_source=langchain&utm_medium=package&utm_campaign=guerrilla-2026-11)
|
|
84
|
+
- [Pricing](https://www.importly.io/pricing?utm_source=langchain&utm_medium=package&utm_campaign=guerrilla-2026-11)
|
|
85
|
+
- Support: support@importly.io
|
|
86
|
+
|
|
87
|
+
MIT licensed.
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# langchain-importly
|
|
2
|
+
|
|
3
|
+
A LangChain document loader for video and audio links. Give it links from YouTube, TikTok, X, Instagram, a podcast or 1,000+ other sites, and get transcript `Document`s with the title, duration, source URL and per-chunk timestamps.
|
|
4
|
+
|
|
5
|
+
It runs on the [Importly API](https://www.importly.io/?utm_source=langchain&utm_medium=package&utm_campaign=guerrilla-2026-11), so it keeps working once your app is deployed: from servers, serverless functions, Hugging Face Spaces and agent sandboxes, where video sites usually block downloads. Free to try, no card required.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install -U langchain-importly
|
|
11
|
+
export IMPORTLY_API_KEY=... # https://www.importly.io/login?mode=signup&utm_source=langchain&utm_medium=package&utm_campaign=guerrilla-2026-11
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Use
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
from langchain_importly import ImportlyLoader
|
|
18
|
+
|
|
19
|
+
loader = ImportlyLoader(
|
|
20
|
+
[
|
|
21
|
+
"https://www.youtube.com/watch?v=jNQXAC9IVRw",
|
|
22
|
+
"https://www.tiktok.com/@scout2015/video/6718335390845095173",
|
|
23
|
+
],
|
|
24
|
+
transcript_format="chunks", # "text" (default), "chunks" or "segments"
|
|
25
|
+
chunk_size_seconds=60,
|
|
26
|
+
)
|
|
27
|
+
docs = loader.load() # or: await loader.aload(), loader.lazy_load()
|
|
28
|
+
|
|
29
|
+
docs[0].metadata
|
|
30
|
+
# {'source': 'https://www.youtube.com/watch?v=jNQXAC9IVRw', 'url': '...', 'job_id': '...',
|
|
31
|
+
# 'language': 'en', 'transcript_source': 'platform_captions', 'duration': 19.0,
|
|
32
|
+
# 'title': 'Me at the zoo', 'thumbnail': '...', 'chunk_index': 0,
|
|
33
|
+
# 'start_seconds': 1.2, 'end_seconds': 14.367, 'start_timestamp': '00:00:01', 'end_timestamp': '00:00:14'}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Then split, embed and store them like any other documents. With `"chunks"`, every piece keeps its start and end time, so your app can cite or link to the moment an answer came from.
|
|
37
|
+
|
|
38
|
+
## Options
|
|
39
|
+
|
|
40
|
+
| Option | Default | What it does |
|
|
41
|
+
| --- | --- | --- |
|
|
42
|
+
| `transcript_format` | `"text"` | One Document per link, per ~`chunk_size_seconds` window, or per caption segment |
|
|
43
|
+
| `chunk_size_seconds` | `120` | Window length for `"chunks"` (segments are never split) |
|
|
44
|
+
| `language` | captions' default | Two-letter code, e.g. `"es"` |
|
|
45
|
+
| `provider` | `None` | `"importly"` turns on speech-to-text for media without captions (billed per minute) |
|
|
46
|
+
| `max_cost_dollars` | `None` | Cap per link for speech-to-text |
|
|
47
|
+
| `include_metadata` | `True` | Adds `title` and `thumbnail` (one extra $0.003 call per link) |
|
|
48
|
+
| `continue_on_failure` | `False` | Log and skip links that fail (private, removed, no captions) instead of raising |
|
|
49
|
+
| `max_concurrency` | `4` | Links processed at once in `aload` / `alazy_load` |
|
|
50
|
+
| `api_key` | `IMPORTLY_API_KEY` | |
|
|
51
|
+
|
|
52
|
+
By default transcripts come from the media's captions ($0.003 per link). For media without captions, the loader raises `importly.TranscriptionProviderRequiredError` with a price quote; set `provider="importly"` to transcribe the audio instead.
|
|
53
|
+
|
|
54
|
+
Need the file or full metadata too? The same key works with the [`importly`](https://pypi.org/project/importly/) SDK: `Importly().import_media(url)` returns a download link.
|
|
55
|
+
|
|
56
|
+
## Links
|
|
57
|
+
|
|
58
|
+
- [Importly docs](https://www.importly.io/docs?utm_source=langchain&utm_medium=package&utm_campaign=guerrilla-2026-11)
|
|
59
|
+
- [Pricing](https://www.importly.io/pricing?utm_source=langchain&utm_medium=package&utm_campaign=guerrilla-2026-11)
|
|
60
|
+
- Support: support@importly.io
|
|
61
|
+
|
|
62
|
+
MIT licensed.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""LangChain integration for Importly: transcripts of video and audio links as Documents."""
|
|
2
|
+
|
|
3
|
+
from importlib import metadata
|
|
4
|
+
|
|
5
|
+
from langchain_importly.document_loaders import ImportlyLoader
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
__version__ = metadata.version(__package__ or "langchain_importly")
|
|
9
|
+
except metadata.PackageNotFoundError:
|
|
10
|
+
__version__ = ""
|
|
11
|
+
|
|
12
|
+
__all__ = ["ImportlyLoader", "__version__"]
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""LangChain document loader for video and audio links, backed by the Importly API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
from typing import (
|
|
8
|
+
Any,
|
|
9
|
+
AsyncIterator,
|
|
10
|
+
Dict,
|
|
11
|
+
Iterator,
|
|
12
|
+
List,
|
|
13
|
+
Literal,
|
|
14
|
+
Optional,
|
|
15
|
+
Sequence,
|
|
16
|
+
Tuple,
|
|
17
|
+
Union,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
from langchain_core.document_loaders import BaseLoader
|
|
21
|
+
from langchain_core.documents import Document
|
|
22
|
+
|
|
23
|
+
from importly import (
|
|
24
|
+
AsyncImportly,
|
|
25
|
+
BasicMetadata,
|
|
26
|
+
Importly,
|
|
27
|
+
ImportlyError,
|
|
28
|
+
QueuedJob,
|
|
29
|
+
Transcript,
|
|
30
|
+
format_timestamp,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
TranscriptFormat = Literal["text", "chunks", "segments"]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ImportlyLoader(BaseLoader):
|
|
39
|
+
"""Load transcripts of video and audio links as LangChain ``Document`` objects.
|
|
40
|
+
|
|
41
|
+
Works with YouTube, TikTok, X, Instagram, podcasts and 1,000+ other sites,
|
|
42
|
+
and from servers and agent sandboxes where downloads usually get blocked.
|
|
43
|
+
Needs an Importly API key (``IMPORTLY_API_KEY``); free to try, no card
|
|
44
|
+
required: https://www.importly.io/?utm_source=langchain&utm_medium=package&utm_campaign=guerrilla-2026-11
|
|
45
|
+
|
|
46
|
+
Setup:
|
|
47
|
+
.. code-block:: bash
|
|
48
|
+
|
|
49
|
+
pip install -U langchain-importly
|
|
50
|
+
export IMPORTLY_API_KEY="..."
|
|
51
|
+
|
|
52
|
+
Instantiate:
|
|
53
|
+
.. code-block:: python
|
|
54
|
+
|
|
55
|
+
from langchain_importly import ImportlyLoader
|
|
56
|
+
|
|
57
|
+
loader = ImportlyLoader(
|
|
58
|
+
["https://www.youtube.com/watch?v=jNQXAC9IVRw"],
|
|
59
|
+
transcript_format="chunks",
|
|
60
|
+
chunk_size_seconds=60,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
Load:
|
|
64
|
+
.. code-block:: python
|
|
65
|
+
|
|
66
|
+
docs = loader.load()
|
|
67
|
+
docs[0].metadata
|
|
68
|
+
# {'source': 'https://www.youtube.com/watch?v=jNQXAC9IVRw', 'title': 'Me at the zoo',
|
|
69
|
+
# 'duration': 19.0, 'language': 'en', 'start_seconds': 1.2, 'start_timestamp': '00:00:01', ...}
|
|
70
|
+
|
|
71
|
+
Async load:
|
|
72
|
+
.. code-block:: python
|
|
73
|
+
|
|
74
|
+
docs = await loader.aload()
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
urls: One link or a list of links.
|
|
78
|
+
api_key: Importly API key. Defaults to ``IMPORTLY_API_KEY``.
|
|
79
|
+
transcript_format: ``"text"`` (one Document per link), ``"chunks"``
|
|
80
|
+
(one per ~``chunk_size_seconds`` window) or ``"segments"`` (one per
|
|
81
|
+
caption segment).
|
|
82
|
+
chunk_size_seconds: Window length for ``"chunks"``.
|
|
83
|
+
language: Two-letter language code, e.g. ``"es"``. Picks the caption
|
|
84
|
+
track, or is sent to speech-to-text.
|
|
85
|
+
provider: Set to ``"importly"`` to use built-in speech-to-text for media
|
|
86
|
+
without captions (billed per minute). Default: captions only.
|
|
87
|
+
max_cost_dollars: Cap per link for speech-to-text.
|
|
88
|
+
include_metadata: Also fetch title, duration and thumbnail (one basic
|
|
89
|
+
metadata call per link).
|
|
90
|
+
continue_on_failure: Log and skip links that fail instead of raising.
|
|
91
|
+
timeout: Seconds to wait for each link.
|
|
92
|
+
max_concurrency: Links processed at once by ``alazy_load``.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
def __init__(
|
|
96
|
+
self,
|
|
97
|
+
urls: Union[str, Sequence[str]],
|
|
98
|
+
*,
|
|
99
|
+
api_key: Optional[str] = None,
|
|
100
|
+
transcript_format: TranscriptFormat = "text",
|
|
101
|
+
chunk_size_seconds: float = 120,
|
|
102
|
+
language: Optional[str] = None,
|
|
103
|
+
provider: Optional[str] = None,
|
|
104
|
+
max_cost_dollars: Optional[float] = None,
|
|
105
|
+
include_metadata: bool = True,
|
|
106
|
+
continue_on_failure: bool = False,
|
|
107
|
+
timeout: float = 600,
|
|
108
|
+
poll_interval: float = 3,
|
|
109
|
+
max_concurrency: int = 4,
|
|
110
|
+
base_url: Optional[str] = None,
|
|
111
|
+
client: Optional[Importly] = None,
|
|
112
|
+
async_client: Optional[AsyncImportly] = None,
|
|
113
|
+
) -> None:
|
|
114
|
+
if transcript_format not in ("text", "chunks", "segments"):
|
|
115
|
+
raise ValueError("transcript_format must be 'text', 'chunks' or 'segments'")
|
|
116
|
+
if chunk_size_seconds <= 0:
|
|
117
|
+
raise ValueError("chunk_size_seconds must be positive")
|
|
118
|
+
self.urls: List[str] = [urls] if isinstance(urls, str) else list(urls)
|
|
119
|
+
self.api_key = api_key
|
|
120
|
+
self.base_url = base_url
|
|
121
|
+
self.transcript_format = transcript_format
|
|
122
|
+
self.chunk_size_seconds = chunk_size_seconds
|
|
123
|
+
self.language = language
|
|
124
|
+
self.provider = provider
|
|
125
|
+
self.max_cost_dollars = max_cost_dollars
|
|
126
|
+
self.include_metadata = include_metadata
|
|
127
|
+
self.continue_on_failure = continue_on_failure
|
|
128
|
+
self.timeout = timeout
|
|
129
|
+
self.poll_interval = poll_interval
|
|
130
|
+
self.max_concurrency = max(1, max_concurrency)
|
|
131
|
+
self._client = client
|
|
132
|
+
self._async_client = async_client
|
|
133
|
+
|
|
134
|
+
# -- shared -------------------------------------------------------------
|
|
135
|
+
|
|
136
|
+
def _transcribe_options(self) -> Dict[str, Any]:
|
|
137
|
+
return {"language": self.language, "provider": self.provider, "max_cost_dollars": self.max_cost_dollars}
|
|
138
|
+
|
|
139
|
+
def _documents(self, url: str, job_id: str, transcript: Transcript, basic: Optional[BasicMetadata]) -> List[Document]:
|
|
140
|
+
base: Dict[str, Any] = {
|
|
141
|
+
"source": url,
|
|
142
|
+
"url": url,
|
|
143
|
+
"job_id": job_id,
|
|
144
|
+
"language": transcript.language,
|
|
145
|
+
"transcript_source": transcript.source,
|
|
146
|
+
"duration": transcript.duration,
|
|
147
|
+
}
|
|
148
|
+
if basic is not None:
|
|
149
|
+
base["title"] = basic.title
|
|
150
|
+
base["thumbnail"] = basic.thumbnail
|
|
151
|
+
if base["duration"] is None:
|
|
152
|
+
base["duration"] = basic.duration
|
|
153
|
+
base = {k: v for k, v in base.items() if v is not None}
|
|
154
|
+
|
|
155
|
+
if self.transcript_format == "text":
|
|
156
|
+
return [Document(page_content=transcript.text, metadata=base)]
|
|
157
|
+
if self.transcript_format == "segments":
|
|
158
|
+
pieces: List[Tuple[int, float, float, str]] = [
|
|
159
|
+
(i, s.start, s.end, s.text) for i, s in enumerate(transcript.segments)
|
|
160
|
+
]
|
|
161
|
+
else:
|
|
162
|
+
pieces = [(c.index, c.start, c.end, c.text) for c in transcript.chunks(self.chunk_size_seconds)]
|
|
163
|
+
return [
|
|
164
|
+
Document(
|
|
165
|
+
page_content=text,
|
|
166
|
+
metadata={
|
|
167
|
+
**base,
|
|
168
|
+
"chunk_index": index,
|
|
169
|
+
"start_seconds": start,
|
|
170
|
+
"end_seconds": end,
|
|
171
|
+
"start_timestamp": format_timestamp(start),
|
|
172
|
+
"end_timestamp": format_timestamp(end),
|
|
173
|
+
},
|
|
174
|
+
)
|
|
175
|
+
for index, start, end, text in pieces
|
|
176
|
+
if text.strip()
|
|
177
|
+
]
|
|
178
|
+
|
|
179
|
+
def _handle_failure(self, url: str, error: Exception) -> None:
|
|
180
|
+
if not self.continue_on_failure:
|
|
181
|
+
raise error
|
|
182
|
+
logger.warning("Skipping %s: %s", url, error)
|
|
183
|
+
|
|
184
|
+
# -- sync -------------------------------------------------------------
|
|
185
|
+
|
|
186
|
+
def lazy_load(self) -> Iterator[Document]:
|
|
187
|
+
"""Start every link's jobs first, then yield each link's Documents in order."""
|
|
188
|
+
client = self._client or Importly(self.api_key, base_url=self.base_url)
|
|
189
|
+
try:
|
|
190
|
+
started: List[Tuple[str, QueuedJob, Optional[QueuedJob]]] = []
|
|
191
|
+
for url in self.urls:
|
|
192
|
+
try:
|
|
193
|
+
job = client.start_transcription(url, **self._transcribe_options())
|
|
194
|
+
except ImportlyError as error:
|
|
195
|
+
self._handle_failure(url, error)
|
|
196
|
+
continue
|
|
197
|
+
meta_job = self._start_basic(client, url)
|
|
198
|
+
started.append((url, job, meta_job))
|
|
199
|
+
|
|
200
|
+
for url, job, meta_job in started:
|
|
201
|
+
try:
|
|
202
|
+
transcript = client.wait_for_transcription(job.job_id, timeout=self.timeout, poll_interval=self.poll_interval)
|
|
203
|
+
except ImportlyError as error:
|
|
204
|
+
self._handle_failure(url, error)
|
|
205
|
+
continue
|
|
206
|
+
basic = self._wait_basic(client, url, meta_job)
|
|
207
|
+
yield from self._documents(url, job.job_id, transcript, basic)
|
|
208
|
+
finally:
|
|
209
|
+
if self._client is None:
|
|
210
|
+
client.close()
|
|
211
|
+
|
|
212
|
+
def _start_basic(self, client: Importly, url: str) -> Optional[QueuedJob]:
|
|
213
|
+
if not self.include_metadata:
|
|
214
|
+
return None
|
|
215
|
+
try:
|
|
216
|
+
return client.start_basic_metadata(url)
|
|
217
|
+
except ImportlyError as error:
|
|
218
|
+
logger.warning("No title/thumbnail for %s: %s", url, error)
|
|
219
|
+
return None
|
|
220
|
+
|
|
221
|
+
def _wait_basic(self, client: Importly, url: str, job: Optional[QueuedJob]) -> Optional[BasicMetadata]:
|
|
222
|
+
if job is None:
|
|
223
|
+
return None
|
|
224
|
+
try:
|
|
225
|
+
return client.wait_for_basic_metadata(job.job_id, timeout=self.timeout, poll_interval=1.0)
|
|
226
|
+
except ImportlyError as error:
|
|
227
|
+
logger.warning("No title/thumbnail for %s: %s", url, error)
|
|
228
|
+
return None
|
|
229
|
+
|
|
230
|
+
# -- async -------------------------------------------------------------
|
|
231
|
+
|
|
232
|
+
async def alazy_load(self) -> AsyncIterator[Document]:
|
|
233
|
+
"""Process up to ``max_concurrency`` links at once; yield Documents in input order."""
|
|
234
|
+
client = self._async_client or AsyncImportly(self.api_key, base_url=self.base_url)
|
|
235
|
+
semaphore = asyncio.Semaphore(self.max_concurrency)
|
|
236
|
+
try:
|
|
237
|
+
tasks = [asyncio.ensure_future(self._aload_one(client, semaphore, url)) for url in self.urls]
|
|
238
|
+
try:
|
|
239
|
+
for task in tasks:
|
|
240
|
+
for doc in await task:
|
|
241
|
+
yield doc
|
|
242
|
+
finally:
|
|
243
|
+
for task in tasks:
|
|
244
|
+
task.cancel()
|
|
245
|
+
finally:
|
|
246
|
+
if self._async_client is None:
|
|
247
|
+
await client.aclose()
|
|
248
|
+
|
|
249
|
+
async def _aload_one(self, client: AsyncImportly, semaphore: asyncio.Semaphore, url: str) -> List[Document]:
|
|
250
|
+
async with semaphore:
|
|
251
|
+
basic_task: Optional["asyncio.Future[Optional[BasicMetadata]]"] = None
|
|
252
|
+
try:
|
|
253
|
+
job = await client.start_transcription(url, **self._transcribe_options())
|
|
254
|
+
if self.include_metadata:
|
|
255
|
+
basic_task = asyncio.ensure_future(self._abasic(client, url))
|
|
256
|
+
transcript = await client.wait_for_transcription(job.job_id, timeout=self.timeout, poll_interval=self.poll_interval)
|
|
257
|
+
except ImportlyError as error:
|
|
258
|
+
if basic_task is not None:
|
|
259
|
+
basic_task.cancel()
|
|
260
|
+
self._handle_failure(url, error)
|
|
261
|
+
return []
|
|
262
|
+
basic = await basic_task if basic_task is not None else None
|
|
263
|
+
return self._documents(url, job.job_id, transcript, basic)
|
|
264
|
+
|
|
265
|
+
async def _abasic(self, client: AsyncImportly, url: str) -> Optional[BasicMetadata]:
|
|
266
|
+
try:
|
|
267
|
+
return await client.basic_metadata(url, timeout=self.timeout)
|
|
268
|
+
except ImportlyError as error:
|
|
269
|
+
logger.warning("No title/thumbnail for %s: %s", url, error)
|
|
270
|
+
return None
|
|
271
|
+
|
|
File without changes
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.24"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "langchain-importly"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "LangChain document loader for video and audio links (YouTube, TikTok, podcasts and more) via the Importly API. Works from servers where downloads get blocked."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10,<4.0"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Importly", email = "support@importly.io" }]
|
|
14
|
+
keywords = ["langchain", "document-loader", "transcript", "youtube", "video", "audio", "podcast", "rag"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
20
|
+
"Typing :: Typed",
|
|
21
|
+
]
|
|
22
|
+
dependencies = [
|
|
23
|
+
"importly>=0.1.0,<0.2",
|
|
24
|
+
"langchain-core>=0.3.0,<2.0",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[project.optional-dependencies]
|
|
28
|
+
test = ["pytest>=7", "pytest-asyncio>=0.23"]
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Homepage = "https://www.importly.io/?utm_source=langchain&utm_medium=package&utm_campaign=guerrilla-2026-11"
|
|
32
|
+
Documentation = "https://www.importly.io/docs?utm_source=langchain&utm_medium=package&utm_campaign=guerrilla-2026-11"
|
|
33
|
+
Repository = "https://github.com/importly-io/importly-integrations/tree/main/python/langchain-importly"
|
|
34
|
+
Issues = "https://github.com/importly-io/importly-integrations/issues"
|
|
35
|
+
|
|
36
|
+
[tool.hatch.build.targets.wheel]
|
|
37
|
+
packages = ["langchain_importly"]
|
|
38
|
+
|
|
39
|
+
[tool.pytest.ini_options]
|
|
40
|
+
asyncio_mode = "auto"
|
|
41
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
42
|
+
markers = ["live: calls the real Importly API (needs IMPORTLY_LIVE_TEST=1 and IMPORTLY_API_KEY)"]
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Calls the real API. Opt in with IMPORTLY_LIVE_TEST=1 and IMPORTLY_API_KEY (about $0.006 a run)."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from langchain_importly import ImportlyLoader
|
|
8
|
+
|
|
9
|
+
URL = os.environ.get("IMPORTLY_LIVE_TEST_URL", "https://www.youtube.com/watch?v=jNQXAC9IVRw")
|
|
10
|
+
|
|
11
|
+
pytestmark = [
|
|
12
|
+
pytest.mark.live,
|
|
13
|
+
pytest.mark.skipif(
|
|
14
|
+
os.environ.get("IMPORTLY_LIVE_TEST") != "1" or not os.environ.get("IMPORTLY_API_KEY"),
|
|
15
|
+
reason="live test: set IMPORTLY_LIVE_TEST=1 and IMPORTLY_API_KEY",
|
|
16
|
+
),
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_live_chunks():
|
|
21
|
+
docs = ImportlyLoader(URL, transcript_format="chunks", chunk_size_seconds=30, timeout=300).load()
|
|
22
|
+
assert docs
|
|
23
|
+
assert docs[0].metadata["source"] == URL
|
|
24
|
+
assert docs[0].metadata.get("title")
|
|
25
|
+
assert "start_seconds" in docs[0].metadata
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
from langchain_core.document_loaders import BaseLoader
|
|
5
|
+
|
|
6
|
+
from fake_api import BASIC_RESULT, TRANSCRIPT_RESULT, URL, FakeAPI, err, ok
|
|
7
|
+
from importly import AsyncImportly, Importly, InvalidURLError, TranscriptionProviderRequiredError
|
|
8
|
+
from langchain_importly import ImportlyLoader
|
|
9
|
+
|
|
10
|
+
URL2 = "https://example.com/podcast/episode-1.mp3"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def fake_api(*, transcribe_status=None) -> FakeAPI:
|
|
14
|
+
return (
|
|
15
|
+
FakeAPI()
|
|
16
|
+
.on("POST", "/transcribe", ok({"jobId": "t1", "status": "queued", "message": "q"}))
|
|
17
|
+
.on("GET", "/transcribe/status", *(transcribe_status or [ok({"jobId": "t1", "status": "running"}), ok({"jobId": "t1", "status": "completed", "result": TRANSCRIPT_RESULT})]))
|
|
18
|
+
.on("POST", "/metadata/basic", ok({"jobId": "b1", "status": "queued", "message": "q"}))
|
|
19
|
+
.on("GET", "/metadata/basic/status", ok({"jobId": "b1", "status": "completed", "result": BASIC_RESULT}))
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def sync_client(api: FakeAPI) -> Importly:
|
|
24
|
+
return Importly("k", http_client=api.sync_client(), sleep=lambda _: None)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def async_client(api: FakeAPI) -> AsyncImportly:
|
|
28
|
+
async def no_sleep(_):
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
return AsyncImportly("k", http_client=api.async_client(), sleep=no_sleep)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_is_a_langchain_loader():
|
|
35
|
+
assert isinstance(ImportlyLoader(URL, client=sync_client(FakeAPI())), BaseLoader)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_text_format_one_document_with_metadata():
|
|
39
|
+
api = fake_api()
|
|
40
|
+
docs = ImportlyLoader(URL, client=sync_client(api)).load()
|
|
41
|
+
assert len(docs) == 1
|
|
42
|
+
doc = docs[0]
|
|
43
|
+
assert doc.page_content.startswith("All right, so here we are")
|
|
44
|
+
assert doc.metadata == {
|
|
45
|
+
"source": URL,
|
|
46
|
+
"url": URL,
|
|
47
|
+
"job_id": "t1",
|
|
48
|
+
"language": "en",
|
|
49
|
+
"transcript_source": "platform_captions",
|
|
50
|
+
"duration": 19.0,
|
|
51
|
+
"title": "Me at the zoo",
|
|
52
|
+
"thumbnail": "https://i.ytimg.com/vi/jNQXAC9IVRw/hqdefault.jpg",
|
|
53
|
+
}
|
|
54
|
+
assert api.json_body(0) == {"url": URL}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_chunks_carry_timestamps():
|
|
58
|
+
docs = ImportlyLoader(URL, transcript_format="chunks", chunk_size_seconds=5, client=sync_client(fake_api())).load()
|
|
59
|
+
assert len(docs) == 2
|
|
60
|
+
assert docs[0].metadata["start_seconds"] == 1.2
|
|
61
|
+
assert docs[0].metadata["end_seconds"] == 7.974
|
|
62
|
+
assert docs[1].metadata["start_timestamp"] == "00:00:07"
|
|
63
|
+
assert docs[1].metadata["chunk_index"] == 1
|
|
64
|
+
assert docs[1].metadata["title"] == "Me at the zoo"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_segments_format():
|
|
68
|
+
docs = ImportlyLoader(URL, transcript_format="segments", client=sync_client(fake_api())).load()
|
|
69
|
+
assert [d.page_content for d in docs][2] == "really really long trunks"
|
|
70
|
+
assert docs[3].metadata["end_seconds"] == 14.367
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_options_are_sent_and_metadata_can_be_skipped():
|
|
74
|
+
api = fake_api()
|
|
75
|
+
ImportlyLoader([URL2], language="es", provider="importly", max_cost_dollars=0.5, include_metadata=False, client=sync_client(api)).load()
|
|
76
|
+
assert api.json_body(0) == {"url": URL2, "language": "es", "provider": "importly", "maxCostDollars": 0.5}
|
|
77
|
+
assert not api.calls("POST", "/metadata/basic")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def test_jobs_for_all_links_start_before_waiting():
|
|
81
|
+
api = fake_api()
|
|
82
|
+
ImportlyLoader([URL, URL2], client=sync_client(api)).load()
|
|
83
|
+
posts = [r.url.path for r in api.requests if r.method == "POST"]
|
|
84
|
+
first_poll = next(i for i, r in enumerate(api.requests) if r.method == "GET")
|
|
85
|
+
assert posts == ["/transcribe", "/metadata/basic", "/transcribe", "/metadata/basic"]
|
|
86
|
+
assert first_poll == 4
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_failure_raises_by_default():
|
|
90
|
+
api = fake_api(transcribe_status=[ok({"jobId": "t1", "status": "failed", "message": "no captions", "code": "TRANSCRIPTION_PROVIDER_REQUIRED"})])
|
|
91
|
+
with pytest.raises(TranscriptionProviderRequiredError):
|
|
92
|
+
ImportlyLoader(URL, client=sync_client(api)).load()
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def test_continue_on_failure_skips_bad_links(caplog):
|
|
96
|
+
api = fake_api()
|
|
97
|
+
api.routes[("POST", "/transcribe")] = [err(400, "Invalid URL format", "INVALID_URL"), ok({"jobId": "t1", "status": "queued", "message": "q"})]
|
|
98
|
+
with caplog.at_level(logging.WARNING):
|
|
99
|
+
docs = ImportlyLoader(["not a url", URL], continue_on_failure=True, client=sync_client(api)).load()
|
|
100
|
+
assert len(docs) == 1 and docs[0].metadata["source"] == URL
|
|
101
|
+
assert "not a url" in caplog.text
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def test_invalid_url_raises_without_continue():
|
|
105
|
+
api = fake_api()
|
|
106
|
+
api.routes[("POST", "/transcribe")] = [err(400, "Invalid URL format", "INVALID_URL")]
|
|
107
|
+
with pytest.raises(InvalidURLError):
|
|
108
|
+
ImportlyLoader("nope", client=sync_client(api)).load()
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_metadata_failure_does_not_fail_the_document():
|
|
112
|
+
api = fake_api()
|
|
113
|
+
api.routes[("GET", "/metadata/basic/status")] = [ok({"jobId": "b1", "status": "failed", "message": "x", "code": "VIDEO_UNAVAILABLE"})]
|
|
114
|
+
[doc] = ImportlyLoader(URL, client=sync_client(api)).load()
|
|
115
|
+
assert "title" not in doc.metadata
|
|
116
|
+
assert doc.metadata["duration"] == 19.0
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def test_bad_arguments():
|
|
120
|
+
with pytest.raises(ValueError):
|
|
121
|
+
ImportlyLoader(URL, transcript_format="lines", client=sync_client(FakeAPI())) # type: ignore[arg-type]
|
|
122
|
+
with pytest.raises(ValueError):
|
|
123
|
+
ImportlyLoader(URL, chunk_size_seconds=0, client=sync_client(FakeAPI()))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
async def test_async_load_keeps_order():
|
|
127
|
+
api = fake_api()
|
|
128
|
+
loader = ImportlyLoader([URL, URL2], transcript_format="chunks", chunk_size_seconds=5, async_client=async_client(api))
|
|
129
|
+
docs = await loader.aload()
|
|
130
|
+
assert [d.metadata["source"] for d in docs] == [URL, URL, URL2, URL2]
|
|
131
|
+
assert docs[0].metadata["title"] == "Me at the zoo"
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
async def test_async_continue_on_failure():
|
|
135
|
+
api = fake_api()
|
|
136
|
+
api.routes[("POST", "/transcribe")] = [err(400, "Invalid URL format", "INVALID_URL"), ok({"jobId": "t1", "status": "queued", "message": "q"})]
|
|
137
|
+
loader = ImportlyLoader(["bad", URL], continue_on_failure=True, max_concurrency=1, async_client=async_client(api))
|
|
138
|
+
docs = [d async for d in loader.alazy_load()]
|
|
139
|
+
assert len(docs) == 1
|