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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import requests
|
| 4 |
+
import shutil
|
| 5 |
+
import uuid
|
| 6 |
+
from ftplib import FTP
|
| 7 |
+
from spandrel import ImageModelDescriptor, ModelLoader
|
| 8 |
+
import torch
|
| 9 |
+
import subprocess
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# 新增日志开关
|
| 13 |
+
log_to_terminal = True
|
| 14 |
+
|
| 15 |
+
# 新增日志函数
|
| 16 |
+
def print_log(task_id, filename, stage, status):
|
| 17 |
+
if log_to_terminal:
|
| 18 |
+
print(f"任务 ID: {task_id}, 文件名: {filename}, 状态: [{status}], 阶段: {stage}")
|
| 19 |
+
|
| 20 |
+
# 修改 process_file 函数,接收 shape 数组
|
| 21 |
+
def process_file(task_id, file_path, model_name, output_folder, shape0, shape1):
|
| 22 |
+
# 使用 torch.rand 生成 input_shape
|
| 23 |
+
log = ""
|
| 24 |
+
print_log(task_id, model_name, "生成输入张量", "开始")
|
| 25 |
+
pt_path = output_folder + "/" + model_name + ".pt"
|
| 26 |
+
input_tensor0 = torch.rand(shape0) if any(shape0) else None
|
| 27 |
+
input_tensor1 = torch.rand(shape1) if any(shape1) else None
|
| 28 |
+
if input_tensor0 is not None and input_tensor1 is not None:
|
| 29 |
+
example_input = (input_tensor0, input_tensor1)
|
| 30 |
+
# 修改此处,去除 shape 字符串中的空格
|
| 31 |
+
command = f"pnnx {pt_path} inputshape={str(shape0).replace(' ', '')} inputshape2={str(shape1).replace(' ', '')}"
|
| 32 |
+
elif input_tensor0 is not None:
|
| 33 |
+
example_input = input_tensor0
|
| 34 |
+
command = f"pnnx {pt_path} inputshape={str(shape0).replace(' ', '')}"
|
| 35 |
+
else:
|
| 36 |
+
example_input = input_tensor1
|
| 37 |
+
command = f"pnnx {pt_path}"
|
| 38 |
+
print_log(task_id, model_name, "生成输入张量", "完成")
|
| 39 |
+
|
| 40 |
+
# 确保 output_folder 存在
|
| 41 |
+
if not os.path.exists(output_folder):
|
| 42 |
+
os.makedirs(output_folder)
|
| 43 |
+
|
| 44 |
+
# load a model from disk
|
| 45 |
+
model = ModelLoader().load_from_file(file_path)
|
| 46 |
+
|
| 47 |
+
# make sure it's an image to image model
|
| 48 |
+
assert isinstance(model, ImageModelDescriptor)
|
| 49 |
+
|
| 50 |
+
print_log(task_id, model_name, "加载模型", "完成")
|
| 51 |
+
# send it to the GPU and put it in inference mode
|
| 52 |
+
# model.cuda().eval()
|
| 53 |
+
model.eval()
|
| 54 |
+
torch_model = model.model
|
| 55 |
+
print_log(task_id, model_name, "获得模型对象", "完成")
|
| 56 |
+
if os.path.exists(pt_path):
|
| 57 |
+
print_log(task_id, model_name, "转换为TorchScript模型", "跳过")
|
| 58 |
+
else:
|
| 59 |
+
print_log(task_id, model_name, "转换为TorchScript模型", "开始")
|
| 60 |
+
# 使用 torch.jit.trace 进行模型转换
|
| 61 |
+
traced_torch_model = torch.jit.trace(torch_model, example_input)
|
| 62 |
+
traced_torch_model.save(output_folder + "/" + model_name + ".pt")
|
| 63 |
+
print_log(task_id, model_name, "转换为TorchScript模型", "完成")
|
| 64 |
+
|
| 65 |
+
print_log(task_id, model_name, "运行命令"+command, "开始")
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
# 使用 subprocess.Popen 执行命令
|
| 69 |
+
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
| 70 |
+
while True:
|
| 71 |
+
output = process.stdout.readline()
|
| 72 |
+
if output == '' and process.poll() is not None:
|
| 73 |
+
break
|
| 74 |
+
if output:
|
| 75 |
+
log += output.strip() + '\n'
|
| 76 |
+
if log_to_terminal:
|
| 77 |
+
print(output.strip())
|
| 78 |
+
returncode = process.poll()
|
| 79 |
+
if returncode != 0:
|
| 80 |
+
log += f"执行命令: {command} 失败,返回码: {returncode}\n"
|
| 81 |
+
else:
|
| 82 |
+
log += f"执行命令: {command} 成功\n"
|
| 83 |
+
except Exception as e:
|
| 84 |
+
log += f"执行命令: {command} 失败,错误信息: {str(e)}\n"
|
| 85 |
+
|
| 86 |
+
return [os.path.join(output_folder, f) for f in os.listdir(output_folder) if os.path.isfile(os.path.join(output_folder, f))], log
|
| 87 |
+
|
| 88 |
+
# 修改为字典类型
|
| 89 |
+
downloaded_files = {}
|
| 90 |
+
# 修改 start_process 函数,处理新增输入
|
| 91 |
+
def start_process(input1, input2, shape0_str, shape1_str, input_suffix=".pth"):
|
| 92 |
+
task_id = str(uuid.uuid4())
|
| 93 |
+
log = ""
|
| 94 |
+
try:
|
| 95 |
+
# 判断 input1 是地址还是文件,增加对 ftp 和 webdav 协议的支持
|
| 96 |
+
supported_protocols = ('http://', 'https://', 'ftp://', 'webdav://')
|
| 97 |
+
if isinstance(input1, str) and input1.startswith(supported_protocols):
|
| 98 |
+
url = input1
|
| 99 |
+
if url in downloaded_files and os.path.exists(downloaded_files[url]):
|
| 100 |
+
file_path = downloaded_files[url]
|
| 101 |
+
log += f"跳过下载,文件已存在: {file_path}\n"
|
| 102 |
+
print_log(task_id, input2, "检查下载状态", "跳过下载")
|
| 103 |
+
yield [], log
|
| 104 |
+
else:
|
| 105 |
+
# 生成唯一文件名
|
| 106 |
+
file_name = str(uuid.uuid4()) + input_suffix
|
| 107 |
+
file_path = os.path.join(os.getcwd(), file_name)
|
| 108 |
+
if url.startswith('ftp://'):
|
| 109 |
+
try:
|
| 110 |
+
# 解析 ftp 地址
|
| 111 |
+
parts = url.replace('ftp://', '').split('/')
|
| 112 |
+
host = parts[0]
|
| 113 |
+
remote_file_path = '/'.join(parts[1:])
|
| 114 |
+
ftp = FTP(host)
|
| 115 |
+
ftp.login()
|
| 116 |
+
with open(file_path, 'wb') as f:
|
| 117 |
+
ftp.retrbinary('RETR ' + remote_file_path, f.write)
|
| 118 |
+
ftp.quit()
|
| 119 |
+
downloaded_files[url] = file_path
|
| 120 |
+
log += f"文件下载成功: {file_path}\n"
|
| 121 |
+
yield [], log
|
| 122 |
+
except Exception as e:
|
| 123 |
+
log += f"FTP 文件下载失败: {str(e)}\n"
|
| 124 |
+
print_log(task_id, input2, "下载文件", f"失败 (FTP): {str(e)}")
|
| 125 |
+
yield [], log
|
| 126 |
+
return
|
| 127 |
+
else :
|
| 128 |
+
if url.startswith(('http://', 'https://')):
|
| 129 |
+
response = requests.get(url)
|
| 130 |
+
if response.status_code == 200:
|
| 131 |
+
with open(file_path, 'wb') as f:
|
| 132 |
+
f.write(response.content)
|
| 133 |
+
downloaded_files[url] = file_path
|
| 134 |
+
log += f"文件下载成功: {file_path}\n"
|
| 135 |
+
yield [], log
|
| 136 |
+
else:
|
| 137 |
+
log += f"文件下载失败,状态码: {response.status_code}\n"
|
| 138 |
+
yield [], log
|
| 139 |
+
return
|
| 140 |
+
|
| 141 |
+
elif input1 is not None:
|
| 142 |
+
file_path = input1.name
|
| 143 |
+
log += f"使用上传的文件: {file_path}\n"
|
| 144 |
+
print_log(task_id, input2, "使用上传文件", "开始")
|
| 145 |
+
yield [], log
|
| 146 |
+
else:
|
| 147 |
+
log += "未提供有效文件或地址\n"
|
| 148 |
+
print_log(task_id, input2, "检查文件输入", "失败 (无有效输入)")
|
| 149 |
+
yield [], log
|
| 150 |
+
return
|
| 151 |
+
|
| 152 |
+
# 生成新文件夹用于暂存结果
|
| 153 |
+
output_folder = os.path.join(os.getcwd(), str(uuid.uuid4()))
|
| 154 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 155 |
+
log += f"创建临时文件夹: {output_folder}\n"
|
| 156 |
+
print_log(task_id, input2, "创建临时文件夹", "完成")
|
| 157 |
+
yield [], log
|
| 158 |
+
|
| 159 |
+
# 解析输入的字符串为数组
|
| 160 |
+
try:
|
| 161 |
+
# 尝试解析 shape0_str
|
| 162 |
+
shape0 = [int(x) for x in shape0_str.split(',')] if shape0_str else [0, 0, 0, 0]
|
| 163 |
+
# 检查 shape0 是否为 4 个元素,如果不是则设置为全 0
|
| 164 |
+
if len(shape0) != 4:
|
| 165 |
+
shape0 = [0, 0, 0, 0]
|
| 166 |
+
# 尝试解析 shape1_str
|
| 167 |
+
shape1 = [int(x) for x in shape1_str.split(',')] if shape1_str else [0, 0, 0, 0]
|
| 168 |
+
# 检查 shape1 是否为 4 个元素,如果不是则设置为全 0
|
| 169 |
+
if len(shape1) != 4:
|
| 170 |
+
shape1 = [0, 0, 0, 0]
|
| 171 |
+
except ValueError:
|
| 172 |
+
# 如果解析过程中出现 ValueError,将 shape0 和 shape1 设置为全 0
|
| 173 |
+
shape0 = [0, 0, 0, 0]
|
| 174 |
+
shape1 = [0, 0, 0, 0]
|
| 175 |
+
log += "输入的 shape 字符串格式不正确,请使用逗号分隔的整数。\n"
|
| 176 |
+
yield [], log
|
| 177 |
+
return
|
| 178 |
+
|
| 179 |
+
# 调用处理函数,传递 shape 数组
|
| 180 |
+
output_files, process_log = process_file(task_id, file_path, input2, output_folder, shape0, shape1)
|
| 181 |
+
log += process_log
|
| 182 |
+
log += f"处理完成,输出文件: {output_files}\n"
|
| 183 |
+
print_log(task_id, input2, "调用处理函数", "完成")
|
| 184 |
+
yield output_files, log
|
| 185 |
+
except Exception as e:
|
| 186 |
+
log += f"发生错误: {str(e)}\n"
|
| 187 |
+
print_log(task_id, input2, "整体处理", f"失败: {str(e)}")
|
| 188 |
+
yield [], log
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
# 创建 Gradio 界面
|
| 192 |
+
with gr.Blocks() as demo:
|
| 193 |
+
gr.Markdown("文件处理界面")
|
| 194 |
+
with gr.Row():
|
| 195 |
+
# 左侧列,包含输入组件和按钮
|
| 196 |
+
with gr.Column():
|
| 197 |
+
with gr.Row():
|
| 198 |
+
input1 = gr.Textbox(label="粘贴地址")
|
| 199 |
+
input1_file = gr.File(label="上传文件")
|
| 200 |
+
input2 = gr.Textbox(label="自定义文件名")
|
| 201 |
+
# 修改为字符串输入控件
|
| 202 |
+
shape0_str = gr.Textbox(label="shape0 (逗号分隔的整数)", value="1,3,128,128")
|
| 203 |
+
shape1_str = gr.Textbox(label="shape1 (逗号分隔的整数)", value="0,0,0,0")
|
| 204 |
+
start_button = gr.Button("开始")
|
| 205 |
+
# 右侧列,包含输出组件和日志文本框
|
| 206 |
+
with gr.Column():
|
| 207 |
+
output = gr.File(label="输出文件", file_count="multiple")
|
| 208 |
+
log_textbox = gr.Textbox(label="日志", lines=10, interactive=False)
|
| 209 |
+
|
| 210 |
+
# 绑定事件,修改输入参数
|
| 211 |
+
start_button.click(
|
| 212 |
+
fn=start_process,
|
| 213 |
+
inputs=[input1_file if input1_file.value else input1, input2, shape0_str, shape1_str],
|
| 214 |
+
outputs=[output, log_textbox]
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
demo.launch()
|