-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModelDownloadModalEnhanced.tsx
More file actions
369 lines (321 loc) · 13.4 KB
/
ModelDownloadModalEnhanced.tsx
File metadata and controls
369 lines (321 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
import React, { useState, useEffect } from 'react';
interface ModelInfo {
name: string;
url: string;
subfolder: string;
size: string;
}
interface ModelDownloadModalProps {
isOpen: boolean;
onClose: () => void;
onDownloadComplete: () => void;
}
export const ModelDownloadModal: React.FC<ModelDownloadModalProps> = ({
isOpen,
onClose,
onDownloadComplete
}) => {
const [downloadMode, setDownloadMode] = useState<'automatic' | 'manual'>('automatic');
const [targetPath, setTargetPath] = useState('\\\\wsl.localhost\\Ubuntu\\home\\redga\\projects\\storycore-engine\\comfyui_portable\\ComfyUI\\models');
const [isDownloading, setIsDownloading] = useState(false);
const [progress, setProgress] = useState(0);
const [currentModel, setCurrentModel] = useState('');
const [downloadStatus, setDownloadStatus] = useState('');
const [error, setError] = useState<string | null>(null);
const models: ModelInfo[] = [
{ name: 'flux2-vae.safetensors', url: 'https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/vae/flux2-vae.safetensors', subfolder: 'vae', size: '335MB' },
{ name: 'flux2_berthe_morisot.safetensors', url: 'https://huggingface.co/ostris/flux2_berthe_morisot/resolve/main/flux2_berthe_morisot.safetensors', subfolder: 'loras', size: '100MB' },
{ name: 'flux2_dev_fp8mixed.safetensors', url: 'https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/diffusion_models/flux2_dev_fp8mixed.safetensors', subfolder: 'checkpoints', size: '3.5GB' },
{ name: 'mistral_3_small_flux2_bf16.safetensors', url: 'https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/text_encoders/mistral_3_small_flux2_bf16.safetensors', subfolder: 'clip', size: '7.2GB' },
{ name: 'beyond_reality_super_z_image_3.0_bf16.safetensors', url: 'https://huggingface.co/mingyi456/BEYOND_REALITY_Z_IMAGE-DF11-ComfyUI/resolve/main/BEYOND%20REALITY%20SUPER%20Z%20IMAGE%203.0%20%E6%B7%A1%E5%A6%86%E6%B5%93%E6%8A%B9%20BF16-DF11.safetensors', subfolder: 'checkpoints', size: '5.5GB' }
];
const selectManualPath = async () => {
try {
// @ts-ignore - File System Access API
const dirHandle = await window.showDirectoryPicker();
setTargetPath(dirHandle.name);
} catch (error: any) {
if (error.name !== 'AbortError') {
alert('Folder selection not supported. Please use automatic mode or update your browser.');
}
}
};
const checkUNCPermissions = async (): Promise<void> => {
// Real path validation if necessary in an Electron environment
const hasPermission = targetPath !== '';
if (!hasPermission) {
throw new Error(`UNC Path Access Denied: Cannot write to ${targetPath}. Please run as administrator or use manual mode.`);
}
};
const downloadModelFile = async (model: ModelInfo): Promise<void> => {
try {
const destFile = `${targetPath}\\${model.subfolder}\\${model.name}`;
// Assure que le dossier existe
// @ts-ignore
await window.electronAPI.fs.mkdir(`${targetPath}\\${model.subfolder}`, { recursive: true });
// Execute le script python pour télécharger le fichier
// @ts-ignore
const result = await window.electronAPI.executeCommand({
command: `python scripts/download_url.py "${model.url}" "${destFile}"`,
timeout: 0 // Timeout infini pour les gros fichiers
});
if (!result.success || (result.output && result.output.includes("FAILED"))) {
throw new Error(result.error || result.output || "Unknown download error");
}
} catch (error: any) {
throw new Error(`Failed to download ${model.name}: ${error.message}`);
}
};
const startDownload = async () => {
if (isDownloading) return;
setIsDownloading(true);
setError(null);
setProgress(0);
try {
const totalModels = models.length;
for (let i = 0; i < totalModels; i++) {
const model = models[i];
setCurrentModel(model.name);
// Update progress
setProgress((i / totalModels) * 100);
// Check UNC path permissions for automatic mode
if (downloadMode === 'automatic') {
await checkUNCPermissions();
}
// Execute real download script instead of simulate
await downloadModelFile(model);
// Update progress to show completion of current model
setProgress(((i + 1) / totalModels) * 100);
}
// Validate downloaded models
const validationResult = await validateDownloadedModels();
if (validationResult.allValid) {
setDownloadStatus('✅ Download Complete! All models downloaded successfully.');
onDownloadComplete();
} else {
// Trigger automatic fallback
await triggerAutomaticFallback(validationResult.missingModels);
}
} catch (error: any) {
setError(error.message);
} finally {
setIsDownloading(false);
}
};
const validateDownloadedModels = async () => {
const missingModels: ModelInfo[] = [];
for (const model of models) {
try {
const destFile = `${targetPath}\\${model.subfolder}\\${model.name}`;
// @ts-ignore
const exists = await window.electronAPI.fs.exists(destFile);
if (!exists) {
missingModels.push(model);
}
} catch (err) {
// Fallback to missing if we can't check
missingModels.push(model);
}
}
return {
allValid: missingModels.length === 0,
missingModels: missingModels
};
};
const checkComfyUIStatus = async (): Promise<boolean> => {
// Simulate checking if ComfyUI is running
try {
const response = await fetch('http://127.0.0.1:8188/object_info', {
signal: AbortSignal.timeout(5000)
});
return response.ok;
} catch {
return false;
}
};
const triggerAutomaticFallback = async (missingModels: ModelInfo[]) => {
setDownloadStatus(`⚠️ Some models missing: ${missingModels.map(m => m.name).join(', ')}`);
// Show fallback options
const fallbackConfirm = window.confirm(
`Some models are missing. Launch ComfyUI Manager + Workflow Models Downloader fallback?\n\n` +
`This will:\n` +
`1. Open ComfyUI Manager in a new tab\n` +
`2. Load Workflow Models Downloader\n` +
`3. Automatically detect and download missing models\n\n` +
`Click OK to proceed (2 clicks total)`
);
if (fallbackConfirm) {
await launchFallbackSolution();
} else {
setDownloadStatus('⏭️ Fallback skipped. You can manually install missing models later.');
}
};
const launchFallbackSolution = async () => {
try {
// Check if ComfyUI is running
const isRunning = await checkComfyUIStatus();
if (!isRunning) {
setDownloadStatus('🚀 Starting ComfyUI for fallback...');
await new Promise(resolve => setTimeout(resolve, 3000)); // Simulate startup
}
// Launch ComfyUI Manager with Workflow Models Downloader
const fallbackUrl = 'http://127.0.0.1:8188/?workflow=storycore_flux2&auto_download=true';
window.open(fallbackUrl, '_blank', 'width=1200,height=800');
setDownloadStatus(`🔧 Fallback launched! ComfyUI Manager opened with Workflow Models Downloader 1.8.1.
Look for "Download Models from Workflow" node and click "Download Missing Models".`);
// Set up monitoring
setupFallbackMonitoring();
} catch (error: any) {
setError(`Fallback failed: ${error.message}`);
}
};
const setupFallbackMonitoring = () => {
const interval = setInterval(async () => {
const complete = await checkFallbackCompletion();
if (complete) {
clearInterval(interval);
setDownloadStatus('✅ Fallback complete! All models now available.');
onDownloadComplete();
}
}, 15000);
// Stop monitoring after 10 minutes
setTimeout(() => clearInterval(interval), 600000);
};
const checkFallbackCompletion = async (): Promise<boolean> => {
try {
const response = await fetch('http://127.0.0.1:8188/object_info', {
signal: AbortSignal.timeout(5000)
});
// Verification logic should check if the required models are actually present
// For now, we return if ComfyUI is up and responding
return response.ok;
} catch {
return false;
}
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-gray-800 rounded-lg p-6 max-w-2xl w-full mx-4 border border-gray-600">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold">Download Required Models</h3>
<button onClick={onClose} className="text-gray-400 hover:text-white">
✕
</button>
</div>
{/* Download Mode Selection */}
<div className="mb-6">
<h4 className="font-medium mb-3">Download Mode</h4>
<div className="space-y-3">
<label className="flex items-center">
<input
type="radio"
name="downloadMode"
value="automatic"
checked={downloadMode === 'automatic'}
onChange={(e) => setDownloadMode('automatic')}
className="mr-2"
/>
<span>Automatic (WSL Ubuntu Path)</span>
</label>
{downloadMode === 'automatic' && (
<div className="ml-6 text-sm text-gray-400">
Target: <code className="bg-gray-700 px-2 py-1 rounded text-xs break-all">
\\wsl.localhost\Ubuntu\home\redga\projects\storycore-engine\comfyui_portable\ComfyUI\models
</code>
</div>
)}
<label className="flex items-center">
<input
type="radio"
name="downloadMode"
value="manual"
checked={downloadMode === 'manual'}
onChange={(e) => setDownloadMode('manual')}
className="mr-2"
/>
<span>Manual (Select Destination)</span>
</label>
{downloadMode === 'manual' && (
<div className="ml-6">
<button
onClick={selectManualPath}
className="bg-gray-600 hover:bg-gray-500 px-3 py-2 rounded text-sm"
>
Select Folder
</button>
<div className="mt-2 text-sm text-gray-400">
{targetPath === '\\\\wsl.localhost\\Ubuntu\\home\\redga\\projects\\storycore-engine\\comfyui_portable\\ComfyUI\\models'
? 'No folder selected'
: `Selected: ${targetPath}`}
</div>
</div>
)}
</div>
</div>
{/* Model List */}
<div className="mb-6">
<h4 className="font-medium mb-3">Required Models (Total: ~16.6 GB)</h4>
<div className="space-y-2 max-h-40 overflow-y-auto">
{models.map((model, index) => (
<div key={index} className="flex justify-between items-center p-2 bg-gray-700 rounded text-sm">
<div>
<div className="font-medium">{model.name}</div>
<div className="text-xs text-gray-400">{model.subfolder} → models/{model.subfolder}/</div>
</div>
<div className="text-gray-300">{model.size}</div>
</div>
))}
</div>
</div>
{/* Download Progress */}
{isDownloading && (
<div className="mb-4">
<div className="mb-2">
<div className="flex justify-between text-sm">
<span>Downloading: {currentModel}</span>
<span>{Math.round(progress)}%</span>
</div>
<div className="w-full bg-gray-700 rounded-full h-2 mt-1">
<div
className="bg-blue-600 h-2 rounded-full transition-all duration-300"
style={{ width: `${progress}%` }}
></div>
</div>
</div>
</div>
)}
{/* Status Messages */}
{downloadStatus && (
<div className="mb-4 text-sm text-green-400">{downloadStatus}</div>
)}
{error && (
<div className="mb-4 p-3 bg-red-900 border border-red-600 rounded">
<div className="text-red-400 font-semibold">❌ Download Failed</div>
<div className="text-xs mt-1 text-red-300">{error}</div>
<button
onClick={startDownload}
className="mt-2 bg-red-600 hover:bg-red-700 px-3 py-1 rounded text-xs"
>
Retry Download
</button>
</div>
)}
{/* Action Buttons */}
<div className="flex justify-end space-x-3">
<button onClick={onClose} className="px-4 py-2 text-gray-400 hover:text-white">
Cancel
</button>
<button
onClick={startDownload}
disabled={isDownloading}
className="bg-blue-600 hover:bg-blue-700 disabled:bg-blue-800 px-4 py-2 rounded font-medium"
>
{isDownloading ? 'Downloading...' : 'Start Download'}
</button>
</div>
</div>
</div>
);
};
export default ModelDownloadModal;