feat!: migrate to OpenAI native tool calls and fix circular deps (#fuck-gemini)
- Fix circular dependencies in agent/tools - Migrate from custom JSON to OpenAI tool calls format - Add async streaming (step_stream, complete_stream) - Simplify prompt system and remove token counting - Add 5 new API endpoints (/health, /v1/models, /api/memory/*) - Add 3 new tools (get_torrent_by_index, add_torrent_by_index, set_language) - Fix all 500 tests and add coverage config (80% threshold) - Add comprehensive docs (README, pytest guide) BREAKING: LLM interface changed, memory injection via get_memory()
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
"""Subtitles domain - Business logic for subtitle management (shared across movies and TV shows)."""
|
||||
|
||||
from .entities import Subtitle
|
||||
from .value_objects import Language, SubtitleFormat
|
||||
from .exceptions import SubtitleNotFound
|
||||
from .services import SubtitleService
|
||||
from .value_objects import Language, SubtitleFormat
|
||||
|
||||
__all__ = [
|
||||
"Subtitle",
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""Subtitle domain entities."""
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from ..shared.value_objects import ImdbId, FilePath
|
||||
from dataclasses import dataclass
|
||||
|
||||
from ..shared.value_objects import FilePath, ImdbId
|
||||
from .value_objects import Language, SubtitleFormat, TimingOffset
|
||||
|
||||
|
||||
@@ -10,62 +10,65 @@ from .value_objects import Language, SubtitleFormat, TimingOffset
|
||||
class Subtitle:
|
||||
"""
|
||||
Subtitle entity representing a subtitle file.
|
||||
|
||||
|
||||
Can be associated with either a movie or a TV show episode.
|
||||
"""
|
||||
|
||||
media_imdb_id: ImdbId
|
||||
language: Language
|
||||
format: SubtitleFormat
|
||||
file_path: FilePath
|
||||
|
||||
|
||||
# Optional: for TV shows
|
||||
season_number: Optional[int] = None
|
||||
episode_number: Optional[int] = None
|
||||
|
||||
season_number: int | None = None
|
||||
episode_number: int | None = None
|
||||
|
||||
# Subtitle metadata
|
||||
timing_offset: TimingOffset = TimingOffset(0)
|
||||
hearing_impaired: bool = False
|
||||
forced: bool = False # Forced subtitles (for foreign language parts)
|
||||
|
||||
|
||||
# Source information
|
||||
source: Optional[str] = None # e.g., "OpenSubtitles", "Subscene"
|
||||
uploader: Optional[str] = None
|
||||
download_count: Optional[int] = None
|
||||
rating: Optional[float] = None
|
||||
|
||||
source: str | None = None # e.g., "OpenSubtitles", "Subscene"
|
||||
uploader: str | None = None
|
||||
download_count: int | None = None
|
||||
rating: float | None = None
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate subtitle entity."""
|
||||
# Ensure ImdbId is actually an ImdbId instance
|
||||
if not isinstance(self.media_imdb_id, ImdbId):
|
||||
if isinstance(self.media_imdb_id, str):
|
||||
object.__setattr__(self, 'media_imdb_id', ImdbId(self.media_imdb_id))
|
||||
|
||||
object.__setattr__(self, "media_imdb_id", ImdbId(self.media_imdb_id))
|
||||
|
||||
# Ensure Language is actually a Language instance
|
||||
if not isinstance(self.language, Language):
|
||||
if isinstance(self.language, str):
|
||||
object.__setattr__(self, 'language', Language.from_code(self.language))
|
||||
|
||||
object.__setattr__(self, "language", Language.from_code(self.language))
|
||||
|
||||
# Ensure SubtitleFormat is actually a SubtitleFormat instance
|
||||
if not isinstance(self.format, SubtitleFormat):
|
||||
if isinstance(self.format, str):
|
||||
object.__setattr__(self, 'format', SubtitleFormat.from_extension(self.format))
|
||||
|
||||
object.__setattr__(
|
||||
self, "format", SubtitleFormat.from_extension(self.format)
|
||||
)
|
||||
|
||||
# Ensure FilePath is actually a FilePath instance
|
||||
if not isinstance(self.file_path, FilePath):
|
||||
object.__setattr__(self, 'file_path', FilePath(self.file_path))
|
||||
|
||||
object.__setattr__(self, "file_path", FilePath(self.file_path))
|
||||
|
||||
def is_for_movie(self) -> bool:
|
||||
"""Check if this subtitle is for a movie."""
|
||||
return self.season_number is None and self.episode_number is None
|
||||
|
||||
|
||||
def is_for_episode(self) -> bool:
|
||||
"""Check if this subtitle is for a TV show episode."""
|
||||
return self.season_number is not None and self.episode_number is not None
|
||||
|
||||
|
||||
def get_filename(self) -> str:
|
||||
"""
|
||||
Get the suggested filename for this subtitle.
|
||||
|
||||
|
||||
Format for movies: "Movie.Title.{lang}.{format}"
|
||||
Format for episodes: "S01E05.{lang}.{format}"
|
||||
"""
|
||||
@@ -74,20 +77,20 @@ class Subtitle:
|
||||
else:
|
||||
# For movies, use the file path stem
|
||||
base = self.file_path.value.stem
|
||||
|
||||
|
||||
parts = [base, self.language.value]
|
||||
|
||||
|
||||
if self.hearing_impaired:
|
||||
parts.append("hi")
|
||||
if self.forced:
|
||||
parts.append("forced")
|
||||
|
||||
|
||||
return f"{'.'.join(parts)}.{self.format.value}"
|
||||
|
||||
|
||||
def __str__(self) -> str:
|
||||
if self.is_for_episode():
|
||||
return f"Subtitle S{self.season_number:02d}E{self.episode_number:02d} ({self.language.value})"
|
||||
return f"Subtitle ({self.language.value})"
|
||||
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Subtitle(media={self.media_imdb_id}, lang={self.language.value})"
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
"""Subtitle domain exceptions."""
|
||||
|
||||
from ..shared.exceptions import DomainException, NotFoundError
|
||||
|
||||
|
||||
class SubtitleNotFound(NotFoundError):
|
||||
"""Raised when a subtitle is not found."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class InvalidSubtitleFormat(DomainException):
|
||||
"""Raised when subtitle format is invalid."""
|
||||
|
||||
pass
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Subtitle repository interfaces (abstract)."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import List, Optional
|
||||
|
||||
from ..shared.value_objects import ImdbId
|
||||
from .entities import Subtitle
|
||||
@@ -10,50 +10,50 @@ from .value_objects import Language
|
||||
class SubtitleRepository(ABC):
|
||||
"""
|
||||
Abstract repository for subtitle persistence.
|
||||
|
||||
|
||||
This defines the interface that infrastructure implementations must follow.
|
||||
"""
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def save(self, subtitle: Subtitle) -> None:
|
||||
"""
|
||||
Save a subtitle to the repository.
|
||||
|
||||
|
||||
Args:
|
||||
subtitle: Subtitle entity to save
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def find_by_media(
|
||||
self,
|
||||
media_imdb_id: ImdbId,
|
||||
language: Optional[Language] = None,
|
||||
season: Optional[int] = None,
|
||||
episode: Optional[int] = None
|
||||
) -> List[Subtitle]:
|
||||
language: Language | None = None,
|
||||
season: int | None = None,
|
||||
episode: int | None = None,
|
||||
) -> list[Subtitle]:
|
||||
"""
|
||||
Find subtitles for a media item.
|
||||
|
||||
|
||||
Args:
|
||||
media_imdb_id: IMDb ID of the media
|
||||
language: Optional language filter
|
||||
season: Optional season number (for TV shows)
|
||||
episode: Optional episode number (for TV shows)
|
||||
|
||||
|
||||
Returns:
|
||||
List of matching subtitles
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def delete(self, subtitle: Subtitle) -> bool:
|
||||
"""
|
||||
Delete a subtitle from the repository.
|
||||
|
||||
|
||||
Args:
|
||||
subtitle: Subtitle to delete
|
||||
|
||||
|
||||
Returns:
|
||||
True if deleted, False if not found
|
||||
"""
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
"""Subtitle domain services - Business logic."""
|
||||
import logging
|
||||
from typing import List, Optional
|
||||
|
||||
from ..shared.value_objects import ImdbId, FilePath
|
||||
import logging
|
||||
|
||||
from ..shared.value_objects import FilePath, ImdbId
|
||||
from .entities import Subtitle
|
||||
from .value_objects import Language, SubtitleFormat
|
||||
from .repositories import SubtitleRepository
|
||||
from .exceptions import SubtitleNotFound
|
||||
from .repositories import SubtitleRepository
|
||||
from .value_objects import Language, SubtitleFormat
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -14,42 +14,42 @@ logger = logging.getLogger(__name__)
|
||||
class SubtitleService:
|
||||
"""
|
||||
Domain service for subtitle-related business logic.
|
||||
|
||||
|
||||
This service is SHARED between movies and TV shows domains.
|
||||
Both can use this service to manage subtitles.
|
||||
"""
|
||||
|
||||
|
||||
def __init__(self, repository: SubtitleRepository):
|
||||
"""
|
||||
Initialize subtitle service.
|
||||
|
||||
|
||||
Args:
|
||||
repository: Subtitle repository for persistence
|
||||
"""
|
||||
self.repository = repository
|
||||
|
||||
|
||||
def add_subtitle(self, subtitle: Subtitle) -> None:
|
||||
"""
|
||||
Add a subtitle to the library.
|
||||
|
||||
|
||||
Args:
|
||||
subtitle: Subtitle entity to add
|
||||
"""
|
||||
self.repository.save(subtitle)
|
||||
logger.info(f"Added subtitle: {subtitle.language.value} for {subtitle.media_imdb_id}")
|
||||
|
||||
logger.info(
|
||||
f"Added subtitle: {subtitle.language.value} for {subtitle.media_imdb_id}"
|
||||
)
|
||||
|
||||
def find_subtitles_for_movie(
|
||||
self,
|
||||
imdb_id: ImdbId,
|
||||
languages: Optional[List[Language]] = None
|
||||
) -> List[Subtitle]:
|
||||
self, imdb_id: ImdbId, languages: list[Language] | None = None
|
||||
) -> list[Subtitle]:
|
||||
"""
|
||||
Find subtitles for a movie.
|
||||
|
||||
|
||||
Args:
|
||||
imdb_id: IMDb ID of the movie
|
||||
languages: Optional list of languages to filter by
|
||||
|
||||
|
||||
Returns:
|
||||
List of matching subtitles
|
||||
"""
|
||||
@@ -61,23 +61,23 @@ class SubtitleService:
|
||||
return all_subtitles
|
||||
else:
|
||||
return self.repository.find_by_media(imdb_id)
|
||||
|
||||
|
||||
def find_subtitles_for_episode(
|
||||
self,
|
||||
imdb_id: ImdbId,
|
||||
season: int,
|
||||
episode: int,
|
||||
languages: Optional[List[Language]] = None
|
||||
) -> List[Subtitle]:
|
||||
languages: list[Language] | None = None,
|
||||
) -> list[Subtitle]:
|
||||
"""
|
||||
Find subtitles for a TV show episode.
|
||||
|
||||
|
||||
Args:
|
||||
imdb_id: IMDb ID of the TV show
|
||||
season: Season number
|
||||
episode: Episode number
|
||||
languages: Optional list of languages to filter by
|
||||
|
||||
|
||||
Returns:
|
||||
List of matching subtitles
|
||||
"""
|
||||
@@ -85,66 +85,61 @@ class SubtitleService:
|
||||
all_subtitles = []
|
||||
for lang in languages:
|
||||
subs = self.repository.find_by_media(
|
||||
imdb_id,
|
||||
language=lang,
|
||||
season=season,
|
||||
episode=episode
|
||||
imdb_id, language=lang, season=season, episode=episode
|
||||
)
|
||||
all_subtitles.extend(subs)
|
||||
return all_subtitles
|
||||
else:
|
||||
return self.repository.find_by_media(
|
||||
imdb_id,
|
||||
season=season,
|
||||
episode=episode
|
||||
imdb_id, season=season, episode=episode
|
||||
)
|
||||
|
||||
|
||||
def remove_subtitle(self, subtitle: Subtitle) -> None:
|
||||
"""
|
||||
Remove a subtitle from the library.
|
||||
|
||||
|
||||
Args:
|
||||
subtitle: Subtitle to remove
|
||||
|
||||
|
||||
Raises:
|
||||
SubtitleNotFound: If subtitle not found
|
||||
"""
|
||||
if not self.repository.delete(subtitle):
|
||||
raise SubtitleNotFound(f"Subtitle not found: {subtitle}")
|
||||
|
||||
|
||||
logger.info(f"Removed subtitle: {subtitle}")
|
||||
|
||||
|
||||
def detect_format_from_file(self, file_path: FilePath) -> SubtitleFormat:
|
||||
"""
|
||||
Detect subtitle format from file extension.
|
||||
|
||||
|
||||
Args:
|
||||
file_path: Path to subtitle file
|
||||
|
||||
|
||||
Returns:
|
||||
Detected subtitle format
|
||||
"""
|
||||
extension = file_path.value.suffix
|
||||
return SubtitleFormat.from_extension(extension)
|
||||
|
||||
|
||||
def validate_subtitle_file(self, file_path: FilePath) -> bool:
|
||||
"""
|
||||
Validate that a file is a valid subtitle file.
|
||||
|
||||
|
||||
Args:
|
||||
file_path: Path to the file
|
||||
|
||||
|
||||
Returns:
|
||||
True if valid subtitle file, False otherwise
|
||||
"""
|
||||
if not file_path.exists():
|
||||
logger.warning(f"File does not exist: {file_path}")
|
||||
return False
|
||||
|
||||
|
||||
if not file_path.is_file():
|
||||
logger.warning(f"Path is not a file: {file_path}")
|
||||
return False
|
||||
|
||||
|
||||
# Check file extension
|
||||
try:
|
||||
self.detect_format_from_file(file_path)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Subtitle domain value objects."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
|
||||
@@ -7,29 +8,21 @@ from ..shared.exceptions import ValidationError
|
||||
|
||||
class Language(Enum):
|
||||
"""Supported subtitle languages."""
|
||||
|
||||
ENGLISH = "en"
|
||||
FRENCH = "fr"
|
||||
SPANISH = "es"
|
||||
GERMAN = "de"
|
||||
ITALIAN = "it"
|
||||
PORTUGUESE = "pt"
|
||||
RUSSIAN = "ru"
|
||||
JAPANESE = "ja"
|
||||
KOREAN = "ko"
|
||||
CHINESE = "zh"
|
||||
ARABIC = "ar"
|
||||
|
||||
|
||||
@classmethod
|
||||
def from_code(cls, code: str) -> "Language":
|
||||
"""
|
||||
Get language from ISO 639-1 code.
|
||||
|
||||
|
||||
Args:
|
||||
code: Two-letter language code
|
||||
|
||||
|
||||
Returns:
|
||||
Language enum value
|
||||
|
||||
|
||||
Raises:
|
||||
ValidationError: If code is not supported
|
||||
"""
|
||||
@@ -42,27 +35,28 @@ class Language(Enum):
|
||||
|
||||
class SubtitleFormat(Enum):
|
||||
"""Supported subtitle formats."""
|
||||
|
||||
SRT = "srt" # SubRip
|
||||
ASS = "ass" # Advanced SubStation Alpha
|
||||
SSA = "ssa" # SubStation Alpha
|
||||
VTT = "vtt" # WebVTT
|
||||
SUB = "sub" # MicroDVD
|
||||
|
||||
|
||||
@classmethod
|
||||
def from_extension(cls, extension: str) -> "SubtitleFormat":
|
||||
"""
|
||||
Get format from file extension.
|
||||
|
||||
|
||||
Args:
|
||||
extension: File extension (with or without dot)
|
||||
|
||||
|
||||
Returns:
|
||||
SubtitleFormat enum value
|
||||
|
||||
|
||||
Raises:
|
||||
ValidationError: If extension is not supported
|
||||
"""
|
||||
ext = extension.lower().lstrip('.')
|
||||
ext = extension.lower().lstrip(".")
|
||||
for fmt in cls:
|
||||
if fmt.value == ext:
|
||||
return fmt
|
||||
@@ -73,22 +67,25 @@ class SubtitleFormat(Enum):
|
||||
class TimingOffset:
|
||||
"""
|
||||
Value object representing subtitle timing offset in milliseconds.
|
||||
|
||||
|
||||
Used for synchronizing subtitles with video.
|
||||
"""
|
||||
|
||||
milliseconds: int
|
||||
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate timing offset."""
|
||||
if not isinstance(self.milliseconds, int):
|
||||
raise ValidationError(f"Timing offset must be an integer, got {type(self.milliseconds)}")
|
||||
|
||||
raise ValidationError(
|
||||
f"Timing offset must be an integer, got {type(self.milliseconds)}"
|
||||
)
|
||||
|
||||
def to_seconds(self) -> float:
|
||||
"""Convert to seconds."""
|
||||
return self.milliseconds / 1000.0
|
||||
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.milliseconds}ms"
|
||||
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"TimingOffset({self.milliseconds})"
|
||||
|
||||
Reference in New Issue
Block a user