langchain-importly 0.1.0__py3-none-any.whl

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.
@@ -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,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,7 @@
1
+ langchain_importly/__init__.py,sha256=8gI0w47gr8xyxZANysTddpOdVBmzq-fGc0soVEm5r40,371
2
+ langchain_importly/document_loaders.py,sha256=Bd7Hxr8LtiJFv3vt0lnb4_4j1sqNaaz3v7eW3K47F44,10777
3
+ langchain_importly/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ langchain_importly-0.1.0.dist-info/METADATA,sha256=-qYxdRXNviuVeQeIt1WnPnwIEEAEWN-Kc_-90m-giFI,4655
5
+ langchain_importly-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ langchain_importly-0.1.0.dist-info/licenses/LICENSE,sha256=DM7rHwJ0ae3SFn-uVR_HVj6Vw6nKoBqX3QITy6M1sSY,1065
7
+ langchain_importly-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.