yt-meta 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.
- yt_meta-0.1.0/LICENSE +21 -0
- yt_meta-0.1.0/PKG-INFO +222 -0
- yt_meta-0.1.0/README.md +168 -0
- yt_meta-0.1.0/pyproject.toml +60 -0
- yt_meta-0.1.0/setup.cfg +4 -0
- yt_meta-0.1.0/tests/test_caching.py +111 -0
- yt_meta-0.1.0/tests/test_client.py +107 -0
- yt_meta-0.1.0/tests/test_date_filtering.py +93 -0
- yt_meta-0.1.0/tests/test_date_utils.py +64 -0
- yt_meta-0.1.0/tests/test_parsing.py +185 -0
- yt_meta-0.1.0/yt_meta/__init__.py +14 -0
- yt_meta-0.1.0/yt_meta/client.py +311 -0
- yt_meta-0.1.0/yt_meta/date_utils.py +49 -0
- yt_meta-0.1.0/yt_meta/exceptions.py +33 -0
- yt_meta-0.1.0/yt_meta/parsing.py +293 -0
- yt_meta-0.1.0/yt_meta/utils.py +28 -0
- yt_meta-0.1.0/yt_meta.egg-info/PKG-INFO +222 -0
- yt_meta-0.1.0/yt_meta.egg-info/SOURCES.txt +19 -0
- yt_meta-0.1.0/yt_meta.egg-info/dependency_links.txt +1 -0
- yt_meta-0.1.0/yt_meta.egg-info/requires.txt +12 -0
- yt_meta-0.1.0/yt_meta.egg-info/top_level.txt +1 -0
yt_meta-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Shane Isley
|
|
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.
|
yt_meta-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: yt-meta
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A lightweight YouTube metadata library.
|
|
5
|
+
Author-email: Shane <shane.isley@gmail.com>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2025 Shane Isley
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
Project-URL: Homepage, https://github.com/shaneisley/yt-meta
|
|
28
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
29
|
+
Classifier: Programming Language :: Python
|
|
30
|
+
Classifier: Programming Language :: Python :: 3
|
|
31
|
+
Classifier: Development Status :: 4 - Beta
|
|
32
|
+
Classifier: Intended Audience :: Developers
|
|
33
|
+
Classifier: Intended Audience :: Science/Research
|
|
34
|
+
Classifier: Natural Language :: English
|
|
35
|
+
Classifier: Operating System :: OS Independent
|
|
36
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
37
|
+
Classifier: Topic :: Multimedia :: Video
|
|
38
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
39
|
+
Requires-Python: >=3.9
|
|
40
|
+
Description-Content-Type: text/markdown
|
|
41
|
+
License-File: LICENSE
|
|
42
|
+
Requires-Dist: youtube-comment-downloader>=0.1.76
|
|
43
|
+
Requires-Dist: beautifulsoup4>=4.12.3
|
|
44
|
+
Requires-Dist: httpx>=0.27.0
|
|
45
|
+
Requires-Dist: python-dateutil>=2.9.0
|
|
46
|
+
Requires-Dist: loguru>=0.7.2
|
|
47
|
+
Provides-Extra: dev
|
|
48
|
+
Requires-Dist: pytest>=8.3.2; extra == "dev"
|
|
49
|
+
Requires-Dist: pytest-cov>=6.2.1; extra == "dev"
|
|
50
|
+
Requires-Dist: pytest-mock>=3.14.1; extra == "dev"
|
|
51
|
+
Requires-Dist: freezegun>=1.5.1; extra == "dev"
|
|
52
|
+
Requires-Dist: ruff>=0.5.5; extra == "dev"
|
|
53
|
+
Dynamic: license-file
|
|
54
|
+
|
|
55
|
+
# yt-meta
|
|
56
|
+
|
|
57
|
+
A Python library for finding video and channel metadata from YouTube.
|
|
58
|
+
|
|
59
|
+
## Purpose
|
|
60
|
+
|
|
61
|
+
This library is designed to provide a simple and efficient way to collect metadata for YouTube videos and channels, such as titles, view counts, likes, and descriptions. It is built to support data analysis, research, or any application that needs structured information from YouTube.
|
|
62
|
+
|
|
63
|
+
## Installation
|
|
64
|
+
|
|
65
|
+
You can install `yt-meta` from PyPI:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
pip install yt-meta
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
To install the latest development version directly from GitHub:
|
|
72
|
+
```bash
|
|
73
|
+
pip install git+https://github.com/sw-yx/yt-meta.git
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Inspiration
|
|
77
|
+
|
|
78
|
+
This project extends the great `youtube-comment-downloader` library, inheriting its session management while adding additional metadata capabilities.
|
|
79
|
+
|
|
80
|
+
## Core Features
|
|
81
|
+
|
|
82
|
+
The library offers several ways to fetch metadata.
|
|
83
|
+
|
|
84
|
+
### 1. Get Video Metadata
|
|
85
|
+
|
|
86
|
+
Fetches comprehensive metadata for a specific YouTube video.
|
|
87
|
+
|
|
88
|
+
**Example:**
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from yt_meta import YtMetaClient
|
|
92
|
+
|
|
93
|
+
client = YtMetaClient()
|
|
94
|
+
video_url = "https://www.youtube.com/watch?v=B68agR-OeJM"
|
|
95
|
+
metadata = client.get_video_metadata(video_url)
|
|
96
|
+
print(f"Title: {metadata['title']}")
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### 2. Get Channel Metadata
|
|
100
|
+
|
|
101
|
+
Fetches metadata for a specific YouTube channel.
|
|
102
|
+
|
|
103
|
+
**Example:**
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
from yt_meta import YtMetaClient
|
|
107
|
+
|
|
108
|
+
client = YtMetaClient()
|
|
109
|
+
channel_url = "https://www.youtube.com/@samwitteveenai"
|
|
110
|
+
channel_metadata = client.get_channel_metadata(channel_url)
|
|
111
|
+
print(f"Channel Name: {channel_metadata['title']}")
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### 3. Get All Videos from a Channel
|
|
115
|
+
|
|
116
|
+
Returns a generator that yields metadata for all videos on a channel's "Videos" tab, handling pagination automatically.
|
|
117
|
+
|
|
118
|
+
**Example:**
|
|
119
|
+
```python
|
|
120
|
+
import itertools
|
|
121
|
+
from yt_meta import YtMetaClient
|
|
122
|
+
|
|
123
|
+
client = YtMetaClient()
|
|
124
|
+
channel_url = "https://www.youtube.com/@AI-Makerspace/videos"
|
|
125
|
+
videos_generator = client.get_channel_videos(channel_url)
|
|
126
|
+
|
|
127
|
+
# Print the first 5 videos
|
|
128
|
+
for video in itertools.islice(videos_generator, 5):
|
|
129
|
+
print(f"- {video['title']} (ID: {video['videoId']})")
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### 4. Filtering Channel Videos by Date
|
|
133
|
+
|
|
134
|
+
You can efficiently filter videos by a date range using the `start_date` and `end_date` arguments. The library automatically stops fetching older videos once it passes the `start_date`, saving time and network requests.
|
|
135
|
+
|
|
136
|
+
The date arguments can be a `datetime.date` object or a string in two formats:
|
|
137
|
+
* **Shorthand:** `"1d"`, `"2w"`, `"3m"`, `"4y"` (days, weeks, months, years)
|
|
138
|
+
* **Human-readable:** `"1 day ago"`, `"2 weeks ago"`
|
|
139
|
+
|
|
140
|
+
**Example:**
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
from datetime import date, timedelta
|
|
144
|
+
from yt_meta import YtMetaClient
|
|
145
|
+
import itertools
|
|
146
|
+
|
|
147
|
+
client = YtMetaClient()
|
|
148
|
+
channel_url = "https://www.youtube.com/@samwitteveenai/videos"
|
|
149
|
+
|
|
150
|
+
# Get videos from the last 30 days
|
|
151
|
+
print("\n--- Videos from the last 30 days ---")
|
|
152
|
+
recent_videos = client.get_channel_videos(channel_url, start_date="30d")
|
|
153
|
+
for video in itertools.islice(recent_videos, 5):
|
|
154
|
+
print(f"- {video.get('title')}")
|
|
155
|
+
|
|
156
|
+
# Get videos from a specific window (90 to 60 days ago)
|
|
157
|
+
print("\n--- Videos from a specific 30-day window in the past ---")
|
|
158
|
+
start = date.today() - timedelta(days=90)
|
|
159
|
+
end = date.today() - timedelta(days=60)
|
|
160
|
+
window_videos = client.get_channel_videos(channel_url, start_date=start, end_date=end)
|
|
161
|
+
for video in itertools.islice(window_videos, 5):
|
|
162
|
+
print(f"- {video.get('title')}")
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
## Logging
|
|
166
|
+
|
|
167
|
+
`yt-meta` uses Python's `logging` module to provide insights into its operations. To see the log output, you can configure a basic logger.
|
|
168
|
+
|
|
169
|
+
**Example:**
|
|
170
|
+
```python
|
|
171
|
+
import logging
|
|
172
|
+
|
|
173
|
+
# Configure logging to print INFO-level messages
|
|
174
|
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
|
175
|
+
|
|
176
|
+
# Now, when you use the client, you will see logs
|
|
177
|
+
# ...
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
## API Reference
|
|
181
|
+
|
|
182
|
+
### `YtMetaClient()`
|
|
183
|
+
|
|
184
|
+
The main client for interacting with the library. It inherits from `youtube-comment-downloader` and handles session management and caching.
|
|
185
|
+
|
|
186
|
+
#### `get_video_metadata(youtube_url: str) -> dict`
|
|
187
|
+
Fetches comprehensive metadata for a single YouTube video.
|
|
188
|
+
- **`youtube_url`**: The full URL of the YouTube video.
|
|
189
|
+
- **Returns**: A dictionary containing metadata such as `title`, `description`, `view_count`, `like_count`, `publish_date`, `category`, and more.
|
|
190
|
+
- **Raises**: `VideoUnavailableError` if the video page cannot be fetched or the video is private/deleted.
|
|
191
|
+
|
|
192
|
+
#### `get_channel_metadata(channel_url: str, force_refresh: bool = False) -> dict`
|
|
193
|
+
Fetches metadata for a YouTube channel.
|
|
194
|
+
- **`channel_url`**: The URL of the channel's main page or "Videos" tab.
|
|
195
|
+
- **`force_refresh`**: If `True`, bypasses the internal cache and fetches fresh data.
|
|
196
|
+
- **Returns**: A dictionary with channel metadata like `title`, `description`, `subscriber_count`, `vanity_url`, etc.
|
|
197
|
+
- **Raises**: `VideoUnavailableError`, `MetadataParsingError`.
|
|
198
|
+
|
|
199
|
+
#### `get_channel_videos(channel_url: str, fetch_full_metadata: bool = False, start_date: Optional[Union[str, date]] = None, end_date: Optional[Union[str, date]] = None) -> Generator[dict, None, None]`
|
|
200
|
+
Returns a generator that yields metadata for all videos on a channel's "Videos" tab. It handles pagination automatically.
|
|
201
|
+
- **`channel_url`**: URL of the channel's "Videos" tab.
|
|
202
|
+
- **`fetch_full_metadata`**: If `True`, fetches the complete, detailed metadata for each video. This is slower as it requires an additional request per video. If `False` (default), returns basic metadata available directly from the channel page.
|
|
203
|
+
- **`start_date`**: The earliest date for videos to include. Can be a `datetime.date` object or a string (e.g., `"30d"`, `"2 months ago"`). The generator will efficiently stop once it encounters videos older than this date.
|
|
204
|
+
- **`end_date`**: The latest date for videos to include. Can be a `datetime.date` object or a string.
|
|
205
|
+
- **Yields**: Dictionaries of video metadata. The contents depend on the `fetch_full_metadata` flag.
|
|
206
|
+
|
|
207
|
+
#### `clear_cache(channel_url: str = None)`
|
|
208
|
+
Clears the internal in-memory cache.
|
|
209
|
+
- **`channel_url`**: If provided, clears the cache for only that specific channel. If `None` (default), the entire cache is cleared.
|
|
210
|
+
|
|
211
|
+
## Error Handling
|
|
212
|
+
|
|
213
|
+
The library uses custom exceptions to signal specific error conditions.
|
|
214
|
+
|
|
215
|
+
### `YtMetaError`
|
|
216
|
+
The base exception for all errors in this library.
|
|
217
|
+
|
|
218
|
+
### `MetadataParsingError`
|
|
219
|
+
Raised when the necessary metadata (e.g., the `ytInitialData` JSON object) cannot be found or parsed from the YouTube page. This can happen if YouTube changes its page structure.
|
|
220
|
+
|
|
221
|
+
### `VideoUnavailableError`
|
|
222
|
+
Raised when a video or channel page cannot be fetched. This could be due to a network error, a deleted/private video, or an invalid URL.
|
yt_meta-0.1.0/README.md
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
# yt-meta
|
|
2
|
+
|
|
3
|
+
A Python library for finding video and channel metadata from YouTube.
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
This library is designed to provide a simple and efficient way to collect metadata for YouTube videos and channels, such as titles, view counts, likes, and descriptions. It is built to support data analysis, research, or any application that needs structured information from YouTube.
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
You can install `yt-meta` from PyPI:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install yt-meta
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
To install the latest development version directly from GitHub:
|
|
18
|
+
```bash
|
|
19
|
+
pip install git+https://github.com/sw-yx/yt-meta.git
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Inspiration
|
|
23
|
+
|
|
24
|
+
This project extends the great `youtube-comment-downloader` library, inheriting its session management while adding additional metadata capabilities.
|
|
25
|
+
|
|
26
|
+
## Core Features
|
|
27
|
+
|
|
28
|
+
The library offers several ways to fetch metadata.
|
|
29
|
+
|
|
30
|
+
### 1. Get Video Metadata
|
|
31
|
+
|
|
32
|
+
Fetches comprehensive metadata for a specific YouTube video.
|
|
33
|
+
|
|
34
|
+
**Example:**
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from yt_meta import YtMetaClient
|
|
38
|
+
|
|
39
|
+
client = YtMetaClient()
|
|
40
|
+
video_url = "https://www.youtube.com/watch?v=B68agR-OeJM"
|
|
41
|
+
metadata = client.get_video_metadata(video_url)
|
|
42
|
+
print(f"Title: {metadata['title']}")
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### 2. Get Channel Metadata
|
|
46
|
+
|
|
47
|
+
Fetches metadata for a specific YouTube channel.
|
|
48
|
+
|
|
49
|
+
**Example:**
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from yt_meta import YtMetaClient
|
|
53
|
+
|
|
54
|
+
client = YtMetaClient()
|
|
55
|
+
channel_url = "https://www.youtube.com/@samwitteveenai"
|
|
56
|
+
channel_metadata = client.get_channel_metadata(channel_url)
|
|
57
|
+
print(f"Channel Name: {channel_metadata['title']}")
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### 3. Get All Videos from a Channel
|
|
61
|
+
|
|
62
|
+
Returns a generator that yields metadata for all videos on a channel's "Videos" tab, handling pagination automatically.
|
|
63
|
+
|
|
64
|
+
**Example:**
|
|
65
|
+
```python
|
|
66
|
+
import itertools
|
|
67
|
+
from yt_meta import YtMetaClient
|
|
68
|
+
|
|
69
|
+
client = YtMetaClient()
|
|
70
|
+
channel_url = "https://www.youtube.com/@AI-Makerspace/videos"
|
|
71
|
+
videos_generator = client.get_channel_videos(channel_url)
|
|
72
|
+
|
|
73
|
+
# Print the first 5 videos
|
|
74
|
+
for video in itertools.islice(videos_generator, 5):
|
|
75
|
+
print(f"- {video['title']} (ID: {video['videoId']})")
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### 4. Filtering Channel Videos by Date
|
|
79
|
+
|
|
80
|
+
You can efficiently filter videos by a date range using the `start_date` and `end_date` arguments. The library automatically stops fetching older videos once it passes the `start_date`, saving time and network requests.
|
|
81
|
+
|
|
82
|
+
The date arguments can be a `datetime.date` object or a string in two formats:
|
|
83
|
+
* **Shorthand:** `"1d"`, `"2w"`, `"3m"`, `"4y"` (days, weeks, months, years)
|
|
84
|
+
* **Human-readable:** `"1 day ago"`, `"2 weeks ago"`
|
|
85
|
+
|
|
86
|
+
**Example:**
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from datetime import date, timedelta
|
|
90
|
+
from yt_meta import YtMetaClient
|
|
91
|
+
import itertools
|
|
92
|
+
|
|
93
|
+
client = YtMetaClient()
|
|
94
|
+
channel_url = "https://www.youtube.com/@samwitteveenai/videos"
|
|
95
|
+
|
|
96
|
+
# Get videos from the last 30 days
|
|
97
|
+
print("\n--- Videos from the last 30 days ---")
|
|
98
|
+
recent_videos = client.get_channel_videos(channel_url, start_date="30d")
|
|
99
|
+
for video in itertools.islice(recent_videos, 5):
|
|
100
|
+
print(f"- {video.get('title')}")
|
|
101
|
+
|
|
102
|
+
# Get videos from a specific window (90 to 60 days ago)
|
|
103
|
+
print("\n--- Videos from a specific 30-day window in the past ---")
|
|
104
|
+
start = date.today() - timedelta(days=90)
|
|
105
|
+
end = date.today() - timedelta(days=60)
|
|
106
|
+
window_videos = client.get_channel_videos(channel_url, start_date=start, end_date=end)
|
|
107
|
+
for video in itertools.islice(window_videos, 5):
|
|
108
|
+
print(f"- {video.get('title')}")
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Logging
|
|
112
|
+
|
|
113
|
+
`yt-meta` uses Python's `logging` module to provide insights into its operations. To see the log output, you can configure a basic logger.
|
|
114
|
+
|
|
115
|
+
**Example:**
|
|
116
|
+
```python
|
|
117
|
+
import logging
|
|
118
|
+
|
|
119
|
+
# Configure logging to print INFO-level messages
|
|
120
|
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
|
121
|
+
|
|
122
|
+
# Now, when you use the client, you will see logs
|
|
123
|
+
# ...
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
## API Reference
|
|
127
|
+
|
|
128
|
+
### `YtMetaClient()`
|
|
129
|
+
|
|
130
|
+
The main client for interacting with the library. It inherits from `youtube-comment-downloader` and handles session management and caching.
|
|
131
|
+
|
|
132
|
+
#### `get_video_metadata(youtube_url: str) -> dict`
|
|
133
|
+
Fetches comprehensive metadata for a single YouTube video.
|
|
134
|
+
- **`youtube_url`**: The full URL of the YouTube video.
|
|
135
|
+
- **Returns**: A dictionary containing metadata such as `title`, `description`, `view_count`, `like_count`, `publish_date`, `category`, and more.
|
|
136
|
+
- **Raises**: `VideoUnavailableError` if the video page cannot be fetched or the video is private/deleted.
|
|
137
|
+
|
|
138
|
+
#### `get_channel_metadata(channel_url: str, force_refresh: bool = False) -> dict`
|
|
139
|
+
Fetches metadata for a YouTube channel.
|
|
140
|
+
- **`channel_url`**: The URL of the channel's main page or "Videos" tab.
|
|
141
|
+
- **`force_refresh`**: If `True`, bypasses the internal cache and fetches fresh data.
|
|
142
|
+
- **Returns**: A dictionary with channel metadata like `title`, `description`, `subscriber_count`, `vanity_url`, etc.
|
|
143
|
+
- **Raises**: `VideoUnavailableError`, `MetadataParsingError`.
|
|
144
|
+
|
|
145
|
+
#### `get_channel_videos(channel_url: str, fetch_full_metadata: bool = False, start_date: Optional[Union[str, date]] = None, end_date: Optional[Union[str, date]] = None) -> Generator[dict, None, None]`
|
|
146
|
+
Returns a generator that yields metadata for all videos on a channel's "Videos" tab. It handles pagination automatically.
|
|
147
|
+
- **`channel_url`**: URL of the channel's "Videos" tab.
|
|
148
|
+
- **`fetch_full_metadata`**: If `True`, fetches the complete, detailed metadata for each video. This is slower as it requires an additional request per video. If `False` (default), returns basic metadata available directly from the channel page.
|
|
149
|
+
- **`start_date`**: The earliest date for videos to include. Can be a `datetime.date` object or a string (e.g., `"30d"`, `"2 months ago"`). The generator will efficiently stop once it encounters videos older than this date.
|
|
150
|
+
- **`end_date`**: The latest date for videos to include. Can be a `datetime.date` object or a string.
|
|
151
|
+
- **Yields**: Dictionaries of video metadata. The contents depend on the `fetch_full_metadata` flag.
|
|
152
|
+
|
|
153
|
+
#### `clear_cache(channel_url: str = None)`
|
|
154
|
+
Clears the internal in-memory cache.
|
|
155
|
+
- **`channel_url`**: If provided, clears the cache for only that specific channel. If `None` (default), the entire cache is cleared.
|
|
156
|
+
|
|
157
|
+
## Error Handling
|
|
158
|
+
|
|
159
|
+
The library uses custom exceptions to signal specific error conditions.
|
|
160
|
+
|
|
161
|
+
### `YtMetaError`
|
|
162
|
+
The base exception for all errors in this library.
|
|
163
|
+
|
|
164
|
+
### `MetadataParsingError`
|
|
165
|
+
Raised when the necessary metadata (e.g., the `ytInitialData` JSON object) cannot be found or parsed from the YouTube page. This can happen if YouTube changes its page structure.
|
|
166
|
+
|
|
167
|
+
### `VideoUnavailableError`
|
|
168
|
+
Raised when a video or channel page cannot be fetched. This could be due to a network error, a deleted/private video, or an invalid URL.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "yt-meta"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "A lightweight YouTube metadata library."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [{ name = "Shane", email = "shane.isley@gmail.com" }]
|
|
7
|
+
license = { file = "LICENSE" }
|
|
8
|
+
classifiers = [
|
|
9
|
+
"License :: OSI Approved :: MIT License",
|
|
10
|
+
"Programming Language :: Python",
|
|
11
|
+
"Programming Language :: Python :: 3",
|
|
12
|
+
"Development Status :: 4 - Beta",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"Intended Audience :: Science/Research",
|
|
15
|
+
"Natural Language :: English",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
18
|
+
"Topic :: Multimedia :: Video",
|
|
19
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
20
|
+
]
|
|
21
|
+
dependencies = [
|
|
22
|
+
"youtube-comment-downloader>=0.1.76",
|
|
23
|
+
"beautifulsoup4>=4.12.3",
|
|
24
|
+
"httpx>=0.27.0",
|
|
25
|
+
"python-dateutil>=2.9.0",
|
|
26
|
+
"loguru>=0.7.2",
|
|
27
|
+
]
|
|
28
|
+
requires-python = ">=3.9"
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Homepage = "https://github.com/shaneisley/yt-meta"
|
|
32
|
+
|
|
33
|
+
[project.optional-dependencies]
|
|
34
|
+
dev = [
|
|
35
|
+
"pytest>=8.3.2",
|
|
36
|
+
"pytest-cov>=6.2.1",
|
|
37
|
+
"pytest-mock>=3.14.1",
|
|
38
|
+
"freezegun>=1.5.1",
|
|
39
|
+
"ruff>=0.5.5",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
[build-system]
|
|
43
|
+
requires = ["setuptools>=61.0"]
|
|
44
|
+
build-backend = "setuptools.build_meta"
|
|
45
|
+
|
|
46
|
+
[tool.pytest.ini_options]
|
|
47
|
+
markers = [
|
|
48
|
+
"integration: marks tests as integration tests (slow, requires network)",
|
|
49
|
+
]
|
|
50
|
+
addopts = "--durations=10"
|
|
51
|
+
|
|
52
|
+
[tool.ruff]
|
|
53
|
+
line-length = 120
|
|
54
|
+
|
|
55
|
+
[tool.ruff.lint]
|
|
56
|
+
# Enable Pyflakes, pycodestyle, and isort rules.
|
|
57
|
+
select = ["E", "F", "I"]
|
|
58
|
+
|
|
59
|
+
[tool.ruff.format]
|
|
60
|
+
quote-style = "double"
|
yt_meta-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import time
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from yt_meta import YtMetaClient
|
|
6
|
+
|
|
7
|
+
# A list of diverse YouTube channels for live testing
|
|
8
|
+
LIVE_CHANNEL_URLS = [
|
|
9
|
+
"https://www.youtube.com/@samwitteveenai/videos",
|
|
10
|
+
"https://www.youtube.com/@bulwarkmedia/videos",
|
|
11
|
+
"https://www.youtube.com/@AI-Makerspace/videos",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@pytest.fixture
|
|
16
|
+
def client():
|
|
17
|
+
"""Provides a fresh instance of the client for each test, ensuring no state is shared."""
|
|
18
|
+
return YtMetaClient()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@pytest.mark.integration
|
|
22
|
+
@pytest.mark.parametrize("channel_url", LIVE_CHANNEL_URLS)
|
|
23
|
+
def test_live_caching_is_faster(client, channel_url):
|
|
24
|
+
"""
|
|
25
|
+
Tests that a cached call is significantly faster than the initial network call
|
|
26
|
+
by fetching from a live channel.
|
|
27
|
+
"""
|
|
28
|
+
# First call - makes a network request
|
|
29
|
+
start_time_first = time.time()
|
|
30
|
+
client.get_channel_metadata(channel_url)
|
|
31
|
+
duration_first = time.time() - start_time_first
|
|
32
|
+
|
|
33
|
+
# Second call - should hit the cache
|
|
34
|
+
start_time_second = time.time()
|
|
35
|
+
client.get_channel_metadata(channel_url)
|
|
36
|
+
duration_second = time.time() - start_time_second
|
|
37
|
+
|
|
38
|
+
print(
|
|
39
|
+
f"\n[{channel_url}] First call: {duration_first:.4f}s, Cached call: {duration_second:.4f}s"
|
|
40
|
+
)
|
|
41
|
+
# The cached call should be at least 100x faster (realistically more)
|
|
42
|
+
assert duration_second < duration_first / 100
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@pytest.mark.integration
|
|
46
|
+
@pytest.mark.parametrize("channel_url", LIVE_CHANNEL_URLS)
|
|
47
|
+
def test_live_force_refresh_bypasses_cache(client, channel_url):
|
|
48
|
+
"""
|
|
49
|
+
Tests that `force_refresh=True` correctly re-fetches data by making two
|
|
50
|
+
network calls of similar duration.
|
|
51
|
+
"""
|
|
52
|
+
# Initial call to populate the cache
|
|
53
|
+
start_time_initial = time.time()
|
|
54
|
+
client.get_channel_metadata(channel_url)
|
|
55
|
+
duration_initial = time.time() - start_time_initial
|
|
56
|
+
|
|
57
|
+
# Second call with force_refresh should also make a network request
|
|
58
|
+
start_time_refresh = time.time()
|
|
59
|
+
client.get_channel_metadata(channel_url, force_refresh=True)
|
|
60
|
+
duration_refresh = time.time() - start_time_refresh
|
|
61
|
+
|
|
62
|
+
print(
|
|
63
|
+
f"\n[{channel_url}] Initial call: {duration_initial:.4f}s, Refresh call: {duration_refresh:.4f}s"
|
|
64
|
+
)
|
|
65
|
+
# Both calls should take a similar amount of time; we'll check if the refresh
|
|
66
|
+
# call took at least 20% of the time of the initial call.
|
|
67
|
+
assert duration_refresh > duration_initial * 0.2
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_clear_cache_all(client, mocker):
|
|
71
|
+
"""Tests that clear_cache() without arguments clears the entire cache."""
|
|
72
|
+
# Mock the internal cache to control its state
|
|
73
|
+
client._channel_page_cache = {"url1": "data1", "url2": "data2"}
|
|
74
|
+
|
|
75
|
+
# Act
|
|
76
|
+
client.clear_cache()
|
|
77
|
+
|
|
78
|
+
# Assert
|
|
79
|
+
assert not client._channel_page_cache # Cache should be empty
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_clear_cache_specific_url(client, mocker):
|
|
83
|
+
"""Tests that clear_cache() with a URL clears only that entry."""
|
|
84
|
+
# Arrange
|
|
85
|
+
client._channel_page_cache = {
|
|
86
|
+
"https://www.youtube.com/@channel1/videos": "data1",
|
|
87
|
+
"https://www.youtube.com/@channel2/videos": "data2",
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
# Act
|
|
91
|
+
client.clear_cache("https://www.youtube.com/@channel1/videos")
|
|
92
|
+
|
|
93
|
+
# Assert
|
|
94
|
+
assert "https://www.youtube.com/@channel1/videos" not in client._channel_page_cache
|
|
95
|
+
assert "https://www.youtube.com/@channel2/videos" in client._channel_page_cache
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def test_clear_cache_handles_trailing_slash(client, mocker):
|
|
99
|
+
"""
|
|
100
|
+
Tests that clear_cache() correctly handles URLs with or without a trailing slash.
|
|
101
|
+
"""
|
|
102
|
+
# Arrange
|
|
103
|
+
url_with_slash = "https://www.youtube.com/@channel1/videos/"
|
|
104
|
+
url_without_slash = "https://www.youtube.com/@channel1/videos"
|
|
105
|
+
client._channel_page_cache = {url_without_slash: "data1"}
|
|
106
|
+
|
|
107
|
+
# Act
|
|
108
|
+
client.clear_cache(url_with_slash)
|
|
109
|
+
|
|
110
|
+
# Assert
|
|
111
|
+
assert not client._channel_page_cache
|