├── tests ├── __init__.py ├── util.py ├── test_store.py ├── test_rss.py ├── test_loop.py ├── test_config.py ├── test_tg.py ├── test_template.py ├── test_mediainfo.py ├── test_pool.py ├── test_bt.py └── test_encode.py ├── animepipeline ├── cli │ ├── __init__.py │ ├── btf │ │ ├── __init__.py │ │ └── __main__.py │ ├── rename │ │ ├── __init__.py │ │ └── __main__.py │ └── README.md ├── bt │ ├── __init__.py │ └── qb.py ├── post │ ├── __init__.py │ └── tg.py ├── encode │ ├── __init__.py │ ├── type.py │ └── finalrip.py ├── store │ ├── __init__.py │ └── task.py ├── util │ ├── __init__.py │ ├── video.py │ └── bt.py ├── pool │ ├── __init__.py │ └── task.py ├── rss │ ├── __init__.py │ ├── type.py │ └── nyaa.py ├── __init__.py ├── config │ ├── __init__.py │ ├── server.py │ └── rss.py ├── mediainfo │ ├── __init__.py │ ├── type.py │ ├── name.py │ └── mediainfo.py ├── template │ ├── __init__.py │ ├── bangumi.py │ ├── mediainfo.py │ └── template.py ├── __main__.py └── loop.py ├── conf ├── params │ └── default.txt ├── scripts │ └── default.py ├── server.yml └── rss.yml ├── assets └── test_144p.mp4 ├── Dockerfile ├── Makefile ├── deploy ├── docker-compose-dev.yml └── docker-compose-animepipeline.yml ├── .dockerignore ├── .github └── workflows │ ├── CI-docker.yml │ ├── CI-test.yml │ ├── CI-test-cli.yml │ └── Release.yml ├── .pre-commit-config.yaml ├── pyproject.toml ├── README.md ├── .gitignore └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /animepipeline/cli/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /animepipeline/cli/btf/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /animepipeline/cli/rename/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /conf/params/default.txt: -------------------------------------------------------------------------------- 1 | ffmpeg -i - -vcodec libx264 -preset ultrafast 2 | -------------------------------------------------------------------------------- /animepipeline/bt/__init__.py: -------------------------------------------------------------------------------- 1 | from animepipeline.bt.qb import QBittorrentManager # noqa 2 | -------------------------------------------------------------------------------- /animepipeline/post/__init__.py: -------------------------------------------------------------------------------- 1 | from animepipeline.post.tg import TGChannelSender # noqa 2 | -------------------------------------------------------------------------------- /animepipeline/encode/__init__.py: -------------------------------------------------------------------------------- 1 | from animepipeline.encode.finalrip import FinalRipClient # noqa 2 | -------------------------------------------------------------------------------- /assets/test_144p.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EutropicAI/AnimePipeline/HEAD/assets/test_144p.mp4 -------------------------------------------------------------------------------- /animepipeline/store/__init__.py: -------------------------------------------------------------------------------- 1 | from animepipeline.store.task import AsyncJsonStore, TaskStatus # noqa 2 | -------------------------------------------------------------------------------- /animepipeline/util/__init__.py: -------------------------------------------------------------------------------- 1 | from animepipeline.util.bt import gen_magnet_link, ANNOUNCE_URLS # noqa 2 | -------------------------------------------------------------------------------- /animepipeline/pool/__init__.py: -------------------------------------------------------------------------------- 1 | from animepipeline.pool.task import AsyncTaskExecutor 2 | 3 | TASK_EXECUTOR = AsyncTaskExecutor() 4 | -------------------------------------------------------------------------------- /animepipeline/rss/__init__.py: -------------------------------------------------------------------------------- 1 | from animepipeline.rss.nyaa import parse_nyaa # noqa 2 | from animepipeline.rss.type import TorrentInfo # noqa 3 | -------------------------------------------------------------------------------- /animepipeline/__init__.py: -------------------------------------------------------------------------------- 1 | from animepipeline.loop import Loop # noqa 2 | from animepipeline.config import ServerConfig, RSSConfig # noqa 3 | from animepipeline.store import AsyncJsonStore # noqa 4 | -------------------------------------------------------------------------------- /animepipeline/config/__init__.py: -------------------------------------------------------------------------------- 1 | from animepipeline.config.server import ServerConfig, QBitTorrentConfig, FinalRipConfig, TelegramConfig # noqa 2 | from animepipeline.config.rss import RSSConfig, BaseConfig, NyaaConfig # noqa 3 | -------------------------------------------------------------------------------- /animepipeline/mediainfo/__init__.py: -------------------------------------------------------------------------------- 1 | from animepipeline.mediainfo.mediainfo import get_media_info # noqa 2 | from animepipeline.mediainfo.name import gen_file_name, rename_file # noqa 3 | from animepipeline.mediainfo.type import FileNameInfo, MediaInfo # noqa 4 | -------------------------------------------------------------------------------- /animepipeline/template/__init__.py: -------------------------------------------------------------------------------- 1 | from animepipeline.template.mediainfo import get_media_info_block # noqa 2 | from animepipeline.template.bangumi import get_bangumi_info # noqa 3 | from animepipeline.template.template import get_telegram_text, PostTemplate # noqa 4 | -------------------------------------------------------------------------------- /conf/scripts/default.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from vapoursynth import core 4 | 5 | if os.getenv("FINALRIP_SOURCE"): 6 | clip = core.bs.VideoSource(source=os.getenv("FINALRIP_SOURCE")) 7 | else: 8 | clip = core.bs.VideoSource(source="s.mkv") 9 | 10 | clip.set_output() 11 | -------------------------------------------------------------------------------- /tests/util.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | 3 | CONFIG_PATH = Path(__file__).resolve().parent.parent.absolute() / "conf" 4 | ASSETS_PATH = Path(__file__).resolve().parent.parent.absolute() / "assets" 5 | TEST_VIDEO_PATH = ASSETS_PATH / "test_144p.mp4" 6 | 7 | print(TEST_VIDEO_PATH) 8 | -------------------------------------------------------------------------------- /animepipeline/cli/README.md: -------------------------------------------------------------------------------- 1 | # CLI 2 | 3 | Some useful cli are provided in this package! 4 | 5 | ### ap-rename 6 | 7 | Rename anime video files. 8 | 9 | ### ap-btf 10 | 11 | Generate all post info files for the anime. 12 | 13 | - why it's named `btf`? cuz once we use `ptf` to generate for PT ~ 14 | -------------------------------------------------------------------------------- /conf/server.yml: -------------------------------------------------------------------------------- 1 | loop: 2 | interval: 200 3 | 4 | qbittorrent: 5 | host: localhost 6 | port: 8091 7 | username: admin 8 | password: adminadmin 9 | download_path: . 10 | 11 | finalrip: 12 | url: http://localhost:8848 13 | token: 114514 14 | 15 | telegram: 16 | enable: true 17 | bot_token: sCz0 18 | channel_id: -591 19 | -------------------------------------------------------------------------------- /animepipeline/rss/type.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | from typing import Union 3 | 4 | from pydantic import AnyUrl, BaseModel 5 | 6 | 7 | class TorrentInfo(BaseModel): 8 | name: str 9 | translation: str 10 | bangumi: Union[str, AnyUrl] 11 | episode: int 12 | title: str 13 | link: Union[str, AnyUrl] 14 | hash: str 15 | pub_date: datetime 16 | size: str 17 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.11.10 2 | 3 | RUN apt update && apt install -y \ 4 | curl \ 5 | make \ 6 | iputils-ping \ 7 | libmediainfo-dev \ 8 | libgl1-mesa-glx 9 | 10 | WORKDIR /app 11 | 12 | COPY . . 13 | 14 | ENV POETRY_HOME="/opt/poetry" 15 | ENV PATH="$POETRY_HOME/bin:$PATH" 16 | 17 | RUN curl -sSL https://install.python-poetry.org | python3 - 18 | 19 | RUN poetry install 20 | 21 | CMD ["make", "run"] 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .DEFAULT_GOAL := default 2 | 3 | .PHONY: test 4 | test: 5 | poetry run pytest --cov=animepipeline --cov-report=xml --cov-report=html 6 | 7 | .PHONY: lint 8 | lint: 9 | poetry run pre-commit install 10 | poetry run pre-commit run --all-files 11 | 12 | .PHONY: build 13 | build: 14 | poetry build --format wheel 15 | 16 | .PHONY: run 17 | run: 18 | poetry run python -m animepipeline 19 | 20 | .PHONY: docker 21 | docker: 22 | docker buildx build -t lychee0/animepipeline . 23 | -------------------------------------------------------------------------------- /deploy/docker-compose-dev.yml: -------------------------------------------------------------------------------- 1 | version: "3.8" 2 | 3 | name: animepipeline-dev 4 | 5 | services: 6 | qb: 7 | image: superng6/qbittorrentee:4.4.5.10 8 | restart: always 9 | environment: 10 | - PUID=1026 11 | - PGID=100 12 | volumes: 13 | - ./docker/qb-config:/config 14 | - ./docker/downloads:/downloads 15 | ports: 16 | - "6881:6881" 17 | - "6881:6881/udp" 18 | - "48008:48008" 19 | - "48008:48008/udp" 20 | - "8091:8080" 21 | -------------------------------------------------------------------------------- /tests/test_store.py: -------------------------------------------------------------------------------- 1 | from animepipeline.store.task import AsyncJsonStore, TaskStatus 2 | 3 | 4 | async def test_task_store() -> None: 5 | store = AsyncJsonStore() 6 | 7 | # 添加一个任务 8 | await store.add_task("task_1", TaskStatus()) 9 | 10 | # 获取任务 11 | task = await store.get_task("task_1") 12 | print(task) 13 | 14 | # 更新任务状态 15 | await store.update_task("task_1", task) 16 | print(await store.get_task("task_1")) 17 | 18 | # 删除任务 19 | await store.delete_task("task_1") 20 | -------------------------------------------------------------------------------- /tests/test_rss.py: -------------------------------------------------------------------------------- 1 | from animepipeline.config import NyaaConfig 2 | from animepipeline.rss.nyaa import parse_nyaa 3 | 4 | 5 | def test_parse_nyaa() -> None: 6 | # 测试解析nyaa rss 7 | res = parse_nyaa( 8 | NyaaConfig( 9 | name="Make Heroine ga Oosugiru!", 10 | translation="败犬女主太多了!", 11 | bangumi="https://bangumi.tv/subject/464376", 12 | link="https://nyaa.si/?page=rss&q=%5BSubsPlease%5D+Make+Heroine+ga+Oosugiru%21+-++%281080p%29&c=0_0&f=0", 13 | pattern=r"Make Heroine ga Oosugiru! - (\d+) \(1080p\)", 14 | ), 15 | ) 16 | print(res) 17 | assert len(res) > 0 18 | -------------------------------------------------------------------------------- /animepipeline/util/video.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | VIDEO_EXTENSIONS: List[str] = [ 4 | ".avi", 5 | ".wmv", 6 | ".mpg", 7 | ".mpeg", 8 | ".mpe", 9 | ".mp4", 10 | ".mkv", 11 | ".flv", 12 | ".f4v", 13 | ".f4p", 14 | ".f4a", 15 | ".f4b", 16 | ".asf", 17 | ".asx", 18 | ".mov", 19 | ".qt", 20 | ".rm", 21 | ".rmvb", 22 | ".3gp", 23 | ".3g2", 24 | ".m4v", 25 | ".mpv", 26 | ".m4p", 27 | ".smv", 28 | ".3g3", 29 | ".webm", 30 | ".m2ts", 31 | ".ts", 32 | ".vob", 33 | ".mxf", 34 | ".yuv", 35 | ".divx", 36 | ".swf", 37 | ".avchd", 38 | ".nsv", 39 | ] 40 | -------------------------------------------------------------------------------- /animepipeline/__main__.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from pathlib import Path 3 | 4 | from animepipeline import AsyncJsonStore, Loop, RSSConfig, ServerConfig 5 | 6 | CONFIG_PATH = Path(__file__).resolve().parent.parent.absolute() / "conf" 7 | 8 | 9 | async def main() -> None: 10 | server_config: ServerConfig = ServerConfig.from_yaml(CONFIG_PATH / "server.yml") 11 | rss_config: RSSConfig = RSSConfig.from_yaml(CONFIG_PATH / "rss.yml") 12 | json_store = AsyncJsonStore(CONFIG_PATH / "store.json") 13 | loop = Loop(server_config=server_config, rss_config=rss_config, json_store=json_store) 14 | await loop.start() 15 | 16 | 17 | if __name__ == "__main__": 18 | asyncio.run(main()) 19 | -------------------------------------------------------------------------------- /tests/test_loop.py: -------------------------------------------------------------------------------- 1 | from animepipeline.config import RSSConfig, ServerConfig 2 | from animepipeline.loop import TaskInfo, build_task_info 3 | from animepipeline.rss import parse_nyaa 4 | 5 | from .util import CONFIG_PATH 6 | 7 | 8 | def test_build_task_info() -> None: 9 | rss_config: RSSConfig = RSSConfig.from_yaml(CONFIG_PATH / "rss.yml") 10 | server_config: ServerConfig = ServerConfig.from_yaml(CONFIG_PATH / "server.yml") 11 | for cfg in rss_config.nyaa: 12 | torrent_info_list = parse_nyaa(cfg) 13 | 14 | for torrent_info in torrent_info_list: 15 | task_info = build_task_info(torrent_info, cfg, rss_config, server_config) 16 | assert isinstance(task_info, TaskInfo) 17 | print(task_info) 18 | -------------------------------------------------------------------------------- /tests/test_config.py: -------------------------------------------------------------------------------- 1 | from animepipeline.config.rss import RSSConfig 2 | from animepipeline.config.server import ServerConfig 3 | 4 | from .util import CONFIG_PATH 5 | 6 | 7 | def test_load_server_config() -> None: 8 | # 使用 from_yaml 加载配置 9 | server_config: ServerConfig = ServerConfig.from_yaml(CONFIG_PATH / "server.yml") 10 | print(server_config) 11 | 12 | 13 | def test_load_rss_config() -> None: 14 | # 使用 from_yaml 加载配置 15 | rss_config: RSSConfig = RSSConfig.from_yaml(CONFIG_PATH / "rss.yml") 16 | print(rss_config) 17 | # time.sleep(5) 18 | # 使用 refresh_config 刷新配置 19 | rss_config.refresh_config() 20 | print(rss_config) 21 | # test get script 22 | script_name = rss_config.nyaa[0].script 23 | assert isinstance(script_name, str) 24 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | # Include any files or directories that you don't want to be copied to your 2 | # container here (e.g., local build artifacts, temporary files, etc.). 3 | # 4 | # For more help, visit the .dockerignore file reference guide at 5 | # https://docs.docker.com/engine/reference/builder/#dockerignore-file 6 | 7 | **/.DS_Store 8 | **/.classpath 9 | **/.dockerignore 10 | **/.env 11 | **/.git 12 | **/.gitignore 13 | **/.project 14 | **/.settings 15 | **/.toolstarget 16 | **/.vs 17 | **/.vscode 18 | **/*.*proj.user 19 | **/*.dbmdl 20 | **/*.jfm 21 | **/bin 22 | **/charts 23 | scripts/docker-compose-dev.yml 24 | **/compose* 25 | **/Dockerfile* 26 | **/node_modules 27 | **/npm-debug.log 28 | **/obj 29 | **/secrets.dev.yaml 30 | **/values.dev.yaml 31 | LICENSE 32 | README.md 33 | ./deploy 34 | -------------------------------------------------------------------------------- /conf/rss.yml: -------------------------------------------------------------------------------- 1 | base: 2 | uploader: EutropicAI 3 | script: default.py 4 | param: default.txt 5 | slice: true 6 | timeout: 20 7 | queue: priority 8 | 9 | nyaa: 10 | - name: "Make Heroine ga Oosugiru!" 11 | translation: "败犬女主太多了!" 12 | bangumi: "https://bangumi.tv/subject/464376" 13 | link: "https://nyaa.si/?page=rss&q=%5BSubsPlease%5D+Make+Heroine+ga+Oosugiru%21+-++%281080p%29&c=0_0&f=0" 14 | pattern: 'Make Heroine ga Oosugiru! - (\d+) \(1080p\)' 15 | # uploader: '114514Raws' # override uploader 16 | # script: default2.py # override script 17 | # param: default2.txt # override param 18 | # slice: true # override slice 19 | timeout: 18 # override timeout 20 | # queue: priority # override queue (now support "priority" or "default") 21 | -------------------------------------------------------------------------------- /animepipeline/mediainfo/type.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | from typing import List, Tuple 3 | 4 | from pydantic import BaseModel, FilePath 5 | 6 | 7 | class FileNameInfo(BaseModel): 8 | path: FilePath 9 | episode: int 10 | name: str 11 | uploader: str 12 | type: str = "WEBRip" 13 | 14 | 15 | class MediaInfo(BaseModel): 16 | release_name: str 17 | release_date: datetime 18 | release_size: str # 1.35 GiB 19 | release_format: str # Matroska 20 | overall_bitrate: str # 1919.8 Mb/s 21 | resolution: Tuple[int, int] # (1920, 1080) 22 | bit_depth: int # 10 23 | frame_rate: float # 23.976 24 | format: str # HEVC 25 | format_profile: str # Main@L5@Main 26 | audios: List[Tuple[str, int, str]] # Chinese, 2 channels, FLAC 27 | subtitles: List[Tuple[str, str]] # CHS, PGS 28 | -------------------------------------------------------------------------------- /.github/workflows/CI-docker.yml: -------------------------------------------------------------------------------- 1 | name: Docker Build CI 2 | 3 | on: 4 | push: 5 | branches: ["main"] 6 | paths-ignore: 7 | - "**.md" 8 | - "LICENSE" 9 | 10 | workflow_dispatch: 11 | 12 | jobs: 13 | docker: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | with: 18 | submodules: recursive 19 | 20 | - name: Set up Docker Buildx 21 | uses: docker/setup-buildx-action@v3 22 | 23 | - name: Login to Docker Hub 24 | uses: docker/login-action@v3 25 | with: 26 | username: lychee0 27 | password: ${{ secrets.DOCKERHUB_TOKEN }} 28 | 29 | - name: Build and push 30 | uses: docker/build-push-action@v6 31 | with: 32 | platforms: linux/amd64 33 | push: true 34 | tags: lychee0/animepipeline:dev 35 | -------------------------------------------------------------------------------- /tests/test_tg.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import pytest 4 | 5 | from animepipeline.config import ServerConfig 6 | from animepipeline.post.tg import TGChannelSender 7 | from animepipeline.template import get_telegram_text 8 | 9 | from .util import CONFIG_PATH 10 | 11 | 12 | @pytest.mark.skipif(os.environ.get("GITHUB_ACTIONS") == "true", reason="Only test locally") 13 | async def test_tg_bot() -> None: 14 | server_config: ServerConfig = ServerConfig.from_yaml(CONFIG_PATH / "server.yml") 15 | 16 | sender = TGChannelSender(server_config.telegram) 17 | 18 | await sender.send_text( 19 | text=get_telegram_text( 20 | chinese_name="from unit test ~~~ | 败犬女主太多了!", 21 | episode=2, 22 | file_name="[EutropicAI] Make Heroine ga Oosugiru! [02] [1080p AVC-8bit FLAC].mkv", 23 | torrent_file_hash="this_is_a_fake_hash", 24 | ) 25 | ) 26 | -------------------------------------------------------------------------------- /tests/test_template.py: -------------------------------------------------------------------------------- 1 | from animepipeline.template import PostTemplate, get_bangumi_info, get_media_info_block 2 | 3 | from .util import TEST_VIDEO_PATH 4 | 5 | 6 | def test_get_media_info_block() -> None: 7 | print("\n") 8 | media_info_block = get_media_info_block(video_path=TEST_VIDEO_PATH) 9 | print(media_info_block) 10 | 11 | 12 | def test_get_bangumi_info() -> None: 13 | summary, chinese_name = get_bangumi_info(bangumi_url="https://bgm.tv/subject/454684") 14 | print(chinese_name) 15 | print("\n ---------------------------------- \n") 16 | print(summary) 17 | 18 | 19 | def test_post_template() -> None: 20 | post_template = PostTemplate( 21 | video_path=TEST_VIDEO_PATH, 22 | bangumi_url="https://bgm.tv/subject/454684", 23 | chinese_name="BanG Dream! Ave Mujica", 24 | uploader="EutropicAI", 25 | ) 26 | print(post_template.html()) 27 | print(post_template.markdown()) 28 | print(post_template.bbcode()) 29 | -------------------------------------------------------------------------------- /deploy/docker-compose-animepipeline.yml: -------------------------------------------------------------------------------- 1 | version: "3.8" 2 | 3 | name: animepipeline 4 | 5 | services: 6 | animepipeline: 7 | image: lychee0/animepipeline:latest 8 | restart: always 9 | volumes: 10 | - ./animepipeline:/app/conf 11 | - ./downloads:/downloads 12 | 13 | qb: 14 | image: linuxserver/qbittorrent:latest 15 | restart: always 16 | environment: 17 | - PUID=1026 18 | - PGID=100 19 | volumes: 20 | - ./allinone/qb-config:/config 21 | - ./downloads:/downloads 22 | ports: 23 | - "6881:6881" 24 | - "6881:6881/udp" 25 | - "48008:48008" 26 | - "48008:48008/udp" 27 | - "8091:8080" 28 | # qb-ee: 29 | # image: superng6/qbittorrentee:4.4.5.10 30 | # restart: always 31 | # environment: 32 | # - PUID=1026 33 | # - PGID=100 34 | # volumes: 35 | # - ./allinone/qb-config:/config 36 | # - ./downloads:/downloads 37 | # ports: 38 | # - "6881:6881" 39 | # - "6881:6881/udp" 40 | # - "48008:48008" 41 | # - "48008:48008/udp" 42 | # - "8091:8080" 43 | -------------------------------------------------------------------------------- /.github/workflows/CI-test.yml: -------------------------------------------------------------------------------- 1 | name: CI-test 2 | 3 | env: 4 | GITHUB_ACTIONS: true 5 | 6 | on: 7 | push: 8 | branches: ["main"] 9 | paths-ignore: 10 | - "**.md" 11 | - "LICENSE" 12 | 13 | pull_request: 14 | branches: ["main"] 15 | paths-ignore: 16 | - "**.md" 17 | - "LICENSE" 18 | 19 | workflow_dispatch: 20 | 21 | jobs: 22 | CI: 23 | strategy: 24 | matrix: 25 | os-version: ["ubuntu-latest", "windows-latest", "macos-14"] 26 | python-version: ["3.9"] 27 | poetry-version: ["1.8.3"] 28 | 29 | runs-on: ${{ matrix.os-version }} 30 | steps: 31 | - uses: actions/checkout@v4 32 | with: 33 | submodules: recursive 34 | 35 | - uses: actions/setup-python@v5 36 | with: 37 | python-version: ${{ matrix.python-version }} 38 | 39 | - uses: abatilo/actions-poetry@v3 40 | with: 41 | poetry-version: ${{ matrix.poetry-version }} 42 | 43 | - name: Install dependencies 44 | run: | 45 | poetry install 46 | 47 | - name: Test 48 | run: | 49 | make lint 50 | make test 51 | -------------------------------------------------------------------------------- /.github/workflows/CI-test-cli.yml: -------------------------------------------------------------------------------- 1 | name: CI-test-cli 2 | 3 | on: 4 | push: 5 | branches: ["main"] 6 | paths-ignore: 7 | - "**.md" 8 | - "LICENSE" 9 | 10 | pull_request: 11 | branches: ["main"] 12 | paths-ignore: 13 | - "**.md" 14 | - "LICENSE" 15 | 16 | workflow_dispatch: 17 | 18 | env: 19 | GITHUB_ACTIONS: true 20 | 21 | jobs: 22 | cli: 23 | strategy: 24 | matrix: 25 | os-version: ["ubuntu-latest"] 26 | python-version: ["3.9"] 27 | poetry-version: ["1.8.3"] 28 | 29 | runs-on: ${{ matrix.os-version }} 30 | steps: 31 | - uses: actions/checkout@v4 32 | with: 33 | submodules: recursive 34 | 35 | - uses: actions/setup-python@v5 36 | with: 37 | python-version: ${{ matrix.python-version }} 38 | 39 | - uses: abatilo/actions-poetry@v3 40 | with: 41 | poetry-version: ${{ matrix.poetry-version }} 42 | 43 | - name: Build package 44 | run: | 45 | make build 46 | 47 | - name: Install package and test CLI 48 | run: | 49 | cd dist 50 | pip install *.whl 51 | 52 | ap-rename -h 53 | ap-btf -h 54 | -------------------------------------------------------------------------------- /tests/test_mediainfo.py: -------------------------------------------------------------------------------- 1 | import shutil 2 | 3 | from animepipeline.mediainfo import gen_file_name, get_media_info, rename_file 4 | from animepipeline.mediainfo.type import FileNameInfo 5 | 6 | from .util import ASSETS_PATH, TEST_VIDEO_PATH 7 | 8 | 9 | def test_get_media_info() -> None: 10 | media_info = get_media_info(video_path=TEST_VIDEO_PATH) 11 | print(media_info) 12 | 13 | 14 | def test_gen_file_name() -> None: 15 | anime_info = FileNameInfo( 16 | path=str(TEST_VIDEO_PATH), 17 | episode=1, 18 | name="test 114", 19 | uploader="EutropicAI", 20 | ) 21 | 22 | name = gen_file_name(anime_info=anime_info) 23 | assert name == "[EutropicAI] test 114 [01] [WEBRip 144p AVC-8bit AAC].mp4" 24 | 25 | 26 | def test_rename_file() -> None: 27 | # copy TEST_VIDEO_PATH to a new file 28 | if not (ASSETS_PATH / "copy_test_144p.mp4").exists(): 29 | shutil.copy(TEST_VIDEO_PATH, ASSETS_PATH / "copy_test_144p.mp4") 30 | 31 | anime_info = FileNameInfo( 32 | path=str(ASSETS_PATH / "copy_test_144p.mp4"), 33 | episode=1, 34 | name="test 114", 35 | uploader="EutropicAI", 36 | ) 37 | 38 | p = rename_file(anime_info=anime_info) 39 | assert p.name == "[EutropicAI] test 114 [01] [WEBRip 144p AVC-8bit AAC].mp4" 40 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/pre-commit-hooks 3 | rev: v4.5.0 4 | hooks: 5 | - id: trailing-whitespace 6 | - id: end-of-file-fixer 7 | - id: check-json 8 | - id: check-yaml 9 | - id: check-xml 10 | - id: check-toml 11 | 12 | # autofix json, yaml, markdown... 13 | - repo: https://github.com/pre-commit/mirrors-prettier 14 | rev: v3.1.0 15 | hooks: 16 | - id: prettier 17 | 18 | # autofix toml 19 | - repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks 20 | rev: v2.12.0 21 | hooks: 22 | - id: pretty-format-toml 23 | args: [--autofix] 24 | 25 | - repo: https://github.com/astral-sh/ruff-pre-commit 26 | rev: v0.1.6 27 | hooks: 28 | - id: ruff-format 29 | - id: ruff 30 | args: [--fix, --exit-non-zero-on-fix] 31 | 32 | - repo: https://github.com/pre-commit/mirrors-mypy 33 | rev: v1.7.1 34 | hooks: 35 | - id: mypy 36 | args: [animepipeline, tests] 37 | pass_filenames: false 38 | additional_dependencies: 39 | - types-requests 40 | - types-certifi 41 | - types-pyyaml 42 | - types-aiofiles 43 | - pytest 44 | - pydantic 45 | - tenacity 46 | -------------------------------------------------------------------------------- /animepipeline/post/tg.py: -------------------------------------------------------------------------------- 1 | import telegram 2 | from loguru import logger 3 | from telegram import Bot 4 | from tenacity import retry, stop_after_attempt, wait_random 5 | 6 | from animepipeline.config import TelegramConfig 7 | 8 | 9 | class TGChannelSender: 10 | """ 11 | TG Channel Sender. 12 | 13 | :param config: The telegram configuration. 14 | """ 15 | 16 | def __init__(self, config: TelegramConfig) -> None: 17 | self.bot = Bot(token=config.bot_token) 18 | self.channel_id = config.channel_id 19 | 20 | @retry(wait=wait_random(min=3, max=15), stop=stop_after_attempt(10)) 21 | async def send_text(self, text: str) -> None: 22 | """ 23 | Send text to the channel. 24 | 25 | :param text: The text to send. 26 | """ 27 | try: 28 | await self.bot.send_message( 29 | chat_id=self.channel_id, 30 | text=text, 31 | read_timeout=60, 32 | write_timeout=60, 33 | connect_timeout=60, 34 | pool_timeout=600, 35 | ) 36 | except telegram.error.NetworkError as e: 37 | logger.error(f"Network error: {e}, text: {text}") 38 | raise e 39 | except Exception as e: 40 | logger.error(f"Unknown Error sending text: {e}, text: {text}") 41 | -------------------------------------------------------------------------------- /animepipeline/rss/nyaa.py: -------------------------------------------------------------------------------- 1 | import re 2 | from datetime import datetime 3 | from typing import List 4 | 5 | import feedparser 6 | import httpx 7 | from loguru import logger 8 | from tenacity import retry, stop_after_attempt, wait_random 9 | 10 | from animepipeline.config import NyaaConfig 11 | from animepipeline.rss.type import TorrentInfo 12 | 13 | 14 | @retry(wait=wait_random(min=3, max=15), stop=stop_after_attempt(10)) 15 | def parse_nyaa(cfg: NyaaConfig) -> List[TorrentInfo]: 16 | rss_content = httpx.get(cfg.link).text 17 | 18 | # 使用feedparser解析XML 19 | feed = feedparser.parse(rss_content) 20 | 21 | res: List[TorrentInfo] = [] 22 | 23 | # 遍历每个item 24 | for item in feed.entries: 25 | # 使用正则表达式搜索集数 26 | match = re.search(cfg.pattern, item.title) 27 | 28 | # 如果找到匹配项,则提取集数 29 | if match: 30 | episode_number = match.group(1) 31 | else: 32 | logger.warning(f"Found unmatched item: {item.title}") 33 | continue 34 | 35 | res.append( 36 | TorrentInfo( 37 | name=cfg.name, 38 | translation=cfg.translation, 39 | bangumi=cfg.bangumi, 40 | episode=episode_number, 41 | title=item.title, 42 | link=item.link, 43 | hash=item.nyaa_infohash, 44 | pub_date=datetime.strptime(item.published, "%a, %d %b %Y %H:%M:%S %z"), 45 | size=item.nyaa_size, 46 | ) 47 | ) 48 | 49 | res.sort(key=lambda x: x.episode, reverse=False) 50 | 51 | return res 52 | -------------------------------------------------------------------------------- /tests/test_pool.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | 3 | from animepipeline.pool.task import AsyncTaskExecutor 4 | 5 | 6 | async def example_task(task_id: str, duration: int) -> None: 7 | # Example task function 8 | print(f"Task {task_id} started, will take {duration} seconds.") 9 | await asyncio.sleep(duration) 10 | print(f"Task {task_id} completed.") 11 | 12 | 13 | async def test_task_executor() -> None: 14 | executor = AsyncTaskExecutor() 15 | 16 | for task_id in range(114): 17 | await executor.submit_task(f"task{task_id}", example_task, f"task{task_id}", 3) 18 | print(f"Task {task_id} has been submitted.") 19 | 20 | await executor.wait_all_tasks() 21 | 22 | assert len(executor.tasks) == 114 23 | for task_id in range(114): 24 | assert await executor.task_status(f"task{task_id}") == "Completed" 25 | 26 | 27 | async def test_task_executor_shutdown() -> None: 28 | executor = AsyncTaskExecutor() 29 | 30 | for task_id in range(114): 31 | await executor.submit_task(f"task{task_id}", example_task, f"task{task_id}", 300) 32 | print(f"Task {task_id} has been submitted.") 33 | 34 | await executor.shutdown() 35 | 36 | print(executor.tasks) 37 | 38 | assert len(executor.tasks) == 114 39 | for task_id in range(114): 40 | assert await executor.task_status(f"task{task_id}") == "Pending" 41 | 42 | 43 | async def test_task_dump() -> None: 44 | executor = AsyncTaskExecutor() 45 | 46 | await executor.submit_task(f"task{1}", example_task, f"task{1}", 0) 47 | await asyncio.sleep(1) 48 | await executor.submit_task(f"task{1}", example_task, f"task{1}", 0) 49 | -------------------------------------------------------------------------------- /animepipeline/template/bangumi.py: -------------------------------------------------------------------------------- 1 | from typing import Optional, Tuple 2 | 3 | import httpx 4 | from tenacity import retry, stop_after_attempt, wait_random 5 | 6 | 7 | @retry(wait=wait_random(min=3, max=5), stop=stop_after_attempt(5)) 8 | def get_bangumi_info(bangumi_url: str, chinese_name: Optional[str] = None) -> Tuple[str, str]: 9 | """ 10 | Get bangumi info, first is summary, second is chinese name. 11 | 12 | :param bangumi_url: Bangumi URL 13 | :param chinese_name: Bangumi Chinese name. When it is None, it will auto fetch from bangumi. 14 | """ 15 | summary = "!!!!!Fetch failed!!!!!" 16 | 17 | if bangumi_url[-1] == "/": 18 | bangumi_url = bangumi_url[:-1] 19 | 20 | headers = { 21 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", 22 | "Accept": "*/*", 23 | "Host": "api.bgm.tv", 24 | "Connection": "keep-alive", 25 | } 26 | 27 | with httpx.Client(headers=headers, timeout=20) as client: 28 | response = client.get(bangumi_url) 29 | response.raise_for_status() 30 | 31 | res = response.json() 32 | 33 | summary = res["summary"] 34 | 35 | if chinese_name is None: 36 | try: 37 | chinese_name = res["name_cn"] 38 | if chinese_name is None or chinese_name == "": 39 | raise ValueError("name_cn is empty") 40 | except Exception: 41 | chinese_name = res["name"] 42 | 43 | if chinese_name is None or chinese_name == "": 44 | chinese_name = "!!!!!Fetch Chinese Name failed!!!!!" 45 | 46 | return summary, chinese_name 47 | -------------------------------------------------------------------------------- /animepipeline/config/server.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pathlib import Path 3 | from typing import Any, Union 4 | 5 | import yaml 6 | from pydantic import AnyUrl, BaseModel, DirectoryPath, Field, ValidationError 7 | 8 | 9 | class LoopConfig(BaseModel): 10 | interval: int 11 | 12 | 13 | class QBitTorrentConfig(BaseModel): 14 | host: str 15 | port: int = Field(..., ge=1, le=65535) 16 | username: Union[str, int] 17 | password: Union[str, int] 18 | download_path: DirectoryPath 19 | 20 | 21 | class FinalRipConfig(BaseModel): 22 | url: AnyUrl 23 | token: Union[str, int] 24 | 25 | 26 | class TelegramConfig(BaseModel): 27 | enable: bool 28 | bot_token: str 29 | channel_id: Union[str, int] 30 | 31 | 32 | class ServerConfig(BaseModel): 33 | loop: LoopConfig 34 | qbittorrent: QBitTorrentConfig 35 | finalrip: FinalRipConfig 36 | telegram: TelegramConfig 37 | 38 | @classmethod 39 | def from_yaml(cls, path: Union[Path, str]) -> Any: 40 | """ 41 | Load configuration from a YAML file. 42 | 43 | :param path: The path to the yaml file. 44 | """ 45 | if not os.path.exists(path): 46 | raise FileNotFoundError(f"Config file {path} not found") 47 | with open(path, "r", encoding="utf-8") as file: 48 | try: 49 | config_data = yaml.safe_load(file) 50 | except yaml.YAMLError as e: 51 | raise ValueError(f"Error loading YAML: {e}") 52 | except ValidationError as e: 53 | raise ValueError(f"Config validation error: {e}") 54 | except Exception as e: 55 | raise ValueError(f"Error loading config: {e}") 56 | 57 | config = cls(**config_data) 58 | 59 | return config 60 | -------------------------------------------------------------------------------- /animepipeline/cli/btf/__main__.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from pathlib import Path 3 | 4 | from loguru import logger 5 | 6 | from animepipeline.bt import QBittorrentManager 7 | from animepipeline.template import PostTemplate 8 | 9 | parser = argparse.ArgumentParser(description="Generate all post info files for the anime.") 10 | 11 | # Input Path 12 | parser.add_argument("-p", "--PATH", help="Path to the video file", required=True) 13 | # Bangumi URL 14 | parser.add_argument("-b", "--BANGUMI", help="Bangumi URL", required=True) 15 | # Chinese Name 16 | parser.add_argument("-n", "--NAME", help="Chinese name", required=False) 17 | # Uploader Name 18 | parser.add_argument("-u", "--UPLOADER", help="Uploader name", required=False) 19 | # Make Torrent 20 | parser.add_argument("-t", "--TORRENT", help="file_path -> torrent", required=False) 21 | 22 | args = parser.parse_args() 23 | 24 | 25 | def main() -> None: 26 | if args.UPLOADER is None: 27 | args.UPLOADER = "EutropicAI" 28 | 29 | # Make torrent file 30 | if args.TORRENT is not None: 31 | file_path = Path(args.TORRENT) 32 | h = QBittorrentManager.make_torrent_file( 33 | file_path=file_path, torrent_file_save_path=file_path.name + ".torrent" 34 | ) 35 | logger.info(f"Make torrent file success, hash: {h}") 36 | 37 | # Generate post info files 38 | path = Path(args.PATH) 39 | 40 | post_template = PostTemplate( 41 | video_path=path, 42 | bangumi_url=args.BANGUMI, 43 | chinese_name=args.NAME, 44 | uploader=args.UPLOADER, 45 | ) 46 | 47 | post_template.save( 48 | html_path=path.name + ".html", 49 | markdown_path=path.name + ".md", 50 | bbcode_path=path.name + ".txt", 51 | ) 52 | logger.info("Generate post info files success.") 53 | 54 | 55 | if __name__ == "__main__": 56 | main() 57 | -------------------------------------------------------------------------------- /animepipeline/mediainfo/name.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | 3 | from loguru import logger 4 | 5 | from animepipeline.mediainfo.mediainfo import get_media_info 6 | from animepipeline.mediainfo.type import FileNameInfo 7 | 8 | 9 | def gen_file_name(anime_info: FileNameInfo) -> str: 10 | """ 11 | Auto generate the file name, based on the media info of the file 12 | 13 | anime_info: FileNameInfo (path: xx.mkv, episode: 1, name: Fate/Kaleid Liner Prisma Illya, uploader: EutropicAI, type: WEBRip) 14 | 15 | -> [EutropicAI] Fate/Kaleid Liner Prisma Illya [01] [WEBRip 1080p HEVC-10bit FLAC].mkv 16 | 17 | :param anime_info: FileNameInfo 18 | :return: 19 | """ 20 | media_info = get_media_info(anime_info.path) 21 | resolution_heigh = str(media_info.resolution[1]) + "p" 22 | bit_depth = str(media_info.bit_depth) + "bit" 23 | 24 | video_format = media_info.format 25 | 26 | audio_format_list = [audio[2] for audio in media_info.audios] 27 | audio_format = "FLAC" if "FLAC" in audio_format_list else audio_format_list[0] 28 | 29 | file_format = Path(anime_info.path).suffix 30 | 31 | return f"[{anime_info.uploader}] {anime_info.name} [{str(anime_info.episode).zfill(2)}] [{anime_info.type} {resolution_heigh} {video_format}-{bit_depth} {audio_format}]{file_format}" 32 | 33 | 34 | def rename_file(anime_info: FileNameInfo) -> Path: 35 | """ 36 | Rename the file name, based on the media info of the file 37 | 38 | :param anime_info: FileNameInfo 39 | :return: 40 | """ 41 | anime_path = Path(anime_info.path) 42 | 43 | gen_name = gen_file_name(anime_info) 44 | gen_path = anime_path.parent / gen_name 45 | 46 | if gen_path.exists(): 47 | gen_path.unlink() 48 | logger.warning(f"Encode File already exists, remove it: {gen_path}") 49 | 50 | anime_path.rename(gen_path) 51 | 52 | return gen_path 53 | -------------------------------------------------------------------------------- /animepipeline/cli/rename/__main__.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from pathlib import Path 3 | 4 | from animepipeline.mediainfo import FileNameInfo, rename_file 5 | 6 | parser = argparse.ArgumentParser(description="Rename anime video files.") 7 | 8 | # Input Path 9 | parser.add_argument("-p", "--PATH", help="Path to the video file or directory", required=True) 10 | # Episode Number 11 | parser.add_argument("-e", "--EPISODE", help="Episode number", required=False) 12 | # Anime Name 13 | parser.add_argument("-n", "--NAME", help="Anime name", required=True) 14 | # Uploader Name 15 | parser.add_argument("-u", "--UPLOADER", help="Uploader name", required=False) 16 | # Encode Type 17 | parser.add_argument("-t", "--TYPE", help="Encode type", required=False) 18 | 19 | args = parser.parse_args() 20 | 21 | 22 | def main() -> None: 23 | # TODO: Support withdraw of renaming 24 | 25 | if args.UPLOADER is None: 26 | args.UPLOADER = "EutropicAI" 27 | 28 | path = Path(args.PATH) 29 | 30 | if args.TYPE is None: 31 | args.TYPE = "WEBRip" 32 | 33 | if args.TYPE not in ["WEBRip", "BDRip", "WEB-DL", "REMUX", "DVDRip"]: 34 | raise ValueError("Encode type must be one of the following: WEBRip, BDRip, WEB-DL, REMUX, DVDRip") 35 | 36 | if not path.is_dir(): 37 | if args.EPISODE is None: 38 | raise ValueError("Episode number is required for single file") 39 | 40 | try: 41 | episode = int(args.EPISODE) 42 | except ValueError: 43 | raise ValueError("Episode number must be an integer") 44 | 45 | anime_info = FileNameInfo( 46 | path=path, 47 | episode=episode, 48 | name=args.NAME, 49 | uploader=args.UPLOADER, 50 | type=args.TYPE, 51 | ) 52 | new_path = rename_file(anime_info=anime_info) 53 | print(f"Renamed: {path} -> {new_path}") 54 | else: 55 | # TODO: Rename all video in the directory 56 | raise NotImplementedError("Not implemented yet") 57 | 58 | 59 | if __name__ == "__main__": 60 | main() 61 | -------------------------------------------------------------------------------- /.github/workflows/Release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | workflow_dispatch: 5 | 6 | push: 7 | tags: 8 | - "v*" 9 | 10 | jobs: 11 | pypi: 12 | strategy: 13 | matrix: 14 | python-version: ["3.9"] 15 | poetry-version: ["1.8.3"] 16 | 17 | runs-on: ubuntu-latest 18 | steps: 19 | - uses: actions/checkout@v4 20 | with: 21 | submodules: recursive 22 | 23 | - uses: actions/setup-python@v5 24 | with: 25 | python-version: ${{ matrix.python-version }} 26 | 27 | - uses: abatilo/actions-poetry@v3 28 | with: 29 | poetry-version: ${{ matrix.poetry-version }} 30 | 31 | - name: Build package 32 | run: | 33 | make build 34 | 35 | - name: Publish a Python distribution to PyPI 36 | uses: pypa/gh-action-pypi-publish@release/v1 37 | with: 38 | password: ${{ secrets.PYPI_API }} 39 | 40 | docker: 41 | runs-on: ubuntu-latest 42 | steps: 43 | - uses: actions/checkout@v4 44 | with: 45 | submodules: recursive 46 | 47 | - name: Set up Docker Buildx 48 | uses: docker/setup-buildx-action@v3 49 | 50 | - name: Login to Docker Hub 51 | uses: docker/login-action@v3 52 | with: 53 | username: lychee0 54 | password: ${{ secrets.DOCKERHUB_TOKEN }} 55 | 56 | - name: Docker meta 57 | id: meta 58 | uses: docker/metadata-action@v5 59 | with: 60 | images: | 61 | lychee0/animepipeline 62 | tags: | 63 | latest 64 | ${{ github.ref_name }} 65 | 66 | - name: Build and push 67 | uses: docker/build-push-action@v6 68 | with: 69 | platforms: linux/amd64 70 | push: true 71 | tags: ${{ steps.meta.outputs.tags }} 72 | 73 | github: 74 | needs: [pypi, docker] 75 | runs-on: ubuntu-latest 76 | steps: 77 | - uses: actions/checkout@v4 78 | with: 79 | submodules: recursive 80 | 81 | - name: Release 82 | uses: softprops/action-gh-release@v2 83 | -------------------------------------------------------------------------------- /animepipeline/pool/task.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from typing import Any, Callable, Dict 3 | 4 | 5 | class AsyncTaskExecutor: 6 | """ 7 | A simple async task executor that can submit tasks and check their status. 8 | This class uses asyncio to run tasks concurrently. 9 | """ 10 | 11 | def __init__(self) -> None: 12 | self.lock = asyncio.Lock() 13 | self.tasks: Dict[str, asyncio.Task] = {} 14 | 15 | async def submit_task(self, task_id: str, func: Callable[..., Any], *args: Any, **kwargs: Any) -> None: 16 | """ 17 | Submit a task to the executor. 18 | 19 | :param task_id: The task ID. 20 | :param func: The function to run asynchronously. 21 | :param args: The arguments to pass to the function. 22 | :param kwargs: The keyword arguments to pass to the function. 23 | """ 24 | async with self.lock: 25 | if task_id in self.tasks: 26 | return # Task is already running 27 | 28 | # Wrap the function in asyncio.create_task to run it concurrently 29 | self.tasks[task_id] = asyncio.create_task(func(*args, **kwargs)) 30 | 31 | async def task_status(self, task_id: str) -> str: 32 | """ 33 | Check the status of a task. 34 | 35 | :param task_id: The task ID to check. 36 | """ 37 | async with self.lock: 38 | if task_id in self.tasks and not self.tasks[task_id].done(): 39 | return "Pending" 40 | elif task_id in self.tasks and self.tasks[task_id].done(): 41 | return "Completed" 42 | else: 43 | return "Unknown" 44 | 45 | async def shutdown(self) -> None: 46 | """ 47 | Cancel all running tasks and shutdown the executor. 48 | """ 49 | async with self.lock: 50 | for task in self.tasks.values(): 51 | if not task.done(): 52 | task.cancel() 53 | 54 | async def wait_all_tasks(self) -> None: 55 | """ 56 | Wait for all tasks to complete. 57 | """ 58 | async with self.lock: 59 | await asyncio.gather(*self.tasks.values()) 60 | -------------------------------------------------------------------------------- /tests/test_bt.py: -------------------------------------------------------------------------------- 1 | import os 2 | import shutil 3 | import time 4 | from pathlib import Path 5 | 6 | import pytest 7 | 8 | from animepipeline.bt.qb import QBittorrentManager 9 | from animepipeline.config import ServerConfig 10 | 11 | from .util import CONFIG_PATH, TEST_VIDEO_PATH 12 | 13 | 14 | @pytest.mark.skipif( 15 | os.environ.get("GITHUB_ACTIONS") == "true", reason="Only test locally cuz BT may not suitable for CI" 16 | ) 17 | def test_qbittorrent() -> None: 18 | torrent_hash = "5484cff30b108ca1d1987fb6ea4eebed356b9ddd" 19 | torrent_url = "https://nyaa.si/download/1878677.torrent" 20 | 21 | if Path("../deploy/docker/downloads").exists(): 22 | download_path = Path("../deploy/docker/downloads") 23 | else: 24 | download_path = Path("./deploy/docker/downloads") 25 | 26 | server_config: ServerConfig = ServerConfig.from_yaml(CONFIG_PATH / "server.yml") 27 | cfg = server_config.qbittorrent 28 | cfg.download_path = download_path.absolute() 29 | qb_manager = QBittorrentManager(config=cfg) 30 | 31 | qb_manager.add_torrent(torrent_hash=torrent_hash, torrent_url=torrent_url) 32 | 33 | # Check if the download is complete 34 | while True: 35 | time.sleep(5) 36 | if qb_manager.check_download_complete(torrent_hash): 37 | print("Download is complete.") 38 | break 39 | else: 40 | print("Download is not complete.") 41 | 42 | # Get the downloaded filename 43 | file_path = qb_manager.get_downloaded_path(torrent_hash) 44 | if file_path is not None: 45 | print(f"Downloaded file: {file_path}") 46 | else: 47 | print("Download is not complete or failed.") 48 | 49 | h = QBittorrentManager.make_torrent_file( 50 | file_path=TEST_VIDEO_PATH, 51 | torrent_file_save_path=download_path / "test_144p.torrent", 52 | ) 53 | print(f"Torrent hash: {h}") 54 | 55 | # copy the torrent file to the download path 56 | shutil.copy(TEST_VIDEO_PATH, download_path) 57 | 58 | qb_manager.add_torrent(torrent_hash=h, torrent_file_path=download_path / "test_144p.torrent") 59 | 60 | # Check if the reseed is complete 61 | while True: 62 | time.sleep(2) 63 | if qb_manager.check_download_complete(torrent_hash): 64 | print("Reseed is complete.") 65 | break 66 | else: 67 | print("Reseed is not complete.") 68 | -------------------------------------------------------------------------------- /animepipeline/encode/type.py: -------------------------------------------------------------------------------- 1 | from typing import List, Optional 2 | 3 | from pydantic import BaseModel 4 | 5 | 6 | class TaskNotCompletedError(Exception): 7 | """ 8 | Exception raised when a task is not completed yet. 9 | """ 10 | 11 | def __init__(self, message: str = "Task not completed yet") -> None: 12 | self.message = message 13 | super().__init__(self.message) 14 | 15 | 16 | class Error(BaseModel): 17 | message: str 18 | 19 | 20 | class PingResponse(BaseModel): 21 | error: Optional[Error] = None 22 | success: bool 23 | 24 | 25 | class NewTaskRequest(BaseModel): 26 | video_key: str 27 | 28 | 29 | class NewTaskResponse(BaseModel): 30 | error: Optional[Error] = None 31 | success: bool 32 | 33 | 34 | class StartTaskRequest(BaseModel): 35 | encode_param: str 36 | script: str 37 | video_key: str 38 | slice: Optional[bool] = None 39 | timeout: Optional[int] = None 40 | queue: Optional[str] = None 41 | 42 | 43 | class StartTaskResponse(BaseModel): 44 | error: Optional[Error] = None 45 | success: bool 46 | 47 | 48 | class GetTaskProgressRequest(BaseModel): 49 | video_key: str 50 | 51 | 52 | class GetTaskProgressResponse(BaseModel): 53 | class Data(BaseModel): 54 | class Progress(BaseModel): 55 | clip_key: str 56 | clip_url: str 57 | completed: bool 58 | encode_key: str 59 | encode_url: str 60 | index: float 61 | 62 | create_at: int 63 | encode_key: str 64 | encode_param: str 65 | encode_size: str 66 | encode_url: str 67 | key: str 68 | progress: List[Progress] 69 | script: str 70 | size: str 71 | status: str 72 | url: str 73 | 74 | data: Optional[Data] = None 75 | error: Optional[Error] = None 76 | success: bool 77 | 78 | 79 | class OSSPresignedURLRequest(BaseModel): 80 | video_key: str 81 | 82 | 83 | class OSSPresignedURLResponse(BaseModel): 84 | class Data(BaseModel): 85 | exist: bool 86 | url: str 87 | 88 | data: Optional[Data] = None 89 | error: Optional[Error] = None 90 | success: bool 91 | 92 | 93 | class RetryMergeRequest(BaseModel): 94 | video_key: str 95 | 96 | 97 | class RetryMergeResponse(BaseModel): 98 | error: Optional[Error] = None 99 | success: bool 100 | -------------------------------------------------------------------------------- /tests/test_encode.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import os 3 | 4 | import pytest 5 | 6 | from animepipeline.config import RSSConfig, ServerConfig 7 | from animepipeline.encode.finalrip import FinalRipClient 8 | from animepipeline.encode.type import GetTaskProgressRequest, TaskNotCompletedError 9 | 10 | from .util import ASSETS_PATH, CONFIG_PATH 11 | 12 | video_key = "test_144p.mp4" 13 | 14 | 15 | @pytest.mark.skipif(os.environ.get("GITHUB_ACTIONS") == "true", reason="Only test locally") 16 | class Test_FinalRip: 17 | def setup_method(self) -> None: 18 | server_config: ServerConfig = ServerConfig.from_yaml(CONFIG_PATH / "server.yml") 19 | self.finalrip = FinalRipClient(server_config.finalrip) 20 | 21 | async def test_ping(self) -> None: 22 | ping_response = await self.finalrip.ping() 23 | print(ping_response) 24 | 25 | async def test_new_task(self) -> None: 26 | await self.finalrip.upload_and_new_task(ASSETS_PATH / video_key) 27 | 28 | async def test_start_task(self) -> None: 29 | rss_config: RSSConfig = RSSConfig.from_yaml(CONFIG_PATH / "rss.yml") 30 | 31 | p: str = "" 32 | for _, v in rss_config.params.items(): 33 | p = v 34 | print(repr(p)) 35 | s: str = "" 36 | for _, v in rss_config.scripts.items(): 37 | s = v 38 | print(repr(s)) 39 | try: 40 | await self.finalrip.start_task(encode_param=p, script=s, video_key=video_key, slice=True, timeout=10) 41 | except Exception as e: 42 | print(e) 43 | 44 | async def test_check_task_exist(self) -> None: 45 | assert await self.finalrip.check_task_exist(video_key) 46 | 47 | async def test_check_task_completed(self) -> None: 48 | print(await self.finalrip.check_task_completed(video_key)) 49 | 50 | async def test_task_progress(self) -> None: 51 | task_progress = await self.finalrip._get_task_progress(GetTaskProgressRequest(video_key=video_key)) 52 | print(task_progress) 53 | 54 | async def test_retry_merge(self) -> None: 55 | await self.finalrip.retry_merge(video_key) 56 | 57 | async def test_download_completed_task(self) -> None: 58 | while True: 59 | try: 60 | await self.finalrip.download_completed_task(video_key=video_key, save_path=ASSETS_PATH / "encode.mkv") 61 | break 62 | except TaskNotCompletedError: 63 | print("Task not completed yet") 64 | await asyncio.sleep(5) 65 | except Exception as e: 66 | print(e) 67 | await asyncio.sleep(5) 68 | -------------------------------------------------------------------------------- /animepipeline/util/bt.py: -------------------------------------------------------------------------------- 1 | def gen_magnet_link(torrent_hash: str) -> str: 2 | """ 3 | Generate a magnet link from a torrent hash. 4 | 5 | :param torrent_hash: The torrent hash. 6 | """ 7 | return f"magnet:?xt=urn:btih:{torrent_hash}" 8 | 9 | 10 | # bt tracker urls 11 | ANNOUNCE_URLS = [ 12 | "http://nyaa.tracker.wf:7777/announce", 13 | "http://open.acgtracker.com:1096/announce", 14 | "http://t.nyaatracker.com:80/announce", 15 | "http://tracker4.itzmx.com:2710/announce", 16 | "https://tracker.nanoha.org/announce", 17 | "http://t.acg.rip:6699/announce", 18 | "https://tr.bangumi.moe:9696/announce", 19 | "http://tr.bangumi.moe:6969/announce", 20 | "udp://tr.bangumi.moe:6969/announce", 21 | "http://open.acgnxtracker.com/announce", 22 | "https://open.acgnxtracker.com/announce", 23 | "udp://open.stealth.si:80/announce", 24 | "udp://tracker.opentrackr.org:1337/announce", 25 | "udp://exodus.desync.com:6969/announce", 26 | "udp://tracker.torrent.eu.org:451/announce", 27 | "udp://tracker.openbittorrent.com:80/announce", 28 | "udp://tracker.publicbt.com:80/announce", 29 | "udp://tracker.prq.to:80/announce", 30 | "udp://104.238.198.186:8000/announce", 31 | "http://104.238.198.186:8000/announce", 32 | "http://94.228.192.98/announce", 33 | "http://share.dmhy.org/annonuce", 34 | "http://tracker.btcake.com/announce", 35 | "http://tracker.ktxp.com:6868/announce", 36 | "http://tracker.ktxp.com:7070/announce", 37 | "http://bt.sc-ol.com:2710/announce", 38 | "http://btfile.sdo.com:6961/announce", 39 | "https://t-115.rhcloud.com/only_for_ylbud", 40 | "http://exodus.desync.com:6969/announce", 41 | "udp://coppersurfer.tk:6969/announce", 42 | "http://tracker3.torrentino.com/announce", 43 | "http://tracker2.torrentino.com/announce", 44 | "udp://open.demonii.com:1337/announce", 45 | "udp://tracker.ex.ua:80/announce", 46 | "http://pubt.net:2710/announce", 47 | "http://tracker.tfile.me/announce", 48 | "http://bigfoot1942.sektori.org:6969/announce", 49 | "udp://bt.sc-ol.com:2710/announce", 50 | "http://1337.abcvg.info:80/announce", 51 | "http://bt.okmp3.ru:2710/announce", 52 | "http://ipv6.rer.lol:6969/announce", 53 | "https://tr.burnabyhighstar.com:443/announce", 54 | "https://tracker.gbitt.info:443/announce", 55 | "https://tracker.gcrenwp.top:443/announce", 56 | "https://tracker.kuroy.me:443/announce", 57 | "https://tracker.lilithraws.org:443/announce", 58 | "https://tracker.loligirl.cn:443/announce", 59 | "https://tracker1.520.jp:443/announce", 60 | "udp://amigacity.xyz:6969/announce", 61 | "udp://bt1.archive.org:6969/announce", 62 | "udp://bt2.archive.org:6969/announce", 63 | "udp://epider.me:6969/announce", 64 | "wss://tracker.openwebtorrent.com:443/announce", 65 | ] 66 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | build-backend = "poetry-core.masonry.api" 3 | requires = ["poetry-core"] 4 | 5 | [tool.coverage.report] 6 | exclude_also = [ 7 | "raise AssertionError", 8 | "raise NotImplementedError", 9 | "if __name__ == .__main__.:", 10 | "if TYPE_CHECKING:", 11 | "except Exception as e" 12 | ] 13 | 14 | [tool.coverage.run] 15 | omit = [ 16 | ] 17 | 18 | [tool.mypy] 19 | disable_error_code = "attr-defined" 20 | disallow_any_generics = false 21 | disallow_subclassing_any = false 22 | ignore_missing_imports = true 23 | plugins = ["pydantic.mypy"] 24 | strict = true 25 | warn_return_any = false 26 | 27 | [tool.poetry] 28 | authors = ["Tohrusky"] 29 | classifiers = [ 30 | "Programming Language :: Python :: 3.9", 31 | "Programming Language :: Python :: 3.10", 32 | "Programming Language :: Python :: 3.11", 33 | "Programming Language :: Python :: 3.12", 34 | "Programming Language :: Python :: 3.13" 35 | ] 36 | description = "auto encode new anime episode" 37 | homepage = "https://github.com/EutropicAI/AnimePipeline" 38 | license = "MIT" 39 | name = "animepipeline" 40 | readme = "README.md" 41 | repository = "https://github.com/EutropicAI/AnimePipeline" 42 | version = "0.0.6" 43 | 44 | # Requirements 45 | [tool.poetry.dependencies] 46 | feedparser = "^6.0.11" 47 | httpx = "^0.28.1" 48 | loguru = "^0.7.3" 49 | pydantic = "^2.10.4" 50 | pymediainfo-tensoraws = "6.1.0" 51 | python = "^3.9" 52 | python-telegram-bot = "^21.9" 53 | pyyaml = "^6.0.2" 54 | qbittorrent-api = "^2024.9.67" 55 | tenacity = "^9.0.0" 56 | torrentool = "^1.2.0" 57 | 58 | [tool.poetry.group.dev.dependencies] 59 | pre-commit = "^3.7.0" 60 | 61 | [tool.poetry.group.test.dependencies] 62 | coverage = "^7.2.0" 63 | pytest = "^8.0" 64 | pytest-asyncio = "^0.24.0" 65 | pytest-cov = "^4.0" 66 | 67 | [tool.poetry.group.typing.dependencies] 68 | mypy = "^1.8.0" 69 | ruff = "^0.3.7" 70 | types-aiofiles = "^24.1.0.20240626" 71 | types-pyyaml = "^6.0.12.20240917" 72 | types-requests = "^2.28.8" 73 | 74 | [tool.poetry.scripts] 75 | ap-btf = 'animepipeline.cli.btf.__main__:main' 76 | ap-rename = 'animepipeline.cli.rename.__main__:main' 77 | 78 | [tool.pytest.ini_options] 79 | asyncio_mode = "auto" 80 | 81 | [tool.ruff] 82 | extend-ignore = ["B018", "B019", "RUF001", "PGH003", "PGH004", "RUF003", "E402", "RUF002", "B904"] 83 | extend-select = [ 84 | "I", # isort 85 | "B", # flake8-bugbear 86 | "C4", # flake8-comprehensions 87 | "PGH", # pygrep-hooks 88 | "RUF", # ruff 89 | "W", # pycodestyle 90 | "YTT" # flake8-2020 91 | ] 92 | fixable = ["ALL"] 93 | line-length = 120 94 | 95 | [tool.ruff.format] 96 | indent-style = "space" 97 | line-ending = "auto" 98 | quote-style = "double" 99 | skip-magic-trailing-comma = false 100 | 101 | [tool.ruff.isort] 102 | combine-as-imports = true 103 | 104 | [tool.ruff.mccabe] 105 | max-complexity = 10 106 | -------------------------------------------------------------------------------- /animepipeline/template/mediainfo.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import List, Union 3 | 4 | from animepipeline.mediainfo import get_media_info 5 | 6 | 7 | def get_media_info_block(video_path: Union[str, Path], uploader: str = "EutropicAI") -> str: 8 | """ 9 | Generate a code block for media info. 10 | 11 | RELEASE.NAME........: [EutropicAI] Fate/Kaleid Liner Prisma Illya [01] [WEBRip 2160p HEVC-10bit FLAC].mkv 12 | RELEASE.DATE........: 2022-07-09 13 | RELEASE.SIZE........: 114514.1 GiB 14 | RELEASE.FORMAT......: Matroska 15 | OVERALL.BITRATE.....: 1919.8 Mb/s 16 | RESOLUTION..........: 3840x2160 17 | BIT.DEPTH...........: 10 bits 18 | FRAME.RATE..........: 60.000 FPS 19 | VIDEO...............: HEVC, Main@L5@Main 20 | AUDIO#01............: Chinese, 8 channels, E-AC-3 21 | AUDIO#02............: Engilsh, 2 channels, AAC 22 | SUBTITLE#01.........: CHS, PGS 23 | SUBTITLE#02.........: CHT, ASS 24 | SUBTITLE#03.........: CHT, SRT 25 | SUBTITLE#04.........: CHT&ENG, ASS 26 | SUBTITLE#05.........: ENG&CHT, ASS 27 | UPLOADER............: EutropicAI 28 | """ 29 | media_info = get_media_info(video_path=video_path) 30 | 31 | write_info_list: List[str] = [] 32 | 33 | write_info_list.append("RELEASE.NAME........: " + media_info.release_name) 34 | write_info_list.append("RELEASE.DATE........: " + media_info.release_date.strftime("%Y-%m-%d")) 35 | write_info_list.append("RELEASE.SIZE........: " + media_info.release_size) 36 | write_info_list.append("RELEASE.FORMAT......: " + media_info.release_format) 37 | write_info_list.append("OVERALL.BITRATE.....: " + media_info.overall_bitrate) 38 | # VIDEO TRACK 39 | write_info_list.append( 40 | "RESOLUTION..........: " + str(media_info.resolution[0]) + "x" + str(media_info.resolution[1]) 41 | ) 42 | write_info_list.append("BIT.DEPTH...........: " + str(media_info.bit_depth) + " bits") 43 | write_info_list.append("FRAME.RATE..........: " + str(media_info.frame_rate) + " FPS") 44 | write_info_list.append("VIDEO...............: " + media_info.format + ", " + media_info.format_profile) 45 | # AUDIO TRACK 46 | for audio_track_id, audio_track in enumerate(media_info.audios): 47 | write_info_list.append( 48 | "AUDIO#" 49 | + str(audio_track_id + 1).zfill(2) 50 | + "............: " 51 | + audio_track[0] 52 | + ", " 53 | + str(audio_track[1]) 54 | + " channels, " 55 | + audio_track[2] 56 | ) 57 | # SUBTITLE TRACK 58 | for subtitle_track_id, subtitle_track in enumerate(media_info.subtitles): 59 | write_info_list.append( 60 | "SUBTITLE#" 61 | + str(subtitle_track_id + 1).zfill(2) 62 | + ".........: " 63 | + subtitle_track[0] 64 | + ", " 65 | + subtitle_track[1] 66 | ) 67 | write_info_list.append("UPLOADER............: " + uploader) 68 | 69 | return "\n".join(write_info_list) 70 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AnimePipeline 2 | 3 | auto encode new anime episode, driven by [**FinalRip**](https://github.com/EutropicAI/FinalRip) 4 | 5 | [](https://github.com/EutropicAI/AnimePipeline/actions/workflows/CI-test.yml) 6 | [](https://github.com/EutropicAI/AnimePipeline/actions/workflows/CI-test-cli.yml) 7 | [](https://github.com/EutropicAI/AnimePipeline/actions/workflows/CI-docker.yml) 8 | [](https://github.com/EutropicAI/AnimePipeline/actions/workflows/Release.yml) 9 | [](https://badge.fury.io/py/animepipeline) 10 |  11 | 12 | ### Installation 13 | 14 | FinalRip is required, if you don't familiar with it, please play with it first. 15 | 16 | Python 3.9 or higher is required, we use poetry to manage dependencies. 17 | 18 | btw, `make` is required to run the commands in the `Makefile`. 19 | 20 | ```bash 21 | poetry install 22 | make run 23 | ``` 24 | 25 | or you can use docker to run the project, see [docker-compose.yml](./deploy/docker-compose.yml) for more details. 26 | 27 | ### CLI 28 | 29 | some useful command line tools are provided, you can use them to rename or generate some info 30 | 31 | ``` 32 | pip install animepipeline 33 | ap-rename -h 34 | ap-btf -h 35 | ``` 36 | 37 | ### Configuration 38 | 39 | #### Server Config: 40 | 41 | - loop interval: the interval of the loop, default is 200s 42 | - _download path_: the path to save the downloaded torrent file, if you use docker, you should mount the volume to the container, then use the path in the container. like `/downloads` 43 | - telegram bot token & channel id: your own bot token and channel id 44 | 45 | #### RSS Config: 46 | 47 | supports hot reloading, which means you can update your config without needing to restart the service. 48 | 49 | you should provide the compatible params and scripts in the [params](./conf/params) and [scripts](./conf/scripts) folder. 50 | 51 | **the file name will be used as the key** 52 | 53 | - base: the default settings, can be overridden in the rss list 54 | - link: the rss link, make sure it's a valid rss link 55 | - pattern: to match the episode(int), use regex 56 | 57 | ### Reference 58 | 59 | - [**FinalRip**](https://github.com/EutropicAI/FinalRip) 60 | - [FFmpeg](https://github.com/FFmpeg/FFmpeg) 61 | - [VapourSynth](https://github.com/vapoursynth/vapoursynth) 62 | - [asyncio](https://docs.python.org/3/library/asyncio.html) 63 | - [httpx](https://github.com/encode/httpx) 64 | - [qbittorrent](https://github.com/qbittorrent/qBittorrent) 65 | - [qbittorrent-api](https://github.com/rmartin16/qbittorrent-api) 66 | - [python-telegram-bot](https://github.com/python-telegram-bot/python-telegram-bot) 67 | 68 | ### License 69 | 70 | This project is licensed under the GPL-3.0 license - see the [LICENSE file](./LICENSE) for details. 71 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | *.DS_Store 7 | 8 | # Distribution / packaging 9 | .Python 10 | build/ 11 | develop-eggs/ 12 | dist/ 13 | downloads/ 14 | eggs/ 15 | .eggs/ 16 | lib/ 17 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | wheels/ 22 | share/python-wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .nox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *.cover 48 | *.py,cover 49 | .hypothesis/ 50 | .pytest_cache/ 51 | cover/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | db.sqlite3-journal 62 | 63 | # Flask stuff: 64 | instance/ 65 | .webassets-cache 66 | 67 | # Scrapy stuff: 68 | .scrapy 69 | 70 | # Sphinx documentation 71 | docs/_build/ 72 | 73 | # PyBuilder 74 | .pybuilder/ 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | # For a library or package, you might want to ignore these files since the code is 86 | # intended to run in multiple environments; otherwise, check them in: 87 | # .python-version 88 | 89 | # pipenv 90 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 91 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 92 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 93 | # install all needed dependencies. 94 | #Pipfile.lock 95 | 96 | # poetry 97 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 98 | # This is especially recommended for binary packages to ensure reproducibility, and is more 99 | # commonly ignored for libraries. 100 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 101 | #poetry.lock 102 | 103 | # pdm 104 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 105 | #pdm.lock 106 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 107 | # in version control. 108 | # https://pdm.fming.dev/#use-with-ide 109 | .pdm.toml 110 | .pdm-python 111 | .pdm-build/ 112 | 113 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 114 | __pypackages__/ 115 | 116 | # Celery stuff 117 | celerybeat-schedule 118 | celerybeat.pid 119 | 120 | # SageMath parsed files 121 | *.sage.py 122 | 123 | # Environments 124 | .env 125 | .venv 126 | env/ 127 | venv/ 128 | ENV/ 129 | env.bak/ 130 | venv.bak/ 131 | 132 | # Spyder project settings 133 | .spyderproject 134 | .spyproject 135 | 136 | # Rope project settings 137 | .ropeproject 138 | 139 | # mkdocs documentation 140 | /site 141 | 142 | # mypy 143 | .mypy_cache/ 144 | .dmypy.json 145 | dmypy.json 146 | 147 | # Pyre type checker 148 | .pyre/ 149 | 150 | # pytype static type analyzer 151 | .pytype/ 152 | 153 | # Cython debug symbols 154 | cython_debug/ 155 | 156 | # PyCharm 157 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 158 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 159 | # and can be added to the global gitignore or merged into this file. For a more nuclear 160 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 161 | .idea/ 162 | /.ruff_cache/ 163 | 164 | *.mp4 165 | *.mkv 166 | 167 | /deploy/docker/ 168 | /deploy/allinone/ 169 | 170 | /store.json 171 | /conf/store.json 172 | /tests/store.json 173 | 174 | *.torrent 175 | -------------------------------------------------------------------------------- /animepipeline/store/task.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import json 3 | from copy import deepcopy 4 | from pathlib import Path 5 | from typing import Any, Dict, Optional, Union 6 | 7 | from pydantic import BaseModel 8 | 9 | 10 | # use str to store the path, because Path may not serializable on Windows 11 | class TaskStatus(BaseModel): 12 | done: bool = False 13 | bt_downloaded_path: Optional[str] = None 14 | finalrip_downloaded_path: Optional[str] = None 15 | posted: bool = False 16 | ex_status_dict: Optional[Dict[str, Any]] = None 17 | 18 | 19 | class AsyncJsonStore: 20 | """ 21 | a simple JSON store for task status. 22 | 23 | :param file_path: Path to the JSON file. 24 | """ 25 | 26 | def __init__(self, file_path: Union[str, Path] = "store.json") -> None: 27 | self.file_path = Path(file_path) 28 | self.lock = asyncio.Lock() # 使用 asyncio.Lock 确保线程安全 29 | self.data: Dict[str, TaskStatus] = self.load_data() 30 | 31 | def load_data(self) -> Dict[str, TaskStatus]: 32 | """ 33 | Load data from the JSON file. 34 | """ 35 | if self.file_path.exists(): 36 | with open(self.file_path, "r", encoding="utf-8") as file: 37 | try: 38 | j = json.load(file) 39 | except json.JSONDecodeError: 40 | return {} 41 | 42 | return {task_id: TaskStatus(**task) for task_id, task in j.items()} 43 | return {} 44 | 45 | async def save_data(self) -> None: 46 | """ 47 | Save data to the JSON file. 48 | """ 49 | with open(self.file_path, "w", encoding="utf-8") as file: 50 | # convert TaskStatus objects to dictionaries 51 | data = {task_id: task.model_dump() for task_id, task in self.data.items()} 52 | json.dump(data, file, ensure_ascii=False, indent=4) 53 | 54 | async def check_task_exist(self, task_id: str) -> bool: 55 | """ 56 | Check if a task exists. 57 | 58 | :param task_id: Task ID to check. 59 | """ 60 | async with self.lock: 61 | return task_id in self.data 62 | 63 | async def add_task(self, task_id: str, status: TaskStatus) -> None: 64 | """ 65 | Add a task to the store. 66 | 67 | :param task_id: Task ID to add. 68 | :param status: Task status. 69 | """ 70 | async with self.lock: 71 | if task_id not in self.data: 72 | self.data[task_id] = status 73 | await self.save_data() 74 | else: 75 | raise KeyError(f"Task with ID '{task_id}' already exists.") 76 | 77 | async def get_task(self, task_id: str) -> TaskStatus: 78 | """ 79 | Get a task by its ID. 80 | 81 | :param task_id: Task ID to get. 82 | """ 83 | async with self.lock: 84 | if task_id in self.data: 85 | task = deepcopy(self.data.get(task_id)) 86 | if task is None: 87 | raise ValueError("Task value is None!") 88 | return task 89 | else: 90 | raise KeyError(f"Task with ID '{task_id}' not found.") 91 | 92 | async def update_task(self, task_id: str, status: TaskStatus) -> None: 93 | """ 94 | Update a task's status and details. 95 | 96 | :param task_id: Task ID to update. 97 | :param status: New status. 98 | """ 99 | async with self.lock: 100 | if task_id in self.data: 101 | self.data[task_id] = status 102 | await self.save_data() 103 | else: 104 | raise KeyError(f"Task with ID '{task_id}' not found.") 105 | 106 | async def delete_task(self, task_id: str) -> None: 107 | """ 108 | Delete a task by its ID. 109 | 110 | :param task_id: Task ID to delete. 111 | """ 112 | async with self.lock: 113 | if task_id in self.data: 114 | del self.data[task_id] 115 | await self.save_data() 116 | else: 117 | raise KeyError(f"Task with ID '{task_id}' not found.") 118 | -------------------------------------------------------------------------------- /animepipeline/mediainfo/mediainfo.py: -------------------------------------------------------------------------------- 1 | import json 2 | from datetime import datetime 3 | from pathlib import Path 4 | from typing import List, Tuple, Union 5 | 6 | import pymediainfo 7 | from loguru import logger 8 | 9 | from animepipeline.mediainfo.type import MediaInfo 10 | 11 | 12 | def get_media_info(video_path: Union[str, Path]) -> MediaInfo: 13 | """ 14 | Get the mini media info of the video file 15 | 16 | :param video_path: 17 | """ 18 | logger.info(f"Get media info of {video_path}...") 19 | 20 | video_path = Path(video_path) 21 | 22 | encode_media_info = pymediainfo.MediaInfo.parse(video_path, output="JSON") 23 | encode_tracks = json.loads(encode_media_info)["media"]["track"] 24 | 25 | release_name = video_path.name 26 | 27 | try: 28 | release_date = datetime.strptime(encode_tracks[0]["Encoded_Date"], "%Y-%m-%d %H:%M:%S UTC") 29 | if release_date.year < 2020: 30 | raise ValueError("Wow, the release year < 2020, please check the file") 31 | except Exception as e: 32 | logger.warning(f'Failed to get "Encoded_Date" of {video_path}, set to current time, {e}') 33 | release_date = datetime.now() 34 | 35 | try: 36 | release_size = encode_tracks[0]["FileSize_String"] 37 | except Exception: 38 | logger.warning(f'Failed to get "FileSize_String" of {video_path}') 39 | release_size = encode_tracks[0]["FileSize"] 40 | release_size = round(int(release_size) / (1024 * 1024), 2) 41 | if release_size > 1000: 42 | release_size = round(release_size / 1024, 2) 43 | release_size = str(release_size) + " GiB" 44 | else: 45 | release_size = str(release_size) + " MiB" 46 | 47 | try: 48 | release_format = encode_tracks[0]["Format"] 49 | except Exception as e: 50 | logger.error(f'Failed to get "Format" of {video_path}, set to "Unknown", {e}') 51 | raise e 52 | 53 | try: 54 | overall_bitrate = encode_tracks[0]["OverallBitRate_String"] 55 | except Exception: 56 | logger.warning(f'Failed to get "OverallBitRate_String" of {video_path}') 57 | try: 58 | overall_bitrate = encode_tracks[0]["OverallBitRate"] 59 | overall_bitrate = round(int(overall_bitrate) / 1000, 2) 60 | if overall_bitrate > 10000: 61 | overall_bitrate = round(overall_bitrate / 1000, 2) 62 | if overall_bitrate > 1000: 63 | overall_bitrate = round(overall_bitrate / 1000, 2) 64 | overall_bitrate = str(overall_bitrate) + " Gb/s" 65 | else: 66 | overall_bitrate = str(overall_bitrate) + " Mb/s" 67 | else: 68 | overall_bitrate = str(overall_bitrate) + " kb/s" 69 | except Exception as e: 70 | logger.error(f'Failed to get "OverallBitRate" of {video_path}, set to "Unknown", {e}') 71 | raise e 72 | 73 | # VIDEO TRACK 74 | resolution = (0, 0) 75 | bit_depth = 0 76 | frame_rate = 0.0 77 | video_format = "Unknown" 78 | format_profile = "Unknown" 79 | 80 | video_track_id = 0 81 | try: 82 | for _, video_track in enumerate(encode_tracks): 83 | if video_track["@type"] == "Video": 84 | resolution = (int(video_track["Width"]), int(video_track["Height"])) 85 | bit_depth = int(video_track["BitDepth"]) 86 | frame_rate = float(video_track["FrameRate"]) 87 | video_format = video_track["Format"] 88 | format_profile = video_track["Format_Profile"] 89 | video_track_id += 1 90 | except Exception as e: 91 | logger.warning(f"Exceptional video track: {video_track_id} of {video_path}, {e}") 92 | 93 | if video_track_id != 1: 94 | logger.warning(f"There may be multiple video tracks or no video tracks, please check {video_path}") 95 | 96 | # AUDIO TRACK 97 | audios: List[Tuple[str, int, str]] = [] 98 | 99 | audio_track_id = 1 100 | try: 101 | for _, audio_track in enumerate(encode_tracks): 102 | if audio_track["@type"] == "Audio": 103 | language = audio_track.get("Language_String", audio_track.get("Language", "Ambiguous!!!")) 104 | audios.append((language, int(audio_track["Channels"]), audio_track["Format"])) 105 | audio_track_id += 1 106 | except Exception as e: 107 | logger.warning(f"Exceptional audio track: {audio_track_id} of {video_path}, {e}") 108 | 109 | # SUBTITLE TRACK 110 | subtitles: List[Tuple[str, str]] = [] 111 | 112 | subtitle_track_id = 1 113 | try: 114 | for _, subtitle_track in enumerate(encode_tracks): 115 | if subtitle_track["@type"] == "Text": 116 | language = subtitle_track.get("Language_String", subtitle_track.get("Language", "Ambiguous!!!")) 117 | subtitles.append((language, subtitle_track["Format"])) 118 | subtitle_track_id += 1 119 | except Exception as e: 120 | logger.warning(f"Exceptional subtitle track: {subtitle_track_id} of {video_path}, {e}") 121 | 122 | return MediaInfo( 123 | release_name=release_name, 124 | release_date=release_date, 125 | release_size=release_size, 126 | release_format=release_format, 127 | overall_bitrate=overall_bitrate, 128 | resolution=resolution, 129 | bit_depth=bit_depth, 130 | frame_rate=frame_rate, 131 | format=video_format, 132 | format_profile=format_profile, 133 | audios=audios, 134 | subtitles=subtitles, 135 | ) 136 | -------------------------------------------------------------------------------- /animepipeline/bt/qb.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import List, Optional, Tuple, Union 3 | 4 | import qbittorrentapi 5 | from loguru import logger 6 | from torrentool.torrent import Torrent 7 | 8 | from animepipeline.config import QBitTorrentConfig 9 | from animepipeline.util import ANNOUNCE_URLS, gen_magnet_link 10 | 11 | 12 | class QBittorrentManager: 13 | """ 14 | QBittorrent manager 15 | 16 | :param config: QBitTorrentConfig object 17 | """ 18 | 19 | def __init__(self, config: QBitTorrentConfig) -> None: 20 | self.client = qbittorrentapi.Client( 21 | host=config.host, 22 | port=config.port, 23 | username=config.username, 24 | password=config.password, 25 | ) 26 | 27 | self.download_path = config.download_path 28 | 29 | self.COMPLETE_STATES = ["uploading", "stalledUP", "pausedUP", "queuedUP"] 30 | 31 | def add_torrent( 32 | self, torrent_hash: str, torrent_url: Optional[str] = None, torrent_file_path: Optional[Union[str, Path]] = None 33 | ) -> None: 34 | """ 35 | Add a torrent to download, either from a magnet link or a torrent file 36 | 37 | :param torrent_hash: Torrent hash 38 | :param torrent_url: Torrent URL, defaults to None, in which case a magnet link will be generated 39 | :param torrent_file_path: Torrent file path, defaults to None 40 | """ 41 | if self.check_torrent_exist(torrent_hash): 42 | logger.warning(f"Torrent {torrent_hash} already exists.") 43 | return 44 | 45 | if torrent_file_path is None: 46 | # add fron torrent url 47 | if torrent_url is None: 48 | torrent_url = gen_magnet_link(torrent_hash) 49 | 50 | try: 51 | self.client.torrents.add(urls=torrent_url) 52 | logger.info(f"Torrent {torrent_url} added for download.") 53 | except Exception as e: 54 | logger.error(f"Failed to add torrent: {e}") 55 | else: 56 | # add from torrent file path 57 | if not Path(torrent_file_path).exists(): 58 | logger.error(f"Torrent file {torrent_file_path} does not exist.") 59 | return 60 | 61 | with open(torrent_file_path, "rb") as f: 62 | torrent_file = f.read() 63 | 64 | try: 65 | self.client.torrents.add(torrent_files=torrent_file) 66 | logger.info(f"Torrent {torrent_file_path} added for download.") 67 | except Exception as e: 68 | logger.error(f"Failed to add torrent: {e}") 69 | 70 | def check_download_complete(self, torrent_hash: str) -> bool: 71 | """ 72 | Check if the download is complete 73 | 74 | :param torrent_hash: Torrent hash 75 | """ 76 | 77 | try: 78 | torrent = self.client.torrents_info(torrent_hashes=torrent_hash) 79 | # logger.debug(f"Torrent state: {torrent[0].state}") 80 | if torrent[0].state in self.COMPLETE_STATES: 81 | return True 82 | else: 83 | return False 84 | 85 | except Exception as e: 86 | logger.error(f"Error checking download status: {e}") 87 | return False 88 | 89 | def get_downloaded_path(self, torrent_hash: str) -> Optional[Path]: 90 | """ 91 | Get the downloaded path of the torrent, only return the largest file if multiple files are present. 92 | 93 | :param torrent_hash: 94 | """ 95 | try: 96 | torrent = self.client.torrents_info(torrent_hashes=torrent_hash) 97 | 98 | if torrent[0].state in self.COMPLETE_STATES: 99 | file_list: List[Tuple[str, int]] = [(file["name"], file["size"]) for file in torrent[0].files] 100 | file_list.sort(key=lambda x: x[1], reverse=True) 101 | return Path(file_list[0][0]) 102 | 103 | else: 104 | return None 105 | 106 | except Exception as e: 107 | logger.error(f"Error getting filename: {e}") 108 | return None 109 | 110 | def check_torrent_exist(self, torrent_hash: str) -> bool: 111 | """ 112 | Check if the torrent exists in the download list 113 | 114 | :param torrent_hash: Torrent hash 115 | """ 116 | try: 117 | torrent = self.client.torrents_info(torrent_hashes=torrent_hash) 118 | return len(torrent) > 0 119 | 120 | except Exception as e: 121 | logger.error(f"Error checking torrent existence: {e}") 122 | return False 123 | 124 | @staticmethod 125 | def make_torrent_file(file_path: Union[str, Path], torrent_file_save_path: Union[str, Path]) -> str: 126 | """ 127 | Make a torrent file from a file, return the hash of the torrent 128 | 129 | :param file_path: File path 130 | :param torrent_file_save_path: Torrent file save path 131 | """ 132 | if not Path(file_path).exists(): 133 | logger.error(f"File {file_path} does not exist.") 134 | raise FileNotFoundError(f"File {file_path} does not exist.") 135 | 136 | new_torrent = Torrent.create_from(file_path) 137 | logger.info(f"Editing torrent file: {file_path} ...") 138 | new_torrent.private = False 139 | new_torrent.announce_urls = ANNOUNCE_URLS 140 | new_torrent.comment = "Created by EutropicAI/AnimePipeline" 141 | new_torrent.created_by = "EutropicAI" 142 | new_torrent.to_file(torrent_file_save_path) 143 | 144 | return new_torrent.info_hash 145 | -------------------------------------------------------------------------------- /animepipeline/template/template.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import List, Optional, Union 3 | 4 | from animepipeline.template.bangumi import get_bangumi_info 5 | from animepipeline.template.mediainfo import get_media_info_block 6 | from animepipeline.util import gen_magnet_link 7 | 8 | 9 | def get_telegram_text(chinese_name: str, episode: int, file_name: str, torrent_file_hash: str) -> str: 10 | """ 11 | Get telegram text. 12 | 13 | :param chinese_name: Chinese name 14 | :param episode: Episode 15 | :param file_name: File name 16 | :param torrent_file_hash: Torrent file hash 17 | """ 18 | telegram_text = f""" 19 | ✈️ -----> 正在出种... 20 | {chinese_name} | EP {str(episode).zfill(2)} 21 | {file_name} 22 | 🧲 磁力链接 | Magnet Link: 23 | 24 | {gen_magnet_link(torrent_file_hash)} 25 | 26 | """ 27 | return telegram_text 28 | 29 | 30 | class PostTemplate: 31 | def __init__( 32 | self, 33 | video_path: Union[str, Path], 34 | bangumi_url: str, 35 | chinese_name: Optional[str] = None, 36 | uploader: str = "EutropicAI", 37 | announcement: Optional[str] = None, 38 | adivertisement_images: Optional[List[str]] = None, 39 | ) -> None: 40 | """ 41 | Initialize post template. 42 | 43 | :param video_path: Video path 44 | :param bangumi_url: Bangumi URL 45 | :param chinese_name: Chinese name, default is None (auto fetch from bangumi_url) 46 | :param uploader: Uploader 47 | :param announcement: Announcement string 48 | :param adivertisement_images: Adivertisement images, required at least 3 images, Recruitment, Telegram Group, Telegram Channel images 49 | """ 50 | if adivertisement_images is not None and len(adivertisement_images) < 3: 51 | raise ValueError( 52 | "Adivertisement images required at least 3 images, Recruitment, Telegram Group, Telegram Channel images" 53 | ) 54 | 55 | self.video_path = video_path 56 | self.uploader = uploader 57 | 58 | self.media_info_block = get_media_info_block(video_path=self.video_path, uploader=self.uploader) 59 | 60 | self.bangumi_url = bangumi_url 61 | self.summary, self.chinese_name = get_bangumi_info(bangumi_url=self.bangumi_url, chinese_name=chinese_name) 62 | 63 | if announcement is not None: 64 | self.announcement = announcement 65 | else: 66 | self.announcement = """片源来源于网络,感谢原资源提供者! 67 | 本资源使用 FinalRip 分布式压制。 68 | 69 | Resources are from the internet, thanks to the original providers! 70 | Using FinalRip for distributed video processing.""" 71 | 72 | if adivertisement_images is not None: 73 | self.adivertisement_images = adivertisement_images 74 | else: 75 | # 招新海报,电报群,电报频道 76 | self.adivertisement_images = [ 77 | "https://raw.githubusercontent.com/EutropicAI/.github/refs/heads/main/EutropicAI%E6%8B%9B%E6%96%B0.jpg", 78 | "https://raw.githubusercontent.com/EutropicAI/.github/refs/heads/main/EutropicAI%E7%94%B5%E6%8A%A5%E7%BE%A4.png", 79 | "https://raw.githubusercontent.com/EutropicAI/.github/refs/heads/main/EutropicAI%E7%94%B5%E6%8A%A5%E9%A2%91%E9%81%93.png", 80 | ] 81 | 82 | def html(self) -> str: 83 | return f""" 84 |
{self.announcement}
87 | Story:
90 |{self.summary}
91 | {self.media_info_block}
94 |