File size: 7,199 Bytes
bfabd59 208fad8 bfabd59 208fad8 bfabd59 208fad8 bfabd59 208fad8 bfabd59 208fad8 bfabd59 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 |
"""
Gradio interface for converting models.
"""
import os
import uuid
import re
import subprocess
import gradio as gr
from demo import constants, utils
from lczerolens import backends
def get_models_info(onnx=True, leela=True):
"""
Get the names of the models in the model directory.
"""
model_df = []
exp = r"(?P<n_filters>\d+)x(?P<n_blocks>\d+)"
if onnx:
for filename in os.listdir(constants.ONNX_MODEL_DIRECTORY):
if filename.endswith(".onnx"):
match = re.search(exp, filename)
if match is None:
n_filters = -1
n_blocks = -1
else:
n_filters = int(match.group("n_filters"))
n_blocks = int(match.group("n_blocks"))
model_df.append(
[
filename,
"ONNX",
n_blocks,
n_filters,
]
)
if leela:
for filename in os.listdir(constants.LEELA_MODEL_DIRECTORY):
if filename.endswith(".pb.gz"):
match = re.search(exp, filename)
if match is None:
n_filters = -1
n_blocks = -1
else:
n_filters = int(match.group("n_filters"))
n_blocks = int(match.group("n_blocks"))
model_df.append(
[
filename,
"LEELA",
n_blocks,
n_filters,
]
)
return model_df
def save_model(tmp_file_path):
"""
Save the model to the model directory.
"""
popen = subprocess.Popen(
["file", tmp_file_path],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
popen.wait()
if popen.returncode != 0:
raise RuntimeError
file_desc = popen.stdout.read().decode("utf-8").split(tmp_file_path)[1].strip()
rename_match = re.search(r"was\s\"(?P<name>.+)\"", file_desc)
type_match = re.search(r"\:\s(?P<type>[a-zA-Z]+)", file_desc)
if rename_match is None or type_match is None:
raise RuntimeError
model_name = rename_match.group("name")
model_type = type_match.group("type")
if model_type != "gzip":
raise RuntimeError
os.rename(
tmp_file_path,
f"{constants.LEELA_MODEL_DIRECTORY}/{model_name}.gz",
)
try:
backends.describenet(
f"{constants.LEELA_MODEL_DIRECTORY}/{model_name}.gz",
)
except RuntimeError:
os.remove(f"{constants.LEELA_MODEL_DIRECTORY}/{model_name}.gz")
raise RuntimeError
def list_models():
"""
List the models in the model directory.
"""
models_info = get_models_info()
return sorted([[model_info[0]] for model_info in models_info])
def on_select_model_df(
evt: gr.SelectData,
):
"""
When a model is selected, update the statement.
"""
return evt.value
def convert_model(
model_name: str,
):
"""
Convert the model.
"""
if model_name == "":
gr.Warning(
"Please select a model.",
)
return list_models(), ""
if model_name.endswith(".onnx"):
gr.Warning(
"ONNX conversion not implemented.",
)
return list_models(), ""
try:
backends.convert_to_onnx(
f"{constants.LEELA_MODEL_DIRECTORY}/{model_name}",
f"{constants.ONNX_MODEL_DIRECTORY}/{model_name[:-6]}.onnx",
)
except RuntimeError:
gr.Warning(
f"Could not convert net at `{model_name}`.",
)
return list_models(), "Conversion failed"
return list_models(), "Conversion successful"
def upload_model(
model_file: gr.File,
):
"""
Convert the model.
"""
if model_file is None:
gr.Warning(
"File not uploaded.",
)
return list_models()
try:
id = uuid.uuid4()
tmp_file_path = f"{constants.LEELA_MODEL_DIRECTORY}/{id}"
with open(
tmp_file_path,
"wb",
) as f:
f.write(model_file)
save_model(tmp_file_path)
except RuntimeError:
gr.Warning(
"Invalid file type.",
)
finally:
if os.path.exists(tmp_file_path):
os.remove(tmp_file_path)
return list_models()
def get_model_description(
model_name: str,
):
"""
Get the model description.
"""
if model_name == "":
gr.Warning(
"Please select a model.",
)
return ""
if model_name.endswith(".onnx"):
gr.Warning(
"ONNX description not implemented.",
)
return ""
try:
description = backends.describenet(
f"{constants.LEELA_MODEL_DIRECTORY}/{model_name}",
)
except RuntimeError:
raise gr.Error(
f"Could not describe net at `{model_name}`.",
)
return description
def get_model_path(
model_name: str,
):
"""
Get the model path.
"""
if model_name == "":
gr.Warning(
"Please select a model.",
)
return None
if model_name.endswith(".onnx"):
return f"{constants.ONNX_MODEL_DIRECTORY}/{model_name}"
else:
return f"{constants.LEELA_MODEL_DIRECTORY}/{model_name}"
with gr.Blocks() as interface:
model_file = gr.File(type="binary")
upload_button = gr.Button(
value="Upload",
)
with gr.Row():
with gr.Column(scale=2):
model_df = gr.Dataframe(
headers=["Available models"],
datatype=["str"],
interactive=False,
type="array",
value=list_models,
)
with gr.Column(scale=1):
with gr.Row():
model_name = gr.Textbox(label="Selected model", lines=1, interactive=False, scale=7)
conversion_status = gr.Textbox(
label="Conversion status",
lines=1,
interactive=False,
)
convert_button = gr.Button(
value="Convert",
)
describe_button = gr.Button(
value="Describe model",
)
model_description = gr.Textbox(
label="Model description",
lines=1,
interactive=False,
)
download_button = gr.Button(
value="Get download link",
)
download_file = gr.File(
type="filepath",
label="Download link",
interactive=False,
)
model_df.select(
on_select_model_df,
None,
model_name,
)
upload_button.click(
upload_model,
model_file,
model_df,
)
convert_button.click(
convert_model,
model_name,
[model_df, conversion_status],
)
describe_button.click(
get_model_description,
model_name,
model_description,
)
download_button.click(
get_model_path,
model_name,
download_file,
)
|