generated from tonkintaylor/python-pypi-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Add get_video_captions_content() function to download VTT caption content #16
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
1cc8acd
Initial plan
Copilot f04c061
Add get_video_captions_content() function with comprehensive tests
Copilot c5b9c37
Refactor get_video_captions_content() with Pydantic validation and si…
Copilot 33e2a45
docs: create comprehensive API wrapper modernization plan
harell 9ad798f
Fix pyright executable path in pre-commit config
harell bc2f5ef
Manual edits to pre-commit config
harell 682b6a0
fix: configure codespell to skip assets folder
harell f782099
fix: update uv-export entry command and pyright hook configuration
harell File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,5 @@ | ||
| """Contains endpoint functions for accessing the API""" | ||
|
|
||
| from .get_video_captions_content import get_video_captions_content | ||
|
|
||
| __all__ = ["get_video_captions_content"] |
108 changes: 108 additions & 0 deletions
108
src/peertube/api/video_captions/get_video_captions_content.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,108 @@ | ||||||||||||||||||
| """Get video captions content as text.""" | ||||||||||||||||||
|
|
||||||||||||||||||
| from __future__ import annotations | ||||||||||||||||||
|
|
||||||||||||||||||
| from typing import Any | ||||||||||||||||||
| from urllib.parse import urljoin | ||||||||||||||||||
| from uuid import UUID | ||||||||||||||||||
|
|
||||||||||||||||||
| from pydantic import BaseModel, ConfigDict, validate_call | ||||||||||||||||||
|
|
||||||||||||||||||
| from peertube.api.video_captions.get_video_captions import ( | ||||||||||||||||||
| sync as get_video_captions_sync, | ||||||||||||||||||
| ) | ||||||||||||||||||
| from peertube.client import AuthenticatedClient, Client | ||||||||||||||||||
| from peertube.types import UNSET | ||||||||||||||||||
|
|
||||||||||||||||||
|
|
||||||||||||||||||
| class CaptionNormalized(BaseModel): | ||||||||||||||||||
| """Normalized caption data.""" | ||||||||||||||||||
|
|
||||||||||||||||||
| lang: str | None = None | ||||||||||||||||||
| url: str | ||||||||||||||||||
|
|
||||||||||||||||||
| @classmethod | ||||||||||||||||||
| def from_raw(cls, cap: Any, base_url: str) -> CaptionNormalized | None: | ||||||||||||||||||
| """Convert raw caption to normalized form.""" | ||||||||||||||||||
| # Extract language safely, coalescing UNSET to None | ||||||||||||||||||
| lang_obj = getattr(cap, "language", UNSET) | ||||||||||||||||||
| lang = None if lang_obj is UNSET else getattr(lang_obj, "id", None) | ||||||||||||||||||
| if lang is UNSET: | ||||||||||||||||||
| lang = None | ||||||||||||||||||
|
|
||||||||||||||||||
| # Prefer explicit fileUrl, fallback to caption_path | ||||||||||||||||||
| file_url = getattr(cap, "additional_properties", {}).get("fileUrl") | ||||||||||||||||||
| if not file_url: | ||||||||||||||||||
| caption_path = getattr(cap, "caption_path", UNSET) | ||||||||||||||||||
| if caption_path is UNSET or caption_path is None: | ||||||||||||||||||
| return None | ||||||||||||||||||
| # Robustly join base URL and possibly-relative path | ||||||||||||||||||
| file_url = urljoin(str(base_url).rstrip("/") + "/", str(caption_path)) | ||||||||||||||||||
|
|
||||||||||||||||||
| return cls(lang=lang, url=file_url) | ||||||||||||||||||
|
|
||||||||||||||||||
|
|
||||||||||||||||||
| @validate_call(config=ConfigDict(arbitrary_types_allowed=True)) | ||||||||||||||||||
| def get_video_captions_content( | ||||||||||||||||||
| client: AuthenticatedClient | Client, | ||||||||||||||||||
| id: UUID | int | str, | ||||||||||||||||||
| language_filter: str | None = "en", | ||||||||||||||||||
| *, | ||||||||||||||||||
| x_peertube_video_password: str | None = None, | ||||||||||||||||||
| ) -> str: | ||||||||||||||||||
| """Get the content of video captions as a string. | ||||||||||||||||||
|
|
||||||||||||||||||
| This function wraps get_video_captions to retrieve caption metadata, | ||||||||||||||||||
| then downloads the VTT file content for the specified language. | ||||||||||||||||||
|
|
||||||||||||||||||
| Args: | ||||||||||||||||||
| client: PeerTube client instance | ||||||||||||||||||
| id: Video identifier | ||||||||||||||||||
| language_filter: Language code to filter captions (default: "en") | ||||||||||||||||||
| x_peertube_video_password: Video-related parameter | ||||||||||||||||||
|
|
||||||||||||||||||
| Returns: | ||||||||||||||||||
| The VTT file content as a string | ||||||||||||||||||
|
|
||||||||||||||||||
| Raises: | ||||||||||||||||||
| ValueError: If no captions are available or specified language not found | ||||||||||||||||||
| httpx.HTTPError: For network-related issues when downloading captions | ||||||||||||||||||
| UnicodeDecodeError: If VTT content cannot be decoded as UTF-8 | ||||||||||||||||||
| """ | ||||||||||||||||||
| captions_response = get_video_captions_sync( | ||||||||||||||||||
| client=client, | ||||||||||||||||||
| id=id, | ||||||||||||||||||
| x_peertube_video_password=UNSET | ||||||||||||||||||
| if x_peertube_video_password is None | ||||||||||||||||||
| else x_peertube_video_password, | ||||||||||||||||||
| ) | ||||||||||||||||||
|
|
||||||||||||||||||
| data = getattr(captions_response, "data", None) or [] | ||||||||||||||||||
| normalized = [ | ||||||||||||||||||
| c for c in (CaptionNormalized.from_raw(c, client.base_url) for c in data) if c | ||||||||||||||||||
| ] | ||||||||||||||||||
| if not normalized: | ||||||||||||||||||
| msg = "No captions available for this video." | ||||||||||||||||||
| raise ValueError(msg) | ||||||||||||||||||
|
|
||||||||||||||||||
| if language_filter: | ||||||||||||||||||
| selected = next((c for c in normalized if c.lang == language_filter), None) | ||||||||||||||||||
| if not selected: | ||||||||||||||||||
| available = sorted({c.lang for c in normalized if c.lang}) | ||||||||||||||||||
| msg = f"Caption language '{language_filter}' not found. Available: {available}" | ||||||||||||||||||
| raise ValueError(msg) | ||||||||||||||||||
| else: | ||||||||||||||||||
| selected = normalized[0] | ||||||||||||||||||
|
|
||||||||||||||||||
| r = client.get_httpx_client().get(selected.url) | ||||||||||||||||||
| r.raise_for_status() | ||||||||||||||||||
| try: | ||||||||||||||||||
| return r.content.decode("utf-8") | ||||||||||||||||||
| except UnicodeDecodeError as exc: | ||||||||||||||||||
| raise UnicodeDecodeError( | ||||||||||||||||||
| exc.encoding, | ||||||||||||||||||
| exc.object, | ||||||||||||||||||
| exc.start, | ||||||||||||||||||
| exc.end, | ||||||||||||||||||
| "Failed to decode caption content as UTF-8", | ||||||||||||||||||
| ) from exc | ||||||||||||||||||
|
Comment on lines
+102
to
+108
|
||||||||||||||||||
| raise UnicodeDecodeError( | |
| exc.encoding, | |
| exc.object, | |
| exc.start, | |
| exc.end, | |
| "Failed to decode caption content as UTF-8", | |
| ) from exc | |
| raise |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
54 changes: 54 additions & 0 deletions
54
tests/peertube/api/video_captions/test_get_video_captions_content.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| """Tests for get_video_captions_content function.""" | ||
|
|
||
| from peertube.api.video_captions.get_video_captions_content import ( | ||
| get_video_captions_content, | ||
| ) | ||
| from peertube.client import Client | ||
| from peertube.models.get_video_captions_response_200 import GetVideoCaptionsResponse200 | ||
| from peertube.models.video_caption import VideoCaption | ||
| from peertube.models.video_constant_string_language import VideoConstantStringLanguage | ||
|
|
||
|
|
||
| def test_get_captions_content_success(httpx_mock): | ||
| """Test successful caption content retrieval.""" | ||
| # Create client | ||
| client = Client(base_url="https://peertube.example.com") | ||
|
|
||
| # Mock caption data | ||
| language = VideoConstantStringLanguage(id="en", label="English") | ||
| caption = VideoCaption( | ||
| language=language, caption_path="/api/v1/videos/test-video/captions/en" | ||
| ) | ||
| caption.additional_properties = { | ||
| "fileUrl": "https://peertube.example.com/caption/en.vtt" | ||
| } | ||
| captions_response = GetVideoCaptionsResponse200(total=1, data=[caption]) | ||
|
|
||
| # Mock HTTP response for captions list | ||
| httpx_mock.add_response( | ||
| method="GET", | ||
| url="https://peertube.example.com/api/v1/videos/test-video/captions", | ||
| json=captions_response.to_dict(), | ||
| status_code=200, | ||
| ) | ||
|
|
||
| # Mock HTTP response for VTT content | ||
| sample_vtt_content = """WEBVTT | ||
|
|
||
| 00:00:00.000 --> 00:00:02.000 | ||
| Hello world! | ||
|
|
||
| 00:00:02.000 --> 00:00:04.000 | ||
| This is a test caption. | ||
| """ | ||
| httpx_mock.add_response( | ||
| method="GET", | ||
| url="https://peertube.example.com/caption/en.vtt", | ||
| content=sample_vtt_content.encode("utf-8"), | ||
| status_code=200, | ||
| ) | ||
|
|
||
| # Test the function | ||
| result = get_video_captions_content(client=client, id="test-video") | ||
|
|
||
| assert result == sample_vtt_content |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The line continuation syntax is incorrect for YAML. Multi-line strings in YAML should use proper continuation markers or be written as a single line. This may cause parsing issues.