1+ """
2+ InspireFace Resource Manager
3+
4+ This module provides model downloading functionality with two modes:
5+ 1. Original mode: Download models from COS (Tencent Cloud Object Storage)
6+ 2. ModelScope mode: Download models from ModelScope platform
7+
8+ ModelScope mode usage:
9+ rm = ResourceManager(use_modelscope=True, modelscope_model_id="tunmxy/InspireFace")
10+ model_path = rm.get_model("Gundam_RV1106")
11+
12+ Requirements for ModelScope mode:
13+ pip install modelscope
14+ """
15+
116import os
217import sys
318from pathlib import Path
419import urllib .request
520import ssl
621import hashlib
722
23+ try :
24+ from modelscope .hub .snapshot_download import snapshot_download
25+ MODELSCOPE_AVAILABLE = True
26+ except ImportError :
27+ MODELSCOPE_AVAILABLE = False
28+
29+ # Global configuration for resource downloading
30+ USE_OSS_DOWNLOAD = False # If True, force use OSS download instead of ModelScope
31+
32+ def set_use_oss_download (use_oss : bool ):
33+ """Set whether to use OSS download instead of ModelScope
34+
35+ Args:
36+ use_oss (bool): If True, use OSS download; if False, use ModelScope (default)
37+ """
38+ global USE_OSS_DOWNLOAD
39+ USE_OSS_DOWNLOAD = use_oss
40+
841def get_file_hash_sha256 (file_path ):
942 sha256 = hashlib .sha256 ()
1043 with open (file_path , 'rb' ) as f :
@@ -13,15 +46,35 @@ def get_file_hash_sha256(file_path):
1346 return sha256 .hexdigest ()
1447
1548class ResourceManager :
16- def __init__ (self ):
17- """Initialize resource manager and create necessary directories"""
49+ def __init__ (self , use_modelscope : bool = True , modelscope_model_id : str = "tunmxy/InspireFace" ):
50+ """Initialize resource manager and create necessary directories
51+
52+ Args:
53+ use_modelscope: Whether to download models from ModelScope platform
54+ modelscope_model_id: ModelScope model ID (default: tunmxy/InspireFace)
55+ """
1856 self .user_home = Path .home ()
1957 self .base_dir = self .user_home / '.inspireface'
2058 self .models_dir = self .base_dir / 'models'
2159
60+ # ModelScope configuration
61+ self .use_modelscope = use_modelscope
62+ self .modelscope_model_id = modelscope_model_id
63+ self .modelscope_cache_dir = self .base_dir / 'ms'
64+
2265 # Create directories
2366 self .base_dir .mkdir (exist_ok = True )
2467 self .models_dir .mkdir (exist_ok = True )
68+ if self .use_modelscope :
69+ self .modelscope_cache_dir .mkdir (exist_ok = True )
70+
71+ # Check ModelScope availability
72+ if self .use_modelscope and not MODELSCOPE_AVAILABLE :
73+ raise ImportError (
74+ "ModelScope is not available. You have two options:\n "
75+ "1. Install ModelScope: pip install modelscope\n "
76+ "2. Switch to OSS download mode by calling: inspireface.use_oss_download(True) before using InspireFace"
77+ )
2578
2679 # Model URLs
2780 self ._MODEL_LIST = {
@@ -52,6 +105,39 @@ def __init__(self):
52105 }
53106 }
54107
108+ def _download_from_modelscope (self , model_name : str ) -> str :
109+ """Download model from ModelScope platform
110+
111+ Args:
112+ model_name: Name of the model to download
113+
114+ Returns:
115+ str: Path to the downloaded model file
116+ """
117+ if not MODELSCOPE_AVAILABLE :
118+ raise ImportError ("ModelScope is not available. Please install it with: pip install modelscope" )
119+
120+ print (f"Downloading model '{ model_name } ' from ModelScope..." )
121+
122+ try :
123+ # Download specific model file from ModelScope
124+ cache_dir = snapshot_download (
125+ model_id = self .modelscope_model_id ,
126+ cache_dir = str (self .modelscope_cache_dir ),
127+ allow_file_pattern = [model_name ] # Only download the specific model file
128+ )
129+
130+ model_file_path = Path (cache_dir ) / model_name
131+
132+ if not model_file_path .exists ():
133+ raise FileNotFoundError (f"Model file '{ model_name } ' not found in downloaded repository" )
134+
135+ print (f"ModelScope download completed: { model_file_path } " )
136+ return str (model_file_path )
137+
138+ except Exception as e :
139+ raise RuntimeError (f"Failed to download model from ModelScope: { e } " )
140+
55141 def get_model (self , name : str , re_download : bool = False , ignore_verification : bool = False ) -> str :
56142 """
57143 Get model path. Download if not exists or re_download is True.
@@ -64,6 +150,15 @@ def get_model(self, name: str, re_download: bool = False, ignore_verification: b
64150 Returns:
65151 str: Full path to model file
66152 """
153+ # Check global OSS setting first, then instance setting
154+ use_oss = USE_OSS_DOWNLOAD
155+ use_modelscope_actual = self .use_modelscope and not use_oss
156+
157+ # Use ModelScope download if enabled and OSS is not forced
158+ if use_modelscope_actual :
159+ return self ._download_from_modelscope_with_cache (name , re_download )
160+
161+ # Original download logic for backwards compatibility
67162 if name not in self ._MODEL_LIST :
68163 raise ValueError (f"Model '{ name } ' not found. Available models: { list (self ._MODEL_LIST .keys ())} " )
69164
@@ -124,13 +219,51 @@ def get_model(self, name: str, re_download: bool = False, ignore_verification: b
124219 if downloading_flag .exists ():
125220 downloading_flag .unlink ()
126221 raise RuntimeError (f"Failed to download model: { e } " )
222+
223+ def _download_from_modelscope_with_cache (self , name : str , re_download : bool = False ) -> str :
224+ """Download model from ModelScope with local caching logic
225+
226+ Args:
227+ name: Model name
228+ re_download: Force re-download if True
229+
230+ Returns:
231+ str: Path to the model file
232+ """
233+ # Check if model exists in ModelScope cache
234+ model_file_path = self .modelscope_cache_dir / name
127235
128- # Usage example
236+ if model_file_path .exists () and not re_download :
237+ print (f"Using cached model '{ name } ' from ModelScope" )
238+ return str (model_file_path )
239+
240+ # Download from ModelScope
241+ return self ._download_from_modelscope (name )
242+
243+ # Usage examples
129244if __name__ == "__main__" :
130245 try :
246+ # Example 1: Default mode (ModelScope)
247+ print ("=== Default mode (ModelScope) ===" )
131248 rm = ResourceManager ()
132- model_path = rm .get_model ("Pikachu" )
133- print (f"Model path: { model_path } " )
249+ model_path = rm .get_model ("Gundam_RV1106" )
250+ print (f"ModelScope model path: { model_path } " )
251+
252+ # Example 2: Force OSS mode using global setting
253+ print ("\n === OSS mode (global setting) ===" )
254+ set_use_oss_download (True )
255+ rm_oss = ResourceManager ()
256+ model_path_oss = rm_oss .get_model ("Pikachu" )
257+ print (f"OSS model path: { model_path_oss } " )
258+
259+ # Reset to default
260+ set_use_oss_download (False )
261+
262+ # Example 3: Explicit ModelScope mode
263+ print ("\n === Explicit ModelScope mode ===" )
264+ rm_ms = ResourceManager (use_modelscope = True , modelscope_model_id = "tunmxy/InspireFace" )
265+ model_path_ms = rm_ms .get_model ("Gundam_RV1106" )
266+ print (f"Explicit ModelScope model path: { model_path_ms } " )
134267
135268 except Exception as e :
136269 print (f"Error: { e } " )
0 commit comments