├── .dockerignore
├── .github
└── workflows
│ ├── CI-docker.yml
│ ├── CI-test-cli.yml
│ ├── CI-test.yml
│ └── Release.yml
├── .gitignore
├── .pre-commit-config.yaml
├── Dockerfile
├── LICENSE
├── Makefile
├── README.md
├── animepipeline
├── __init__.py
├── __main__.py
├── bt
│ ├── __init__.py
│ └── qb.py
├── cli
│ ├── README.md
│ ├── __init__.py
│ ├── btf
│ │ ├── __init__.py
│ │ └── __main__.py
│ └── rename
│ │ ├── __init__.py
│ │ └── __main__.py
├── config
│ ├── __init__.py
│ ├── rss.py
│ └── server.py
├── encode
│ ├── __init__.py
│ ├── finalrip.py
│ └── type.py
├── loop.py
├── mediainfo
│ ├── __init__.py
│ ├── mediainfo.py
│ ├── name.py
│ └── type.py
├── pool
│ ├── __init__.py
│ └── task.py
├── post
│ ├── __init__.py
│ └── tg.py
├── rss
│ ├── __init__.py
│ ├── nyaa.py
│ └── type.py
├── store
│ ├── __init__.py
│ └── task.py
├── template
│ ├── __init__.py
│ ├── bangumi.py
│ ├── mediainfo.py
│ └── template.py
└── util
│ ├── __init__.py
│ ├── bt.py
│ └── video.py
├── assets
└── test_144p.mp4
├── conf
├── params
│ └── default.txt
├── rss.yml
├── scripts
│ └── default.py
└── server.yml
├── deploy
├── docker-compose-animepipeline.yml
└── docker-compose-dev.yml
├── poetry.lock
├── pyproject.toml
└── tests
├── __init__.py
├── test_bt.py
├── test_config.py
├── test_encode.py
├── test_loop.py
├── test_mediainfo.py
├── test_pool.py
├── test_rss.py
├── test_store.py
├── test_template.py
├── test_tg.py
└── util.py
/.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 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/.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/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 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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/__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 |
--------------------------------------------------------------------------------
/animepipeline/bt/__init__.py:
--------------------------------------------------------------------------------
1 | from animepipeline.bt.qb import QBittorrentManager # noqa
2 |
--------------------------------------------------------------------------------
/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/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 |
--------------------------------------------------------------------------------
/animepipeline/cli/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EutropicAI/AnimePipeline/943c84797492f04a0ef2e5fbca261d0911eed406/animepipeline/cli/__init__.py
--------------------------------------------------------------------------------
/animepipeline/cli/btf/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EutropicAI/AnimePipeline/943c84797492f04a0ef2e5fbca261d0911eed406/animepipeline/cli/btf/__init__.py
--------------------------------------------------------------------------------
/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/cli/rename/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EutropicAI/AnimePipeline/943c84797492f04a0ef2e5fbca261d0911eed406/animepipeline/cli/rename/__init__.py
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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/config/rss.py:
--------------------------------------------------------------------------------
1 | import os
2 | from pathlib import Path
3 | from typing import Any, Dict, List, Optional, Union
4 |
5 | import yaml
6 | from pydantic import AnyUrl, BaseModel, DirectoryPath, FilePath, ValidationError
7 |
8 |
9 | class BaseConfig(BaseModel):
10 | uploader: str
11 | script: str
12 | param: str
13 | slice: Optional[bool] = True
14 | timeout: Optional[int] = 20
15 | queue: Optional[str] = "priority"
16 |
17 |
18 | class NyaaConfig(BaseModel):
19 | name: str
20 | translation: str
21 | bangumi: Union[str, AnyUrl]
22 | link: Union[str, AnyUrl]
23 | pattern: str
24 | uploader: Optional[str] = None
25 | script: Optional[str] = None
26 | param: Optional[str] = None
27 | slice: Optional[bool] = None
28 | timeout: Optional[int] = None
29 | queue: Optional[str] = None
30 |
31 |
32 | class RSSConfig(BaseModel):
33 | base: BaseConfig
34 | nyaa: List[NyaaConfig]
35 | scripts: Dict[str, str]
36 | params: Dict[str, str]
37 |
38 | config_path: Optional[FilePath] = None
39 | scripts_path: Optional[DirectoryPath] = None
40 | params_path: Optional[DirectoryPath] = None
41 |
42 | @classmethod
43 | def from_yaml(
44 | cls,
45 | path: Union[Path, str],
46 | scripts_path: Optional[Union[Path, str]] = None,
47 | params_path: Optional[Union[Path, str]] = None,
48 | ) -> Any:
49 | """
50 | Load configuration from a YAML file.
51 |
52 | :param path: The path to the yaml file.
53 | :param scripts_path: The path to the folder containing scripts files (xx.py).
54 | :param params_path: The path to the folder containing params files (xx.txt).
55 | """
56 | if not os.path.exists(path):
57 | raise FileNotFoundError(f"Config file {path} not found")
58 | with open(path, "r", encoding="utf-8") as file:
59 | try:
60 | config_data = yaml.safe_load(file)
61 | except yaml.YAMLError as e:
62 | raise ValueError(f"Error loading YAML: {e}")
63 | except ValidationError as e:
64 | raise ValueError(f"Config validation error: {e}")
65 | except Exception as e:
66 | raise ValueError(f"Error loading config: {e}")
67 |
68 | def _gen_dict(folder_path: Union[Path, str]) -> Dict[str, str]:
69 | """
70 | Generate a dictionary from the files in the folder. file_name -> file_content.
71 |
72 | :param folder_path: The path to the folder.
73 | """
74 | if not os.path.exists(folder_path):
75 | raise FileNotFoundError(f"Folder {folder_path} not found")
76 | res = {}
77 | for _file in os.listdir(folder_path):
78 | with open(os.path.join(folder_path, _file), "r", encoding="utf-8") as f:
79 | res[_file] = f.read()
80 |
81 | # remove newline symbol at the end
82 | # cuz the encode param will be passed to the server, that will directly "param" + "encode.mkv"
83 | # if there is a newline symbol at the end, the server will not find the file
84 | if res[_file].endswith("\n"):
85 | res[_file] = res[_file][:-1]
86 | elif res[_file].endswith("\r\n"):
87 | res[_file] = res[_file][:-2]
88 | elif res[_file].endswith("\r"):
89 | res[_file] = res[_file][:-1]
90 |
91 | return res
92 |
93 | if scripts_path is None:
94 | scripts_path = os.path.join(os.path.dirname(path), "scripts")
95 |
96 | if params_path is None:
97 | params_path = os.path.join(os.path.dirname(path), "params")
98 |
99 | config_data["scripts"] = _gen_dict(scripts_path)
100 | config_data["params"] = _gen_dict(params_path)
101 |
102 | config = cls(**config_data)
103 |
104 | # validate the config
105 | # base
106 | if config.base.script not in config.scripts:
107 | raise ValueError(f"base: script {config.base.script} not found")
108 |
109 | if config.base.param not in config.params:
110 | raise ValueError(f"base: param {config.base.param} not found")
111 |
112 | # nyaa
113 | for item in config.nyaa:
114 | if item.uploader is None:
115 | item.uploader = config.base.uploader
116 |
117 | if item.slice is None:
118 | item.slice = config.base.slice
119 |
120 | if item.timeout is None:
121 | item.timeout = config.base.timeout
122 |
123 | if item.queue is None:
124 | item.queue = config.base.queue
125 |
126 | if item.script is None:
127 | item.script = config.base.script
128 | else:
129 | if item.script not in config.scripts:
130 | raise ValueError(f"nyaa: script {item.script} not found")
131 |
132 | if item.param is None:
133 | item.param = config.base.param
134 | else:
135 | if item.param not in config.params:
136 | raise ValueError(f"nyaa: param {item.param} not found")
137 |
138 | config.config_path = Path(path)
139 | config.scripts_path = Path(scripts_path)
140 | config.params_path = Path(params_path)
141 |
142 | return config
143 |
144 | def refresh_config(self) -> None:
145 | """
146 | Refresh configuration from the yaml file.
147 | """
148 | try:
149 | if self.config_path is None:
150 | raise ValueError("No configuration file path provided")
151 | new_config = RSSConfig.from_yaml(self.config_path, self.scripts_path, self.params_path)
152 | except Exception as e:
153 | print(f"Failed to load new configuration: {e}")
154 | return
155 |
156 | self.base = new_config.base
157 | self.nyaa = new_config.nyaa
158 | self.scripts = new_config.scripts
159 | self.params = new_config.params
160 |
--------------------------------------------------------------------------------
/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/encode/__init__.py:
--------------------------------------------------------------------------------
1 | from animepipeline.encode.finalrip import FinalRipClient # noqa
2 |
--------------------------------------------------------------------------------
/animepipeline/encode/finalrip.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import gc
3 | import mimetypes
4 | import time
5 | from pathlib import Path
6 | from typing import Optional, Union
7 |
8 | import httpx
9 | from httpx import AsyncClient
10 | from loguru import logger
11 | from tenacity import retry, stop_after_attempt, wait_random
12 |
13 | from animepipeline.config import FinalRipConfig
14 | from animepipeline.encode.type import (
15 | GetTaskProgressRequest,
16 | GetTaskProgressResponse,
17 | NewTaskRequest,
18 | NewTaskResponse,
19 | OSSPresignedURLRequest,
20 | OSSPresignedURLResponse,
21 | PingResponse,
22 | RetryMergeRequest,
23 | RetryMergeResponse,
24 | StartTaskRequest,
25 | StartTaskResponse,
26 | TaskNotCompletedError,
27 | )
28 | from animepipeline.util.video import VIDEO_EXTENSIONS
29 |
30 |
31 | class FinalRipClient:
32 | def __init__(self, config: FinalRipConfig):
33 | self.client = AsyncClient(base_url=str(config.url), headers={"token": str(config.token)}, timeout=30)
34 |
35 | async def ping(self) -> PingResponse:
36 | try:
37 | response = await self.client.get("/")
38 | return PingResponse(**response.json())
39 | except Exception as e:
40 | logger.error(f"Error ping: {e}")
41 | raise e
42 |
43 | async def _new_task(self, data: NewTaskRequest) -> NewTaskResponse:
44 | try:
45 | response = await self.client.post("/api/v1/task/new", params=data.model_dump())
46 | return NewTaskResponse(**response.json())
47 | except Exception as e:
48 | logger.error(f"Error creating task: {e}, {data}")
49 | raise e
50 |
51 | async def _start_task(self, data: StartTaskRequest) -> StartTaskResponse:
52 | try:
53 | response = await self.client.post("/api/v1/task/start", params=data.model_dump())
54 | return StartTaskResponse(**response.json())
55 | except Exception as e:
56 | logger.error(f"Error starting task: {e}, {data}")
57 | raise e
58 |
59 | async def _get_task_progress(self, data: GetTaskProgressRequest) -> GetTaskProgressResponse:
60 | try:
61 | response = await self.client.get("/api/v1/task/progress", params=data.model_dump())
62 | return GetTaskProgressResponse(**response.json())
63 | except Exception as e:
64 | raise e
65 |
66 | async def _get_oss_presigned_url(self, data: OSSPresignedURLRequest) -> OSSPresignedURLResponse:
67 | try:
68 | response = await self.client.get("/api/v1/task/oss/presigned", params=data.model_dump())
69 | return OSSPresignedURLResponse(**response.json())
70 | except Exception as e:
71 | logger.error(f"Error getting presigned URL: {e}, {data}")
72 | raise e
73 |
74 | async def _retry_merge(self, data: RetryMergeRequest) -> RetryMergeResponse:
75 | try:
76 | response = await self.client.post("/api/v1/task/retry/merge", params=data.model_dump())
77 | return RetryMergeResponse(**response.json())
78 | except Exception as e:
79 | logger.error(f"Error retrying merge: {e}, {data}")
80 | raise e
81 |
82 | async def check_task_exist(self, video_key: str) -> bool:
83 | try:
84 | get_task_progress_response = await self._get_task_progress(GetTaskProgressRequest(video_key=video_key))
85 | return get_task_progress_response.success
86 | except Exception:
87 | return False
88 |
89 | async def check_task_completed(self, video_key: str) -> bool:
90 | try:
91 | get_task_progress_response = await self._get_task_progress(GetTaskProgressRequest(video_key=video_key))
92 | if not get_task_progress_response.success:
93 | logger.error(f"Error getting task progress: {get_task_progress_response.error.message}") # type: ignore
94 | return False
95 | return get_task_progress_response.data.encode_url != "" # type: ignore
96 | except Exception as e:
97 | logger.error(f"Error checking task completed: {e}, video_key: {video_key}")
98 | return False
99 |
100 | async def check_task_all_clips_done(self, video_key: str) -> bool:
101 | try:
102 | get_task_progress_response = await self._get_task_progress(GetTaskProgressRequest(video_key=video_key))
103 | if not get_task_progress_response.success:
104 | logger.error(f"Error getting task progress: {get_task_progress_response.error.message}") # type: ignore
105 | return False
106 |
107 | for clip in get_task_progress_response.data.progress: # type: ignore
108 | if not clip.completed:
109 | return False
110 |
111 | return True
112 | except Exception as e:
113 | logger.error(f"Error checking task all clips done: {e}, video_key: {video_key}")
114 | return False
115 |
116 | async def retry_merge(self, video_key: str) -> None:
117 | retry_merge_response = await self._retry_merge(RetryMergeRequest(video_key=video_key))
118 | if not retry_merge_response.success:
119 | logger.error(f"Error retrying merge: {retry_merge_response.error.message}") # type: ignore
120 |
121 | @retry(wait=wait_random(min=3, max=5), stop=stop_after_attempt(5))
122 | async def upload_and_new_task(self, video_path: Union[str, Path]) -> None:
123 | """
124 | use file name as video_key, gen oss presigned url, upload file, and new_task, all in one function
125 |
126 | :param video_path: local video file path
127 | """
128 | if not Path(video_path).exists():
129 | logger.error(f"File not found: {video_path}")
130 | raise FileNotFoundError(f"File not found: {video_path}")
131 |
132 | if Path(video_path).suffix not in VIDEO_EXTENSIONS:
133 | logger.error(f"Only support these video extensions: {', '.join(VIDEO_EXTENSIONS)}")
134 | raise ValueError("Only support these video extensions: " + ", ".join(VIDEO_EXTENSIONS))
135 |
136 | # gen oss presigned url
137 | video_key = Path(video_path).name
138 | try:
139 | oss_presigned_url_response = await self._get_oss_presigned_url(OSSPresignedURLRequest(video_key=video_key))
140 | if not oss_presigned_url_response.success:
141 | logger.error(f"Error getting presigned URL: {oss_presigned_url_response.error.message}") # type: ignore
142 | raise ValueError(f"Error getting presigned URL: {oss_presigned_url_response.error.message}") # type: ignore
143 | except Exception as e:
144 | logger.error(f"Error getting presigned URL: {e}")
145 | raise e
146 |
147 | if not oss_presigned_url_response.data.exist: # type: ignore
148 | try:
149 | content_type = mimetypes.guess_type(video_path)[0]
150 | except Exception:
151 | content_type = "application/octet-stream"
152 |
153 | # upload file
154 | try:
155 | logger.info(f"Uploading file: {video_path}")
156 | t0 = time.time()
157 |
158 | # 这里不要用异步,会内存泄漏
159 | def _upload_file() -> None:
160 | with open(video_path, mode="rb") as v:
161 | video_content = v.read()
162 | logger.info(f"Read file Successfully! path: {video_path} time: {time.time() - t0:.2f}s")
163 | response = httpx.put(
164 | url=oss_presigned_url_response.data.url, # type: ignore
165 | content=video_content,
166 | headers={"Content-Type": content_type},
167 | timeout=60 * 60,
168 | )
169 | if response.status_code != 200:
170 | raise IOError(f"Error uploading file: {response.text}")
171 |
172 | _upload_file()
173 | del _upload_file
174 | gc.collect()
175 | logger.info(f"Upload file Successfully! path: {video_path} time: {time.time() - t0:.2f}s")
176 | except Exception as e:
177 | logger.error(f"Error in uploading file: {video_path}: {e}")
178 | raise e
179 |
180 | await asyncio.sleep(2)
181 |
182 | # new task
183 | new_task_response = await self._new_task(NewTaskRequest(video_key=video_key))
184 | if not new_task_response.success:
185 | logger.error(f"Error creating task: {new_task_response.error.message}") # type: ignore
186 |
187 | async def start_task(
188 | self,
189 | video_key: str,
190 | encode_param: str,
191 | script: str,
192 | slice: Optional[bool] = True,
193 | timeout: Optional[int] = 20,
194 | queue: Optional[str] = "priority",
195 | ) -> None:
196 | """
197 | start encode task
198 |
199 | :param video_key: video_key of the task
200 | :param encode_param: encode param
201 | :param script: encode script
202 | :param slice: cut video into clips or not
203 | :param timeout: clip timeout, default 20 minutes
204 | :param queue: queue name, default is "priority"
205 | """
206 | resp = await self._start_task(
207 | StartTaskRequest(
208 | video_key=video_key, encode_param=encode_param, script=script, slice=slice, timeout=timeout, queue=queue
209 | )
210 | )
211 | if not resp.success:
212 | logger.warning(f"Failed to start finalrip task: {resp.error.message}") # type: ignore
213 |
214 | async def download_completed_task(self, video_key: str, save_path: Union[str, Path]) -> None:
215 | """
216 | download completed task to local
217 |
218 | :param video_key: video_key of the task
219 | :param save_path: local save path
220 | """
221 | if not await self.check_task_completed(video_key):
222 | raise TaskNotCompletedError()
223 |
224 | get_task_progress_response = await self._get_task_progress(GetTaskProgressRequest(video_key=video_key))
225 |
226 | try:
227 | logger.info(f"Downloading completed task: {save_path} ...")
228 | t0 = time.time()
229 |
230 | def _download_file() -> None:
231 | with open(save_path, mode="wb") as v:
232 | response = httpx.get(
233 | url=get_task_progress_response.data.encode_url, # type: ignore
234 | timeout=60 * 60,
235 | )
236 | if response.status_code != 200:
237 | raise IOError(f"Error downloading file: {response.text}")
238 | v.write(response.content)
239 |
240 | _download_file()
241 | del _download_file
242 | gc.collect()
243 | logger.info(f"Download completed task Successfully! path: {save_path}, time: {time.time() - t0:.2f}s")
244 | except Exception as e:
245 | logger.error(f"Error in downloading completed task: {save_path}: {e}")
246 | raise e
247 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/animepipeline/loop.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | from pathlib import Path
3 | from typing import Any, Callable, Coroutine, List, Optional
4 |
5 | from loguru import logger
6 | from pydantic import DirectoryPath
7 |
8 | from animepipeline.bt import QBittorrentManager
9 | from animepipeline.config import NyaaConfig, RSSConfig, ServerConfig
10 | from animepipeline.encode import FinalRipClient
11 | from animepipeline.mediainfo import FileNameInfo, rename_file
12 | from animepipeline.pool import AsyncTaskExecutor
13 | from animepipeline.post import TGChannelSender
14 | from animepipeline.rss import TorrentInfo, parse_nyaa
15 | from animepipeline.store import AsyncJsonStore, TaskStatus
16 | from animepipeline.template import PostTemplate, get_telegram_text
17 |
18 |
19 | class TaskInfo(TorrentInfo):
20 | download_path: DirectoryPath
21 | uploader: str
22 | script_content: str
23 | param_content: str
24 | slice: Optional[bool] = True
25 | timeout: Optional[int] = 20
26 | queue: Optional[str] = "priority"
27 |
28 |
29 | def build_task_info(
30 | torrent_info: TorrentInfo, nyaa_config: NyaaConfig, rss_config: RSSConfig, server_config: ServerConfig
31 | ) -> TaskInfo:
32 | """
33 | Build TaskInfo from TorrentInfo, NyaaConfig and RSSConfig
34 |
35 | :param torrent_info: TorrentInfo
36 | :param nyaa_config: NyaaConfig
37 | :param rss_config: RSSConfig
38 | :param server_config: ServerConfig
39 | :return: TaskInfo
40 | """
41 | if nyaa_config.script not in rss_config.scripts:
42 | raise ValueError(f"script not found: {nyaa_config.script}")
43 | if nyaa_config.param not in rss_config.params:
44 | raise ValueError(f"param not found: {nyaa_config.param}")
45 |
46 | script_content = rss_config.scripts[nyaa_config.script]
47 | param_content = rss_config.params[nyaa_config.param]
48 |
49 | return TaskInfo(
50 | **torrent_info.model_dump(),
51 | download_path=server_config.qbittorrent.download_path,
52 | uploader=nyaa_config.uploader,
53 | script_content=script_content,
54 | param_content=param_content,
55 | slice=nyaa_config.slice,
56 | timeout=nyaa_config.timeout,
57 | queue=nyaa_config.queue,
58 | )
59 |
60 |
61 | class Loop:
62 | """
63 | Loop: main loop for animepipeline
64 |
65 | :param server_config: an instance of ServerConfig
66 | :param rss_config: an instance of RSSConfig
67 | :param json_store: an instance of AsyncJsonStore
68 | """
69 |
70 | def __init__(self, server_config: ServerConfig, rss_config: RSSConfig, json_store: AsyncJsonStore):
71 | self.stop_event = asyncio.Event()
72 |
73 | self.server_config = server_config
74 | self.rss_config = rss_config
75 |
76 | self.json_store = json_store
77 |
78 | self.task_executor = AsyncTaskExecutor() # async task pool
79 |
80 | self.qbittorrent_manager = QBittorrentManager(config=self.server_config.qbittorrent)
81 |
82 | self.finalrip_client = FinalRipClient(config=self.server_config.finalrip)
83 |
84 | self.tg_channel_sender = (
85 | TGChannelSender(config=self.server_config.telegram) if self.server_config.telegram.enable else None
86 | )
87 |
88 | self.pipeline_tasks: List[Callable[[TaskInfo], Coroutine[Any, Any, None]]] = []
89 | self.add_pipeline_task()
90 |
91 | async def stop(self) -> None:
92 | """
93 | Stop the loop
94 | """
95 | self.stop_event.set()
96 | await self.task_executor.shutdown()
97 | logger.warning("Loop stopped successfully!")
98 |
99 | async def start(self) -> None:
100 | """
101 | Start the loop
102 | """
103 | while not self.stop_event.is_set():
104 | # refresh rss config
105 | self.rss_config.refresh_config()
106 | for cfg in self.rss_config.nyaa:
107 | try:
108 | torrent_info_list = parse_nyaa(cfg)
109 | except Exception as e:
110 | logger.error(f"Failed to parse nyaa for {cfg.name}: {e}")
111 | continue
112 |
113 | for torrent_info in torrent_info_list:
114 | task_info = build_task_info(
115 | torrent_info=torrent_info,
116 | nyaa_config=cfg,
117 | rss_config=self.rss_config,
118 | server_config=self.server_config,
119 | )
120 |
121 | await self.task_executor.submit_task(torrent_info.hash, self.pipeline, task_info)
122 |
123 | await asyncio.sleep(self.server_config.loop.interval)
124 |
125 | def add_pipeline_task(self) -> None:
126 | """
127 | Add pipeline task to the loop
128 |
129 | """
130 | self.pipeline_tasks.append(self.pipeline_bt)
131 | self.pipeline_tasks.append(self.pipeline_finalrip)
132 | self.pipeline_tasks.append(self.pipeline_post)
133 |
134 | async def pipeline(self, task_info: TaskInfo) -> None:
135 | # init task status
136 | if not await self.json_store.check_task_exist(task_info.hash):
137 | await self.json_store.add_task(task_id=task_info.hash, status=TaskStatus())
138 |
139 | task_status = await self.json_store.get_task(task_info.hash)
140 | if task_status.done:
141 | return
142 |
143 | logger.info(f'Start pipeline for "{task_info.name}" EP {task_info.episode}')
144 |
145 | # pipeline tasks
146 | for pipeline_task in self.pipeline_tasks:
147 | await pipeline_task(task_info)
148 |
149 | # Done!
150 | task_status = await self.json_store.get_task(task_info.hash) # update task_status!!!!!!!!
151 | task_status.done = True
152 | await self.json_store.update_task(task_info.hash, task_status)
153 | logger.info(f'Finish pipeline for "{task_info.name}" EP {task_info.episode}')
154 |
155 | async def pipeline_bt(self, task_info: TaskInfo) -> None:
156 | task_status = await self.json_store.get_task(task_info.hash)
157 |
158 | # check bt
159 | if task_status.bt_downloaded_path is not None:
160 | return
161 |
162 | logger.info(f'Start BT download for "{task_info.name}" EP {task_info.episode}')
163 | # download torrent file
164 | while not self.qbittorrent_manager.check_torrent_exist(task_info.hash):
165 | self.qbittorrent_manager.add_torrent(torrent_hash=task_info.hash, torrent_url=task_info.link) # type: ignore
166 | await asyncio.sleep(10)
167 |
168 | # check download complete
169 | while not self.qbittorrent_manager.check_download_complete(task_info.hash):
170 | await asyncio.sleep(10)
171 |
172 | # get downloaded path
173 | bt_downloaded_path = self.qbittorrent_manager.get_downloaded_path(task_info.hash)
174 |
175 | # update task status
176 | task_status.bt_downloaded_path = str(bt_downloaded_path)
177 | await self.json_store.update_task(task_info.hash, task_status)
178 |
179 | async def pipeline_finalrip(self, task_info: TaskInfo) -> None:
180 | task_status = await self.json_store.get_task(task_info.hash)
181 |
182 | # check finalrip
183 | if task_status.finalrip_downloaded_path is not None:
184 | return
185 |
186 | if task_status.bt_downloaded_path is None:
187 | logger.error("BT download path is None! bt download task not finished?")
188 | raise ValueError("BT download path is None! bt download task not finished?")
189 |
190 | logger.info(f'Start FinalRip Encode for "{task_info.name}" EP {task_info.episode}')
191 | # start finalrip task
192 |
193 | bt_downloaded_path = Path(task_info.download_path) / task_status.bt_downloaded_path
194 |
195 | while not await self.finalrip_client.check_task_exist(bt_downloaded_path.name):
196 | try:
197 | await self.finalrip_client.upload_and_new_task(bt_downloaded_path)
198 | logger.info(f'FinalRip Task Created for "{task_info.name}" EP {task_info.episode}')
199 | except Exception as e:
200 | logger.error(f"Failed to upload and new finalrip task: {e}")
201 | await asyncio.sleep(10)
202 |
203 | try:
204 | await self.finalrip_client.start_task(
205 | video_key=bt_downloaded_path.name,
206 | encode_param=task_info.param_content,
207 | script=task_info.script_content,
208 | slice=task_info.slice,
209 | timeout=task_info.timeout,
210 | queue=task_info.queue,
211 | )
212 | logger.info(f'FinalRip Task Started for "{task_info.name}" EP {task_info.episode}')
213 | except Exception as e:
214 | logger.error(f"Failed to start FinalRip task: {e}")
215 |
216 | # check task progress
217 | while not await self.finalrip_client.check_task_completed(bt_downloaded_path.name):
218 | await asyncio.sleep(30)
219 | logger.info(f'FinalRip encode task completed for "{task_info.name}" EP {task_info.episode}')
220 |
221 | # download temp file to bt_downloaded_path's parent directory
222 | temp_saved_path: Path = bt_downloaded_path.parent / (bt_downloaded_path.name + "-encoded.mkv")
223 | await self.finalrip_client.download_completed_task(video_key=bt_downloaded_path.name, save_path=temp_saved_path)
224 |
225 | # rename temp file
226 | try:
227 | finalrip_downloaded_path = rename_file(
228 | FileNameInfo(
229 | path=temp_saved_path,
230 | episode=task_info.episode,
231 | name=task_info.name,
232 | uploader=task_info.uploader,
233 | type="WEBRip",
234 | )
235 | )
236 | except Exception as e:
237 | logger.error(f"Failed to generate file name: {e}")
238 | raise e
239 |
240 | logger.info(f'FinalRip Encode Done for "{finalrip_downloaded_path.name}"')
241 |
242 | # update task status
243 | task_status.finalrip_downloaded_path = finalrip_downloaded_path.name
244 | await self.json_store.update_task(task_info.hash, task_status)
245 |
246 | async def pipeline_post(self, task_info: TaskInfo) -> None:
247 | task_status = await self.json_store.get_task(task_info.hash)
248 |
249 | # check posted
250 | if task_status.posted:
251 | return
252 |
253 | if task_status.finalrip_downloaded_path is None:
254 | logger.error("FinalRip download path is None! finalrip download task not finished?")
255 | raise ValueError("FinalRip download path is None! finalrip download task not finished?")
256 |
257 | finalrip_downloaded_path = Path(task_info.download_path) / task_status.finalrip_downloaded_path
258 | torrent_file_save_path = Path(task_info.download_path) / (str(finalrip_downloaded_path.name) + ".torrent")
259 |
260 | try:
261 | torrent_file_hash = QBittorrentManager.make_torrent_file(
262 | file_path=finalrip_downloaded_path,
263 | torrent_file_save_path=torrent_file_save_path,
264 | )
265 | logger.info(f"Torrent file created: {torrent_file_save_path}, hash: {torrent_file_hash}")
266 | except Exception as e:
267 | logger.error(f"Failed to create torrent file: {e}")
268 | raise e
269 |
270 | self.qbittorrent_manager.add_torrent(torrent_hash=torrent_file_hash, torrent_file_path=torrent_file_save_path)
271 |
272 | logger.info(f"Generate all post info files for {task_info.name} EP {task_info.episode} ...")
273 |
274 | try:
275 | post_template = PostTemplate(
276 | video_path=finalrip_downloaded_path,
277 | bangumi_url=task_info.bangumi, # type: ignore
278 | chinese_name=task_info.translation,
279 | uploader="EutropicAI",
280 | )
281 |
282 | post_template.save(
283 | html_path=Path(task_info.download_path) / (finalrip_downloaded_path.name + ".html"),
284 | markdown_path=Path(task_info.download_path) / (finalrip_downloaded_path.name + ".md"),
285 | bbcode_path=Path(task_info.download_path) / (finalrip_downloaded_path.name + ".txt"),
286 | )
287 | except Exception as e:
288 | logger.error(f"Failed to generate post info files: {e}")
289 |
290 | logger.info(f"Post to Telegram Channel for {task_info.name} EP {task_info.episode} ...")
291 |
292 | if self.tg_channel_sender is None:
293 | logger.info("Telegram Channel Sender is not enabled. Skip upload.")
294 | else:
295 | tg_text = get_telegram_text(
296 | chinese_name=task_info.translation,
297 | episode=task_info.episode,
298 | file_name=finalrip_downloaded_path.name,
299 | torrent_file_hash=torrent_file_hash,
300 | )
301 | await self.tg_channel_sender.send_text(text=tg_text)
302 |
303 | # update task status
304 | task_status.posted = True
305 | await self.json_store.update_task(task_info.hash, task_status)
306 |
--------------------------------------------------------------------------------
/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/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/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/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 |
--------------------------------------------------------------------------------
/animepipeline/pool/__init__.py:
--------------------------------------------------------------------------------
1 | from animepipeline.pool.task import AsyncTaskExecutor
2 |
3 | TASK_EXECUTOR = AsyncTaskExecutor()
4 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/animepipeline/post/__init__.py:
--------------------------------------------------------------------------------
1 | from animepipeline.post.tg import TGChannelSender # noqa
2 |
--------------------------------------------------------------------------------
/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/__init__.py:
--------------------------------------------------------------------------------
1 | from animepipeline.rss.nyaa import parse_nyaa # noqa
2 | from animepipeline.rss.type import TorrentInfo # noqa
3 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/animepipeline/store/__init__.py:
--------------------------------------------------------------------------------
1 | from animepipeline.store.task import AsyncJsonStore, TaskStatus # noqa
2 |
--------------------------------------------------------------------------------
/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/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 |
--------------------------------------------------------------------------------
/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/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 |
--------------------------------------------------------------------------------
/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 |
85 |
Announcement:
86 |
{self.announcement}
87 |
88 |
{self.chinese_name}
89 |
Story:
90 |
{self.summary}
91 |
92 |
MediaInfo:
93 |
{self.media_info_block}
94 |
95 |

96 |
97 |
98 |

99 |

100 |
101 |
102 | """
103 |
104 | def markdown(self) -> str:
105 | return f"""### Announcement:
106 | ```
107 | {self.announcement}
108 | ```
109 |
110 | ### {self.chinese_name}
111 | Story:
112 | {self.summary}
113 |
114 | ### MediaInfo:
115 | ```
116 | {self.media_info_block}
117 | ```
118 |
119 | [招新链接 | Recruitment Link]({self.adivertisement_images[0]})
120 |
121 | [电报群链接 | Telegram Group Link]({self.adivertisement_images[1]})
122 |
123 | [电报频道链接 | Telegram Channel Link]({self.adivertisement_images[2]})
124 | """
125 |
126 | def bbcode(self) -> str:
127 | advertisement_images_block = "\n".join(
128 | [f"[url={url}][img]{url}[/img][/url]" for url in self.adivertisement_images]
129 | )
130 |
131 | return f"""[quote][b]Announcement:[size=3]
132 | {self.announcement}
133 | [/size]
134 | [/b][/quote]
135 |
136 | [b][size=4]{self.chinese_name}[/size][/b]
137 | [b]Story: [/b]
138 | {self.summary}
139 |
140 | [quote][font=Courier New]
141 | [b]MediaInfo: [/b]
142 | {self.media_info_block}
143 | [/font][/quote]
144 |
145 | {advertisement_images_block}
146 | """
147 |
148 | def save(
149 | self,
150 | html_path: Optional[Union[str, Path]],
151 | markdown_path: Optional[Union[str, Path]],
152 | bbcode_path: Optional[Union[str, Path]],
153 | ) -> None:
154 | """
155 | Save the post template to file.
156 |
157 | :param html_path: HTML file path
158 | :param markdown_path: Markdown file path
159 | :param bbcode_path: BBCode file path
160 | """
161 | if html_path is not None:
162 | with open(html_path, "w", encoding="utf-8") as f:
163 | f.write(self.html())
164 |
165 | if markdown_path is not None:
166 | with open(markdown_path, "w", encoding="utf-8") as f:
167 | f.write(self.markdown())
168 |
169 | if bbcode_path is not None:
170 | with open(bbcode_path, "w", encoding="utf-8") as f:
171 | f.write(self.bbcode())
172 |
--------------------------------------------------------------------------------
/animepipeline/util/__init__.py:
--------------------------------------------------------------------------------
1 | from animepipeline.util.bt import gen_magnet_link, ANNOUNCE_URLS # noqa
2 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/assets/test_144p.mp4:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EutropicAI/AnimePipeline/943c84797492f04a0ef2e5fbca261d0911eed406/assets/test_144p.mp4
--------------------------------------------------------------------------------
/conf/params/default.txt:
--------------------------------------------------------------------------------
1 | ffmpeg -i - -vcodec libx264 -preset ultrafast
2 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EutropicAI/AnimePipeline/943c84797492f04a0ef2e5fbca261d0911eed406/tests/__init__.py
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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_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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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_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 |
--------------------------------------------------------------------------------
/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/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 |
--------------------------------------------------------------------------------