17 Commits
v1.0 ... 1.1

Author SHA1 Message Date
nnwang
b318144230 更新README 2026-01-10 02:10:10 +08:00
nnwang
56490460fa 添加打包下载 2026-01-10 02:07:34 +08:00
nnwang
f422eb32c1 Merge branch 'main' of https://git.liulikeji.cn/xingluo/GMapiServer 2026-01-09 21:40:31 +08:00
nnwang
cad3a033a3 添加视频切片功能 2026-01-09 21:40:03 +08:00
85ee16d1e6 上传文件至 / 2025-12-05 02:24:29 +08:00
c930c0828a 上传文件至 / 2025-12-05 02:00:09 +08:00
HKXluo
408fcd3f1b 修复 下载url 错误的bug 2025-11-20 21:06:13 +08:00
HKXluo
0e3f229260 添加创建请求和读取进度接口 2025-11-20 20:54:15 +08:00
eede77a848 Merge pull request '修复assert位置错误问题' (#2) from Hatanezumi/GMapiServer:main into main
Reviewed-on: #2
2025-08-08 09:41:47 +08:00
b0439e0d74 merge upstream 2025-08-08 08:30:56 +08:00
7ac56b4035 修复assert位置错误问题 2025-08-08 08:29:40 +08:00
992286db7a Merge pull request '修复status_code静态检测不通过' (#1) from Hatanezumi/GMapiServer:main into main
Reviewed-on: #1
2025-08-07 23:14:31 +08:00
6e92b3b937 修复status_code静态检测不通过 2025-08-07 23:10:41 +08:00
0bdd622645 更新 README.md 2025-05-04 18:36:11 +08:00
91a70e1d4d 更新 README.md 2025-05-04 18:21:47 +08:00
HKXluo
df76a58370 Merge branch 'main' of https://git.liulikeji.cn/xingluo/GMapiServer 2025-05-04 18:20:42 +08:00
HKXluo
b1cef60d76 添加自定义端口和健康检测 2025-05-04 18:20:35 +08:00
12 changed files with 157016 additions and 124 deletions

2
.gitignore vendored
View File

@@ -1,3 +1,5 @@
.history
__pycache__/
app.log
temp_files
frames

117
LICENSE Normal file
View File

@@ -0,0 +1,117 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.
signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice

239
README.md
View File

@@ -1,84 +1,215 @@
---
GMapiServer
# GMapiServer
GMapiServer 是一个基于 Python 和 Flask 构建的高性能 API 服务器,支持通过 URL 输入文件并输出下载链接,提供同步和异步两种处理模式。内置缓存自动清理机制(默认保留 2 小时),支持多种工具接口调用,包括实时任务状态查询和视频帧处理功能。
**GMapiServer** 是一个基于 Python 和 Flask 构建的高性能 API 服务器,支持通过 URL 输入文件并输出下载链接,提供异步处理功能,确保主进程不被阻塞。内置缓存自动清理机制(默认保留 2 小时),支持多种工具接口调用。
🚀 项目简介
---
GMapiServer 是一个轻量级、模块化的 API 服务框架,旨在为开发者提供以下核心功能:
## 🚀 项目简介
• URL 输入与输出:支持通过 URL 提交文件,返回生成文件的下载链接。
**GMapiServer** 是一个轻量级、模块化的 API 服务框架,旨在为开发者提供以下核心功能:
• 异步处理:任务在后台异步执行,不阻塞主进程,提升服务器并发性能。
- **URL 输入与输出**:支持通过 URL 提交文件,返回生成文件的下载链接
- **异步处理**:任务在后台异步执行,不阻塞主进程,提升服务器并发性能。
- **自动缓存清理**:内置定时清理机制,自动删除过期的缓存文件(包括输出文件),默认保留时间 2 小时。
- **多工具接口集成**:集成 FFmpeg 和 Sanjuuni 工具接口,支持在线调用。
• 自动缓存清理:内置定时清理机制,自动删除过期的缓存文件(包括输出文件),默认保留时间 2 小时
---
• 多工具接口集成:集成 FFmpeg 和 Sanjuuni 工具接口,支持在线调用。
## 🛠️ 技术栈
• 实时任务状态:提供任务状态查询接口,支持日志实时推送。
- **编程语言**: Python
- **Web 框架**: Flask
- **异步处理**: 基于 `threading`
- **缓存清理**: 定时任务
- **依赖管理**: pip
• 视频帧提取:支持从视频中提取指定分辨率、帧率的图片帧,可打包为二进制格式。
---
🛠️ 技术栈
## 🧩 支持的接口
• 编程语言: Python
### 1. FFmpeg 工具接口
- **功能**: 在线调用 FFmpeg 工具进行视频/音频处理(如转码、裁剪、合并等)。
- **接口文档**: [FFmpegApi 文档](https://www.liulikeji.cn/archives/FFmpegApi)
• Web 框架: Flask
### 2. Sanjuuni 工具接口
- **功能**: 在线调用 [Sanjuuni 工具](https://github.com/MCJack123/sanjuuni/tree/master)(具体功能需参考其官方文档)。
- **接口文档**: [SanjuuniApi 文档](https://www.liulikeji.cn/archives/SanjuuniApi)
• 异步处理: 基于 threading
---
• 缓存清理: 定时任务
## 📦 部署与使用
• 依赖管理: pip
🧩 支持的接口
1. FFmpeg 工具接口
• 功能: 在线调用 FFmpeg 工具进行视频/音频处理(如转码、裁剪、合并等)。
• 接口文档: https://www.liulikeji.cn/archives/FFmpegApi
• 同步接口: POST /api/ffmpeg
• 异步接口: POST /api/ffmpeg/async
2. Sanjuuni 工具接口
• 功能: 在线调用 https://github.com/MCJack123/sanjuuni/tree/master具体功能需参考其官方文档
• 接口文档: https://www.liulikeji.cn/archives/SanjuuniApi
• 同步接口: POST /api/sanjuuni
• 异步接口: POST /api/sanjuuni/async
3. 视频帧提取接口
• 功能: 从视频中提取指定分辨率、帧率的图片帧,支持强制分辨率调整和填充。
• 异步接口: POST /api/video_frame/async
• 参数:
• video_url: 视频文件 URL
• w: 输出宽度
• h: 输出高度
• fps: 输出帧率
• force_resolution: 是否强制调整分辨率
• pad_to_target: 是否填充到目标分辨率
4. 异步任务状态查询
• 功能: 查询异步任务状态和进度,支持日志实时推送。
• 接口: GET /api/task/<task_id>
• 返回字段:
• status: 任务状态pending/running/completed/error
• progress: 进度百分比
• new_logs: 新增的日志条目
• result: 完成后的结果包含下载URL
• error: 错误信息如果状态为error
5. 帧打包接口
• 功能: 将多个帧图片打包为二进制格式,便于批量下载。
• 接口: POST /api/framepack
• 参数:
• urls: 帧图片URL列表格式为 /frames/<job_id>/<filename>.png
• 返回: 二进制流,格式为帧数(4字节) + 各帧数据
6. 文件下载接口
• 功能: 下载处理完成的文件。
• 接口: GET /download/<file_id>/<filename>
7. 任务列表查询
• 功能: 列出所有任务状态(调试用)。
• 接口: GET /api/tasks
8. 健康检查
• 功能: 服务健康检查。
• 接口: GET /health
📦 部署与使用
1. 安装依赖
### 1. 安装依赖
```bash
pip install -r requirements.txt
```
### 2. 启动服务器
```bash
python main.py
```
---
2. 启动服务器
## ⏰ 自动缓存清理配置
- **默认保留时间**: 2 小时
- **自定义配置**:
```python
python main.py --port 5000
3. 异步任务使用示例
创建异步FFmpeg任务
curl -X POST http://localhost:5000/api/ffmpeg/async \
-H "Content-Type: application/json" \
-d '{
"input_url": "http://example.com/input.mp4",
"output_format": "mp4",
"args": ["-c:v", "libx264", "-crf", "23"]
}'
查询任务状态
curl http://localhost:5000/api/task/<task_id>
4. 指定公网地址
在相应工具模块中配置下载URL
# sanjuuni_utils.py
return {
'status': 'success',
'download_url': f"http://ffmpeg.liulikeji.cn/download/{output_id}/{output_filename}", # 外部访问地址
'file_id': output_id,
'temp_dir': temp_dir
}
# ffmpeg_utils.py
return {
'status': 'success',
'download_url': f"http://ffmpeg.liulikeji.cn/download/{output_id}/{output_filename}", # 外部访问地址
'file_id': output_id,
'temp_dir': temp_dir
}
⏰ 自动缓存清理配置
• 默认保留时间: 2 小时
• 自定义配置:
# 在logging_config.py文件中修改缓存清理时间
CLEANUP_INTERVAL = 3600 # 清理临时文件的间隔(秒)
FILE_EXPIRY = 7200 # 文件过期时间(秒)
```
## 端口配置
- **默认端口**: 5000
- **自定义配置**:
```python
# 在main.py文件底部中修改
app.run(debug=True,port=5000)
```
---
🔧 异步任务处理流程
## ⚠️ 注意事项
1. **文件合法性**: 请确保上传文件符合法律法规,不得用于非法用途。
2. **缓存文件**: 系统会自动清理过期文件,请及时下载生成的输出文件。
1. 任务创建: 客户端提交任务请求服务器返回任务ID和状态查询URL
2. 后台处理: 任务在独立线程中执行,不阻塞主进程
3. 状态查询: 客户端可轮询状态接口获取任务进度和实时日志
4. 结果获取: 任务完成后可通过状态接口或文件下载接口获取结果
5. 自动清理: 任务结果文件在指定时间后自动清理
---
⚠️ 注意事项
1. 文件合法性: 请确保上传文件符合法律法规,不得用于非法用途。
2. 缓存文件: 系统会自动清理过期文件,请及时下载生成的输出文件。
3. 异步任务: 异步任务结果在服务器重启后会丢失,请及时处理完成的任务。
4. 资源限制: 视频帧提取和转码操作可能消耗较多CPU和内存资源。
📝 贡献与反馈
## 📝 贡献与反馈
欢迎提交 Issue 或 Pull Request
如有问题,请联系:[xingluo01@liulikeji.cn] 或 [qq:180877430]
---
📁 项目结构
GMapiServer/
├── main.py # 主程序入口
├── shared_utils.py # 共享工具函数
├── ffmpeg_utils.py # FFmpeg处理模块
├── sanjuuni_utils.py # Sanjuuni处理模块
├── video_frame_utils.py # 视频帧提取模块
├── file_cleanup.py # 文件清理模块
├── logging_config.py # 日志配置
├── requirements.txt # 依赖包列表
└── README.md # 项目说明文档

View File

@@ -8,6 +8,7 @@ import logging
import threading
import time
from contextlib import contextmanager
from shared_utils import add_task_log
UPLOAD_FOLDER = 'temp_files'
@@ -17,26 +18,39 @@ def temp_directory(dir=None):
try:
yield temp_dir
finally:
# 不再在这里自动删除临时目录
pass
def download_file(url, temp_dir):
def download_file(url, temp_dir, task_id=None, task_registry=None, task_lock=None):
try:
headers = {
'User-Agent': 'Mozilla/5.0',
'Accept': '*/*'
}
if task_id and task_registry and task_lock:
add_task_log(task_id, f"开始从URL下载文件: {url}", task_registry, task_lock)
logging.info(f"开始从URL下载文件: {url}")
response = requests.get(url, headers=headers, stream=True, timeout=30)
response.raise_for_status()
file_path = os.path.join(temp_dir, 'input_audio')
total_size = int(response.headers.get('content-length', 0))
downloaded_size = 0
with open(file_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
downloaded_size += len(chunk)
# 更新下载进度
if total_size > 0 and task_id and task_registry and task_lock:
progress = min(50, int((downloaded_size / total_size) * 50)) # 下载占50%进度
with task_lock:
if task_id in task_registry:
task_registry[task_id]['progress'] = progress
file_size = os.path.getsize(file_path)
if file_size < 1024:
@@ -44,56 +58,104 @@ def download_file(url, temp_dir):
logging.error(error_msg)
raise Exception(error_msg)
if task_id and task_registry and task_lock:
add_task_log(task_id, f"文件下载成功,保存到: {file_path} (大小: {file_size}字节)", task_registry, task_lock)
logging.info(f"文件下载成功,保存到: {file_path} (大小: {file_size}字节)")
return file_path
except Exception as e:
logging.error(f"{url} 下载文件时出错: {e}")
error_msg = f"{url} 下载文件时出错: {e}"
if task_id and task_registry and task_lock:
add_task_log(task_id, error_msg, task_registry, task_lock)
logging.error(error_msg)
raise
def execute_ffmpeg(input_path, output_path, ffmpeg_args):
def execute_ffmpeg(input_path, output_path, ffmpeg_args, task_id=None, task_registry=None, task_lock=None):
try:
filtered_args = [arg for arg in ffmpeg_args if not (arg.lower() in ['-i', '-input'] or
(ffmpeg_args.index(arg) > 0 and ffmpeg_args[ffmpeg_args.index(arg) - 1].lower() == '-i'))]
cmd = ['lib/ffmpeg/bin/ffmpeg', '-i', input_path] + filtered_args + [output_path]
if task_id and task_registry and task_lock:
add_task_log(task_id, f"执行FFmpeg命令: {' '.join(cmd)}", task_registry, task_lock)
logging.info(f"执行FFmpeg命令: {' '.join(cmd)}")
result = subprocess.run(
# 使用Popen来实时捕获输出
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stderr=subprocess.STDOUT, # 将stderr重定向到stdout
universal_newlines=True,
encoding='utf-8',
errors='replace'
errors='replace',
bufsize=1
)
if result.returncode != 0:
error_msg = f"FFmpeg处理失败返回码: {result.returncode}, 错误: {result.stderr}"
# 实时读取输出
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
output = output.strip()
if output and task_id and task_registry and task_lock:
add_task_log(task_id, output, task_registry, task_lock)
# 简单的进度解析可以根据FFmpeg的输出格式进行优化
if 'time=' in output and 'bitrate=' in output:
# 这里可以添加更复杂的进度解析逻辑
if task_id and task_registry and task_lock:
with task_lock:
if task_id in task_registry:
# 处理进度从50%开始到100%
task_registry[task_id]['progress'] = 50 + 50 // 2 # 简单示例
returncode = process.poll()
if returncode != 0:
error_msg = f"FFmpeg处理失败返回码: {returncode}"
if task_id and task_registry and task_lock:
add_task_log(task_id, error_msg, task_registry, task_lock)
logging.error(error_msg)
raise Exception(error_msg)
if task_id and task_registry and task_lock:
add_task_log(task_id, "FFmpeg处理成功完成", task_registry, task_lock)
logging.info("FFmpeg处理成功完成")
return True
except Exception as e:
logging.error(f"执行FFmpeg时出错: {e}")
error_msg = f"执行FFmpeg时出错: {e}"
if task_id and task_registry and task_lock:
add_task_log(task_id, error_msg, task_registry, task_lock)
logging.error(error_msg)
raise
def process_ffmpeg(data, file_registry, file_lock):
def process_ffmpeg(data, file_registry, file_lock, task_id=None, task_registry=None, task_lock=None):
try:
temp_dir = tempfile.mkdtemp(dir=UPLOAD_FOLDER)
if task_id and task_registry and task_lock:
add_task_log(task_id, f"创建临时目录: {temp_dir}", task_registry, task_lock)
logging.info(f"创建临时目录: {temp_dir}")
input_url = data.get('input_url')
ffmpeg_args = data.get('args', [])
input_path = download_file(input_url, temp_dir)
input_path = download_file(input_url, temp_dir, task_id, task_registry, task_lock)
output_id = str(uuid.uuid4())[:8]
output_format = data.get('output_format', 'mp4')
output_filename = f"{output_id}.{output_format}"
output_path = os.path.join(temp_dir, output_filename)
execute_ffmpeg(input_path, output_path, ffmpeg_args)
if task_id and task_registry and task_lock:
add_task_log(task_id, f"开始FFmpeg处理输出格式: {output_format}", task_registry, task_lock)
with task_lock:
if task_id in task_registry:
task_registry[task_id]['progress'] = 50 # 开始处理进度50%
execute_ffmpeg(input_path, output_path, ffmpeg_args, task_id, task_registry, task_lock)
with file_lock:
file_registry[output_id] = {
@@ -102,16 +164,26 @@ def process_ffmpeg(data, file_registry, file_lock):
'last_access': time.time(),
'download_count': 0
}
logging.info(f"已注册新文件ID: {output_id}, 路径: {output_path}")
if task_id and task_registry and task_lock:
add_task_log(task_id, f"已注册新文件ID: {output_id}, 路径: {output_path}", task_registry, task_lock)
with task_lock:
if task_id in task_registry:
task_registry[task_id]['progress'] = 100 # 处理完成进度100%
logging.info(f"已注册新文件ID: {output_id}, 路径: {output_path}")
# 返回临时目录路径以便在主函数中删除
return {
'status': 'success',
'download_url': f"http://ffmpeg.liulikeji.cn/download/{output_id}/{output_filename}",
'download_url': f"http://newgmapi.liulikeji.cn/download/{output_id}/{output_filename}",
'file_id': output_id,
'temp_dir': temp_dir # 返回临时目录路径
'temp_dir': temp_dir
}
except Exception as e:
logging.error(f"处理过程中出错: {e}")
return {'error': str(e)}
error_msg = f"处理过程中出错: {e}"
if task_id and task_registry and task_lock:
add_task_log(task_id, error_msg, task_registry, task_lock)
logging.error(error_msg)
return {'error': str(e)}

View File

@@ -3,33 +3,53 @@ import shutil
import threading
import time
import logging
from shared_utils import file_registry, file_lock, task_registry, task_lock
UPLOAD_FOLDER = 'temp_files'
FRAMES_FOLDER = 'frames' # 视频帧提取任务文件夹
CLEANUP_INTERVAL = 3600 # 清理临时文件的间隔(秒)
FILE_EXPIRY = 7200 # 文件过期时间(秒)
file_registry = {}
file_lock = threading.Lock()
TASK_EXPIRY = 7200 # 任务记录过期时间(秒)
def cleanup_temp_files():
current_time = time.time()
expired_folders = []
for folder_name in os.listdir(UPLOAD_FOLDER):
folder_path = os.path.join(UPLOAD_FOLDER, folder_name)
if not os.path.isdir(folder_path):
continue
# 清理temp_files目录
if os.path.exists(UPLOAD_FOLDER):
for folder_name in os.listdir(UPLOAD_FOLDER):
folder_path = os.path.join(UPLOAD_FOLDER, folder_name)
try:
folder_mtime = os.path.getmtime(folder_path)
if current_time - folder_mtime > FILE_EXPIRY:
expired_folders.append(folder_path)
logging.info(f"检测到过期文件夹: {folder_path} (修改时间: {time.ctime(folder_mtime)})")
except Exception as e:
logging.error(f"获取文件夹 {folder_path} 信息失败: {e}")
if not os.path.isdir(folder_path):
continue
try:
folder_mtime = os.path.getmtime(folder_path)
if current_time - folder_mtime > FILE_EXPIRY:
expired_folders.append(folder_path)
logging.info(f"检测到过期文件夹: {folder_path} (修改时间: {time.ctime(folder_mtime)})")
except Exception as e:
logging.error(f"获取文件夹 {folder_path} 信息失败: {e}")
# 清理frames目录
if os.path.exists(FRAMES_FOLDER):
for folder_name in os.listdir(FRAMES_FOLDER):
folder_path = os.path.join(FRAMES_FOLDER, folder_name)
if not os.path.isdir(folder_path):
continue
try:
folder_mtime = os.path.getmtime(folder_path)
if current_time - folder_mtime > FILE_EXPIRY:
expired_folders.append(folder_path)
logging.info(f"检测到过期视频帧文件夹: {folder_path} (修改时间: {time.ctime(folder_mtime)})")
except Exception as e:
logging.error(f"获取视频帧文件夹 {folder_path} 信息失败: {e}")
# 删除所有过期文件夹
for folder_path in expired_folders:
try:
shutil.rmtree(folder_path)
@@ -39,6 +59,35 @@ def cleanup_temp_files():
logging.info(f"清理完成,共删除 {len(expired_folders)} 个过期文件夹")
# 清理过期的任务记录和文件记录
cleanup_expired_registries(current_time)
def cleanup_expired_registries(current_time):
"""清理过期的任务记录和文件记录"""
# 清理过期的任务记录
with task_lock:
expired_tasks = []
for task_id, task_info in list(task_registry.items()):
if current_time - task_info['create_time'] > TASK_EXPIRY:
expired_tasks.append(task_id)
for task_id in expired_tasks:
del task_registry[task_id]
logging.info(f"已清理过期任务记录: {task_id}")
# 清理过期的文件记录(基于最后访问时间)
with file_lock:
expired_files = []
for file_id, file_info in list(file_registry.items()):
if current_time - file_info['last_access'] > FILE_EXPIRY:
expired_files.append(file_id)
for file_id in expired_files:
del file_registry[file_id]
logging.info(f"已清理过期文件记录: {file_id}")
logging.info(f"共清理 {len(expired_tasks)} 个任务记录和 {len(expired_files)} 个文件记录")
def start_cleanup_thread():
def cleanup_loop():
while True:

371
main.py
View File

@@ -4,15 +4,30 @@ from flask import Flask, request, jsonify
import threading
import queue
import time
from ffmpeg_utils import process_ffmpeg
from sanjuuni_utils import process_sanjuuni
from file_cleanup import start_cleanup_thread
import argparse
import uuid
from shared_utils import task_registry, file_registry, file_lock, task_lock, add_task_log
# 在导入其他模块之前先定义全局变量
app = Flask(__name__)
# 假设这些是主文件中已定义的变量
file_registry = {}
file_lock = threading.Lock()
# 延迟导入,避免循环导入
try:
from ffmpeg_utils import process_ffmpeg
from sanjuuni_utils import process_sanjuuni
from video_frame_utils import process_video_frame_extraction
from file_cleanup import start_cleanup_thread
except ImportError as e:
logging.error(f"导入模块时出错: {e}")
# 定义空函数作为备用
def process_ffmpeg(*args, **kwargs):
return {'error': 'FFmpeg模块未正确导入'}
def process_sanjuuni(*args, **kwargs):
return {'error': 'Sanjuuni模块未正确导入'}
def process_video_frame_extraction(*args, **kwargs):
return {'error': '视频帧提取模块未正确导入'}
def start_cleanup_thread():
pass
# 输入参数列表
enter_parameter_table = {
@@ -25,6 +40,14 @@ enter_parameter_table = {
"input_url": str,
"output_format": str,
"args": list
},
"video_frame": {
"video_url": str,
"w": int,
"h": int,
"fps": int,
"force_resolution": bool,
"pad_to_target": bool
}
}
@@ -39,6 +62,222 @@ def validate_request(data, api_name):
return jsonify({'error': f"{key}参数类型错误,您输入为{type(data[key])},应为{enter_parameter_table[api_name][key]}" }), 400
return None, None
def run_async_task(task_id, process_func, data):
"""运行异步任务"""
try:
with app.app_context():
# 更新任务状态为运行中
with task_lock:
task_registry[task_id]['status'] = 'running'
task_registry[task_id]['start_time'] = time.time()
# 执行处理函数
result = process_func(data, file_registry, file_lock, task_id, task_registry, task_lock)
# 更新任务状态
with task_lock:
if 'error' in result:
task_registry[task_id]['status'] = 'error'
task_registry[task_id]['error'] = result['error']
else:
task_registry[task_id]['status'] = 'completed'
task_registry[task_id]['result'] = result
task_registry[task_id]['end_time'] = time.time()
except Exception as e:
logging.error(f"任务 {task_id} 执行异常: {e}")
with task_lock:
task_registry[task_id]['status'] = 'error'
task_registry[task_id]['error'] = str(e)
task_registry[task_id]['end_time'] = time.time()
@app.route('/api/ffmpeg/async', methods=['POST'])
def ffmpeg_async_api():
"""创建异步FFmpeg任务"""
logging.info("收到异步FFmpeg API请求")
data = request.get_json()
# 检测参数类型
error_response, status_code = validate_request(data, "ffmpeg")
if error_response:
return error_response, status_code
# 生成任务ID
task_id = str(uuid.uuid4())[:8]
# 获取请求的主机信息用于构建URL
host = request.host
scheme = request.scheme
# 初始化任务状态
with task_lock:
task_registry[task_id] = {
'status': 'pending',
'type': 'ffmpeg',
'create_time': time.time(),
'logs': [],
'last_returned_index': 0, # 记录最后返回的日志索引
'progress': 0
}
# 启动异步任务
thread = threading.Thread(
target=run_async_task,
args=(task_id, process_ffmpeg, data)
)
thread.daemon = True
thread.start()
status_url = f"{scheme}://{host}/api/task/{task_id}"
logging.info(f"创建异步FFmpeg任务: {task_id}")
return jsonify({
'status': 'success',
'task_id': task_id,
'status_url': status_url,
'message': '任务已创建请使用状态URL查询进度'
}), 202
@app.route('/api/sanjuuni/async', methods=['POST'])
def sanjuuni_async_api():
"""创建异步Sanjuuni任务"""
logging.info("收到异步Sanjuuni API请求")
data = request.get_json()
# 检测参数类型
error_response, status_code = validate_request(data, "sanjuuni")
if error_response:
return error_response, status_code
# 生成任务ID
task_id = str(uuid.uuid4())[:8]
# 获取请求的主机信息用于构建URL
host = request.host
scheme = request.scheme
# 初始化任务状态
with task_lock:
task_registry[task_id] = {
'status': 'pending',
'type': 'sanjuuni',
'create_time': time.time(),
'logs': [],
'last_returned_index': 0, # 记录最后返回的日志索引
'progress': 0
}
# 启动异步任务
thread = threading.Thread(
target=run_async_task,
args=(task_id, process_sanjuuni, data)
)
thread.daemon = True
thread.start()
status_url = f"{scheme}://{host}/api/task/{task_id}"
logging.info(f"创建异步Sanjuuni任务: {task_id}")
return jsonify({
'status': 'success',
'task_id': task_id,
'status_url': status_url,
'message': '任务已创建请使用状态URL查询进度'
}), 202
@app.route('/api/video_frame/async', methods=['POST'])
def video_frame_async_api():
"""创建异步视频帧提取任务"""
logging.info("收到异步视频帧提取API请求")
data = request.get_json()
# 检测参数类型
error_response, status_code = validate_request(data, "video_frame")
if error_response:
return error_response, status_code
# 生成任务ID
task_id = str(uuid.uuid4())[:8]
# 获取请求的主机信息用于构建URL
host = request.host
scheme = request.scheme
# 初始化任务状态
with task_lock:
task_registry[task_id] = {
'status': 'pending',
'type': 'video_frame',
'create_time': time.time(),
'logs': [],
'last_returned_index': 0, # 记录最后返回的日志索引
'progress': 0
}
# 启动异步任务
thread = threading.Thread(
target=run_async_task,
args=(task_id, process_video_frame_extraction, data)
)
thread.daemon = True
thread.start()
status_url = f"{scheme}://{host}/api/task/{task_id}"
logging.info(f"创建异步视频帧提取任务: {task_id}")
return jsonify({
'status': 'success',
'task_id': task_id,
'status_url': status_url,
'message': '任务已创建请使用状态URL查询进度'
}), 202
@app.route('/api/task/<task_id>', methods=['GET'])
def get_task_status(task_id):
"""查询任务状态和进度(自动返回新增日志)"""
with task_lock:
if task_id not in task_registry:
return jsonify({'error': '任务不存在'}), 404
task_info = task_registry[task_id].copy()
current_log_count = len(task_info['logs'])
last_returned_index = task_info['last_returned_index']
# 计算新增日志
if last_returned_index < current_log_count:
new_logs = task_info['logs'][last_returned_index:]
# 更新最后返回的日志索引
task_registry[task_id]['last_returned_index'] = current_log_count
else:
new_logs = []
# 构建响应
response = {
'task_id': task_id,
'status': task_info['status'],
'type': task_info['type'],
'create_time': task_info['create_time'],
'progress': task_info.get('progress', 0),
'total_logs': current_log_count,
'new_logs': new_logs,
'last_index': current_log_count # 返回当前日志总数,方便客户端跟踪
}
if 'start_time' in task_info:
response['start_time'] = task_info['start_time']
if 'end_time' in task_info:
response['end_time'] = task_info['end_time']
# 根据状态返回不同信息
if task_info['status'] == 'completed':
response['result'] = task_info['result']
elif task_info['status'] == 'error':
response['error'] = task_info['error']
return jsonify(response), 200
# 原有的同步接口保持不变
@app.route('/api/ffmpeg', methods=['POST'])
def ffmpeg_api():
logging.info("收到FFmpeg API请求")
@@ -46,12 +285,14 @@ def ffmpeg_api():
# 检测参数类型
error_response, status_code = validate_request(data, "ffmpeg")
if error_response: return error_response, status_code
if error_response:
assert status_code is not None
return error_response, status_code
# 创建处理进程
result_queue = queue.Queue()
def run_process(data, file_registry, file_lock, result_queue):
with app.app_context(): # 设置应用上下文
with app.app_context():
result = process_ffmpeg(data, file_registry, file_lock)
result_queue.put(result)
@@ -78,12 +319,14 @@ def sanjuuni_api():
# 检测参数类型
error_response, status_code = validate_request(data, "sanjuuni")
if error_response: return error_response, status_code
if error_response:
assert status_code is not None
return error_response, status_code
# 创建处理进程
result_queue = queue.Queue()
def run_process(data, file_registry, file_lock, result_queue):
with app.app_context(): # 设置应用上下文
with app.app_context():
result = process_sanjuuni(data, file_registry, file_lock)
result_queue.put(result)
@@ -122,7 +365,111 @@ def download_file_endpoint(file_id, filename):
logging.error(f"下载文件时出错: {e}")
return jsonify({'status': 'error', 'error': str(e)}), 500
@app.route('/frames/<job_id>/<filename>', methods=['GET'])
def serve_video_frames(job_id, filename):
"""提供视频帧和音频文件访问"""
import os
from flask import send_from_directory
from video_frame_utils import FRAMES_ROOT
safe_job = os.path.basename(job_id)
safe_file = os.path.basename(filename)
dir_path = os.path.join(FRAMES_ROOT, safe_job)
if not os.path.isdir(dir_path):
return jsonify({"error": "文件不存在"}), 404
allowed = safe_file.endswith(('.png', '.dfpwm'))
if not allowed:
return jsonify({"error": "文件类型不支持"}), 400
try:
return send_from_directory(dir_path, safe_file)
except Exception as e:
logging.error(f"提供文件时出错: {e}")
return jsonify({"error": "文件访问失败"}), 500
@app.route('/api/framepack', methods=['POST'])
def create_framepack():
"""接收一组相对路径(如 /frames/abc123/frame_0001.png打包返回二进制"""
import struct
from video_frame_utils import FRAMES_ROOT
import os
data = request.get_json()
if not data or 'urls' not in data or not isinstance(data['urls'], list):
return jsonify({'error': 'Missing urls list'}), 400
# 构建完整本地路径,验证安全性
file_paths = []
for url in data['urls']:
# 只允许以 /frames/ 开头的路径
if not url.startswith('/frames/'):
return jsonify({'error': f'Invalid URL prefix: {url}'}), 400
# 提取 job_id 和 filename
parts = url[len('/frames/'):].split('/', 1)
if len(parts) != 2:
return jsonify({'error': f'Malformed URL: {url}'}), 400
job_id, filename = parts
# 安全路径拼接
safe_job = os.path.basename(job_id)
safe_file = os.path.basename(filename)
if not safe_file.endswith('.png'):
return jsonify({'error': f'Only .png allowed: {filename}'}), 400
full_path = os.path.join(FRAMES_ROOT, safe_job, safe_file)
if not os.path.isfile(full_path):
return jsonify({'error': f'File not found: {full_path}'}), 404
file_paths.append(full_path)
# 构建 FramePack 二进制
pack_data = bytearray()
frame_count = len(file_paths)
pack_data.extend(struct.pack('>I', frame_count)) # big-endian uint32
# 先读所有文件到内存(小批量安全)
frames = []
for path in file_paths:
with open(path, 'rb') as f:
frames.append(f.read())
for frame in frames:
pack_data.extend(struct.pack('>I', len(frame)))
pack_data.extend(frame)
response = app.response_class(
response=bytes(pack_data),
status=200,
mimetype='application/octet-stream'
)
response.headers['Content-Disposition'] = 'inline; filename="framepack.bin"'
return response
@app.route('/health', methods=['GET'])
def health_check():
"""健康检查接口,直接返回 'ok'"""
return "OK"
@app.route('/api/tasks', methods=['GET'])
def list_tasks():
"""列出所有任务(用于调试)"""
with task_lock:
tasks = {}
for task_id, task_info in task_registry.items():
tasks[task_id] = {
'status': task_info['status'],
'type': task_info['type'],
'create_time': task_info['create_time'],
'progress': task_info.get('progress', 0)
}
return jsonify(tasks), 200
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
# 配置命令行参数解析
parser = argparse.ArgumentParser(description='启动FFmpeg处理服务')
parser.add_argument('--port', type=int, default=5000, help='服务监听的端口号(默认: 5000')
args = parser.parse_args()
logging.info(f"启动应用程序,端口: {args.port}...")
start_cleanup_thread()
app.run(debug=True)
app.run(host='0.0.0.0', port=args.port, threaded=True)

View File

@@ -1,2 +1,3 @@
Flask==3.1.0
Requests==2.32.3
yt-dlp

View File

@@ -6,7 +6,8 @@ import tempfile
import shutil
import logging
from contextlib import contextmanager
import time # 导入 time 模块
import time
from shared_utils import add_task_log
@contextmanager
def temp_directory(dir=None):
@@ -16,13 +17,16 @@ def temp_directory(dir=None):
finally:
pass
def download_file(url, temp_dir):
def download_file(url, temp_dir, task_id=None, task_registry=None, task_lock=None):
try:
headers = {
'User-Agent': 'Mozilla/5.0',
'Accept': '*/*'
}
if task_id and task_registry and task_lock:
add_task_log(task_id, f"开始从URL下载文件: {url}", task_registry, task_lock)
logging.info(f"开始从URL下载文件: {url}")
response = requests.get(url, headers=headers, stream=True, timeout=30)
response.raise_for_status()
@@ -40,44 +44,79 @@ def download_file(url, temp_dir):
logging.error(error_msg)
raise Exception(error_msg)
if task_id and task_registry and task_lock:
add_task_log(task_id, f"文件下载成功,保存到: {file_path} (大小: {file_size}字节)", task_registry, task_lock)
logging.info(f"文件下载成功,保存到: {file_path} (大小: {file_size}字节)")
return file_path
except Exception as e:
logging.error(f"{url} 下载文件时出错: {e}")
error_msg = f"{url} 下载文件时出错: {e}"
if task_id and task_registry and task_lock:
add_task_log(task_id, error_msg, task_registry, task_lock)
logging.error(error_msg)
raise
def execute_sanjuuni(input_path, output_path, sanjuuni_args):
def execute_sanjuuni(input_path, output_path, sanjuuni_args, task_id=None, task_registry=None, task_lock=None):
try:
cmd = ['lib/sanjuuni/sanjuuni', '-i', input_path] + sanjuuni_args + ['-o', output_path]
if task_id and task_registry and task_lock:
add_task_log(task_id, f"执行Sanjuuni命令: {' '.join(cmd)}", task_registry, task_lock)
logging.info(f"执行Sanjuuni命令: {' '.join(cmd)}")
result = subprocess.run(
# 使用Popen来实时捕获输出
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
encoding='utf-8',
errors='replace'
errors='replace',
bufsize=1
)
if result.returncode != 0:
error_msg = f"Sanjuuni处理失败返回码: {result.returncode}, 错误: {result.stderr}"
# 实时读取输出
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
output = output.strip()
if output and task_id and task_registry and task_lock:
add_task_log(task_id, output, task_registry, task_lock)
returncode = process.poll()
if returncode != 0:
error_msg = f"Sanjuuni处理失败返回码: {returncode}"
if task_id and task_registry and task_lock:
add_task_log(task_id, error_msg, task_registry, task_lock)
logging.error(error_msg)
raise Exception(error_msg)
if task_id and task_registry and task_lock:
add_task_log(task_id, "Sanjuuni处理成功完成", task_registry, task_lock)
logging.info("Sanjuuni处理成功完成")
return True
except Exception as e:
logging.error(f"执行Sanjuuni时出错: {e}")
error_msg = f"执行Sanjuuni时出错: {e}"
if task_id and task_registry and task_lock:
add_task_log(task_id, error_msg, task_registry, task_lock)
logging.error(error_msg)
raise
def process_sanjuuni(data, file_registry, file_lock):
def process_sanjuuni(data, file_registry, file_lock, task_id=None, task_registry=None, task_lock=None):
try:
temp_dir = tempfile.mkdtemp(dir='temp_files')
if task_id and task_registry and task_lock:
add_task_log(task_id, f"创建临时目录: {temp_dir}", task_registry, task_lock)
logging.info(f"创建临时目录: {temp_dir}")
input_url = data.get('input_url')
sanjuuni_args = data.get('args', []) # 从请求数据中获取 args 参数
sanjuuni_args = data.get('args', [])
# 定义不允许的参数
disallowed_params = [
@@ -114,33 +153,46 @@ def process_sanjuuni(data, file_registry, file_lock):
else:
raise ValueError(f"Unsupported output format: {output_format}")
input_path = download_file(input_url, temp_dir)
input_path = download_file(input_url, temp_dir, task_id, task_registry, task_lock)
output_id = str(uuid.uuid4())[:8]
output_filename = f"{output_id}.{output_format}"
output_path = os.path.join(temp_dir, output_filename)
execute_sanjuuni(input_path, output_path, sanjuuni_args)
if task_id and task_registry and task_lock:
add_task_log(task_id, f"开始Sanjuuni处理输出格式: {output_format}", task_registry, task_lock)
with task_lock:
if task_id in task_registry:
task_registry[task_id]['progress'] = 50
execute_sanjuuni(input_path, output_path, sanjuuni_args, task_id, task_registry, task_lock)
with file_lock:
file_registry[output_id] = {
'path': os.path.abspath(output_path),
'filename': output_filename,
'last_access': time.time(), # 使用 time.time() 记录最后访问时间
'last_access': time.time(),
'download_count': 0
}
logging.info(f"已注册新文件ID: {output_id}, 路径: {output_path}")
if task_id and task_registry and task_lock:
add_task_log(task_id, f"已注册新文件ID: {output_id}, 路径: {output_path}", task_registry, task_lock)
with task_lock:
if task_id in task_registry:
task_registry[task_id]['progress'] = 100
logging.info(f"已注册新文件ID: {output_id}, 路径: {output_path}")
return {
'status': 'success',
'download_url': f"http://ffmpeg.liulikeji.cn/download/{output_id}/{output_filename}",
'download_url': f"http://newgmapi.liulikeji.cn/download/{output_id}/{output_filename}",
'file_id': output_id,
'temp_dir': temp_dir # 返回临时目录路径
'temp_dir': temp_dir
}
except Exception as e:
logging.error(f"处理过程中出错: {e}")
return {'error': str(e)}
error_msg = f"处理过程中出错: {e}"
if task_id and task_registry and task_lock:
add_task_log(task_id, error_msg, task_registry, task_lock)
logging.error(error_msg)
return {'error': str(e)}

155640
server.log Normal file

File diff suppressed because it is too large Load Diff

22
shared_utils.py Normal file
View File

@@ -0,0 +1,22 @@
# shared_utils.py
import time
import logging
from threading import Lock
# 全局变量
task_registry = {}
file_registry = {}
file_lock = Lock()
task_lock = Lock()
def add_task_log(task_id, message, task_registry, task_lock):
"""添加任务日志"""
with task_lock:
if task_id in task_registry:
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
log_entry = f"[{timestamp}] {message}"
task_registry[task_id]['logs'].append(log_entry)
# 保持日志数量不超过1000条
if len(task_registry[task_id]['logs']) > 1000:
task_registry[task_id]['logs'] = task_registry[task_id]['logs'][-1000:]

68
start_server.py Normal file
View File

@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""
启动GMapiServer的启动脚本
包含所有功能FFmpeg处理、Sanjuuni处理、视频帧提取
"""
import os
import sys
import logging
from main import app
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler('server.log')
]
)
def main():
print("🚀 GMapiServer 启动中...")
print("=" * 50)
print("📋 可用功能:")
print(" • FFmpeg媒体处理 (同步/异步)")
print(" • Sanjuuni工具处理 (同步/异步)")
print(" • 视频帧提取 (异步,支持B站BV号)")
print()
print("🔧 配置信息:")
print(f" 端口: 5000")
print(f" 临时文件目录: temp_files/")
print(f" 视频帧目录: frames/")
print(f" 清理间隔: 1小时")
print()
print("🔗 API 端点:")
print(" 同步接口:")
print(" POST /api/ffmpeg - FFmpeg处理")
print(" POST /api/sanjuuni - Sanjuuni处理")
print()
print(" 异步接口:")
print(" POST /api/ffmpeg/async - 异步FFmpeg处理")
print(" POST /api/sanjuuni/async - 异步Sanjuuni处理")
print(" POST /api/video_frame/async - 异步视频帧提取")
print(" GET /api/task/<task_id> - 查询异步任务状态")
print(" GET /api/tasks - 所有任务列表")
print()
print(" 文件下载:")
print(" GET /download/<file_id>/<filename> - 下载处理后的文件")
print(" GET /frames/<job_id>/<filename> - 下载视频帧/音频文件")
print()
print(" 其他:")
print(" GET /health - 健康检查")
print(" GET /api/tasks - 任务列表(调试)")
print("=" * 50)
print()
print("🌐 服务器地址: http://0.0.0.0:5000")
print("🔄 自动清理机制已启用 - 临时文件将在2小时后自动删除")
print()
# 启动Flask应用
from file_cleanup import start_cleanup_thread
start_cleanup_thread()
app.run(host='0.0.0.0', port=5000, debug=False, threaded=True)
if __name__ == '__main__':
main()

391
video_frame_utils.py Normal file
View File

@@ -0,0 +1,391 @@
import os
import sys
import uuid
import subprocess
import tempfile
import threading
import time
from datetime import datetime, timedelta
import json
import glob
import requests
import logging
from shared_utils import task_registry, file_registry, file_lock, task_lock, add_task_log
# ======================
# 配置
# ======================
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
FRAMES_ROOT = os.path.abspath("./frames")
TASK_TIMEOUT_HOURS = 1 # 任务过期时间(小时)
# 确保frames目录存在
os.makedirs(FRAMES_ROOT, exist_ok=True)
if sys.platform.startswith('win'):
FFMPEG_PATH = os.path.join(BASE_DIR, 'lib', 'ffmpeg', 'bin', 'ffmpeg.exe')
FFPROBE_PATH = os.path.join(BASE_DIR, 'lib', 'ffmpeg', 'bin', 'ffprobe.exe')
else:
FFMPEG_PATH = os.path.join(BASE_DIR, 'lib', 'ffmpeg', 'bin', 'ffmpeg')
FFPROBE_PATH = os.path.join(BASE_DIR, 'lib', 'ffmpeg', 'bin', 'ffprobe')
def log_subprocess_output(pipe, task_id, task_registry, task_lock, prefix=""):
"""从管道实时读取并记录日志"""
if not pipe:
return
try:
for line in iter(pipe.readline, ''):
if line:
clean_line = line.strip()
if clean_line and task_id and task_registry and task_lock:
add_task_log(task_id, f"{prefix}{clean_line}", task_registry, task_lock)
except Exception as e:
if task_id and task_registry and task_lock:
add_task_log(task_id, f"[日志读取错误] {e}", task_registry, task_lock)
finally:
pipe.close()
# ======================
# 任务处理函数
# ======================
def process_video_frame_extraction(data, file_registry, file_lock, task_id=None, task_registry=None, task_lock=None):
"""处理视频帧提取任务"""
try:
if task_id and task_registry and task_lock:
add_task_log(task_id, "开始处理视频帧提取任务", task_registry, task_lock)
logging.info(f"开始处理视频帧提取任务: {task_id}")
# 提取参数
video_url = data.get('video_url')
video_bv = data.get('video_bv') # 支持BV号
w = data.get('w')
h = data.get('h')
fps = data.get('fps', 30)
force_resolution = data.get('force_resolution', False)
pad_to_target = data.get('pad_to_target', False)
# 验证参数
if not video_url and not video_bv:
raise Exception("缺少必要参数: video_url 或 video_bv")
if w is None or h is None:
raise Exception("缺少必要参数: w, h")
try:
w = int(w)
h = int(h)
fps = float(fps)
if w <= 0 or h <= 0 or fps <= 0:
raise ValueError("参数必须为正数")
except (ValueError, TypeError) as e:
raise Exception(f"参数无效: {str(e)}")
# 如果提供了BV号自动生成Bilibili URL
if not video_url and video_bv:
video_bv = str(video_bv).strip()
if not video_bv.startswith(('BV', 'bv')):
raise Exception("video_bv 必须以 BV 或 bv 开头")
video_url = f"https://www.bilibili.com/video/{video_bv.upper()}"
# 准备目录
job_dir = os.path.join(FRAMES_ROOT, task_id)
os.makedirs(job_dir, exist_ok=True)
if task_id and task_registry and task_lock:
add_task_log(task_id, f"创建任务目录: {job_dir}", task_registry, task_lock)
with task_lock:
if task_id in task_registry:
task_registry[task_id]['progress'] = 10
# 下载视频
temp_base = os.path.join(tempfile.gettempdir(), task_id)
# === 替换 yt-dlp 下载部分 ===
if task_id and task_registry and task_lock:
add_task_log(task_id, f"开始下载视频: {video_url}", task_registry, task_lock)
yt_dlp_cmd = [
sys.executable, '-m', 'yt_dlp',
video_url,
'-o', temp_base,
]
# 使用 Popen 实时捕获 stderr
proc = subprocess.Popen(
yt_dlp_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
universal_newlines=True
)
# 启动日志线程(只读 stderr因为 yt-dlp 进度在 stderr
stderr_thread = threading.Thread(
target=log_subprocess_output,
args=(proc.stderr, task_id, task_registry, task_lock, "[yt-dlp] "),
daemon=True
)
stderr_thread.start()
try:
proc.wait(timeout=600)
if proc.returncode != 0:
raise subprocess.CalledProcessError(proc.returncode, yt_dlp_cmd)
except subprocess.TimeoutExpired:
proc.kill()
raise Exception("yt-dlp 下载超时超过10分钟")
finally:
stderr_thread.join(timeout=5) # 等待日志线程结束
# 查找实际生成的文件
candidates = glob.glob(temp_base + ".*")
if not candidates:
raise Exception("yt-dlp 执行成功但未生成任何视频文件")
# 按修改时间取最新
temp_video = max(candidates, key=os.path.getmtime)
if task_id and task_registry and task_lock:
add_task_log(task_id, "下载完成,开始获取视频信息", task_registry, task_lock)
with task_lock:
if task_id in task_registry:
task_registry[task_id]['progress'] = 40
# 获取视频信息
duration = get_video_duration(temp_video)
# 构建滤镜
vf = build_video_filter(w, h, fps, force_resolution, pad_to_target)
# 提取帧
if task_id and task_registry and task_lock:
add_task_log(task_id, "开始提取视频帧", task_registry, task_lock)
with task_lock:
if task_id in task_registry:
task_registry[task_id]['progress'] = 50
frame_pattern = os.path.join(job_dir, "frame_%06d.png")
ffmpeg_cmd = [
FFMPEG_PATH, '-y',
'-i', temp_video,
'-vf', vf,
'-pix_fmt', 'rgb24',
'-stats', # 关键:启用进度统计
'-v', 'info', # 确保输出级别足够
frame_pattern
]
proc = subprocess.Popen(
ffmpeg_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
universal_newlines=True
)
# FFmpeg 的进度在 stderr
stderr_thread = threading.Thread(
target=log_subprocess_output,
args=(proc.stderr, task_id, task_registry, task_lock, "[FFmpeg] "),
daemon=True
)
stderr_thread.start()
try:
proc.wait()
if proc.returncode != 0:
raise subprocess.CalledProcessError(proc.returncode, ffmpeg_cmd)
finally:
stderr_thread.join(timeout=5)
# 获取输出分辨率
if task_id and task_registry and task_lock:
add_task_log(task_id, "分析输出结果", task_registry, task_lock)
with task_lock:
if task_id in task_registry:
task_registry[task_id]['progress'] = 80
out_w, out_h = get_output_resolution(job_dir)
total_frames = len([f for f in os.listdir(job_dir) if f.endswith('.png')])
# 检查音频
audio_exists = has_audio(temp_video)
if audio_exists:
if task_id and task_registry and task_lock:
add_task_log(task_id, "提取音频(左/右/混合声道)", task_registry, task_lock)
with task_lock:
if task_id in task_registry:
task_registry[task_id]['progress'] = 90
# 公共参数
dfpwm_args = [
FFMPEG_PATH, '-y',
'-i', temp_video,
'-vn',
'-ar', '48000',
'-ac', '1',
'-f', 'dfpwm'
]
# 混合声道
dfpwm_path_mix = os.path.join(job_dir, "audio.dfpwm")
subprocess.run(
dfpwm_args + [dfpwm_path_mix],
check=True, capture_output=True
)
# 左声道
dfpwm_path_left = os.path.join(job_dir, "audio_left.dfpwm")
subprocess.run(
dfpwm_args + ['-af', 'pan=mono|c0=c0'] + [dfpwm_path_left],
check=True, capture_output=True
)
# 右声道
dfpwm_path_right = os.path.join(job_dir, "audio_right.dfpwm")
subprocess.run(
dfpwm_args + ['-af', 'pan=mono|c0=c1'] + [dfpwm_path_right],
check=True, capture_output=True
)
# 生成结果
result_data = {
"duration_seconds": round(duration, 3),
"total_frames": total_frames,
"fps": fps,
"output_resolution": {"w": out_w, "h": out_h},
"frame_urls": [f"/frames/{task_id}/frame_{i:06d}.png" for i in range(1, total_frames + 1)],
"audio_dfpwm_url": f"/frames/{task_id}/audio.dfpwm" if has_audio else None,
"audio_dfpwm_left_url": f"/frames/{task_id}/audio_left.dfpwm" if has_audio else None,
"audio_dfpwm_right_url": f"/frames/{task_id}/audio_right.dfpwm" if has_audio else None
}
# 注册文件到文件注册表
with file_lock:
for frame_file in glob.glob(os.path.join(job_dir, "frame_*.png")):
filename = os.path.basename(frame_file)
file_id = f"frame_{task_id}_{filename}"
file_registry[file_id] = {
'path': os.path.abspath(frame_file),
'filename': filename,
'last_access': time.time(),
'download_count': 0
}
if audio_exists:
for audio_file in ["audio.dfpwm", "audio_left.dfpwm", "audio_right.dfpwm"]:
audio_path = os.path.join(job_dir, audio_file)
if os.path.exists(audio_path):
file_id = f"audio_{task_id}_{audio_file}"
file_registry[file_id] = {
'path': os.path.abspath(audio_path),
'filename': audio_file,
'last_access': time.time(),
'download_count': 0
}
if task_id and task_registry and task_lock:
add_task_log(task_id, "视频帧提取任务完成", task_registry, task_lock)
with task_lock:
if task_id in task_registry:
task_registry[task_id]['progress'] = 100
return {
'status': 'success',
'result': result_data,
'task_id': task_id,
'temp_dir': job_dir
}
except subprocess.CalledProcessError as e:
stderr_str = e.stderr.strip() if e.stderr else ""
stdout_str = e.stdout.strip() if e.stdout else ""
error_output = stderr_str or stdout_str or str(e)
error_msg = error_output[-500:] if len(error_output) > 500 else error_output
if task_id and task_registry and task_lock:
add_task_log(task_id, f"FFmpeg处理失败: {error_msg}", task_registry, task_lock)
return {'error': f'FFmpeg处理失败: {error_msg}'}
except requests.RequestException as e:
error_msg = f'视频下载失败: {str(e)}'
if task_id and task_registry and task_lock:
add_task_log(task_id, error_msg, task_registry, task_lock)
return {'error': error_msg}
except Exception as e:
error_msg = f'处理失败: {str(e)}'
if task_id and task_registry and task_lock:
add_task_log(task_id, error_msg, task_registry, task_lock)
return {'error': error_msg}
finally:
# 清理临时视频文件
for f in glob.glob(os.path.join(tempfile.gettempdir(), f"{task_id}.*")):
try:
os.remove(f)
except:
pass
# ======================
# 辅助函数
# ======================
def get_video_duration(video_path):
"""获取视频时长"""
result = subprocess.run([
FFPROBE_PATH, '-v', 'error',
'-show_entries', 'format=duration',
'-of', 'csv=p=0',
video_path
], capture_output=True, text=True, check=True)
duration_str = result.stdout.strip()
return float(duration_str) if duration_str and duration_str != 'N/A' else 0.0
def build_video_filter(w, h, fps, force_resolution, pad_to_target):
"""构建视频滤镜"""
if force_resolution:
return f"scale={w}:{h},fps={fps}"
else:
scale_expr = f"scale='min({w},iw*min(1,{h}/ih))':'min({h},ih*min(1,{w}/iw))'"
if pad_to_target:
return f"{scale_expr},pad={w}:{h}:(ow-iw)/2:(oh-ih)/2,fps={fps}"
else:
return f"{scale_expr},fps={fps}"
def get_output_resolution(job_dir):
"""获取输出分辨率"""
first_frame = None
for f in sorted(os.listdir(job_dir)):
if f.endswith('.png'):
first_frame = os.path.join(job_dir, f)
break
if first_frame:
probe_res = subprocess.run([
FFPROBE_PATH, '-v', 'error',
'-select_streams', 'v:0',
'-show_entries', 'stream=width,height',
'-of', 'csv=p=0',
first_frame
], capture_output=True, text=True, check=True)
out_w, out_h = map(int, probe_res.stdout.strip().split(','))
return out_w, out_h
return 0, 0
def has_audio(video_path):
"""检查视频是否有音频"""
probe_streams = subprocess.run([
FFPROBE_PATH, '-v', 'error',
'-show_entries', 'stream=codec_type',
'-of', 'csv=p=0',
video_path
], capture_output=True, text=True)
return 'audio' in probe_streams.stdout.lower()