R-Kentaren commited on
Commit
955e4e6
·
verified ·
1 Parent(s): ea614ac

Create civitai.py

Browse files
Files changed (1) hide show
  1. civitai.py +97 -0
civitai.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import os
3
+ from google.colab import output
4
+
5
+ # ==========================================
6
+ # CONFIGURATION
7
+ # ==========================================
8
+
9
+ # 1. Paste the Civitai Download Link here
10
+ # (Get this by right-clicking the download button on the website and selecting 'Copy Link')
11
+ download_link = "" #@param {type:"string"}
12
+
13
+ # 2. (Optional) Specify a custom filename (including extension, e.g., model.safetensors)
14
+ # Leave empty to use the original filename from the server.
15
+ custom_filename = "" #@param {type:"string"}
16
+
17
+ # 3. Download destination folder
18
+ destination_folder = "/content/downloaded_models" #@param {type:"string"}
19
+
20
+ # ==========================================
21
+ # SCRIPT
22
+ # ==========================================
23
+
24
+ def download_civitai_model(url, folder, filename=None):
25
+ if not url:
26
+ print("Error: Please paste the download link in the 'download_link' variable.")
27
+ return
28
+
29
+ # Create folder if it doesn't exist
30
+ os.makedirs(folder, exist_ok=True)
31
+
32
+ print(f"Connecting to Civitai...")
33
+
34
+ # Send a HEAD request first to get headers (allows us to find filename without downloading yet)
35
+ # We use a User-Agent because some servers block python-requests default agent
36
+ headers = {
37
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
38
+ }
39
+
40
+ try:
41
+ # First, let's try to get the headers to determine filename
42
+ response = requests.head(url, headers=headers, allow_redirects=True)
43
+
44
+ # Determine filename
45
+ if not filename:
46
+ # Try to get filename from Content-Disposition header
47
+ content_disp = response.headers.get('Content-Disposition')
48
+ if content_disp and 'filename=' in content_disp:
49
+ # Parse filename from header (handles quotes)
50
+ fname_str = content_disp.split('filename=')[1].strip('"')
51
+ final_filename = fname_str
52
+ else:
53
+ # Fallback if header missing (extract from URL or use generic name)
54
+ print("Warning: Could not determine filename automatically. Using 'downloaded_model.safetensors'")
55
+ final_filename = "downloaded_model.safetensors"
56
+ else:
57
+ final_filename = filename
58
+
59
+ file_path = os.path.join(folder, final_filename)
60
+
61
+ print(f"Downloading: {final_filename}")
62
+ print(f"Saving to: {file_path}")
63
+
64
+ # Stream download to handle large files
65
+ response = requests.get(url, headers=headers, stream=True)
66
+
67
+ # Check for errors
68
+ if response.status_code != 200:
69
+ print(f"Error: Failed to download. Status Code: {response.status_code}")
70
+ print("Response:", response.text[:500])
71
+ return
72
+
73
+ # Write file
74
+ total_size = int(response.headers.get('content-length', 0))
75
+ bytes_downloaded = 0
76
+
77
+ with open(file_path, 'wb') as f:
78
+ for chunk in response.iter_content(chunk_size=8192):
79
+ if chunk:
80
+ f.write(chunk)
81
+ bytes_downloaded += len(chunk)
82
+ # Print progress
83
+ if total_size > 0:
84
+ percent = (bytes_downloaded / total_size) * 100
85
+ print(f"\rProgress: {percent:.1f}% ({bytes_downloaded/1024/1024:.1f} MB / {total_size/1024/1024:.1f} MB)", end="")
86
+
87
+ print("\n\n✅ Download Complete!")
88
+
89
+ # List file info
90
+ file_size = os.path.getsize(file_path) / (1024 * 1024)
91
+ print(f"File Size: {file_size:.2f} MB")
92
+
93
+ except Exception as e:
94
+ print(f"\nAn error occurred: {e}")
95
+
96
+ # Run the function
97
+ download_civitai_model(download_link, destination_folder, custom_filename)