├── log
└── README.md
├── utils
├── __init__.py
├── config.py
├── models.py
├── logger.py
├── common.py
└── video_generate.py
├── 1.双击我启动程序.bat
├── requirements.txt
├── static
├── imgs
│ ├── 1.png
│ └── 2.png
├── audios
│ ├── 1.mp3
│ └── 2.mp3
├── videos
│ ├── 1.mp4
│ └── 2.mp4
└── index.html
├── tests
├── musetalk.py
├── anitalker.py
├── genefaceplusplus.py
├── test.py
├── sadtalker.py
└── linly_talker.py
├── config.json
├── .gitignore
├── requirements_common.txt
├── README.md
├── api_server.py
└── LICENSE
/log/README.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/utils/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1.双击我启动程序.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 | Miniconda3\python.exe api_server.py
3 |
4 | cmd /k
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | # quart
2 | selenium
3 | gradio_client==1.2.0
4 | colorlog
5 | fastapi
--------------------------------------------------------------------------------
/static/imgs/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Ikaros-521/digital_human_video_player/HEAD/static/imgs/1.png
--------------------------------------------------------------------------------
/static/imgs/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Ikaros-521/digital_human_video_player/HEAD/static/imgs/2.png
--------------------------------------------------------------------------------
/static/audios/1.mp3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Ikaros-521/digital_human_video_player/HEAD/static/audios/1.mp3
--------------------------------------------------------------------------------
/static/audios/2.mp3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Ikaros-521/digital_human_video_player/HEAD/static/audios/2.mp3
--------------------------------------------------------------------------------
/static/videos/1.mp4:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Ikaros-521/digital_human_video_player/HEAD/static/videos/1.mp4
--------------------------------------------------------------------------------
/static/videos/2.mp4:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Ikaros-521/digital_human_video_player/HEAD/static/videos/2.mp4
--------------------------------------------------------------------------------
/tests/musetalk.py:
--------------------------------------------------------------------------------
1 | # gradio_client-0.16.3
2 | from gradio_client import Client, file
3 |
4 | client = Client("http://127.0.0.1:7860/")
5 | result = client.predict(
6 | audio_path=file('F:\\MuseTalk\\data\\audio\\yongen.wav'),
7 | video_path={"video":file('F:\\MuseTalk\data\\video\\yongen.mp4')},
8 | bbox_shift=0,
9 | api_name="/inference"
10 | )
11 | print(result)
--------------------------------------------------------------------------------
/tests/anitalker.py:
--------------------------------------------------------------------------------
1 | # gradio_client==1.2.0
2 | from gradio_client import Client, handle_file
3 |
4 | client = Client("http://127.0.0.1:7860/")
5 | result = client.predict(
6 | face=handle_file('C:\\Users\\Administrator\\Pictures\\test\\1.png'),
7 | audio=handle_file('C:\\Users\\Administrator\\Pictures\\test\\2.mp3'),
8 | is_mor=False,
9 | face_d="0",
10 | api_name="/do_cloth"
11 | )
12 | print(result["video"])
--------------------------------------------------------------------------------
/utils/config.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | class Config:
4 | # 单例模式
5 | # _instance = None
6 | config = None
7 |
8 | # def __new__(cls, *args, **kwargs):
9 | # if not cls._instance:
10 | # cls._instance = super(Config, cls).__new__(cls) # 不再传递 *args, **kwargs
11 | # return cls._instance
12 |
13 | def __init__(self, config_file):
14 | if self.config is None:
15 | with open(config_file, 'r', encoding="utf-8") as f:
16 | self.config = json.load(f)
17 |
18 | def get(self, *keys):
19 | result = self.config
20 | for key in keys:
21 | result = result.get(key, None)
22 | if result is None:
23 | break
24 | return result
25 |
--------------------------------------------------------------------------------
/utils/models.py:
--------------------------------------------------------------------------------
1 | from pydantic import BaseModel, Field
2 | from typing import List, Dict, Any, Optional
3 |
4 | class ShowMessage(BaseModel):
5 | type: str
6 | video_path: str
7 | audio_path: str
8 | captions_printer: Optional[dict] = Field(None)
9 | insert_index: int
10 | move_file: Optional[bool] = Field(None)
11 |
12 | class DelVideoWithIndexMessage(BaseModel):
13 | index: int
14 |
15 | class GetNonDefaultVideoCountResult(BaseModel):
16 | code: int
17 | message: str
18 | count: int
19 |
20 | class GetVideoQueueResult(BaseModel):
21 | code: int
22 | data: list
23 | message: str
24 |
25 | class SetConfigMessage(BaseModel):
26 | captions_printer_api_url: Optional[str] = Field(None)
27 |
28 | """
29 | 通用
30 | """
31 | class CommonResult(BaseModel):
32 | code: int
33 | message: str
34 | data: Optional[Dict[str, Any]] = None
35 |
--------------------------------------------------------------------------------
/utils/logger.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import colorlog
3 |
4 | def Configure_logger(log_file):
5 | log_format = '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
6 | color_format = '%(log_color)s%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s%(reset)s'
7 |
8 | logger = logging.getLogger()
9 | logger.setLevel(logging.INFO)
10 |
11 | # 创建一个处理程序
12 | handler = logging.FileHandler(log_file, encoding='utf-8', mode='a+')
13 |
14 | handlers = [handler]
15 |
16 | # 创建控制台处理程序并设置颜色
17 | console = colorlog.StreamHandler()
18 | console.setFormatter(colorlog.ColoredFormatter(
19 | color_format,
20 | datefmt='%Y-%m-%d %H:%M:%S',
21 | log_colors={
22 | 'DEBUG': 'cyan',
23 | 'INFO': 'white', # 将INFO的颜色设置为白色
24 | 'WARNING': 'yellow',
25 | 'ERROR': 'red',
26 | 'CRITICAL': 'red,bg_white',
27 | }
28 | ))
29 | handlers.append(console)
30 |
31 | logger.handlers = handlers
32 |
33 | formatter = colorlog.ColoredFormatter(
34 | color_format,
35 | datefmt='%Y-%m-%d %H:%M:%S'
36 | )
37 |
38 | # 将处理程序添加到记录器,并设置格式化器
39 | handler.setFormatter(formatter)
--------------------------------------------------------------------------------
/tests/genefaceplusplus.py:
--------------------------------------------------------------------------------
1 | from gradio_client import Client
2 |
3 | client = Client("http://127.0.0.1:7860/")
4 | result = client.predict(
5 | "C:\\Users\\Administrator\\Pictures\\test\\2.mp3", # filepath in 'Input audio (required)' Audio component
6 | "period", # Literal['none', 'period'] in '眨眼模式' Radio component
7 | 0, # float (numeric value between 0.0 and 1.0) in 'temperature' Slider component
8 | 0, # float (numeric value between 0.0 and 1.0) in 'lle_percent' Slider component
9 | 0.4, # float (numeric value between 0.0 and 1.0) in '嘴部幅度' Slider component
10 | 0.01, # float (numeric value between 0.0 and 0.1) in 'ray marching end-threshold' Slider component
11 | False, # bool in 'fp16模式:是否使用并加速推理' Checkbox component
12 | [["checkpoints", "audio2motion_vae", "model_ckpt_steps_400000.ckpt"]], # List[List[str]] in 'audio2secc model ckpt path or directory' Fileexplorer component
13 | [], # List[List[str]] in '(optional) pose net model ckpt path or directory' Fileexplorer component
14 | [], # List[List[str]] in '(按需) 选择人物头部模型(如果选择了躯干模型,该选项将被忽略)' Fileexplorer component
15 | [["checkpoints", "motion2video_nerf", "May_torso", "model_ckpt_steps_250000.ckpt"]], # List[List[str]] in '选择人物躯干模型' Fileexplorer component
16 | False, # bool in '低内存使用模式:以较低的推理速度为代价节省内存。在运行长音频合成视频时很有用。' Checkbox component
17 | api_name="/infer_once_args"
18 | )
19 | print(result)
--------------------------------------------------------------------------------
/tests/test.py:
--------------------------------------------------------------------------------
1 | from gradio_client import Client
2 |
3 | client = Client("http://127.0.0.1:7860/")
4 | result = client.predict(
5 | "C:\\Users\\Administrator\\Pictures\\test\\1.png", # filepath in '支持图片、视频格式' File component
6 | "C:\\Users\\Administrator\\Pictures\\test\\2.mp3", # filepath in '支持mp3、wav格式' Audio component
7 | "Enhanced", # Literal['Fast', 'Improved', 'Enhanced', 'Experimental'] in '视频质量选项' Radio component
8 | "full resolution", # Literal['full resolution', 'half resolution'] in '分辨率选项' Radio component
9 | "Wav2Lip", # Literal['Wav2Lip', 'Wav2Lip_GAN'] in 'Wav2Lip版本选项' Radio component
10 | "True", # Literal['True', 'False'] in '启用追踪旧数据' Radio component
11 | "True", # Literal['True', 'False'] in '启用脸部平滑' Radio component
12 | 0, # float (numeric value between -100 and 100) in '嘴部mask上边缘' Slider component
13 | 10, # float (numeric value between -100 and 100) in '嘴部mask下边缘' Slider component
14 | 20, # float (numeric value between -100 and 100) in '嘴部mask左边缘' Slider component
15 | 0, # float (numeric value between -100 and 100) in '嘴部mask右边缘' Slider component
16 | 2.05, # float (numeric value between -10 and 10) in 'mask尺寸' Slider component
17 | 5, # float (numeric value between -100 and 100) in 'mask羽化' Slider component
18 | "True", # Literal['True', 'False'] in '启用mask嘴部跟踪' Radio component
19 | "False", # Literal['True', 'False'] in '启用mask调试' Radio component
20 | "False", # Literal['False'] in '批量处理多个视频' Radio component
21 | api_name="/execute_pipeline"
22 | )
23 | print(result)
--------------------------------------------------------------------------------
/tests/sadtalker.py:
--------------------------------------------------------------------------------
1 | from gradio_client import Client
2 |
3 | #client = Client("http://127.0.0.1:7860/")
4 | # result = client.predict(
5 | # "C:\\Users\\Administrator\\Pictures\\test\\1.png", # filepath in 'Source image' Image component
6 | # "C:\\Users\\Administrator\\Pictures\\test\\2.mp3", # filepath in 'Input audio' Audio component
7 | # "crop", # Literal[crop, resize, full, extcrop, extfull] in 'preprocess' Radio component
8 | # True, # bool in 'Still Mode (fewer head motion, works with preprocess `full`)' Checkbox component
9 | # True, # bool in 'GFPGAN as Face enhancer' Checkbox component
10 | # 2, # float (numeric value between 0 and 10) in 'batch size in generation' Slider component
11 | # 256, # Literal[256, 512] in 'face model resolution' Radio component
12 | # 0, # float (numeric value between 0 and 46) in 'Pose style' Slider component
13 | # api_name="/test"
14 | # )
15 |
16 | client = Client("https://--.westc.gpuhub.com:8443/")
17 | result = client.predict(
18 | "C:\\Users\\Administrator\\Pictures\\test\\1.png", # filepath in 'Source image' Image component
19 | "C:\\Users\\Administrator\\Pictures\\test\\2.mp3", # filepath in 'Input audio' Audio component
20 | "crop", # Literal[crop, resize, full, extcrop, extfull] in 'preprocess' Radio component
21 | True, # bool in 'Still Mode (fewer head motion, works with preprocess `full`)' Checkbox component
22 | True, # bool in 'GFPGAN as Face enhancer' Checkbox component
23 | 2, # float (numeric value between 0 and 10) in 'batch size in generation' Slider component
24 | 256, # Literal[256, 512] in 'face model resolution' Radio component
25 | 0, # float (numeric value between 0 and 46) in 'Pose style' Slider component
26 | fn_index=1
27 | )
28 | print(result)
--------------------------------------------------------------------------------
/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "server_ip": "127.0.0.1",
3 | "server_port": 8091,
4 | "default_video": "./videos/long_video.mp4",
5 | "video_read_path": "static/test/*.mp4",
6 | "auto_del_video": false,
7 | "easy_wav2lip": {
8 | "api_ip_port": "http://127.0.0.1:7860",
9 | "video_file": "E:\\GitHub_pro\\digital_human_video_player\\static\\imgs\\1.png",
10 | "quality": "Fast",
11 | "output_height": "full resolution",
12 | "wav2lip_version": "Wav2Lip",
13 | "use_previous_tracking_data": "True",
14 | "nosmooth": "True",
15 | "u": 0,
16 | "d": 10,
17 | "l": 20,
18 | "r": 0,
19 | "size": 2.05,
20 | "feathering": 5,
21 | "mouth_tracking": "True",
22 | "debug_mask": "False",
23 | "batch_process": "False"
24 | },
25 | "sadtalker": {
26 | "gradio_api_type": "fn_index",
27 | "api_ip_port": "http://127.0.0.1:7860",
28 | "img_file": "E:\\GitHub_pro\\digital_human_video_player\\static\\imgs\\2.png",
29 | "preprocess": "crop",
30 | "still_mode": false,
31 | "GFPGAN": false,
32 | "batch_size": 2,
33 | "face_model_resolution": 256,
34 | "pose_style": 0
35 | },
36 | "genefaceplusplus": {
37 | "api_ip_port": "http://127.0.0.1:7860",
38 | "blink_mode": "period",
39 | "temperature": 0,
40 | "lle_percent": 0,
41 | "mouth_amplitude": 0.4,
42 | "ray_marching_end_threshold": 0.01,
43 | "fp16": false,
44 | "audio2secc_model": [["checkpoints", "audio2motion_vae", "model_ckpt_steps_400000.ckpt"]],
45 | "pose_net_model": [],
46 | "head_model": [],
47 | "body_model": [["checkpoints", "motion2video_nerf", "May_torso", "model_ckpt_steps_250000.ckpt"]],
48 | "low_memory_mode": false
49 | },
50 | "musetalk": {
51 | "api_ip_port": "http://127.0.0.1:7860",
52 | "video_path": "E:\\GitHub_pro\\digital_human_video_player\\static\\videos\\3.mp4",
53 | "bbox_shift": 0
54 | },
55 | "anitalker": {
56 | "api_ip_port": "http://127.0.0.1:7860",
57 | "img_file": "E:\\GitHub_pro\\digital_human_video_player\\static\\imgs\\2.png",
58 | "is_mor": false,
59 | "face_d": 0
60 | }
61 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | #db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
105 | __pypackages__/
106 |
107 | # Celery stuff
108 | celerybeat-schedule
109 | celerybeat.pid
110 |
111 | # SageMath parsed files
112 | *.sage.py
113 |
114 | # Environments
115 | .env
116 | .venv
117 | env/
118 | venv/
119 | ENV/
120 | env.bak/
121 | venv.bak/
122 |
123 | # Spyder project settings
124 | .spyderproject
125 | .spyproject
126 |
127 | # Rope project settings
128 | .ropeproject
129 |
130 | # mkdocs documentation
131 | /site
132 |
133 | # mypy
134 | .mypy_cache/
135 | .dmypy.json
136 | dmypy.json
137 |
138 | # Pyre type checker
139 | .pyre/
140 |
141 | # pytype static type analyzer
142 | .pytype/
143 |
144 | # Cython debug symbols
145 | cython_debug/
146 |
147 | # PyCharm
148 | # JetBrains specific template is maintainted in a separate JetBrains.gitignore that can
149 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
150 | # and can be added to the global gitignore or merged into this file. For a more nuclear
151 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
152 | #.idea/
153 |
154 | Miniconda3/
155 |
156 | log/*.txt
157 |
158 | static/videos/*.mp4
159 |
160 | pkg/
161 |
162 | video_player.py
163 |
164 | static/test
165 |
166 | output/
167 |
168 | static/index copy.html
169 | static/index copy 2.html
170 |
171 | api_server copy.py
172 |
173 | static/videos/*.mp4
174 |
--------------------------------------------------------------------------------
/requirements_common.txt:
--------------------------------------------------------------------------------
1 | aiofiles==23.2.1
2 | altgraph==0.17.4
3 | annotated-types==0.7.0
4 | anyio==4.3.0
5 | attrs==23.2.0
6 | auto-py-to-exe==2.43.3
7 | blinker==1.7.0
8 | boltons @ file:///C:/b/abs_707eo7c09t/croot/boltons_1677628723117/work
9 | bottle==0.12.25
10 | bottle-websocket==0.2.9
11 | brotlipy==0.7.0
12 | certifi @ file:///C:/b/abs_85o_6fm0se/croot/certifi_1671487778835/work/certifi
13 | cffi @ file:///C:/b/abs_49n3v2hyhr/croot/cffi_1670423218144/work
14 | charset-normalizer @ file:///tmp/build/80754af9/charset-normalizer_1630003229654/work
15 | click==8.1.7
16 | colorama @ file:///C:/b/abs_a9ozq0l032/croot/colorama_1672387194846/work
17 | colorlog==6.8.2
18 | conda==23.3.1
19 | conda-content-trust @ file:///C:/Windows/TEMP/abs_4589313d-fc62-4ccc-81c0-b801b4449e833j1ajrwu/croots/recipe/conda-content-trust_1658126379362/work
20 | conda-package-handling @ file:///C:/b/abs_fcga8w0uem/croot/conda-package-handling_1672865024290/work
21 | conda_package_streaming @ file:///C:/b/abs_0e5n5hdal3/croot/conda-package-streaming_1670508162902/work
22 | cryptography @ file:///C:/b/abs_8ecplyc3n2/croot/cryptography_1677533105000/work
23 | dnspython==2.6.1
24 | Eel==0.16.0
25 | email_validator==2.2.0
26 | exceptiongroup==1.2.0
27 | fastapi==0.111.0
28 | fastapi-cli==0.0.4
29 | filelock==3.13.1
30 | Flask==3.0.2
31 | fsspec==2024.2.0
32 | future==1.0.0
33 | gevent==24.2.1
34 | gevent-websocket==0.10.1
35 | gradio_client==1.2.0
36 | greenlet==3.0.3
37 | h11==0.14.0
38 | h2==4.1.0
39 | hpack==4.0.0
40 | httpcore==1.0.4
41 | httptools==0.6.1
42 | httpx==0.27.0
43 | huggingface-hub==0.21.4
44 | Hypercorn==0.16.0
45 | hyperframe==6.0.1
46 | idna @ file:///C:/b/abs_bdhbebrioa/croot/idna_1666125572046/work
47 | itsdangerous==2.1.2
48 | Jinja2==3.1.3
49 | jsonpatch @ file:///tmp/build/80754af9/jsonpatch_1615747632069/work
50 | jsonpointer==2.1
51 | markdown-it-py==3.0.0
52 | MarkupSafe==2.1.5
53 | mdurl==0.1.2
54 | menuinst @ file:///C:/Users/BUILDE~1/AppData/Local/Temp/abs_455sf5o0ct/croots/recipe/menuinst_1661805970842/work
55 | orjson==3.10.5
56 | outcome==1.3.0.post0
57 | packaging @ file:///C:/b/abs_ed_kb9w6g4/croot/packaging_1678965418855/work
58 | pefile==2023.2.7
59 | pluggy @ file:///C:/ci/pluggy_1648042746254/work
60 | priority==2.0.0
61 | pycosat @ file:///C:/b/abs_4b1rrw8pn9/croot/pycosat_1666807711599/work
62 | pycparser @ file:///tmp/build/80754af9/pycparser_1636541352034/work
63 | pydantic==2.7.4
64 | pydantic_core==2.18.4
65 | Pygments==2.18.0
66 | pyinstaller==6.6.0
67 | pyinstaller-hooks-contrib==2024.4
68 | pyOpenSSL @ file:///C:/b/abs_552w85x1jz/croot/pyopenssl_1677607703691/work
69 | pyparsing==3.1.2
70 | PySocks @ file:///C:/ci_310/pysocks_1642089375450/work
71 | python-dotenv==1.0.1
72 | python-multipart==0.0.9
73 | pywin32-ctypes==0.2.2
74 | PyYAML==6.0.1
75 | Quart==0.19.4
76 | requests @ file:///C:/b/abs_80_edxtvhu/croot/requests_1678709752318/work
77 | rich==13.7.1
78 | ruamel.yaml @ file:///C:/b/abs_30ee5qbthd/croot/ruamel.yaml_1666304562000/work
79 | ruamel.yaml.clib @ file:///C:/b/abs_aarblxbilo/croot/ruamel.yaml.clib_1666302270884/work
80 | selenium==4.18.1
81 | shellingham==1.5.4
82 | six @ file:///tmp/build/80754af9/six_1644875935023/work
83 | sniffio==1.3.1
84 | sortedcontainers==2.4.0
85 | starlette==0.37.2
86 | taskgroup==0.0.0a4
87 | tomli==2.0.1
88 | toolz @ file:///C:/b/abs_cfvk6rc40d/croot/toolz_1667464080130/work
89 | tqdm @ file:///C:/b/abs_f76j9hg7pv/croot/tqdm_1679561871187/work
90 | trio==0.24.0
91 | trio-websocket==0.11.1
92 | typer==0.12.3
93 | typing_extensions==4.10.0
94 | ujson==5.10.0
95 | urllib3 @ file:///C:/b/abs_3ce53vrdcr/croot/urllib3_1680254693505/work
96 | uvicorn==0.30.1
97 | watchfiles==0.22.0
98 | websockets==11.0.3
99 | Werkzeug==3.0.1
100 | whichcraft==0.6.1
101 | win-inet-pton @ file:///C:/ci_310/win_inet_pton_1642658466512/work
102 | wincertstore==0.2
103 | wsproto==1.2.0
104 | zope.event==5.0
105 | zope.interface==6.3
106 | zstandard==0.19.0
107 |
--------------------------------------------------------------------------------
/utils/common.py:
--------------------------------------------------------------------------------
1 | # 导入所需的库
2 | import re, random, requests, json
3 | import time
4 | import os, shutil
5 | import logging
6 | from datetime import datetime
7 | from datetime import timedelta
8 | from datetime import timezone
9 | import traceback
10 |
11 | from urllib.parse import urlparse
12 |
13 |
14 | class Common:
15 | def __init__(self):
16 | self.count = 1
17 |
18 | """
19 | 数字操作
20 | """
21 |
22 | # 获取北京时间
23 | def get_bj_time(self, type=0):
24 | """获取北京时间
25 |
26 | Args:
27 | type (int, str): 返回时间类型. 默认为 0.
28 | 0 返回数据:年-月-日 时:分:秒
29 | 1 返回数据:年-月-日
30 | 2 返回数据:当前时间的秒
31 | 3 返回数据:自1970年1月1日以来的秒数
32 | 4 返回数据:根据调用次数计数到100循环
33 | 5 返回数据:当前 时点分
34 | 6 返回数据:当前时间的 时, 分
35 | 7 返回数据:年-月-日 时-分-秒 毫秒
36 |
37 | Returns:
38 | str: 返回指定格式的时间字符串
39 | int, int
40 | """
41 | if type == 0:
42 | utc_now = datetime.utcnow().replace(tzinfo=timezone.utc) # 获取当前 UTC 时间
43 | SHA_TZ = timezone(
44 | timedelta(hours=8),
45 | name='Asia/Shanghai',
46 | )
47 | beijing_now = utc_now.astimezone(SHA_TZ) # 将 UTC 时间转换为北京时间
48 | fmt = '%Y-%m-%d %H:%M:%S'
49 | now_fmt = beijing_now.strftime(fmt)
50 | return now_fmt
51 | elif type == 1:
52 | now = datetime.now() # 获取当前时间
53 | year = now.year # 获取当前年份
54 | month = now.month # 获取当前月份
55 | day = now.day # 获取当前日期
56 |
57 | return str(year) + "-" + str(month) + "-" + str(day)
58 | elif type == 2:
59 | now = time.localtime() # 获取当前时间
60 |
61 | # hour = now.tm_hour # 获取当前小时
62 | # minute = now.tm_min # 获取当前分钟
63 | second = now.tm_sec # 获取当前秒数
64 |
65 | return str(second)
66 | elif type == 3:
67 | current_time = time.time() # 返回自1970年1月1日以来的秒数
68 |
69 | return str(current_time)
70 | elif type == 4:
71 | self.count = (self.count % 100) + 1
72 |
73 | return str(self.count)
74 | elif type == 5:
75 | now = time.localtime() # 获取当前时间
76 |
77 | hour = now.tm_hour # 获取当前小时
78 | minute = now.tm_min # 获取当前分钟
79 |
80 | return str(hour) + "点" + str(minute) + "分"
81 | elif type == 6:
82 | now = time.localtime() # 获取当前时间
83 |
84 | hour = now.tm_hour # 获取当前小时
85 | minute = now.tm_min # 获取当前分钟
86 |
87 | return hour, minute
88 | elif type == 7:
89 | utc_now = datetime.utcnow().replace(tzinfo=timezone.utc) # 获取当前 UTC 时间
90 | SHA_TZ = timezone(
91 | timedelta(hours=8),
92 | name='Asia/Shanghai',
93 | )
94 | beijing_now = utc_now.astimezone(SHA_TZ) # 将 UTC 时间转换为北京时间
95 | fmt = '%Y-%m-%d %H-%M-%S %f'
96 | now_fmt = beijing_now.strftime(fmt)
97 | return now_fmt
98 |
99 |
100 |
101 | def move_and_rename(self, src_file_path, target_dir, new_filename=None, max_attempts=3, move_file=True):
102 | """
103 | 移动或复制文件到指定目录,可选地重命名文件。
104 |
105 | :param src_file_path: 源文件的完整路径
106 | :param target_dir: 目标目录的路径
107 | :param new_filename: 可选的新文件名(不包括目录路径)
108 | :param max_attempts: 最大重试次数(默认为3)
109 | :param move_file: 如果为True则移动文件,否则复制文件
110 | """
111 |
112 | # 确保目标目录存在
113 | if not os.path.exists(target_dir):
114 | os.makedirs(target_dir)
115 |
116 | # 如果提供了新文件名,则使用它;否则,保持文件的原始名称
117 | filename = new_filename if new_filename else os.path.basename(src_file_path)
118 | target_file_path = os.path.join(target_dir, filename)
119 | logging.debug(f"target_dir={target_dir}, target_file_path={target_file_path}")
120 |
121 | # 尝试移动或复制文件,如果文件被其他程序占用,则进行重试
122 | attempts = 0
123 | retry_delay = 0.5
124 |
125 | while attempts < max_attempts:
126 | try:
127 | # 如果源文件不存在,则直接返回False
128 | if not os.path.exists(src_file_path):
129 | logging.error(f"文件移动失败: 源文件{src_file_path}不存在")
130 | return False
131 |
132 | if move_file:
133 | shutil.move(src_file_path, target_file_path)
134 | logging.info(f"文件:{src_file_path} 已移动到:{target_file_path}")
135 | else:
136 | shutil.copy2(src_file_path, target_file_path)
137 | logging.info(f"文件:{src_file_path} 已复制到:{target_file_path}")
138 |
139 | return True
140 | except Exception as e:
141 | logging.error(f"文件操作失败: {e}")
142 | logging.info("重试中...")
143 | attempts += 1
144 | time.sleep(retry_delay)
145 |
146 | logging.warning(f"达到最大重试次数({max_attempts}),无法操作文件: {src_file_path}")
147 | return False
148 |
149 |
150 |
151 | def get_filename_with_ext(self, filepath):
152 | """
153 | 获取文件路径中的文件名,包括扩展名
154 |
155 | Args:
156 | filepath: 文件路径
157 |
158 | Returns:
159 | 文件名,包括扩展名
160 | """
161 | import os
162 |
163 | filename = os.path.basename(filepath)
164 | return filename
165 |
166 | # 识别操作系统
167 | def detect_os(self):
168 | """
169 | 识别操作系统
170 | """
171 | import platform
172 |
173 | system = platform.system()
174 | if system == 'Linux':
175 | return 'Linux'
176 | elif system == 'Windows':
177 | return 'Windows'
178 | elif system == 'Darwin':
179 | return 'MacOS'
180 |
181 | # 如果platform模块无法识别,则尝试使用os模块
182 | # system = os.name
183 | # if system == 'posix':
184 | # return '可能是Linux或MacOS'
185 | # elif system == 'nt':
186 | # return 'Windows'
187 |
188 | return '未知系统'
189 |
--------------------------------------------------------------------------------
/tests/linly_talker.py:
--------------------------------------------------------------------------------
1 | from gradio_client import Client, file
2 | import os
3 |
4 | client = Client("http://127.0.0.1:6006/")
5 |
6 | video_path = "C:\\Users\\Administrator\\Pictures\\test\\1.png"
7 |
8 | video_data = {
9 | "video": {
10 | "path": video_path,
11 | "orig_name": os.path.basename(video_path),
12 | "size": os.path.getsize(video_path),
13 | },
14 | "subtitles": None
15 | }
16 |
17 | result = client.predict(
18 | video_data, # Dict(video: filepath, subtitles: filepath | None) in 'Reference Video' Video component
19 | 3, # float in 'BBox_shift value, px' Number component
20 | "C:\\Users\\Administrator\\Pictures\\test\\2.mp3", # filepath in '语音对话' Audio component
21 | "Hello!!", # str in 'Input Text' Textbox component
22 | "zu-ZA-ThembaNeural", # Literal['zu-ZA-ThembaNeural', 'zu-ZA-ThandoNeural', 'zh-TW-YunJheNeural', 'zh-TW-HsiaoYuNeural', 'zh-TW-HsiaoChenNeural', 'zh-HK-WanLungNeural', 'zh-HK-HiuMaanNeural', 'zh-HK-HiuGaaiNeural', 'zh-CN-shaanxi-XiaoniNeural', 'zh-CN-liaoning-XiaobeiNeural', 'zh-CN-YunyangNeural', 'zh-CN-YunxiaNeural', 'zh-CN-YunxiNeural', 'zh-CN-YunjianNeural', 'zh-CN-XiaoyiNeural', 'zh-CN-XiaoxiaoNeural', 'vi-VN-NamMinhNeural', 'vi-VN-HoaiMyNeural', 'uz-UZ-SardorNeural', 'uz-UZ-MadinaNeural', 'ur-PK-UzmaNeural', 'ur-PK-AsadNeural', 'ur-IN-SalmanNeural', 'ur-IN-GulNeural', 'uk-UA-PolinaNeural', 'uk-UA-OstapNeural', 'tr-TR-EmelNeural', 'tr-TR-AhmetNeural', 'th-TH-PremwadeeNeural', 'th-TH-NiwatNeural', 'te-IN-ShrutiNeural', 'te-IN-MohanNeural', 'ta-SG-VenbaNeural', 'ta-SG-AnbuNeural', 'ta-MY-SuryaNeural', 'ta-MY-KaniNeural', 'ta-LK-SaranyaNeural', 'ta-LK-KumarNeural', 'ta-IN-ValluvarNeural', 'ta-IN-PallaviNeural', 'sw-TZ-RehemaNeural', 'sw-TZ-DaudiNeural', 'sw-KE-ZuriNeural', 'sw-KE-RafikiNeural', 'sv-SE-SofieNeural', 'sv-SE-MattiasNeural', 'su-ID-TutiNeural', 'su-ID-JajangNeural', 'sr-RS-SophieNeural', 'sr-RS-NicholasNeural', 'sq-AL-IlirNeural', 'sq-AL-AnilaNeural', 'so-SO-UbaxNeural', 'so-SO-MuuseNeural', 'sl-SI-RokNeural', 'sl-SI-PetraNeural', 'sk-SK-ViktoriaNeural', 'sk-SK-LukasNeural', 'si-LK-ThiliniNeural', 'si-LK-SameeraNeural', 'ru-RU-SvetlanaNeural', 'ru-RU-DmitryNeural', 'ro-RO-EmilNeural', 'ro-RO-AlinaNeural', 'pt-PT-RaquelNeural', 'pt-PT-DuarteNeural', 'pt-BR-ThalitaNeural', 'pt-BR-FranciscaNeural', 'pt-BR-AntonioNeural', 'ps-AF-LatifaNeural', 'ps-AF-GulNawazNeural', 'pl-PL-ZofiaNeural', 'pl-PL-MarekNeural', 'nl-NL-MaartenNeural', 'nl-NL-FennaNeural', 'nl-NL-ColetteNeural', 'nl-BE-DenaNeural', 'nl-BE-ArnaudNeural', 'ne-NP-SagarNeural', 'ne-NP-HemkalaNeural', 'nb-NO-PernilleNeural', 'nb-NO-FinnNeural', 'my-MM-ThihaNeural', 'my-MM-NilarNeural', 'mt-MT-JosephNeural', 'mt-MT-GraceNeural', 'ms-MY-YasminNeural', 'ms-MY-OsmanNeural', 'mr-IN-ManoharNeural', 'mr-IN-AarohiNeural', 'mn-MN-YesuiNeural', 'mn-MN-BataaNeural', 'ml-IN-SobhanaNeural', 'ml-IN-MidhunNeural', 'mk-MK-MarijaNeural', 'mk-MK-AleksandarNeural', 'lv-LV-NilsNeural', 'lv-LV-EveritaNeural', 'lt-LT-OnaNeural', 'lt-LT-LeonasNeural', 'lo-LA-KeomanyNeural', 'lo-LA-ChanthavongNeural', 'ko-KR-SunHiNeural', 'ko-KR-InJoonNeural', 'ko-KR-HyunsuNeural', 'kn-IN-SapnaNeural', 'kn-IN-GaganNeural', 'km-KH-SreymomNeural', 'km-KH-PisethNeural', 'kk-KZ-DauletNeural', 'kk-KZ-AigulNeural', 'ka-GE-GiorgiNeural', 'ka-GE-EkaNeural', 'jv-ID-SitiNeural', 'jv-ID-DimasNeural', 'ja-JP-NanamiNeural', 'ja-JP-KeitaNeural', 'it-IT-IsabellaNeural', 'it-IT-GiuseppeNeural', 'it-IT-ElsaNeural', 'it-IT-DiegoNeural', 'is-IS-GunnarNeural', 'is-IS-GudrunNeural', 'id-ID-GadisNeural', 'id-ID-ArdiNeural', 'hu-HU-TamasNeural', 'hu-HU-NoemiNeural', 'hr-HR-SreckoNeural', 'hr-HR-GabrijelaNeural', 'hi-IN-SwaraNeural', 'hi-IN-MadhurNeural', 'he-IL-HilaNeural', 'he-IL-AvriNeural', 'gu-IN-NiranjanNeural', 'gu-IN-DhwaniNeural', 'gl-ES-SabelaNeural', 'gl-ES-RoiNeural', 'ga-IE-OrlaNeural', 'ga-IE-ColmNeural', 'fr-FR-VivienneMultilingualNeural', 'fr-FR-RemyMultilingualNeural', 'fr-FR-HenriNeural', 'fr-FR-EloiseNeural', 'fr-FR-DeniseNeural', 'fr-CH-FabriceNeural', 'fr-CH-ArianeNeural', 'fr-CA-ThierryNeural', 'fr-CA-SylvieNeural', 'fr-CA-JeanNeural', 'fr-CA-AntoineNeural', 'fr-BE-GerardNeural', 'fr-BE-CharlineNeural', 'fil-PH-BlessicaNeural', 'fil-PH-AngeloNeural', 'fi-FI-NooraNeural', 'fi-FI-HarriNeural', 'fa-IR-FaridNeural', 'fa-IR-DilaraNeural', 'et-EE-KertNeural', 'et-EE-AnuNeural', 'es-VE-SebastianNeural', 'es-VE-PaolaNeural', 'es-UY-ValentinaNeural', 'es-UY-MateoNeural', 'es-US-PalomaNeural', 'es-US-AlonsoNeural', 'es-SV-RodrigoNeural', 'es-SV-LorenaNeural', 'es-PY-TaniaNeural', 'es-PY-MarioNeural', 'es-PR-VictorNeural', 'es-PR-KarinaNeural', 'es-PE-CamilaNeural', 'es-PE-AlexNeural', 'es-PA-RobertoNeural', 'es-PA-MargaritaNeural', 'es-NI-YolandaNeural', 'es-NI-FedericoNeural', 'es-MX-JorgeNeural', 'es-MX-DaliaNeural', 'es-HN-KarlaNeural', 'es-HN-CarlosNeural', 'es-GT-MartaNeural', 'es-GT-AndresNeural', 'es-GQ-TeresaNeural', 'es-GQ-JavierNeural', 'es-ES-XimenaNeural', 'es-ES-ElviraNeural', 'es-ES-AlvaroNeural', 'es-EC-LuisNeural', 'es-EC-AndreaNeural', 'es-DO-RamonaNeural', 'es-DO-EmilioNeural', 'es-CU-ManuelNeural', 'es-CU-BelkysNeural', 'es-CR-MariaNeural', 'es-CR-JuanNeural', 'es-CO-SalomeNeural', 'es-CO-GonzaloNeural', 'es-CL-LorenzoNeural', 'es-CL-CatalinaNeural', 'es-BO-SofiaNeural', 'es-BO-MarceloNeural', 'es-AR-TomasNeural', 'es-AR-ElenaNeural', 'en-ZA-LukeNeural', 'en-ZA-LeahNeural', 'en-US-SteffanNeural', 'en-US-RogerNeural', 'en-US-MichelleNeural', 'en-US-JennyNeural', 'en-US-GuyNeural', 'en-US-EricNeural', 'en-US-EmmaNeural', 'en-US-EmmaMultilingualNeural', 'en-US-ChristopherNeural', 'en-US-BrianNeural', 'en-US-BrianMultilingualNeural', 'en-US-AvaNeural', 'en-US-AvaMultilingualNeural', 'en-US-AriaNeural', 'en-US-AndrewNeural', 'en-US-AndrewMultilingualNeural', 'en-US-AnaNeural', 'en-TZ-ImaniNeural', 'en-TZ-ElimuNeural', 'en-SG-WayneNeural', 'en-SG-LunaNeural', 'en-PH-RosaNeural', 'en-PH-JamesNeural', 'en-NZ-MollyNeural', 'en-NZ-MitchellNeural', 'en-NG-EzinneNeural', 'en-NG-AbeoNeural', 'en-KE-ChilembaNeural', 'en-KE-AsiliaNeural', 'en-IN-PrabhatNeural', 'en-IN-NeerjaNeural', 'en-IN-NeerjaExpressiveNeural', 'en-IE-EmilyNeural', 'en-IE-ConnorNeural', 'en-HK-YanNeural', 'en-HK-SamNeural', 'en-GB-ThomasNeural', 'en-GB-SoniaNeural', 'en-GB-RyanNeural', 'en-GB-MaisieNeural', 'en-GB-LibbyNeural', 'en-CA-LiamNeural', 'en-CA-ClaraNeural', 'en-AU-WilliamNeural', 'en-AU-NatashaNeural', 'el-GR-NestorasNeural', 'el-GR-AthinaNeural', 'de-DE-SeraphinaMultilingualNeural', 'de-DE-KillianNeural', 'de-DE-KatjaNeural', 'de-DE-FlorianMultilingualNeural', 'de-DE-ConradNeural', 'de-DE-AmalaNeural', 'de-CH-LeniNeural', 'de-CH-JanNeural', 'de-AT-JonasNeural', 'de-AT-IngridNeural', 'da-DK-JeppeNeural', 'da-DK-ChristelNeural', 'cy-GB-NiaNeural', 'cy-GB-AledNeural', 'cs-CZ-VlastaNeural', 'cs-CZ-AntoninNeural', 'ca-ES-JoanaNeural', 'ca-ES-EnricNeural', 'bs-BA-VesnaNeural', 'bs-BA-GoranNeural', 'bn-IN-TanishaaNeural', 'bn-IN-BashkarNeural', 'bn-BD-PradeepNeural', 'bn-BD-NabanitaNeural', 'bg-BG-KalinaNeural', 'bg-BG-BorislavNeural', 'az-AZ-BanuNeural', 'az-AZ-BabekNeural', 'ar-YE-SalehNeural', 'ar-YE-MaryamNeural', 'ar-TN-ReemNeural', 'ar-TN-HediNeural', 'ar-SY-LaithNeural', 'ar-SY-AmanyNeural', 'ar-SA-ZariyahNeural', 'ar-SA-HamedNeural', 'ar-QA-MoazNeural', 'ar-QA-AmalNeural', 'ar-OM-AyshaNeural', 'ar-OM-AbdullahNeural', 'ar-MA-MounaNeural', 'ar-MA-JamalNeural', 'ar-LY-OmarNeural', 'ar-LY-ImanNeural', 'ar-LB-RamiNeural', 'ar-LB-LaylaNeural', 'ar-KW-NouraNeural', 'ar-KW-FahedNeural', 'ar-JO-TaimNeural', 'ar-JO-SanaNeural', 'ar-IQ-RanaNeural', 'ar-IQ-BasselNeural', 'ar-EG-ShakirNeural', 'ar-EG-SalmaNeural', 'ar-DZ-IsmaelNeural', 'ar-DZ-AminaNeural', 'ar-BH-LailaNeural', 'ar-BH-AliNeural', 'ar-AE-HamdanNeural', 'ar-AE-FatimaNeural', 'am-ET-MekdesNeural', 'am-ET-AmehaNeural', 'af-ZA-WillemNeural', 'af-ZA-AdriNeural'] in 'Voice' Dropdown component
23 | -100, # float (numeric value between -100 and 100) in 'Rate' Slider component
24 | 0, # float (numeric value between 0 and 100) in 'Volume' Slider component
25 | -100, # float (numeric value between -100 and 100) in 'Pitch' Slider component
26 | "FastSpeech2", # Literal['FastSpeech2'] in '声学模型选择' Dropdown component
27 | "PWGan", # Literal['PWGan', 'HifiGan'] in '声码器选择' Dropdown component
28 | "zh", # Literal['zh', 'en', 'mix', 'canton'] in '语言选择' Dropdown component
29 | True, # bool in '男声(Male)' Checkbox component
30 | "C:\\Users\\Administrator\\Music\\test.wav", # filepath in '请上传3~10秒内参考音频,超过会报错!' Audio component
31 | "大家有什么问题都可以直接问啊,主播会尽力回答的", # str in '参考音频的文本' Textbox component
32 | "中文", # Literal['中文', '英文', '日文'] in '参考音频的语种' Dropdown component
33 | "中文", # Literal['中文', '英文', '日文', '中英混合', '日英混合', '多语种混合'] in '需要合成的语种' Dropdown component
34 | "不切", # Literal['不切', '凑四句一切', '凑50字一切', '按中文句号。切', '按英文句号.切', '按标点符号切'] in '怎么切' Dropdown component
35 | True, # bool in '使用语音问答的麦克风' Checkbox component
36 | "Edge-TTS", # Literal['Edge-TTS', 'PaddleTTS', 'GPT-SoVITS克隆声音', 'Comming Soon!!!'] in 'Text To Speech Method' Radio component
37 | 1, # float (numeric value between 1 and 10) in 'Talker Batch size' Slider component
38 | api_name="/wrapper_2_4"
39 | )
40 | print(result)
--------------------------------------------------------------------------------
/utils/video_generate.py:
--------------------------------------------------------------------------------
1 | import logging, traceback, asyncio
2 | from concurrent.futures import ThreadPoolExecutor
3 |
4 | # 线程池
5 | executor = ThreadPoolExecutor(max_workers=10)
6 |
7 | def get_video(type: str, data: dict, config: dict):
8 | from gradio_client import Client
9 | import gradio_client
10 |
11 | try:
12 | if type == "easy_wav2lip":
13 | client = Client(config.get("easy_wav2lip", "api_ip_port"))
14 | result = client.predict(
15 | gradio_client.file(config.get("easy_wav2lip", "video_file")), # filepath in '支持图片、视频格式' File component
16 | gradio_client.file(data['audio_path']), # filepath in '支持mp3、wav格式' Audio component
17 | config.get("easy_wav2lip", "quality"), # Literal['Fast', 'Improved', 'Enhanced', 'Experimental'] in '视频质量选项' Radio component
18 | config.get("easy_wav2lip", "output_height"), # Literal['full resolution', 'half resolution'] in '分辨率选项' Radio component
19 | config.get("easy_wav2lip", "wav2lip_version"), # Literal['Wav2Lip', 'Wav2Lip_GAN'] in 'Wav2Lip版本选项' Radio component
20 | config.get("easy_wav2lip", "use_previous_tracking_data"), # Literal['True', 'False'] in '启用追踪旧数据' Radio component
21 | config.get("easy_wav2lip", "nosmooth"), # Literal['True', 'False'] in '启用脸部平滑' Radio component
22 | config.get("easy_wav2lip", "u"), # float (numeric value between -100 and 100) in '嘴部mask上边缘' Slider component
23 | config.get("easy_wav2lip", "d"), # float (numeric value between -100 and 100) in '嘴部mask下边缘' Slider component
24 | config.get("easy_wav2lip", "l"), # float (numeric value between -100 and 100) in '嘴部mask左边缘' Slider component
25 | config.get("easy_wav2lip", "r"), # float (numeric value between -100 and 100) in '嘴部mask右边缘' Slider component
26 | config.get("easy_wav2lip", "size"), # float (numeric value between -10 and 10) in 'mask尺寸' Slider component
27 | config.get("easy_wav2lip", "feathering"), # float (numeric value between -100 and 100) in 'mask羽化' Slider component
28 | config.get("easy_wav2lip", "mouth_tracking"), # Literal['True', 'False'] in '启用mask嘴部跟踪' Radio component
29 | config.get("easy_wav2lip", "debug_mask"), # Literal['True', 'False'] in '启用mask调试' Radio component
30 | config.get("easy_wav2lip", "batch_process"), # Literal['False'] in '批量处理多个视频' Radio component
31 | api_name="/execute_pipeline"
32 | )
33 |
34 | logging.info(f'合成成功,生成在:{result[0]["video"]}')
35 |
36 | return result[0]["video"]
37 | elif type == "sadtalker":
38 | client = Client(config.get("sadtalker", "api_ip_port"))
39 |
40 | if config.get("sadtalker", "gradio_api_type") == "api_name":
41 | result = client.predict(
42 | config.get("sadtalker", "img_file"), # filepath in 'Source image' Image component
43 | data['audio_path'], # filepath in 'Input audio' Audio component
44 | config.get("sadtalker", "preprocess"), # Literal[crop, resize, full, extcrop, extfull] in 'preprocess' Radio component
45 | config.get("sadtalker", "still_mode"), # bool in 'Still Mode (fewer head motion, works with preprocess `full`)' Checkbox component
46 | config.get("sadtalker", "GFPGAN"), # bool in 'GFPGAN as Face enhancer' Checkbox component
47 | config.get("sadtalker", "batch_size"), # float (numeric value between 0 and 10) in 'batch size in generation' Slider component
48 | config.get("sadtalker", "face_model_resolution"), # Literal[256, 512] in 'face model resolution' Radio component
49 | config.get("sadtalker", "pose_style"), # float (numeric value between 0 and 46) in 'Pose style' Slider component
50 | api_name="/test"
51 | )
52 |
53 | logging.info(f'{type}合成成功,生成在:{result["video"]}')
54 |
55 | return result["video"]
56 | else:
57 | result = client.predict(
58 | config.get("sadtalker", "img_file"), # filepath in 'Source image' Image component
59 | data['audio_path'], # filepath in 'Input audio' Audio component
60 | config.get("sadtalker", "preprocess"), # Literal[crop, resize, full, extcrop, extfull] in 'preprocess' Radio component
61 | config.get("sadtalker", "still_mode"), # bool in 'Still Mode (fewer head motion, works with preprocess `full`)' Checkbox component
62 | config.get("sadtalker", "GFPGAN"), # bool in 'GFPGAN as Face enhancer' Checkbox component
63 | config.get("sadtalker", "batch_size"), # float (numeric value between 0 and 10) in 'batch size in generation' Slider component
64 | config.get("sadtalker", "face_model_resolution"), # Literal[256, 512] in 'face model resolution' Radio component
65 | config.get("sadtalker", "pose_style"), # float (numeric value between 0 and 46) in 'Pose style' Slider component
66 | fn_index=1
67 | )
68 |
69 | logging.info(f'{type}合成成功,生成在:{result}')
70 |
71 | return result
72 | elif type == "genefaceplusplus":
73 | client = Client(config.get("genefaceplusplus", "api_ip_port"))
74 | result = client.predict(
75 | data['audio_path'], # filepath in 'Input audio (required)' Audio component
76 | config.get("genefaceplusplus", "blink_mode"), # Literal['none', 'period'] in '眨眼模式' Radio component
77 | config.get("genefaceplusplus", "temperature"), # float (numeric value between 0.0 and 1.0) in 'temperature' Slider component
78 | config.get("genefaceplusplus", "lle_percent"), # float (numeric value between 0.0 and 1.0) in 'lle_percent' Slider component
79 | config.get("genefaceplusplus", "mouth_amplitude"), # float (numeric value between 0.0 and 1.0) in '嘴部幅度' Slider component
80 | config.get("genefaceplusplus", "ray_marching_end_threshold"), # float (numeric value between 0.0 and 0.1) in 'ray marching end-threshold' Slider component
81 | config.get("genefaceplusplus", "fp16"), # bool in 'fp16模式:是否使用并加速推理' Checkbox component
82 | config.get("genefaceplusplus", "audio2secc_model"), # List[List[str]] in 'audio2secc model ckpt path or directory' Fileexplorer component
83 | config.get("genefaceplusplus", "pose_net_model"), # List[List[str]] in '(optional) pose net model ckpt path or directory' Fileexplorer component
84 | config.get("genefaceplusplus", "head_model"), # List[List[str]] in '(按需) 选择人物头部模型(如果选择了躯干模型,该选项将被忽略)' Fileexplorer component
85 | config.get("genefaceplusplus", "body_model"), # List[List[str]] in '选择人物躯干模型' Fileexplorer component
86 | config.get("genefaceplusplus", "low_memory_mode"), # bool in '低内存使用模式:以较低的推理速度为代价节省内存。在运行长音频合成视频时很有用。' Checkbox component
87 | api_name="/infer_once_args"
88 | )
89 |
90 | logging.info(f'{type}合成成功,生成在:{result[0]["video"]}')
91 |
92 | return result[0]["video"]
93 | elif type == "musetalk":
94 | # gradio_client-0.16.3
95 | from gradio_client import file
96 |
97 | client = Client(config.get("musetalk", "api_ip_port"))
98 | result = client.predict(
99 | audio_path=file(data['audio_path']),
100 | video_path={"video":file(config.get("musetalk", "video_path"))},
101 | bbox_shift=int(config.get("musetalk", "bbox_shift")),
102 | api_name="/inference"
103 | )
104 |
105 | logging.info(f'{type}合成成功,生成在:{result[0]["video"]}')
106 |
107 | return result[0]["video"]
108 | elif type == "anitalker":
109 | # gradio_client-1.2.0
110 | from gradio_client import handle_file
111 |
112 | client = Client(config.get("anitalker", "api_ip_port"))
113 | result = client.predict(
114 | face=handle_file(config.get("anitalker", "img_file")), # 图片路径,1:1像素比
115 | audio=handle_file(data['audio_path']),
116 | is_mor=config.get("anitalker", "is_mor"), # 视频超分,0为关闭,1为开启
117 | face_d=config.get("anitalker", "face_d"), # 面部朝向,0为正面,0.25为侧面
118 | api_name="/do_cloth"
119 | )
120 |
121 | logging.info(f'{type}合成成功,生成在:{result["video"]}')
122 |
123 | return result["video"]
124 | elif type == "local":
125 | return data['video_path']
126 | except Exception as e:
127 | logging.error(traceback.format_exc())
128 | return None
129 |
130 |
131 | async def run_get_video(type: str, data: dict, config: dict) -> str:
132 | # 将同步请求委托给线程池执行,从而避免阻塞事件循环
133 | loop = asyncio.get_event_loop()
134 | result = await loop.run_in_executor(executor, get_video, type, data, config)
135 | return result
136 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 | # ✨ 洛曦 数字人视频播放器 ✨
10 |
11 | [![][python]][python]
12 | [![][github-release-shield]][github-release-link]
13 | [![][github-stars-shield]][github-stars-link]
14 | [![][github-forks-shield]][github-forks-link]
15 | [![][github-issues-shield]][github-issues-link]
16 | [![][github-contributors-shield]][github-contributors-link]
17 | [![][github-license-shield]][github-license-link]
18 |
19 |
20 |
21 | ## 前言
22 |
23 | 项目名:洛曦 数字人视频播放器
24 | 功能:可以通过HTTP API传入需要播放的视频,并排队在web页面自动播放
25 | 目前支持的项目:
26 | - [Easy-Wav2Lip](https://github.com/anothermartz/Easy-Wav2Lip)(gradio API,使用的B站:眠NEON 提供的整合包:[视频传送门](https://www.bilibili.com/video/BV1rS421N71b))
27 | - [Sadtalker](https://github.com/OpenTalker/SadTalker)(gradio API,整合包:[夸克网盘](https://pan.quark.cn/s/936dcae8aba0#/list/share/56a79e143a8b4877a98a61854e07b229-AI%20Vtuber/741f94606e414157b8d0a021d3a9ca77-%E8%99%9A%E6%8B%9F%E8%BA%AB%E4%BD%93/6ea2ecc2b19e49c4b1eda383a6aab194-Sadtalker), [迅雷云盘](https://pan.xunlei.com/s/VNitDF0Y3l-qwTpE0A5Rh4DaA1))
28 | - [GeneFacePlusPlus](https://github.com/yerfor/GeneFacePlusPlus)(gradio API,使用的B站:眠NEON 提供的整合包:[视频传送门](https://www.bilibili.com/video/BV1vz421R7ot))
29 | - [MuseTalk](https://github.com/TMElyralab/MuseTalk)(gradio API,整合包:)
30 | - [AniTalker](https://github.com/X-LANCE/AniTalker)(gradio API,使用的B站:刘悦的技术博客 提供的整合包:[下载](https://pan.quark.cn/s/936dcae8aba0#/list/share/56a79e143a8b4877a98a61854e07b229-AI%20Vtuber/741f94606e414157b8d0a021d3a9ca77-%E8%99%9A%E6%8B%9F%E8%BA%AB%E4%BD%93/d31da81a7d64488d812ead76d3bc9f9c-AniTalker), [视频传送门](https://www.bilibili.com/video/BV1rS421N71b))
31 |
32 | ### 环境
33 | python:3.10.10
34 |
35 | ## 使用
36 |
37 | ### 安装依赖
38 |
39 | `pip install -r requirements.txt`
40 |
41 | ### 修改配置文件
42 |
43 | 自行根据需求修改`config.json`
44 |
45 | ### 运行API
46 |
47 | `python api_server.py`
48 |
49 |
50 | ## API
51 |
52 | 运行后,可以查看API文档:[http://127.0.0.1:8091/docs](http://127.0.0.1:8091/docs)
53 |
54 | ### 播放视频
55 |
56 | #### 概述
57 |
58 | - **请求地址:** `/show`
59 | - **请求类型:** POST
60 | - **描述:** 传入视频进行播放,可以选择插入索引。
61 |
62 | #### 请求参数
63 |
64 | | 参数名 | 类型 | 是否必需 | 描述 |
65 | |-------- |--------|----------|-------------- |
66 | | type | string | 是 | 使用的视频合成技术类型(easy_wav2lip / sadtalker / genefaceplusplus / musetalk / local) |
67 | | video_path | string | 是 | 视频文件的绝对路径(在local模式下必填) |
68 | | audio_path | string | 是 | 音频文件的绝对路径 |
69 | | captions_printer | dict | 否 | 字幕打印机相关参数,不传则不发送。content显示文本内容 start_delay显示文本内容的延时显示时间(毫秒) keep_time字幕保持时间(毫秒) 例如:{"content": "你好", "start_delay": 1000, "keep_time": 3000} |
70 | | insert_index | int | 是 | 插入索引值,队尾插入:-1,队首插入:0,其他自定义 |
71 | | move_file | bool | 否 | 是否移动合成或指定的视频文件到项目路径内。默认True |
72 |
73 | #### 响应
74 |
75 | | 参数名 | 类型 | 描述 |
76 | |--------|-------- |--------------|
77 | | code | int | 状态码,200为成功,小于0为错误代码,大于0为部分成功代码 |
78 | | msg | string | 响应消息,描述请求的处理结果 |
79 |
80 | ### 跳过当前播放的视频,播放下一个视频
81 |
82 | #### 概述
83 |
84 | - **请求地址:** `/stop_current_video`
85 | - **请求类型:** POST
86 | - **描述:** 跳过当前播放的视频,播放下一个视频。
87 |
88 | #### 请求参数
89 |
90 | | 参数名 | 类型 | 是否必需 | 描述 |
91 | |-------- |--------|----------|-------------- |
92 |
93 |
94 | #### 响应
95 |
96 | | 参数名 | 类型 | 描述 |
97 | |--------|-------- |--------------|
98 | | code | int | 状态码,200为成功,小于0为错误代码,大于0为部分成功代码 |
99 | | msg | string | 响应消息,描述请求的处理结果 |
100 |
101 | ### 获取队列中非默认视频的个数
102 |
103 | #### 概述
104 |
105 | - **请求地址:** `/get_non_default_video_count`
106 | - **请求类型:** POST
107 | - **描述:** 获取队列中非默认视频的个数
108 |
109 | #### 请求参数
110 |
111 | | 参数名 | 类型 | 是否必需 | 描述 |
112 | |-------- |--------|----------|-------------- |
113 |
114 | #### 响应
115 |
116 | | 参数名 | 类型 | 描述 |
117 | |--------|-------- |--------------|
118 | | code | int | 状态码,200为成功,小于0为错误代码,大于0为部分成功代码 |
119 | | count | int | 队列中非默认视频的个数 |
120 | | msg | string | 响应消息,描述请求的处理结果 |
121 |
122 | ### 获取视频播放列表数据
123 |
124 | #### 概述
125 |
126 | - **请求地址:** `/get_video_queue`
127 | - **请求类型:** POST
128 | - **描述:** 获取视频播放列表数据。
129 |
130 | #### 请求参数
131 |
132 | | 参数名 | 类型 | 是否必需 | 描述 |
133 | |-------- |--------|----------|-------------- |
134 |
135 |
136 | #### 响应
137 |
138 | | 参数名 | 类型 | 描述 |
139 | |--------|-------- |--------------|
140 | | code | int | 状态码,200为成功,小于0为错误代码,大于0为部分成功代码 |
141 | | data | list | 存储视频信息的数据列表 |
142 | | message | string | 响应消息,描述请求的处理结果 |
143 |
144 | ### 删除视频播放列表中指定索引的视频数据
145 |
146 | #### 概述
147 |
148 | - **请求地址:** `/del_video_with_index`
149 | - **请求类型:** POST
150 | - **描述:** 删除视频播放列表中指定索引的视频数据,返回删除后的视频列表数据
151 |
152 | #### 请求参数
153 |
154 | | 参数名 | 类型 | 是否必需 | 描述 |
155 | |-------- |--------|----------|-------------- |
156 | | index | int | 是 | 删除索引值,从0开始,0就是首个待播放视频 |
157 |
158 | #### 响应
159 |
160 | | 参数名 | 类型 | 描述 |
161 | |--------|-------- |--------------|
162 | | code | int | 状态码,200为成功,小于0为错误代码,大于0为部分成功代码 |
163 | | data | list | 存储视频信息的数据列表 |
164 | | message | string | 响应消息,描述请求的处理结果 |
165 |
166 | ### 设置相关配置
167 |
168 | #### 概述
169 |
170 | - **请求地址:** `/set_config`
171 | - **请求类型:** POST
172 | - **描述:** 用于设置相关配置
173 |
174 | #### 请求参数
175 |
176 | | 参数名 | 类型 | 是否必需 | 描述 |
177 | |-------- |--------|----------|-------------- |
178 | | captions_printer_api_url | string | 否 | 前端 字幕打印机API请求地址,例如:http://127.0.0.1:5500/send_message |
179 |
180 | #### 响应
181 |
182 | | 参数名 | 类型 | 描述 |
183 | |--------|-------- |--------------|
184 | | code | int | 状态码,200为成功,小于0为错误代码,大于0为部分成功代码 |
185 | | data | list | list数据,存储着转换为url路径的视频地址 |
186 | | msg | string | 响应消息,描述请求的处理结果 |
187 |
188 |
189 | ## 💡 提问的智慧
190 |
191 | 提交issues前请先阅读以下内容
192 |
193 | https://lug.ustc.edu.cn/wiki/doc/smart-questions
194 |
195 | ## 🀅 开发&项目相关
196 |
197 | 可以使用 GitHub Codespaces 进行在线开发:
198 |
199 | [![][github-codespace-shield]][github-codespace-link]
200 |
201 |
202 |
203 | ## ⭐️ Star 经历
204 |
205 | [](https://star-history.com/#Ikaros-521/digital_human_video_player&Date)
206 |
207 | ## 更新日志
208 | - v0.4.0
209 | - 视频列表 视频数据改为播放后才删除,意味着你可以通过get_video_queue 获取视频列表的接口 得到当前播放视频的信息(第一个数据就是)
210 |
211 | - v0.3.4
212 | - 新增接口 del_video_with_index,可以删除指定索引的视频
213 |
214 | - v0.3.3
215 | - 后端允许跨域
216 |
217 | - v0.3.2
218 | - show接口 captions_printer参数改为dict类型,直接传入相关的json数据,新增 keep_time键值,用于控制字幕显示时长(毫秒)
219 | - v0.3.1
220 | - 新增接口 set_config,用于设置相关配置,暂时仅提供前端 字幕打印机API地址设置功能
221 | - 页面自适应拉伸
222 |
223 | - v0.3.0
224 | - show接口 新增参数 captions_printer 控制字幕打印机显示文本内容,不传则不发送
225 | - show接口 新增参数 captions_printer_start_delay 字幕打印机显示文本内容的延时显示时间,不传则不发送
226 |
227 | - v0.2.3
228 | - 新增接口 get_video_queue,获取获取视频播放列表数据。
229 | - 修复 move_file传参不能关闭的bug
230 | - 配置文件新增参数 auto_del_video,支持控制是否在播放完视频后删除视频
231 |
232 | - v0.2.2
233 | - 对接 AniTalker gradio API(gradio_client版本要求1.2.0及以上)
234 | - 删除旧版quart库实现的版本
235 |
236 | - v0.2.1
237 | - 规范化API实现
238 |
239 | - v0.2.0
240 | - 更换Quart为FastAPI
241 | - 针对 gradio视频合成卡播放问题的解决(gradio同步请求阻塞了server的其他请求,而前端的视频加载是通过server的URL加载的,server被阻塞后无法处理URL请求,导致前端被卡视频加载导致卡顿。目前将请求通过线程池(10个)单独托管,避免阻塞)
242 |
243 | - v0.1.9
244 | - easy_wav2lip文件传参改用gradio_client传递,可以支持本地文件传递到云API
245 | - 提高httpx日志等级到WARNING
246 | - 针对linux系统请求win的gradio时,路径解析不正常问题进行针对性修正
247 |
248 | - v0.1.8
249 | - 支持接口 stop_current_video,跳过当前播放的视频,播放下一个视频
250 | - 支持接口 get_non_default_video_count,获取队列中非默认视频的个数
251 | - show接口新增参数 move_file,可以控制是否移动合成或指定的视频文件到项目路径内。默认True
252 |
253 | - v0.1.7
254 | - 支持local类型,直接播放本地视频
255 | - 支持 MuseTalk 对接
256 |
257 | - v0.1.6
258 | - 新增默认配置`default_video`,可以在配置文件定义默认视频,不需要改源码了
259 |
260 | - v0.1.5
261 | - 生成的视频将在播放完毕后直接删除,节省存储
262 |
263 | - v0.1.4
264 | - 支持local类型,可以直接传入本地视频进行播放
265 |
266 | - v0.1.3
267 | - sadtalker新增参数`gradio_api_type`用于适配不同的接口传参(api_name/fn_index)
268 | - 补充测试图和视频
269 |
270 | - v0.1.2
271 | - 对接GeneFacePlusPlus(未测试)
272 |
273 | - v0.1.1
274 | - 对接sadtalker
275 | - API新增参数type
276 | - 优化视频播放逻辑,尝试解决视频过渡时的无效等待问题
277 |
278 |
279 | - v0.1.0
280 | - 初版发布
281 |
282 |
283 |
284 | [python]: https://img.shields.io/badge/python-3.10+-blue.svg?labelColor=black
285 | [back-to-top]: https://img.shields.io/badge/-BACK_TO_TOP-black?style=flat-square
286 | [github-action-release-link]: https://github.com/actions/workflows/Ikaros-521/digital_human_video_player/release.yml
287 | [github-action-release-shield]: https://img.shields.io/github/actions/workflow/status/Ikaros-521/digital_human_video_player/release.yml?label=release&labelColor=black&logo=githubactions&logoColor=white&style=flat-square
288 | [github-action-test-link]: https://github.com/actions/workflows/Ikaros-521/digital_human_video_player/test.yml
289 | [github-action-test-shield]: https://img.shields.io/github/actions/workflow/status/Ikaros-521/digital_human_video_player/test.yml?label=test&labelColor=black&logo=githubactions&logoColor=white&style=flat-square
290 | [github-codespace-link]: https://codespaces.new/Ikaros-521/digital_human_video_player
291 | [github-codespace-shield]: https://github.com/codespaces/badge.svg
292 | [github-contributors-link]: https://github.com/Ikaros-521/digital_human_video_player/graphs/contributors
293 | [github-contributors-shield]: https://img.shields.io/github/contributors/Ikaros-521/digital_human_video_player?color=c4f042&labelColor=black&style=flat-square
294 | [github-forks-link]: https://github.com/Ikaros-521/digital_human_video_player/network/members
295 | [github-forks-shield]: https://img.shields.io/github/forks/Ikaros-521/digital_human_video_player?color=8ae8ff&labelColor=black&style=flat-square
296 | [github-issues-link]: https://github.com/Ikaros-521/digital_human_video_player/issues
297 | [github-issues-shield]: https://img.shields.io/github/issues/Ikaros-521/digital_human_video_player?color=ff80eb&labelColor=black&style=flat-square
298 | [github-license-link]: https://github.com/Ikaros-521/digital_human_video_player/blob/main/LICENSE
299 | [github-license-shield]: https://img.shields.io/github/license/Ikaros-521/digital_human_video_player?color=white&labelColor=black&style=flat-square
300 | [github-release-link]: https://github.com/Ikaros-521/digital_human_video_player/releases
301 | [github-release-shield]: https://img.shields.io/github/v/release/Ikaros-521/digital_human_video_player?color=369eff&labelColor=black&logo=github&style=flat-square
302 | [github-releasedate-link]: https://github.com/Ikaros-521/digital_human_video_player/releases
303 | [github-releasedate-shield]: https://img.shields.io/github/release-date/Ikaros-521/digital_human_video_player?labelColor=black&style=flat-square
304 | [github-stars-link]: https://github.com/Ikaros-521/digital_human_video_player/network/stargazers
305 | [github-stars-shield]: https://img.shields.io/github/stars/Ikaros-521/digital_human_video_player?color=ffcb47&labelColor=black&style=flat-square
306 | [pr-welcome-link]: https://github.com/Ikaros-521/digital_human_video_player/pulls
307 | [pr-welcome-shield]: https://img.shields.io/badge/%F0%9F%A4%AF%20PR%20WELCOME-%E2%86%92-ffcb47?labelColor=black&style=for-the-badge
308 | [profile-link]: https://github.com/Ikaros-521
309 |
310 |
311 |
--------------------------------------------------------------------------------
/static/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 数字人视频播放器
6 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
333 |
334 |
335 |
336 |
--------------------------------------------------------------------------------
/api_server.py:
--------------------------------------------------------------------------------
1 | from fastapi import FastAPI, WebSocket, Request, WebSocketDisconnect
2 | from fastapi.responses import RedirectResponse, JSONResponse
3 | from fastapi.staticfiles import StaticFiles
4 | import uvicorn
5 | import asyncio
6 | import os
7 | import json
8 | import logging
9 | import traceback
10 | import threading
11 | from selenium import webdriver
12 | from urllib.parse import unquote
13 |
14 | from fastapi.middleware.cors import CORSMiddleware
15 |
16 | from utils.config import Config
17 | from utils.common import Common
18 | from utils.logger import Configure_logger
19 | from utils.video_generate import run_get_video
20 | from utils.models import ShowMessage, DelVideoWithIndexMessage, GetNonDefaultVideoCountResult, GetVideoQueueResult, CommonResult, SetConfigMessage
21 |
22 | # 获取 httpx 库的日志记录器
23 | httpx_logger = logging.getLogger("httpx")
24 | # 设置 httpx 日志记录器的级别为 WARNING
25 | httpx_logger.setLevel(logging.WARNING)
26 |
27 | common = Common()
28 | # 日志文件路径
29 | file_path = "./log/log-" + common.get_bj_time(1) + ".txt"
30 | Configure_logger(file_path)
31 | config = Config("config.json")
32 |
33 | # 获取当前脚本的目录
34 | script_dir = os.path.dirname(os.path.abspath(__file__))
35 |
36 | # 设置静态文件夹路径为相对于当前脚本目录的路径
37 | static_folder = os.path.join(script_dir, 'static')
38 | static_folder = os.path.abspath(static_folder)
39 |
40 | logging.info(f"static_folder={static_folder}")
41 |
42 | app = FastAPI()
43 |
44 | # 添加 CORS 中间件,允许所有跨域请求
45 | app.add_middleware(
46 | CORSMiddleware,
47 | allow_origins=["*"], # 允许所有来源
48 | allow_credentials=True, # 允许发送带有凭据的请求
49 | allow_methods=["*"], # 允许所有 HTTP 方法
50 | allow_headers=["*"], # 允许所有请求头
51 | )
52 |
53 | # Mount static folder
54 | app.mount("/static", StaticFiles(directory=static_folder), name="static")
55 |
56 | connected_websockets = set()
57 |
58 |
59 | # 队列中非默认视频个数
60 | non_default_video_count = 0
61 | # 视频播放队列数据
62 | video_queue = []
63 |
64 | @app.get("/")
65 | async def home():
66 | return RedirectResponse(url="/static/index.html")
67 |
68 | @app.get("/videos/{filename:path}")
69 | async def load_video(filename: str):
70 | video_path = os.path.join(static_folder, 'video', filename)
71 | return await StaticFiles(directory=os.path.dirname(video_path)).get_response(os.path.basename(video_path))
72 |
73 | @app.websocket("/ws")
74 | async def websocket_endpoint(websocket: WebSocket):
75 | global non_default_video_count, video_queue
76 |
77 | await websocket.accept()
78 | connected_websockets.add(websocket)
79 | try:
80 | while True:
81 | try:
82 | data = await websocket.receive_text()
83 | data_json = json.loads(data)
84 | logging.info(f"收到客户端数据: {data_json}")
85 | # 处理从客户端接收的数据的逻辑
86 | if data_json['type'] == "videoEnded":
87 | non_default_video_count = data_json['count']
88 | # 跳过默认视频
89 | if common.get_filename_with_ext(config.get("default_video")) not in data_json['video_path']:
90 | # 是否启用了自动删除视频配置(视频由于占用大,建议启用视频删除避免磁盘占满)
91 | if config.get("auto_del_video"):
92 | # 在这里添加删除视频文件的逻辑
93 | await delete_video_file(data_json['video_path'])
94 | elif data_json['type'] == "get_default_video":
95 | logging.info(f"发送默认配置 视频路径: {config.get('default_video')}")
96 | # 在这里添加发送消息到客户端的逻辑
97 | await send_to_all_websockets(json.dumps({"type": "set_default_video", "video_path": config.get("default_video")}))
98 | elif data_json['type'] == "show":
99 | logging.info(f"队列中非默认视频个数: {data_json['count']}")
100 | non_default_video_count = data_json['count']
101 | elif data_json['type'] == "get_non_default_video_count":
102 | logging.info(f"队列中非默认视频个数: {data_json['count']}")
103 | non_default_video_count = data_json['count']
104 | elif data_json['type'] == "get_video_queue":
105 | logging.debug(f"视频队列: {data_json['data']}")
106 | video_queue = data_json['data']
107 | elif data_json['type'] == "del_video_with_index":
108 | logging.debug(f"视频队列: {data_json['data']}")
109 | video_queue = data_json['data']
110 | except WebSocketDisconnect:
111 | logging.info("ws客户端连接已关闭")
112 | break
113 | except Exception as e:
114 | logging.error(traceback.format_exc())
115 | finally:
116 | connected_websockets.remove(websocket)
117 |
118 | # 删除视频文件
119 | async def delete_video_file(video_path: str):
120 | file_name_with_extension = os.path.basename(video_path)
121 | file_name_with_extension = unquote(file_name_with_extension, 'utf-8')
122 | relative_path = os.path.join(static_folder, "videos", file_name_with_extension)
123 |
124 | try:
125 | os.remove(relative_path) # 删除视频文件
126 | logging.info(f"成功删除视频文件 {relative_path}。")
127 | except FileNotFoundError:
128 | logging.error(f"未找到视频文件 {relative_path}。")
129 | except Exception as e:
130 | logging.error(f"删除视频文件时发生错误:{str(e)}")
131 |
132 | async def send_to_all_websockets(data):
133 | for ws in connected_websockets:
134 | await ws.send_text(data)
135 |
136 | def extract_filename(video_path):
137 | import re
138 | if '=' in video_path:
139 | filepath = video_path.split('=')[1]
140 | else:
141 | filepath = video_path
142 |
143 | match = re.search(r'[^\\/:*?"<>|\r\n]+$', filepath)
144 | if match:
145 | return match.group()
146 | else:
147 | return common.get_filename_with_ext(filepath)
148 |
149 | @app.post("/show")
150 | async def show(msg: ShowMessage):
151 | try:
152 | data = msg.model_dump()
153 |
154 | logging.info(f"收到数据:{data}")
155 |
156 | video_path = await run_get_video(data["type"], data, config)
157 |
158 | if video_path:
159 | static_video_path = os.path.join(static_folder, "videos")
160 | logging.debug(f"视频文件移动到的路径:{static_video_path}")
161 |
162 | filename = ""
163 | move_file = data.get("move_file")
164 | is_linux = common.detect_os() == "Linux"
165 |
166 | if move_file:
167 | if is_linux:
168 | filename = extract_filename(video_path)
169 | ret = common.move_and_rename(video_path, static_video_path, new_filename=filename, move_file=move_file)
170 | else:
171 | ret = common.move_and_rename(video_path, static_video_path, move_file=move_file)
172 | filename = common.get_filename_with_ext(video_path)
173 | else:
174 | if is_linux:
175 | filename = extract_filename(video_path)
176 | ret = common.move_and_rename(video_path, static_video_path, new_filename=filename, move_file=False)
177 | else:
178 | ret = common.move_and_rename(video_path, static_video_path, move_file=False)
179 | filename = common.get_filename_with_ext(video_path)
180 | if not ret:
181 | return CommonResult(code=200, message="视频移动失败")
182 |
183 | file_url = f"http://127.0.0.1:{config.get('server_port')}/static/videos/{filename}"
184 |
185 | if "audio_path" not in data:
186 | data["audio_path"] = None
187 |
188 | if "insert_index" not in data:
189 | data["insert_index"] = -1
190 |
191 | if "captions_printer" not in data:
192 | await send_to_all_websockets(
193 | json.dumps(
194 | {
195 | "type": "show",
196 | "video_path": file_url,
197 | "audio_path": data["audio_path"],
198 | "insert_index": data["insert_index"]
199 | }
200 | )
201 | )
202 | else:
203 | await send_to_all_websockets(
204 | json.dumps(
205 | {
206 | "type": "show",
207 | "video_path": file_url,
208 | "audio_path": data["audio_path"],
209 | "captions_printer": data["captions_printer"],
210 | "insert_index": data["insert_index"]
211 | }
212 | )
213 | )
214 |
215 | return CommonResult(code=200, message="操作成功")
216 | return CommonResult(code=200, message="视频合成失败")
217 | except Exception as e:
218 | logging.error(traceback.format_exc())
219 | return CommonResult(code=-1, message=f"操作失败: {str(e)}")
220 |
221 | @app.post("/stop_current_video")
222 | async def stop_current_video():
223 | try:
224 | await send_to_all_websockets(
225 | json.dumps(
226 | {
227 | "type": "stop_current_video"
228 | }
229 | )
230 | )
231 | return CommonResult(code=200, message="操作成功")
232 | except Exception as e:
233 | logging.error(traceback.format_exc())
234 | return CommonResult(code=-1, message=f"操作失败: {str(e)}")
235 |
236 | @app.post("/get_non_default_video_count")
237 | async def get_non_default_video_count():
238 | try:
239 | await send_to_all_websockets(
240 | json.dumps(
241 | {
242 | "type": "get_non_default_video_count"
243 | }
244 | )
245 | )
246 | await asyncio.sleep(0.5)
247 | return GetNonDefaultVideoCountResult(code=200, count=non_default_video_count, message="操作成功")
248 | except Exception as e:
249 | logging.error(traceback.format_exc())
250 | return CommonResult(code=-1, message=f"操作失败: {str(e)}")
251 |
252 | # 获取视频队列
253 | @app.post("/get_video_queue")
254 | async def get_video_queue():
255 | try:
256 | await send_to_all_websockets(
257 | json.dumps(
258 | {
259 | "type": "get_video_queue"
260 | }
261 | )
262 | )
263 | await asyncio.sleep(0.5)
264 | return GetVideoQueueResult(code=200, data=video_queue, message="操作成功")
265 | except Exception as e:
266 | logging.error(traceback.format_exc())
267 | return CommonResult(code=-1, message=f"操作失败: {str(e)}")
268 |
269 | # 删除指定索引的视频
270 | @app.post("/del_video_with_index")
271 | async def del_video_with_index(msg: DelVideoWithIndexMessage):
272 | try:
273 | await send_to_all_websockets(
274 | json.dumps(
275 | {
276 | "type": "del_video_with_index",
277 | "index": msg.index
278 | }
279 | )
280 | )
281 | await asyncio.sleep(0.5)
282 | return GetVideoQueueResult(code=200, data=video_queue, message="操作成功")
283 | except Exception as e:
284 | logging.error(traceback.format_exc())
285 | return CommonResult(code=-1, message=f"操作失败: {str(e)}")
286 |
287 | # 设置配置
288 | @app.post("/set_config")
289 | async def set_config(msg: SetConfigMessage):
290 | try:
291 | await send_to_all_websockets(
292 | json.dumps(
293 | {
294 | "type": "set_config",
295 | "data": msg.dict()
296 | }
297 | )
298 | )
299 | await asyncio.sleep(0.5)
300 | return CommonResult(code=200, message="操作成功")
301 | except Exception as e:
302 | logging.error(traceback.format_exc())
303 | return CommonResult(code=-1, message=f"操作失败: {str(e)}")
304 |
305 | def start_browser(stop_event):
306 | options = webdriver.ChromeOptions()
307 | # 设置为开发者模式,避免被浏览器识别为自动化程序
308 | options.add_experimental_option('excludeSwitches', ['enable-automation'])
309 | options.add_argument('--autoplay-policy=no-user-gesture-required')
310 | # options.add_argument('--disable-gpu') # 禁用GPU硬件加速
311 | # options.add_argument('--disable-software-rasterizer') # 禁用软件光栅化器
312 | # options.add_argument('--no-sandbox') # 禁用沙盒模式
313 | driver = webdriver.Chrome(options=options)
314 |
315 | # 火狐
316 | # options = webdriver.FirefoxOptions()
317 | # # 设置为开发者模式,避免被浏览器识别为自动化程序
318 | # options.set_preference('dom.webdriver.enabled', False)
319 | # options.set_preference('media.autoplay.default', 0) # 设置自动播放策略
320 | # driver = webdriver.Firefox(options=options)
321 |
322 | driver.get(f'http://127.0.0.1:{config.get("server_port")}')
323 | stop_event.wait()
324 |
325 | class StoppableThread(threading.Thread):
326 | def __init__(self, target=None, stop_event=None):
327 | super().__init__()
328 | self._stop_event = stop_event
329 | self._target = target
330 |
331 | def run(self):
332 | if self._target:
333 | self._target(self._stop_event)
334 | self._stop_event.wait()
335 | logging.info("Thread is stopping")
336 |
337 | def stop(self):
338 | self._stop_event.set()
339 |
340 | if __name__ == "__main__":
341 | stop_event = threading.Event()
342 | browser_thread = StoppableThread(target=start_browser, stop_event=stop_event)
343 | browser_thread.start()
344 |
345 | uvicorn.run(app, host=config.get("server_ip"), port=config.get("server_port"))
346 |
347 | browser_thread.stop()
348 | os._exit(0)
349 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------