scrapingrabbit-haystack 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.
- haystack_integrations/components/fetchers/scrapingrabbit/__init__.py +3 -0
- haystack_integrations/components/fetchers/scrapingrabbit/fetcher.py +66 -0
- haystack_integrations/tools/scrapingrabbit/__init__.py +3 -0
- haystack_integrations/tools/scrapingrabbit/toolset.py +108 -0
- scrapingrabbit_haystack-0.1.0.dist-info/METADATA +101 -0
- scrapingrabbit_haystack-0.1.0.dist-info/RECORD +8 -0
- scrapingrabbit_haystack-0.1.0.dist-info/WHEEL +4 -0
- scrapingrabbit_haystack-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""YouTube transcripts as Haystack Documents, for indexing and RAG pipelines."""
|
|
2
|
+
import logging
|
|
3
|
+
from typing import Any, Dict, List, Optional
|
|
4
|
+
|
|
5
|
+
from haystack import Document, component, default_from_dict, default_to_dict
|
|
6
|
+
from haystack.utils import Secret, deserialize_secrets_inplace
|
|
7
|
+
from scrapingrabbit import ScrapingRabbit, ScrapingRabbitError
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@component
|
|
13
|
+
class ScrapingRabbitTranscriptFetcher:
|
|
14
|
+
"""Fetches YouTube transcripts and returns one Document per video.
|
|
15
|
+
|
|
16
|
+
Each video costs 1 credit when it returns a transcript; failures are free. By default a video that fails (no
|
|
17
|
+
captions, private, bad link) is skipped with a warning and listed in `failed`, so one bad link doesn't stop a
|
|
18
|
+
batch; set raise_on_failure=True to stop instead.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(self, api_key: Secret = Secret.from_env_var("SCRAPINGRABBIT_API_KEY"), raise_on_failure: bool = False):
|
|
22
|
+
self.api_key = api_key
|
|
23
|
+
self.raise_on_failure = raise_on_failure
|
|
24
|
+
self._client: Optional[ScrapingRabbit] = None
|
|
25
|
+
|
|
26
|
+
def warm_up(self) -> None:
|
|
27
|
+
if self._client is None:
|
|
28
|
+
self._client = ScrapingRabbit(api_key=self.api_key.resolve_value())
|
|
29
|
+
|
|
30
|
+
@component.output_types(documents=List[Document], failed=List[Dict[str, str]])
|
|
31
|
+
def run(self, urls: List[str]) -> Dict[str, Any]:
|
|
32
|
+
"""Fetch the transcript of each YouTube link or video id in `urls`."""
|
|
33
|
+
self.warm_up()
|
|
34
|
+
assert self._client is not None
|
|
35
|
+
documents: List[Document] = []
|
|
36
|
+
failed: List[Dict[str, str]] = []
|
|
37
|
+
for url in urls:
|
|
38
|
+
try:
|
|
39
|
+
data = self._client.youtube_transcript(url=url)
|
|
40
|
+
except ScrapingRabbitError as error:
|
|
41
|
+
if self.raise_on_failure:
|
|
42
|
+
raise
|
|
43
|
+
logger.warning("Skipping %s: %s", url, error)
|
|
44
|
+
failed.append({"url": url, "code": error.code, "message": error.message})
|
|
45
|
+
continue
|
|
46
|
+
lines = data.get("transcript") or []
|
|
47
|
+
documents.append(
|
|
48
|
+
Document(
|
|
49
|
+
content=" ".join(line["text"] for line in lines if line.get("text")),
|
|
50
|
+
meta={
|
|
51
|
+
"url": url,
|
|
52
|
+
"video_id": data.get("videoId"),
|
|
53
|
+
"language": data.get("language"),
|
|
54
|
+
"is_auto_generated": data.get("isAutoGenerated"),
|
|
55
|
+
},
|
|
56
|
+
)
|
|
57
|
+
)
|
|
58
|
+
return {"documents": documents, "failed": failed}
|
|
59
|
+
|
|
60
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
61
|
+
return default_to_dict(self, api_key=self.api_key.to_dict(), raise_on_failure=self.raise_on_failure)
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def from_dict(cls, data: Dict[str, Any]) -> "ScrapingRabbitTranscriptFetcher":
|
|
65
|
+
deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"])
|
|
66
|
+
return default_from_dict(cls, data)
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""ScrapingRabbit endpoints as Haystack Tools, built from the SDK's ENDPOINTS list."""
|
|
2
|
+
import json
|
|
3
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
4
|
+
|
|
5
|
+
from haystack.core.serialization import generate_qualified_class_name
|
|
6
|
+
from haystack.tools import Tool, Toolset
|
|
7
|
+
from haystack.utils import Secret, deserialize_secrets_inplace
|
|
8
|
+
from scrapingrabbit import ENDPOINTS, ScrapingRabbit, ScrapingRabbitError
|
|
9
|
+
|
|
10
|
+
API_KEY_ENV = "SCRAPINGRABBIT_API_KEY"
|
|
11
|
+
DEFAULT_MAX_CHARS = 60_000
|
|
12
|
+
_NOT_CHARGED = " (failed calls are not charged)"
|
|
13
|
+
_BY_NAME = {endpoint["name"]: endpoint for endpoint in ENDPOINTS}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _parameters(endpoint: Dict[str, Any]) -> Dict[str, Any]:
|
|
17
|
+
return {
|
|
18
|
+
"type": "object",
|
|
19
|
+
"properties": {p["name"]: {"type": "string", "description": p["description"]} for p in endpoint["params"]},
|
|
20
|
+
"required": [p["name"] for p in endpoint["params"] if p["required"]],
|
|
21
|
+
"additionalProperties": False,
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _fit(data: Any, max_chars: int) -> str:
|
|
26
|
+
"""The result as JSON text, cut to max_chars with a note so one call can't flood the model's context."""
|
|
27
|
+
text = json.dumps(data, ensure_ascii=False)
|
|
28
|
+
if len(text) <= max_chars:
|
|
29
|
+
return text
|
|
30
|
+
note = (
|
|
31
|
+
f"\n[Cut: showing {max_chars} of {len(text)} characters of JSON. The last record is incomplete. "
|
|
32
|
+
"Ask for less (a narrower query or fewer items) to see the rest.]"
|
|
33
|
+
)
|
|
34
|
+
return text[: max_chars - len(note)] + note
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ScrapingRabbitToolset(Toolset):
|
|
38
|
+
"""One Tool per ScrapingRabbit endpoint (youtube_transcript, tiktok_profile_viewer, amazon_product_search, ...).
|
|
39
|
+
|
|
40
|
+
Pass it to a Haystack Agent or chat generator as `tools`. The API key is read when a tool is first called, so
|
|
41
|
+
building the toolset never fails for a missing key. Refusals raise `CODE: message (failed calls are not
|
|
42
|
+
charged)`; an Agent hands that to the model as a tool error.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
api_key: Secret = Secret.from_env_var(API_KEY_ENV),
|
|
48
|
+
include: Optional[List[str]] = None,
|
|
49
|
+
max_chars: int = DEFAULT_MAX_CHARS,
|
|
50
|
+
) -> None:
|
|
51
|
+
unknown = [name for name in include or [] if name not in _BY_NAME]
|
|
52
|
+
if unknown:
|
|
53
|
+
raise ValueError(f"Unknown tool name(s): {', '.join(unknown)}")
|
|
54
|
+
if not isinstance(max_chars, int) or max_chars < 1000:
|
|
55
|
+
raise ValueError("max_chars must be an integer of at least 1000")
|
|
56
|
+
self.api_key = api_key
|
|
57
|
+
self.include = list(include) if include is not None else None
|
|
58
|
+
self.max_chars = max_chars
|
|
59
|
+
self._client: Optional[ScrapingRabbit] = None
|
|
60
|
+
wanted = self.include if self.include is not None else list(_BY_NAME)
|
|
61
|
+
super().__init__(tools=[self._tool(_BY_NAME[name]) for name in wanted])
|
|
62
|
+
|
|
63
|
+
def _get_client(self) -> ScrapingRabbit:
|
|
64
|
+
if self._client is None:
|
|
65
|
+
self._client = ScrapingRabbit(api_key=self.api_key.resolve_value())
|
|
66
|
+
return self._client
|
|
67
|
+
|
|
68
|
+
def _tool(self, endpoint: Dict[str, Any]) -> Tool:
|
|
69
|
+
return Tool(
|
|
70
|
+
name=endpoint["name"],
|
|
71
|
+
# The API's description already says what a call costs.
|
|
72
|
+
description=endpoint["description"] or endpoint["summary"],
|
|
73
|
+
parameters=_parameters(endpoint),
|
|
74
|
+
function=self._runner(endpoint),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
def _runner(self, endpoint: Dict[str, Any]) -> Callable[..., str]:
|
|
78
|
+
known = {p["name"] for p in endpoint["params"]}
|
|
79
|
+
|
|
80
|
+
def run(**kwargs: Any) -> str:
|
|
81
|
+
unknown = sorted(set(kwargs) - known)
|
|
82
|
+
if unknown:
|
|
83
|
+
raise ValueError(f"Unknown argument(s): {', '.join(unknown)}. Allowed: {', '.join(sorted(known)) or 'none'}.")
|
|
84
|
+
# Every API parameter is a string; models sometimes send ids as numbers.
|
|
85
|
+
params = {k: str(v) for k, v in kwargs.items() if v is not None}
|
|
86
|
+
try:
|
|
87
|
+
data = getattr(self._get_client(), endpoint["name"])(**params)
|
|
88
|
+
except ScrapingRabbitError as error:
|
|
89
|
+
# Only a refusal from the API (it has an HTTP status) is known to be free; a client-side timeout may still be charged.
|
|
90
|
+
suffix = _NOT_CHARGED if error.status is not None else ""
|
|
91
|
+
raise RuntimeError(f"{error}{suffix}") from error
|
|
92
|
+
return _fit(data, self.max_chars)
|
|
93
|
+
|
|
94
|
+
run.__name__ = endpoint["name"]
|
|
95
|
+
return run
|
|
96
|
+
|
|
97
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
98
|
+
# Serialize the settings, not the tools: they are rebuilt from the SDK's endpoint list on load.
|
|
99
|
+
return {
|
|
100
|
+
"type": generate_qualified_class_name(type(self)),
|
|
101
|
+
"data": {"api_key": self.api_key.to_dict(), "include": self.include, "max_chars": self.max_chars},
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def from_dict(cls, data: Dict[str, Any]) -> "ScrapingRabbitToolset":
|
|
106
|
+
init = dict(data["data"])
|
|
107
|
+
deserialize_secrets_inplace(init, keys=["api_key"])
|
|
108
|
+
return cls(**init)
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: scrapingrabbit-haystack
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: ScrapingRabbit for Haystack: one Tool per endpoint for Agents (video transcripts, social profiles, Amazon and Walmart products, Google results, SEO data) and a YouTube transcript fetcher that returns Documents.
|
|
5
|
+
Project-URL: Homepage, https://scrapingrabbit.com
|
|
6
|
+
Project-URL: Documentation, https://github.com/scrapingrabbit/scrapingrabbit-haystack#readme
|
|
7
|
+
Project-URL: Repository, https://github.com/scrapingrabbit/scrapingrabbit-haystack
|
|
8
|
+
Project-URL: Issues, https://github.com/scrapingrabbit/scrapingrabbit-haystack/issues
|
|
9
|
+
Project-URL: API reference, https://scrapingrabbit.com/docs
|
|
10
|
+
Author: ScrapingRabbit
|
|
11
|
+
License: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: agents,amazon,deepset,haystack,haystack-ai,instagram,llm,rag,scrapingrabbit,serp,tiktok,tools,toolset,web-data,youtube-transcript
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Requires-Dist: haystack-ai>=2.14.0
|
|
25
|
+
Requires-Dist: scrapingrabbit<1.0.0,>=0.2.0
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# scrapingrabbit-haystack
|
|
29
|
+
|
|
30
|
+
[ScrapingRabbit](https://scrapingrabbit.com) for [Haystack](https://haystack.deepset.ai):
|
|
31
|
+
|
|
32
|
+
- `ScrapingRabbitToolset`: one Tool per API endpoint for Haystack Agents and chat generators. That covers YouTube, TikTok and X transcripts, YouTube comments and channels, Instagram, TikTok and Snapchat profiles, Amazon and Walmart products, Google News, Maps, Trends and autocomplete, App Store, SEO data (domain authority, traffic, age) and email verification.
|
|
33
|
+
- `ScrapingRabbitTranscriptFetcher`: a pipeline component that turns YouTube links into Documents for indexing and RAG.
|
|
34
|
+
|
|
35
|
+
Both are built on the [`scrapingrabbit`](https://pypi.org/project/scrapingrabbit/) SDK, and the tools come from its endpoint list, so they match the live API.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install scrapingrabbit-haystack
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Get an API key at [scrapingrabbit.com/login](https://scrapingrabbit.com/login) (100 free credits, no card) and set `SCRAPINGRABBIT_API_KEY`.
|
|
44
|
+
|
|
45
|
+
## Agent with tools
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from haystack.components.agents import Agent
|
|
49
|
+
from haystack.components.generators.chat import OpenAIChatGenerator
|
|
50
|
+
from haystack.dataclasses import ChatMessage
|
|
51
|
+
from haystack_integrations.tools.scrapingrabbit import ScrapingRabbitToolset
|
|
52
|
+
|
|
53
|
+
agent = Agent(
|
|
54
|
+
chat_generator=OpenAIChatGenerator(model="gpt-5-mini"),
|
|
55
|
+
tools=ScrapingRabbitToolset(include=["youtube_transcript", "youtube_comment_extractor"]),
|
|
56
|
+
)
|
|
57
|
+
result = agent.run(messages=[ChatMessage.from_user(
|
|
58
|
+
"Summarise https://www.youtube.com/watch?v=dQw4w9WgXcQ and what commenters think of it."
|
|
59
|
+
)])
|
|
60
|
+
print(result["messages"][-1].text)
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Without `include` you get all 31 tools; a short list helps the model choose and saves prompt tokens.
|
|
64
|
+
|
|
65
|
+
| Option | Default | |
|
|
66
|
+
|---|---|---|
|
|
67
|
+
| `api_key` | `Secret.from_env_var("SCRAPINGRABBIT_API_KEY")` | Read on the first tool call. Saved pipelines store the variable name, never the key. |
|
|
68
|
+
| `include` | all | Tool names, for example `["tiktok_profile_viewer"]` (the SDK's `scrapingrabbit.ENDPOINTS`). |
|
|
69
|
+
| `max_chars` | `60000` | Longer results are cut, with a note that the last record is incomplete. Minimum 1000. |
|
|
70
|
+
|
|
71
|
+
When the API refuses a call (bad link, no captions, rate limit), the tool raises `CODE: message (failed calls are not charged)`. A Haystack Agent passes that to the model as a tool error and keeps going. A client-side timeout is reported without the "not charged" note, because the API may still have finished the call.
|
|
72
|
+
|
|
73
|
+
## Transcripts as Documents
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from haystack_integrations.components.fetchers.scrapingrabbit import ScrapingRabbitTranscriptFetcher
|
|
77
|
+
|
|
78
|
+
fetcher = ScrapingRabbitTranscriptFetcher()
|
|
79
|
+
out = fetcher.run(urls=["https://www.youtube.com/watch?v=dQw4w9WgXcQ", "https://youtu.be/jNQXAC9IVRw"])
|
|
80
|
+
out["documents"] # one Document per video: transcript text, meta url, video_id, language, is_auto_generated
|
|
81
|
+
out["failed"] # videos that returned no transcript, with code and message (not charged)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Each video costs 1 credit when it returns a transcript. Pass `raise_on_failure=True` to stop at the first failure instead of skipping it. It works in any pipeline, for example in front of a `DocumentSplitter` and a document writer.
|
|
85
|
+
|
|
86
|
+
## Also available
|
|
87
|
+
|
|
88
|
+
[Python client](https://github.com/scrapingrabbit/scrapingrabbit-python) · [LangChain](https://github.com/scrapingrabbit/langchain-scrapingrabbit) · [LlamaIndex](https://github.com/scrapingrabbit/llama-index-tools-scrapingrabbit) · [CrewAI](https://github.com/scrapingrabbit/crewai-scrapingrabbit) · [Vercel AI SDK](https://github.com/scrapingrabbit/ai-sdk-scrapingrabbit) · [MCP server](https://github.com/scrapingrabbit/scrapingrabbit-mcp) · [API docs](https://scrapingrabbit.com/docs)
|
|
89
|
+
|
|
90
|
+
## Develop
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
pip install -e .
|
|
94
|
+
python -m unittest discover -s tests # runs everything against a local fake API, including a real Haystack Agent loop
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Release: bump `version` in pyproject.toml and push a matching tag (`v0.1.0`). The publish workflow uses PyPI trusted publishing.
|
|
98
|
+
|
|
99
|
+
## License
|
|
100
|
+
|
|
101
|
+
MIT
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
haystack_integrations/components/fetchers/scrapingrabbit/__init__.py,sha256=shgYAqW1NvHFFMzlefhL6xpVvtpr_Wf1oJdGwpe7SRM,100
|
|
2
|
+
haystack_integrations/components/fetchers/scrapingrabbit/fetcher.py,sha256=8KslvvpKP9CFObOAnVWKXBWRoGBGgyl_9UsCMCEqqi4,2893
|
|
3
|
+
haystack_integrations/tools/scrapingrabbit/__init__.py,sha256=5DrLLAsBN87NPEeXbji4EWbffOiF7rJAoSaop9qttFY,108
|
|
4
|
+
haystack_integrations/tools/scrapingrabbit/toolset.py,sha256=ZCDH3xviqTIOGZ25sC2gDGQVbc2totFF6vebyaDl4vw,4894
|
|
5
|
+
scrapingrabbit_haystack-0.1.0.dist-info/METADATA,sha256=BoXpUMAtlhmBvkdlpmIuVwMN_zfnEmBkxKEqe1TEtEo,5444
|
|
6
|
+
scrapingrabbit_haystack-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
scrapingrabbit_haystack-0.1.0.dist-info/licenses/LICENSE,sha256=FXPQgBSGSg1pNYlXejCIHwEih4rENs1r6PSfRQvthQk,1071
|
|
8
|
+
scrapingrabbit_haystack-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ScrapingRabbit
|
|
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.
|