File size: 9,128 Bytes
d02c2a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
'use client';
import React, { useEffect, useRef, useState } from 'react';
import { createGlobalState } from 'react-global-hooks';
import { Trash2 } from 'lucide-react';
import { Modal } from './Modal';
import { TextInput, SelectInput } from '@/components/formInputs';
import { getFilename } from '@/utils/basic';
import { callScriptStream } from '@/utils/callScript';
import { SelectOption } from '@/types';

export interface MergeLoRAFile {
  path: string;
}

export interface MergeLoRAsModalState {
  folderPath: string;
  outputName: string;
  availableLoRAs: MergeLoRAFile[];
  onClose?: () => void;
}

interface SelectedLoRA {
  path: string;
  strength: number;
}

export const mergeLoRAsModalState = createGlobalState<MergeLoRAsModalState | null>(null);

export const openMergeLoRAsModal = (
  folderPath: string,
  outputName: string,
  availableLoRAs: MergeLoRAFile[],
  onClose?: () => void,
) => {
  mergeLoRAsModalState.set({
    folderPath,
    outputName,
    availableLoRAs,
    onClose,
  });
};

const joinPath = (folder: string, name: string) => {
  const sep = folder.includes('\\') && !folder.includes('/') ? '\\' : '/';
  const trimmed = folder.replace(/[\\/]+$/, '');
  return `${trimmed}${sep}${name}.safetensors`;
};

const MergeLoRAsModal: React.FC = () => {
  const [modalInfo, setModalInfo] = mergeLoRAsModalState.use();
  const isOpen = modalInfo !== null;
  const [selectedLoRAs, setSelectedLoRAs] = useState<SelectedLoRA[]>([]);
  const [isRunning, setIsRunning] = useState(false);
  const [isDone, setIsDone] = useState(false);
  const [hasError, setHasError] = useState(false);
  const [logOutput, setLogOutput] = useState('');
  const logRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (!modalInfo) {
      setSelectedLoRAs([]);
      setIsRunning(false);
      setIsDone(false);
      setHasError(false);
      setLogOutput('');
    }
  }, [modalInfo]);

  useEffect(() => {
    if (logRef.current) {
      logRef.current.scrollTop = logRef.current.scrollHeight;
    }
  }, [logOutput]);

  const onClose = () => {
    if (isRunning) return;
    setModalInfo(null);
    modalInfo?.onClose?.();
  };

  const onSubmit = async () => {
    if (isRunning || !modalInfo) return;
    setIsRunning(true);
    setIsDone(false);
    setHasError(false);
    setLogOutput('');

    const output = joinPath(modalInfo.folderPath, modalInfo.outputName);

    const append = (chunk: string) => setLogOutput(prev => prev + chunk);

    try {
      const finalEvent = await callScriptStream('merge_loras.py', {
        args: {
          loras: JSON.stringify(selectedLoRAs),
          output,
          save_dtype: 'bfloat16',
          device: 'cpu',
        },
        onStdout: append,
        onStderr: append,
      });

      const ok = finalEvent?.type === 'exit' && finalEvent.ok === true;
      if (!ok) {
        setHasError(true);
        if (finalEvent?.type === 'error' && finalEvent.message) {
          append(`\n${finalEvent.message}\n`);
        } else if (finalEvent?.type === 'exit' && finalEvent.timedOut) {
          append('\nScript timed out.\n');
        } else if (finalEvent?.type === 'exit') {
          append(`\nScript exited with code ${finalEvent.exitCode}.\n`);
        }
      }
    } catch (err: any) {
      setHasError(true);
      append(`\n${err?.message || 'Unknown error'}\n`);
    } finally {
      setIsRunning(false);
      setIsDone(true);
    }
  };

  const loraLabel = (path: string) => getFilename(path).replace('.safetensors', '');

  const availableLoRAs = modalInfo?.availableLoRAs ?? [];
  const selectedPaths = selectedLoRAs.map(s => s.path);

  const options: SelectOption[] = availableLoRAs
    .filter(f => !selectedPaths.includes(f.path))
    .map(f => ({ value: f.path, label: loraLabel(f.path) }));

  const rescale = (items: SelectedLoRA[]): SelectedLoRA[] => {
    if (items.length === 0) return items;
    const strength = Math.round((1 / items.length) * 1000) / 1000;
    return items.map(s => ({ ...s, strength }));
  };

  const addLoRA = (path: string) => {
    if (!path || selectedPaths.includes(path)) return;
    setSelectedLoRAs(prev => rescale([...prev, { path, strength: 0 }]));
  };

  const removeLoRA = (path: string) => {
    setSelectedLoRAs(prev => rescale(prev.filter(s => s.path !== path)));
  };

  const updateStrength = (path: string, strength: number | null) => {
    setSelectedLoRAs(prev => prev.map(s => (s.path === path ? { ...s, strength: strength ?? 0 } : s)));
  };

  const showLog = isRunning || isDone;

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title="Merge LoRAs"
      size="lg"
      showCloseButton={!isRunning}
      closeOnOverlayClick={!isRunning}
    >
      {showLog ? (
        <div>
          <div className="mb-2 text-sm">
            {isRunning && <span className="text-amber-400">Merging LoRAs... please do not close this window.</span>}
            {isDone && hasError && <span className="text-rose-400">Merge failed. See log below.</span>}
            {isDone && !hasError && <span className="text-emerald-400">Merge complete.</span>}
          </div>
          <div
            ref={logRef}
            className="font-mono text-xs whitespace-pre-wrap break-all overflow-y-auto rounded-md p-3 min-h-[400px] max-h-[60vh] bg-white text-gray-900 dark:bg-black dark:text-gray-100"
          >
            {logOutput || (isRunning ? 'Starting...\n' : '')}
          </div>
          <div className="mt-4 flex justify-end gap-2">
            <button
              type="button"
              onClick={onClose}
              disabled={isRunning}
              className="px-4 py-2 text-sm bg-gray-700 hover:bg-gray-600 disabled:opacity-40 disabled:cursor-not-allowed text-gray-100 rounded-md"
            >
              Close
            </button>
          </div>
        </div>
      ) : (
        <form
          onSubmit={e => {
            e.preventDefault();
            onSubmit();
          }}
        >
          <TextInput
            label="Output Filename"
            value={modalInfo?.outputName || ''}
            suffix=".safetensors"
            onChange={value => {
              setModalInfo({
                ...modalInfo,
                outputName: value,
              } as MergeLoRAsModalState);
            }}
            placeholder="Enter output filename"
          />

          <div className="mt-4">
            <SelectInput
              label="Add LoRA"
              multiple={false}
              value=""
              onChange={value => addLoRA(value)}
              options={options}
            />
          </div>

          {selectedLoRAs.length > 0 && (
            <div className="mt-4">
              <label className="block text-xs mb-1 text-gray-300">Selected LoRAs</label>
              <div className="bg-purple-500/10 rounded-xl p-2 max-h-48 overflow-y-auto space-y-1">
                {selectedLoRAs.map(s => (
                  <div key={s.path} className="flex items-center gap-2 px-2 py-0.5">
                    <div
                      className="flex-1 min-w-0 text-xs text-gray-200 overflow-hidden text-ellipsis whitespace-nowrap"
                      title={loraLabel(s.path)}
                    >
                      {loraLabel(s.path)}
                    </div>
                    <input
                      type="number"
                      value={s.strength}
                      onChange={e => {
                        const raw = e.target.value;
                        if (raw === '' || raw === '-') return;
                        const n = Number(raw);
                        if (!isNaN(n)) updateStrength(s.path, n);
                      }}
                      step="any"
                      className="w-20 flex-shrink-0 text-xs px-2 py-0.5 bg-gray-950 dark:bg-gray-800 border border-gray-700 rounded-sm text-gray-100 focus:ring-1 focus:ring-gray-600 focus:outline-none"
                    />
                    <button
                      type="button"
                      onClick={() => removeLoRA(s.path)}
                      className="flex-shrink-0 text-gray-400 hover:text-rose-400 p-0.5"
                      aria-label="Remove"
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                  </div>
                ))}
              </div>
            </div>
          )}

          <div className="mt-6 flex justify-end gap-2">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm text-gray-300 hover:text-gray-100 rounded-md"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={selectedLoRAs.length === 0 || !modalInfo?.outputName}
              className="px-4 py-2 text-sm bg-purple-600 hover:bg-purple-700 disabled:opacity-40 disabled:cursor-not-allowed text-white rounded-md"
            >
              Merge
            </button>
          </div>
        </form>
      )}
    </Modal>
  );
};

export default MergeLoRAsModal;