Mightys commited on
Commit
0ead58a
·
verified ·
1 Parent(s): 9942ab6

Update scripts/download_magic.py

Browse files
Files changed (1) hide show
  1. scripts/download_magic.py +136 -40
scripts/download_magic.py CHANGED
@@ -2,14 +2,18 @@
2
  """
3
  Mágica %download para IPython / Jupyter / Colab.
4
  Lee el token de CivitAI desde ~/.civitai_token.pkl (pickle)
 
 
5
  Uso:
6
  import download_magic
7
  %download https://civitai.com/api/download/models/..., https://huggingface.co/...
 
8
  """
9
 
10
  from IPython import get_ipython
11
  from IPython.core.magic import register_line_magic
12
- from IPython.display import HTML, display
 
13
  import os
14
  import subprocess
15
  import re
@@ -27,56 +31,148 @@ if TOKEN_FILE.exists():
27
  pass
28
  # ---------------------------------------------
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  @register_line_magic
31
  def download(line):
32
  """
33
- %download url1, url2, ...
34
  Muestra solo el nombre real y respeta la carpeta actual (%cd).
 
35
  """
36
  dest = os.getcwd()
37
- urls = [u.strip() for u in line.split(",") if u.strip()]
38
-
39
- for url in urls:
40
- # ---------- CivitAI ----------
41
- if "civitai.com" in url:
42
- if not token:
43
- display(HTML("<h4 style='color:red;'>⚠️ Token de CivitAI no encontrado.</h4>"))
44
- continue
45
- url_token = f"{url}{'&' if '?' in url else '?'}token={token}"
46
-
47
- try:
48
- with requests.get(url_token, stream=True, timeout=5) as r:
49
- cd = r.headers.get('Content-Disposition', '')
50
- match = re.findall(r'filename[*]?=(?:UTF-8\'\')?["\']?([^"\';]+)["\']?', cd)
51
- pretty = match[0] if match else url.split('/')[-1].split('?')[0]
52
- except Exception:
53
- pretty = url.split('/')[-1].split('?')[0]
54
-
55
- display(HTML(f"<h3 style='color:yellow;'>📥 Descargando: <code>{pretty}</code></h3>"
56
  f"<h4 style='color:cyan;'>📁 Destino: <code>{dest}</code></h4>"))
 
 
 
 
 
 
 
 
 
57
 
58
- subprocess.run([
59
- "aria2c", "--console-log-level=error", "--content-disposition",
60
- "-c", "-x", "6", "-s", "6", "-k", "1M",
61
- "-d", dest, url_token
62
- ])
 
 
 
63
 
64
- # ---------- HuggingFace ----------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  else:
66
- pretty = url.split('/')[-1].split('?')[0]
67
- display(HTML(f"<h3 style='color:yellow;'>📥 Descargando: <code>{pretty}</code></h3>"
68
  f"<h4 style='color:cyan;'>📁 Destino: <code>{dest}</code></h4>"))
69
- subprocess.run([
70
- "aria2c", "--console-log-level=error", "--content-disposition",
71
- "-c", "-x", "8", "-s", "8", "-k", "1M",
72
- "-d", dest, "-o", pretty, url
73
- ])
74
- for f in os.listdir(dest):
75
- if re.fullmatch(r'[0-9a-f]{64}', f):
76
- os.rename(os.path.join(dest, f), os.path.join(dest, pretty))
77
- break
78
-
79
- display(HTML("<h3 style='color:lightgreen;'>✅ Descarga finalizada</h3>"))
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  # Registramos la línea mágica al importar el módulo
82
  get_ipython().register_magic_function(download, magic_kind='line')
 
2
  """
3
  Mágica %download para IPython / Jupyter / Colab.
4
  Lee el token de CivitAI desde ~/.civitai_token.pkl (pickle)
5
+ Incluye barra de progreso interactiva.
6
+
7
  Uso:
8
  import download_magic
9
  %download https://civitai.com/api/download/models/..., https://huggingface.co/...
10
+ %download https://drive.google.com/file/d/123.../view -o MiModelo.safetensors
11
  """
12
 
13
  from IPython import get_ipython
14
  from IPython.core.magic import register_line_magic
15
+ from IPython.display import HTML, display, clear_output
16
+ import ipywidgets as widgets
17
  import os
18
  import subprocess
19
  import re
 
31
  pass
32
  # ---------------------------------------------
33
 
34
+ def ejecutar_con_progreso(cmd, is_gdown=False):
35
+ """Ejecuta el comando leyendo la salida para animar la barra de progreso."""
36
+ progress_bar = widgets.IntProgress(
37
+ value=0, min=0, max=100,
38
+ description='Progreso:',
39
+ bar_style='info',
40
+ orientation='horizontal',
41
+ layout=widgets.Layout(width='80%')
42
+ )
43
+ status_label = widgets.Label(value="Iniciando descarga...")
44
+ display(widgets.VBox([progress_bar, status_label]))
45
+
46
+ process = subprocess.Popen(
47
+ cmd,
48
+ stdout=subprocess.PIPE,
49
+ stderr=subprocess.STDOUT,
50
+ text=True,
51
+ bufsize=1,
52
+ universal_newlines=True
53
+ )
54
+
55
+ for line in process.stdout:
56
+ if not is_gdown:
57
+ # Capturar progreso de aria2c: ej. (27%) y DL:1.2MiB
58
+ match_pct = re.search(r'\((\d+)%\)', line)
59
+ if match_pct:
60
+ progress_bar.value = int(match_pct.group(1))
61
+
62
+ match_speed = re.search(r'DL:([^\s]+)', line)
63
+ if match_speed:
64
+ status_label.value = f"Descargando... Velocidad: {match_speed.group(1)}"
65
+ else:
66
+ # Capturar progreso de gdown
67
+ match_pct = re.search(r'(\d{1,3})%', line)
68
+ if match_pct:
69
+ progress_bar.value = int(match_pct.group(1))
70
+ status_label.value = "Descargando con gdown..."
71
+
72
+ process.wait()
73
+ progress_bar.value = 100
74
+ progress_bar.bar_style = 'success'
75
+ status_label.value = "¡Descarga de este archivo completada! ✅"
76
+
77
  @register_line_magic
78
  def download(line):
79
  """
80
+ %download url1 [-o nombre1.ext], url2, ...
81
  Muestra solo el nombre real y respeta la carpeta actual (%cd).
82
+ Auto-detecta enlaces de Drive para usar gdown y permite renombrado.
83
  """
84
  dest = os.getcwd()
85
+ # Separar por comas para soportar múltiples descargas en la misma línea
86
+ items = [item.strip() for item in line.split(",") if item.strip()]
87
+
88
+ for item in items:
89
+ # Extraer URL y el posible nombre personalizado usando regex para atrapar " -o "
90
+ parts = re.split(r'\s+-o\s+', item, maxsplit=1)
91
+ url = parts[0].strip()
92
+ custom_name = parts[1].strip() if len(parts) > 1 else None
93
+
94
+ # ---------- Google Drive (gdown) ----------
95
+ if "drive.google.com" in url:
96
+ pretty = custom_name if custom_name else "Archivo de Google Drive (Gdown gestiona el nombre)"
97
+ display(HTML(f"<hr><h3 style='color:yellow;'>🛸 Descargando (gdown): <code>{pretty}</code></h3>"
 
 
 
 
 
 
98
  f"<h4 style='color:cyan;'>📁 Destino: <code>{dest}</code></h4>"))
99
+
100
+ cmd = ["gdown", "--fuzzy", url]
101
+ # Si hay nombre custom, le damos la ruta exacta, si no, el directorio
102
+ if custom_name:
103
+ cmd.extend(["-O", os.path.join(dest, custom_name)])
104
+ else:
105
+ cmd.extend(["-O", f"{dest}/"])
106
+
107
+ ejecutar_con_progreso(cmd, is_gdown=True)
108
 
109
+ # ---------- CivitAI y CivitaiArchive (aria2) ----------
110
+ elif "civitai.com" in url or "civitaiarchive.com" in url:
111
+ if not token and "civitai.com" in url:
112
+ display(HTML("<h4 style='color:red;'>⚠️ Token de CivitAI no encontrado (algunos modelos pueden fallar).</h4>"))
113
+
114
+ url_token = url
115
+ if token and ("civitai.com" in url or "civitaiarchive.com" in url):
116
+ url_token = f"{url}{'&' if '?' in url else '?'}token={token}"
117
 
118
+ # Si el usuario mandó nombre manual, lo usamos. Si no, consultamos la API para saberlo.
119
+ if custom_name:
120
+ pretty = custom_name
121
+ else:
122
+ try:
123
+ with requests.get(url_token, stream=True, timeout=5) as r:
124
+ cd = r.headers.get('Content-Disposition', '')
125
+ match = re.findall(r'filename[*]?=(?:UTF-8\'\')?["\']?([^"\';]+)["\']?', cd)
126
+ pretty = match[0] if match else url.split('/')[-1].split('?')[0]
127
+ except Exception:
128
+ pretty = url.split('/')[-1].split('?')[0]
129
+
130
+ display(HTML(f"<hr><h3 style='color:yellow;'>📥 Descargando (aria2): <code>{pretty}</code></h3>"
131
+ f"<h4 style='color:cyan;'>📁 Destino: <code>{dest}</code></h4>"))
132
+
133
+ cmd = [
134
+ "aria2c", "--summary-interval=1",
135
+ "-c", "-x", "16", "-s", "16", "-k", "1M",
136
+ "-d", dest
137
+ ]
138
+
139
+ # Si hay nombre personalizado, usamos -o. Si no, usamos content-disposition
140
+ if custom_name:
141
+ cmd.extend(["-o", custom_name])
142
+ else:
143
+ cmd.append("--content-disposition")
144
+
145
+ cmd.append(url_token)
146
+ ejecutar_con_progreso(cmd, is_gdown=False)
147
+
148
+ # ---------- HuggingFace / Otros (aria2) ----------
149
  else:
150
+ pretty = custom_name if custom_name else url.split('/')[-1].split('?')[0]
151
+ display(HTML(f"<hr><h3 style='color:yellow;'>📥 Descargando (aria2): <code>{pretty}</code></h3>"
152
  f"<h4 style='color:cyan;'>📁 Destino: <code>{dest}</code></h4>"))
153
+
154
+ cmd = [
155
+ "aria2c", "--summary-interval=1",
156
+ "-c", "-x", "16", "-s", "16", "-k", "1M",
157
+ "-d", dest
158
+ ]
159
+
160
+ if custom_name:
161
+ cmd.extend(["-o", custom_name])
162
+ else:
163
+ cmd.extend(["-o", pretty])
164
+
165
+ cmd.append(url)
166
+ ejecutar_con_progreso(cmd, is_gdown=False)
167
+
168
+ # Limpiar hashes de 64 caracteres típicos de HuggingFace si quedó suelto y no hay nombre custom
169
+ if not custom_name and ("huggingface.co" in url):
170
+ for f in os.listdir(dest):
171
+ if re.fullmatch(r'[0-9a-f]{64}', f):
172
+ os.rename(os.path.join(dest, f), os.path.join(dest, pretty))
173
+ break
174
+
175
+ display(HTML("<br><h3 style='color:lightgreen;'>✅ ¡Todas las descargas solicitadas han finalizado!</h3>"))
176
 
177
  # Registramos la línea mágica al importar el módulo
178
  get_ipython().register_magic_function(download, magic_kind='line')