Skip to content

Commit 42dc0de

Browse files
committed
feat: 增加download脚本
1 parent 8ac0e4f commit 42dc0de

File tree

4 files changed

+230
-0
lines changed

4 files changed

+230
-0
lines changed

rapid_table_det/download.py

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import os
16+
import sys
17+
import tarfile
18+
import zipfile
19+
import requests
20+
from tqdm import tqdm
21+
import logging
22+
23+
24+
# 初始化日志记录器
25+
def get_logger():
26+
logger = logging.getLogger(__name__)
27+
logger.setLevel(logging.INFO)
28+
handler = logging.StreamHandler(sys.stdout)
29+
formatter = logging.Formatter(
30+
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
31+
)
32+
handler.setFormatter(formatter)
33+
logger.addHandler(handler)
34+
return logger
35+
36+
37+
# 获取当前脚本文件的目录
38+
current_file_dir = os.path.dirname(os.path.abspath(__file__))
39+
# 设置存储的根路径
40+
MODELS_DIR = os.path.abspath(os.path.join(current_file_dir, "../models"))
41+
42+
43+
def download_with_progressbar(url, save_path):
44+
logger = get_logger()
45+
if save_path and os.path.exists(save_path):
46+
logger.info(f"Path {save_path} already exists. Skipping...")
47+
return
48+
response = requests.get(url, stream=True)
49+
if response.status_code == 200:
50+
total_size_in_bytes = int(response.headers.get("content-length", 1))
51+
block_size = 1024 # 1 Kibibyte
52+
progress_bar = tqdm(total=total_size_in_bytes, unit="iB", unit_scale=True)
53+
with open(save_path, "wb") as file:
54+
for data in response.iter_content(block_size):
55+
progress_bar.update(len(data))
56+
file.write(data)
57+
progress_bar.close()
58+
else:
59+
logger.error("Something went wrong while downloading models")
60+
sys.exit(0)
61+
62+
63+
def maybe_download(model_storage_directory, url):
64+
supported_extensions = [".tar", ".zip"]
65+
extension = os.path.splitext(url)[1].lower()
66+
67+
if extension not in supported_extensions:
68+
raise ValueError(
69+
f"Unsupported file extension: {extension}. Only .tar and .zip are supported."
70+
)
71+
72+
tmp_path = os.path.join(model_storage_directory, url.split("/")[-1])
73+
logger = get_logger()
74+
logger.info(f"download {url} to {tmp_path}")
75+
os.makedirs(model_storage_directory, exist_ok=True)
76+
download_with_progressbar(url, tmp_path)
77+
78+
if extension == ".tar":
79+
with tarfile.open(tmp_path, "r") as tarObj:
80+
tarObj.extractall(path=model_storage_directory)
81+
elif extension == ".zip":
82+
with zipfile.ZipFile(tmp_path, "r") as zipObj:
83+
zipObj.extractall(path=model_storage_directory)
84+
85+
os.remove(tmp_path)
86+
87+
88+
def maybe_download_params(model_path):
89+
if os.path.exists(model_path) or not is_link(model_path):
90+
return model_path
91+
else:
92+
url = model_path
93+
tmp_path = os.path.join(MODELS_DIR, url.split("/")[-1])
94+
logger = get_logger()
95+
logger.info(f"download {url} to {tmp_path}")
96+
os.makedirs(MODELS_DIR, exist_ok=True)
97+
download_with_progressbar(url, tmp_path)
98+
return tmp_path
99+
100+
101+
def is_link(s):
102+
return s is not None and s.startswith("http")
103+
104+
105+
def confirm_model_dir_url(model_dir, default_model_dir, default_url):
106+
url = default_url
107+
if model_dir is None or is_link(model_dir):
108+
if is_link(model_dir):
109+
url = model_dir
110+
file_name = url.split("/")[-1][:-4]
111+
model_dir = default_model_dir
112+
model_dir = os.path.join(model_dir, file_name)
113+
return model_dir, url

rapid_table_det/requirments.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,5 @@ numpy
22
Pillow
33
opencv-python
44
onnxruntime
5+
requests
6+
tqdm

rapid_table_det_paddle/download.py

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import os
16+
import sys
17+
import tarfile
18+
import zipfile
19+
import requests
20+
from tqdm import tqdm
21+
import logging
22+
23+
24+
# 初始化日志记录器
25+
def get_logger():
26+
logger = logging.getLogger(__name__)
27+
logger.setLevel(logging.INFO)
28+
handler = logging.StreamHandler(sys.stdout)
29+
formatter = logging.Formatter(
30+
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
31+
)
32+
handler.setFormatter(formatter)
33+
logger.addHandler(handler)
34+
return logger
35+
36+
37+
# 获取当前脚本文件的目录
38+
current_file_dir = os.path.dirname(os.path.abspath(__file__))
39+
# 设置存储的根路径
40+
MODELS_DIR = os.path.abspath(os.path.join(current_file_dir, "../models"))
41+
42+
43+
def download_with_progressbar(url, save_path):
44+
logger = get_logger()
45+
if save_path and os.path.exists(save_path):
46+
logger.info(f"Path {save_path} already exists. Skipping...")
47+
return
48+
response = requests.get(url, stream=True)
49+
if response.status_code == 200:
50+
total_size_in_bytes = int(response.headers.get("content-length", 1))
51+
block_size = 1024 # 1 Kibibyte
52+
progress_bar = tqdm(total=total_size_in_bytes, unit="iB", unit_scale=True)
53+
with open(save_path, "wb") as file:
54+
for data in response.iter_content(block_size):
55+
progress_bar.update(len(data))
56+
file.write(data)
57+
progress_bar.close()
58+
else:
59+
logger.error("Something went wrong while downloading models")
60+
sys.exit(0)
61+
62+
63+
def maybe_download(model_storage_directory, url):
64+
supported_extensions = [".tar", ".zip"]
65+
extension = os.path.splitext(url)[1].lower()
66+
67+
if extension not in supported_extensions:
68+
raise ValueError(
69+
f"Unsupported file extension: {extension}. Only .tar and .zip are supported."
70+
)
71+
72+
tmp_path = os.path.join(model_storage_directory, url.split("/")[-1])
73+
logger = get_logger()
74+
logger.info(f"download {url} to {tmp_path}")
75+
os.makedirs(model_storage_directory, exist_ok=True)
76+
download_with_progressbar(url, tmp_path)
77+
78+
if extension == ".tar":
79+
with tarfile.open(tmp_path, "r") as tarObj:
80+
tarObj.extractall(path=model_storage_directory)
81+
elif extension == ".zip":
82+
with zipfile.ZipFile(tmp_path, "r") as zipObj:
83+
zipObj.extractall(path=model_storage_directory)
84+
85+
os.remove(tmp_path)
86+
87+
88+
def maybe_download_params(model_path):
89+
if os.path.exists(model_path) or not is_link(model_path):
90+
return model_path
91+
else:
92+
url = model_path
93+
tmp_path = os.path.join(MODELS_DIR, url.split("/")[-1])
94+
logger = get_logger()
95+
logger.info(f"download {url} to {tmp_path}")
96+
os.makedirs(MODELS_DIR, exist_ok=True)
97+
download_with_progressbar(url, tmp_path)
98+
return tmp_path
99+
100+
101+
def is_link(s):
102+
return s is not None and s.startswith("http")
103+
104+
105+
def confirm_model_dir_url(model_dir, default_model_dir, default_url):
106+
url = default_url
107+
if model_dir is None or is_link(model_dir):
108+
if is_link(model_dir):
109+
url = model_dir
110+
file_name = url.split("/")[-1][:-4]
111+
model_dir = default_model_dir
112+
model_dir = os.path.join(model_dir, file_name)
113+
return model_dir, url

rapid_table_det_paddle/requirments.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,5 @@ numpy
33
Pillow
44
opencv-python
55
onnxruntime
6+
requests
7+
tqdm

0 commit comments

Comments
 (0)