File size: 11,826 Bytes
6d6b815
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Settings management for AI system
 */

document.addEventListener('DOMContentLoaded', function() {
    // DOM elements
    const settingsForm = document.getElementById('settings-form');
    const downloadModelForm = document.getElementById('download-model-form');
    const cloneModelForm = document.getElementById('clone-model-form');
    const advancedSettingsEditor = document.getElementById('advanced-settings');
    
    // Initialize settings page if we're on it
    if (settingsForm) {
        initializeSettingsPage();
    }
    
    /**
     * Initialize settings page components
     */
    function initializeSettingsPage() {
        // Format JSON in advanced settings textarea
        if (advancedSettingsEditor) {
            try {
                const currentSettings = advancedSettingsEditor.value;
                if (currentSettings) {
                    const formattedSettings = JSON.stringify(JSON.parse(currentSettings), null, 2);
                    advancedSettingsEditor.value = formattedSettings;
                }
            } catch (e) {
                console.error('Error formatting advanced settings JSON:', e);
            }
        }
        
        // Set up model download form
        if (downloadModelForm) {
            downloadModelForm.addEventListener('submit', function(e) {
                e.preventDefault();
                downloadModel();
            });
        }
        
        // Set up model clone form
        if (cloneModelForm) {
            cloneModelForm.addEventListener('submit', function(e) {
                e.preventDefault();
                cloneModel();
            });
        }
        
        // Load available models
        loadAvailableModels();
    }
    
    /**
     * Download a model from Hugging Face or GitHub
     */
    function downloadModel() {
        const modelName = document.getElementById('model-name').value;
        const modelSource = document.getElementById('model-source').value;
        
        // Get source-specific fields
        let repoUrl, githubBranch, githubToken, hfToken;
        
        if (modelSource === 'github') {
            repoUrl = document.getElementById('repo-url')?.value;
            githubBranch = document.getElementById('github-branch')?.value;
            githubToken = document.getElementById('github-token')?.value;
        } else {
            hfToken = document.getElementById('hf-token')?.value;
        }
        
        // Validate inputs
        if (!modelName) {
            showAlert('Please enter a model name.', 'danger');
            return;
        }
        
        if (modelSource === 'github' && !repoUrl) {
            showAlert('Please enter a GitHub repository URL.', 'danger');
            return;
        }
        
        // Disable form during download
        toggleFormElements(downloadModelForm, true);
        
        // Show loading status
        showAlert('Starting model download. This may take a while...', 'info', 'download-status');
        
        // Prepare request data
        const data = {
            model_name: modelName,
            source: modelSource
        };
        
        // Add source-specific parameters
        if (modelSource === 'github') {
            data.repo_url = repoUrl;
            if (githubBranch) data.branch = githubBranch;
            if (githubToken) data.github_token = githubToken;
        } else if (modelSource === 'huggingface') {
            if (hfToken) data.hf_token = hfToken;
        }
        
        // Send request to server
        fetch('/api/models/download', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        })
        .then(response => response.json())
        .then(data => {
            toggleFormElements(downloadModelForm, false);
            
            if (data.success) {
                showAlert(`Model ${modelName} downloaded successfully!`, 'success', 'download-status');
                // Refresh model list
                loadAvailableModels();
            } else {
                showAlert(`Error downloading model: ${data.error}`, 'danger', 'download-status');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            toggleFormElements(downloadModelForm, false);
            showAlert(`Error downloading model: ${error.message}`, 'danger', 'download-status');
        });
    }
    
    /**
     * Clone and modify a model
     */
    function cloneModel() {
        const originalModel = document.getElementById('original-model').value;
        const newModelName = document.getElementById('new-model-name').value;
        const modificationsText = document.getElementById('modifications')?.value;
        
        // Validate inputs
        if (!originalModel || !newModelName) {
            showAlert('Please select an original model and provide a name for the clone.', 'danger');
            return;
        }
        
        // Parse modifications JSON if provided
        let modifications = {};
        if (modificationsText) {
            try {
                modifications = JSON.parse(modificationsText);
            } catch (e) {
                showAlert('Invalid JSON in modifications field.', 'danger');
                return;
            }
        }
        
        // Disable form during cloning
        toggleFormElements(cloneModelForm, true);
        
        // Show loading status
        showAlert('Cloning model. This may take a while...', 'info', 'clone-status');
        
        // Send request to server
        fetch('/api/models/clone', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                original_model: originalModel,
                new_model_name: newModelName,
                modifications: modifications
            }),
        })
        .then(response => response.json())
        .then(data => {
            toggleFormElements(cloneModelForm, false);
            
            if (data.success) {
                showAlert(`Model cloned successfully to ${newModelName}!`, 'success', 'clone-status');
                // Refresh model list
                loadAvailableModels();
            } else {
                showAlert(`Error cloning model: ${data.error}`, 'danger', 'clone-status');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            toggleFormElements(cloneModelForm, false);
            showAlert(`Error cloning model: ${error.message}`, 'danger', 'clone-status');
        });
    }
    
    /**
     * Load available models from server
     */
    function loadAvailableModels() {
        const originalModelSelect = document.getElementById('original-model');
        const preferredModelSelect = document.getElementById('preferred-model');
        
        if (!originalModelSelect && !preferredModelSelect) {
            return;
        }
        
        fetch('/api/models/list')
            .then(response => response.json())
            .then(data => {
                const models = data.models || [];
                
                // Update original model select
                if (originalModelSelect) {
                    // Save current selection
                    const currentSelection = originalModelSelect.value;
                    
                    // Clear options
                    originalModelSelect.innerHTML = '';
                    
                    // Add new options
                    models.forEach(model => {
                        const option = document.createElement('option');
                        option.value = model.name;
                        option.textContent = `${model.name} (${model.source})`;
                        originalModelSelect.appendChild(option);
                    });
                    
                    // Restore selection if possible
                    if (currentSelection && originalModelSelect.querySelector(`option[value="${currentSelection}"]`)) {
                        originalModelSelect.value = currentSelection;
                    }
                }
                
                // Update preferred model select
                if (preferredModelSelect) {
                    // Save current selection
                    const currentSelection = preferredModelSelect.value;
                    
                    // Keep existing options (they come from the server-rendered page)
                    // and add any new ones
                    const existingValues = Array.from(preferredModelSelect.options).map(opt => opt.value);
                    
                    models.forEach(model => {
                        if (!existingValues.includes(model.name)) {
                            const option = document.createElement('option');
                            option.value = model.name;
                            option.textContent = `${model.name} (${model.source})`;
                            preferredModelSelect.appendChild(option);
                        }
                    });
                    
                    // Restore selection
                    if (currentSelection) {
                        preferredModelSelect.value = currentSelection;
                    }
                }
            })
            .catch(error => {
                console.error('Error loading models:', error);
                showAlert('Error loading available models', 'danger');
            });
    }
    
    /**
     * Show an alert message
     */
    function showAlert(message, type, elementId = null) {
        if (elementId) {
            // Show in a specific element
            const element = document.getElementById(elementId);
            if (element) {
                element.innerHTML = `<div class="alert alert-${type} mt-3">${message}</div>`;
            }
        } else {
            // Create a new alert at the top of the page
            const alertContainer = document.getElementById('alert-container') || document.createElement('div');
            alertContainer.id = 'alert-container';
            alertContainer.className = 'container mt-3';
            
            const alert = document.createElement('div');
            alert.className = `alert alert-${type} alert-dismissible fade show`;
            alert.role = 'alert';
            alert.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            `;
            
            alertContainer.appendChild(alert);
            
            // Add to page if not already there
            if (!document.getElementById('alert-container')) {
                const contentElement = document.querySelector('main') || document.body;
                contentElement.insertBefore(alertContainer, contentElement.firstChild);
            }
            
            // Auto-dismiss after 5 seconds
            setTimeout(() => {
                alert.classList.remove('show');
                setTimeout(() => {
                    alert.remove();
                    if (alertContainer.children.length === 0) {
                        alertContainer.remove();
                    }
                }, 150);
            }, 5000);
        }
    }
    
    /**
     * Enable or disable all form elements
     */
    function toggleFormElements(form, disabled) {
        if (!form) return;
        
        const elements = form.querySelectorAll('input, select, textarea, button');
        elements.forEach(element => {
            element.disabled = disabled;
        });
    }
});