1+ import os
2+ import requests
3+ import urllib .parse
4+ import json
5+ from beta9 import function , Volume , Image
6+
7+ @function (
8+ app = "volume-imports" ,
9+ name = "civitai-clone-model" ,
10+ secrets = ["CIVITAI_API_KEY" ],
11+ memory = "4gb" ,
12+ image = Image (
13+ python_packages = ["requests" ]
14+ ),
15+ volumes = [Volume (name = "civitai_models" , mount_path = "/civitai_models" )]
16+ )
17+ def handler (* , url : str ):
18+ if not url :
19+ raise ValueError ("url is required" )
20+
21+ print (f"Downloading model from { url } " )
22+ model_id = urllib .parse .urlparse (url ).path .split ("/" )[2 ]
23+ print (f"Model ID: { model_id } " )
24+
25+ try :
26+ response = requests .get (
27+ f"https://civitai.com/api/v1/models/{ model_id } " ,
28+ headers = {
29+ "Content-Type" : "application/json" ,
30+ "Authorization" : f"Bearer { os .getenv ('CIVITAI_API_KEY' )} "
31+ },
32+ )
33+ response .raise_for_status ()
34+ data = response .json ()
35+
36+ latest_version = data ["modelVersions" ][0 ]
37+ download_url = latest_version ["downloadUrl" ]
38+ print (f"Download URL: { download_url } " )
39+
40+ save_path = f"/civitai_models/{ data ['name' ].replace (' ' , '_' )} "
41+ with requests .get (download_url ,
42+ headers = {
43+ "Content-Type" : "application/json" ,
44+ "Authorization" : f"Bearer { os .getenv ('CIVITAI_API_KEY' )} "
45+ },
46+ stream = True ) as response :
47+ response .raise_for_status ()
48+ total_size = int (response .headers .get ('content-length' , 0 ))
49+ print (f"Total file size: { total_size / (1024 * 1024 ):.2f} MB" )
50+
51+ with open (save_path , 'wb' ) as f :
52+ for chunk in response .iter_content (chunk_size = 8192 ):
53+ if chunk :
54+ f .write (chunk )
55+
56+ print ("Model downloaded successfully" )
57+ return {
58+ "model_id" : model_id ,
59+ "downloaded_path" : save_path
60+ }
61+
62+ except Exception as e :
63+ print (f"Failed to get model ID: { str (e )} " )
64+ raise Exception (f"Failed to get model ID: { str (e )} " )
65+
66+ if __name__ == "__main__" :
67+ handler (url = "https://civitai.com/models/1224788/prefect-illustrious-xl" )
0 commit comments