Spaces:
Running
Running
jhj0517
commited on
Commit
•
baa2a55
1
Parent(s):
526c234
Add model download script
Browse files- modules/model_downloader.py +48 -0
modules/model_downloader.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import Optional
|
3 |
+
|
4 |
+
from modules.paths import *
|
5 |
+
|
6 |
+
DEFAULT_MODEL_TYPE = "sam2_hiera_large"
|
7 |
+
AVAILABLE_MODELS = {
|
8 |
+
"sam2_hiera_tiny": ["sam2_hiera_tiny.pt", "https://dl.fbaipublicfiles.com/segment_anything_2/072824/sam2_hiera_tiny.pt"],
|
9 |
+
"sam2_hiera_small": ["sam2_hiera_small.pt", "https://dl.fbaipublicfiles.com/segment_anything_2/072824/sam2_hiera_small.pt"],
|
10 |
+
"sam2_hiera_base_plus": ["sam2_hiera_base_plus.pt", "https://dl.fbaipublicfiles.com/segment_anything_2/072824/sam2_hiera_base_plus.pt"],
|
11 |
+
"sam2_hiera_large": ["sam2_hiera_large.pt", "https://dl.fbaipublicfiles.com/segment_anything_2/072824/sam2_hiera_large.pt"],
|
12 |
+
}
|
13 |
+
|
14 |
+
|
15 |
+
def download_sam_model_url(model_type: str,
|
16 |
+
model_dir: str = MODELS_DIR):
|
17 |
+
filename, url = AVAILABLE_MODELS[model_type]
|
18 |
+
load_file_from_url(url=url, model_dir=model_dir)
|
19 |
+
|
20 |
+
|
21 |
+
def load_file_from_url(
|
22 |
+
url: str,
|
23 |
+
*,
|
24 |
+
model_dir: str,
|
25 |
+
progress: bool = True,
|
26 |
+
filename: Optional[str] = None,
|
27 |
+
) -> str:
|
28 |
+
from urllib.parse import urlparse
|
29 |
+
"""Download a file from `url` into `model_dir`, using the file present if possible.
|
30 |
+
|
31 |
+
Returns the path to the downloaded file.
|
32 |
+
"""
|
33 |
+
os.makedirs(model_dir, exist_ok=True)
|
34 |
+
if not filename:
|
35 |
+
parts = urlparse(url)
|
36 |
+
filename = os.path.basename(parts.path)
|
37 |
+
cached_file = os.path.abspath(os.path.join(model_dir, filename))
|
38 |
+
if not os.path.exists(cached_file):
|
39 |
+
print(f'Downloading: "{url}" to {cached_file}\n')
|
40 |
+
from torch.hub import download_url_to_file
|
41 |
+
download_url_to_file(url, cached_file, progress=progress)
|
42 |
+
return cached_file
|
43 |
+
|
44 |
+
|
45 |
+
def is_sam_exist(model_type: str):
|
46 |
+
filename, url = AVAILABLE_MODELS[model_type]
|
47 |
+
model_path = os.path.join(MODELS_DIR, filename)
|
48 |
+
return os.path.exists(model_path)
|