-
Notifications
You must be signed in to change notification settings - Fork 4
/
handlers_models.go
471 lines (392 loc) · 13.6 KB
/
handlers_models.go
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
package main
import (
"errors"
"eternal/pkg/hfutils"
"eternal/pkg/llm"
"eternal/pkg/llm/openai"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/log"
"github.com/pterm/pterm"
"gorm.io/gorm"
)
// handleModelData retrieves and returns data for a specific model.
func handleModelData() fiber.Handler {
return func(c *fiber.Ctx) error {
var model ModelParams
modelName := c.Params("modelName")
err := sqliteDB.First(modelName, &model)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return c.Status(fiber.StatusNotFound).SendString("Model not found")
}
return c.Status(fiber.StatusInternalServerError).SendString("Server Error")
}
return c.JSON(model)
}
}
// handleModelDownloadUpdate updates the download status of a model.
func handleModelDownloadUpdate() fiber.Handler {
return func(c *fiber.Ctx) error {
modelName := c.Params("modelName")
var payload struct {
Downloaded bool `json:"downloaded"`
}
if err := c.BodyParser(&payload); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Cannot parse JSON"})
}
err := sqliteDB.UpdateDownloadedByName(modelName, payload.Downloaded)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": fmt.Sprintf("Failed to update model: %v", err)})
}
return c.JSON(fiber.Map{
"success": true,
"message": "Model 'Downloaded' status updated successfully",
})
}
}
// handleModelUpdate updates the model data in the database.
func handleModelUpdate() fiber.Handler {
return func(c *fiber.Ctx) error {
var model ModelParams
if err := c.BodyParser(&model); err != nil {
return c.Status(fiber.StatusBadRequest).SendString("Cannot parse JSON")
}
err := sqliteDB.UpdateByName(model.Name, model)
if err != nil {
return c.Status(fiber.StatusInternalServerError).SendString("Server Error")
}
return c.JSON(model)
}
}
// handleModelCards retrieves and renders model cards.
func handleModelCards(modelParams []ModelParams) fiber.Handler {
return func(c *fiber.Ctx) error {
err := sqliteDB.Find(&modelParams)
if err != nil {
log.Errorf("Database error: %v", err)
return c.Status(500).SendString("Server Error")
}
return c.Render("templates/model", fiber.Map{"models": modelParams})
}
}
// handleModelSelect handles the selection of models for use.
func handleModelSelect() fiber.Handler {
return func(c *fiber.Ctx) error {
modelName := c.Params("name")
action := c.Params("action")
if action == "add" {
if err := AddSelectedModel(sqliteDB.db, modelName); err != nil {
return c.Status(fiber.StatusInternalServerError).SendString("Server Error")
}
} else if action == "remove" {
if err := RemoveSelectedModel(sqliteDB.db, modelName); err != nil {
return c.Status(fiber.StatusInternalServerError).SendString("Server Error")
}
} else {
return c.Status(fiber.StatusBadRequest).SendString("Invalid action")
}
return c.SendStatus(fiber.StatusOK)
}
}
// handleSelectedModels retrieves and returns the list of selected models.
func handleSelectedModels() fiber.Handler {
return func(c *fiber.Ctx) error {
selectedModels, err := GetSelectedModels(sqliteDB.db)
if err != nil {
log.Errorf("Error getting selected models: %v", err)
return c.Status(500).SendString("Server Error")
}
var selectedModelNames []string
for _, model := range selectedModels {
selectedModelNames = append(selectedModelNames, model.ModelName)
}
return c.JSON(selectedModelNames)
}
}
// handleModelDownload handles the download of a specified model.
func handleModelDownload(config *AppConfig) fiber.Handler {
return func(c *fiber.Ctx) error {
pterm.Error.Println("Download route hit")
modelName := c.Query("model")
if modelName == "" {
log.Errorf("Missing parameters for download")
return c.Status(fiber.StatusBadRequest).SendString("Missing parameters")
}
var downloadURL string
for _, model := range config.LanguageModels {
if model.Name == modelName {
downloadURL = model.Downloads[0]
break
}
}
modelFileName := filepath.Base(downloadURL)
modelPath := filepath.Join(config.DataPath, "models", modelName, modelFileName)
var partialDownload bool
if info, err := os.Stat(modelPath); err == nil {
if info.Size() > 0 {
expectedSize, err := llm.GetExpectedFileSize(downloadURL)
if err != nil {
log.Errorf("Error getting expected file size: %v", err)
}
partialDownload = info.Size() < expectedSize
}
}
go func() {
var err error
if partialDownload {
pterm.Info.Printf("Resuming download for model: %s\n", modelName)
err = llm.Download(downloadURL, modelPath)
} else {
pterm.Info.Printf("Starting download for model: %s\n", modelName)
err = llm.Download(downloadURL, modelPath)
}
if err != nil {
log.Errorf("Error in download: %v", err)
} else {
err = sqliteDB.UpdateDownloadedByName(modelName, true)
if err != nil {
log.Errorf("Failed to update model downloaded state: %v", err)
}
}
}()
progressErr := fmt.Sprintf("<div class='w-100' id='progress-download-%s' hx-ext='sse' sse-connect='/sseupdates' sse-swap='message' hx-trigger='load'></div>", modelName)
return c.SendString(progressErr)
}
}
// handleImgModelDownload handles the download of image generation models.
func handleImgModelDownload(config *AppConfig) fiber.Handler {
return func(c *fiber.Ctx) error {
config.Tools.ImgGen.Enabled = true
modelName := c.Query("model")
var downloadURL string
for _, model := range config.ImageModels {
if model.Name == modelName {
downloadURL = model.Downloads[0]
}
}
modelFileName := strings.Split(downloadURL, "/")[len(strings.Split(downloadURL, "/"))-1]
if modelName == "" {
log.Errorf("Missing parameters for download")
return c.Status(fiber.StatusBadRequest).SendString("Missing parameters")
}
modelRoot := fmt.Sprintf("%s/models/%s", config.DataPath, modelName)
modelPath := fmt.Sprintf("%s/models/%s/%s", config.DataPath, modelName, modelFileName)
tmpPath := fmt.Sprintf("%s/tmp", config.DataPath)
if _, err := os.Stat(modelRoot); os.IsNotExist(err) {
if err := os.MkdirAll(modelRoot, 0755); err != nil {
log.Errorf("Error creating model directory: %v", err)
return c.Status(fiber.StatusInternalServerError).SendString("Server Error")
}
}
if _, err := os.Stat(tmpPath); os.IsNotExist(err) {
if err := os.MkdirAll(tmpPath, 0755); err != nil {
log.Errorf("Error creating tmp directory: %v", err)
return c.Status(fiber.StatusInternalServerError).SendString("Server Error")
}
}
if _, err := os.Stat(modelPath); err != nil {
dm := hfutils.ConcurrentDownloadManager{
FileName: modelFileName,
URL: downloadURL,
Destination: modelPath,
NumParts: 1,
TempDir: tmpPath,
}
go dm.PrintProgress()
if err := dm.Download(); err != nil {
fmt.Println("Download failed:", err)
} else {
fmt.Println("Download successful!")
}
}
vaeName := "sdxl_vae.safetensors"
vaeURL := "https://huggingface.co/madebyollin/sdxl-vae-fp16-fix/blob/main/sdxl_vae.safetensors"
vaePath := fmt.Sprintf("%s/models/%s/%s", config.DataPath, modelName, vaeName)
if _, err := os.Stat(modelRoot); os.IsNotExist(err) {
if err := os.MkdirAll(modelRoot, 0755); err != nil {
log.Errorf("Error creating model directory: %v", err)
return c.Status(fiber.StatusInternalServerError).SendString("Server Error")
}
}
if _, err := os.Stat(vaePath); os.IsNotExist(err) {
go func() {
response, err := http.Get(vaeURL)
if err != nil {
pterm.Error.Printf("Failed to download file: %v", err)
return
}
defer response.Body.Close()
file, err := os.Create(vaePath)
if err != nil {
pterm.Error.Printf("Failed to create file: %v", err)
return
}
defer file.Close()
_, err = io.Copy(file, response.Body)
if err != nil {
pterm.Error.Printf("Failed to write to file: %v", err)
return
}
pterm.Info.Printf("Downloaded file: %s", vaeName)
}()
}
progressErr := "<div name='sse-messages' class='w-100' id='sse-messages' hx-ext='sse' sse-connect='/sseupdates' sse-swap='message'></div>"
return c.SendString(progressErr)
}
}
// handleOpenAIModels retrieves and returns a list of OpenAI models.
func handleOpenAIModels(config *AppConfig) fiber.Handler {
return func(c *fiber.Ctx) error {
client := openai.NewClient(config.OAIKey)
modelsResponse, err := openai.GetModels(client)
if err != nil {
log.Errorf(err.Error())
return c.Status(500).SendString("Server Error")
}
var gptModels []string
for _, model := range modelsResponse.Data {
if strings.HasPrefix(model.ID, "gpt") {
gptModels = append(gptModels, model.ID)
}
}
return c.JSON(fiber.Map{
"object": "list",
"data": gptModels,
})
}
}
func handleGetRoles(config *AppConfig) fiber.Handler {
return func(c *fiber.Ctx) error {
var optionsHTML strings.Builder
for _, role := range config.AssistantRoles {
optionsHTML.WriteString(fmt.Sprintf("<option value='%s'>%s</option>", role, role))
}
return c.Render(optionsHTML.String(), fiber.Map{
"roles": config.AssistantRoles,
})
}
}
func DownloadDefaultImageModel(config *AppConfig) error {
//modelName := config.ImageModels[0].Name
downloadURL := config.ImageModels[0].Downloads[0]
fileName := strings.Split(downloadURL, "/")[len(strings.Split(downloadURL, "/"))-1]
//modelRoot := fmt.Sprintf("%s/models/%s", config.DataPath, modelName)
modelPath := fmt.Sprintf("%s/sd/ComfyUI-master/models/checkpoints/%s", config.DataPath, fileName)
tmpPath := fmt.Sprintf("%s/tmp", config.DataPath)
if _, err := os.Stat(tmpPath); os.IsNotExist(err) {
if err := os.MkdirAll(tmpPath, 0755); err != nil {
log.Errorf("Error creating tmp directory: %v", err)
}
}
if _, err := os.Stat(modelPath); err != nil {
// If the default model is not present, we assume this is the first time the app runs
// // Run a python command to install the Comfy requirements.txt
// reqPath := fmt.Sprintf("%s/sd/ComfyUI-master/requirements.txt", config.DataPath)
// cmdArgs := []string{
// "install",
// "-r", reqPath,
// }
// cmd := exec.Command("pip3", cmdArgs...)
// // Set the standard output and error to the app's standard output and error
// cmd.Stdout = os.Stdout
// cmd.Stderr = os.Stderr
// if err := cmd.Run(); err != nil {
// log.Fatalf("Failed to run pip command: %v", err)
// }
pterm.Info.Println("Downloading default image model, please wait...")
dm := hfutils.ConcurrentDownloadManager{
FileName: fileName,
URL: downloadURL,
Destination: modelPath,
NumParts: 1,
TempDir: tmpPath,
}
go dm.PrintProgress()
if err := dm.Download(); err != nil {
fmt.Println("Download failed:", err)
} else {
fmt.Println("Download successful!")
}
}
// Check if the upscale model exists and if not, download it
fileName = "4x-UltraSharp.pth"
downloadURL = "https://huggingface.co/lokCX/4x-Ultrasharp/resolve/main/4x-UltraSharp.pth"
modelPath = fmt.Sprintf("%s/sd/ComfyUI-master/models/upscale_models/%s", config.DataPath, fileName)
if _, err := os.Stat(modelPath); err == nil {
pterm.Info.Printf("Upscale model found: %s\n", modelPath)
} else {
pterm.Info.Printf("Upscale model not found: %s\n", modelPath)
pterm.Info.Println("Downloading upscale model, please wait...")
dm := hfutils.ConcurrentDownloadManager{
FileName: fileName,
URL: downloadURL,
Destination: modelPath,
NumParts: 1,
TempDir: tmpPath,
}
go dm.PrintProgress()
if err := dm.Download(); err != nil {
fmt.Println("Download failed:", err)
} else {
fmt.Println("Download successful!")
}
}
// Needs work, implement in future commit
// Check if the Kolors models exist and if not, download them
// fileName = "diffusion_pytorch_model.fp16.safetensors"
// downloadURL = "https://huggingface.co/Kwai-Kolors/Kolors/blob/main/unet/diffusion_pytorch_model.fp16.safetensors"
// modelPath = fmt.Sprintf("%s/sd/ComfyUI-master/models/unet/%s", config.DataPath, fileName)
// if _, err := os.Stat(modelPath); err == nil {
// pterm.Info.Printf("Kolors model found: %s\n", modelPath)
// } else {
// pterm.Info.Println("Downloading Kolors image model, please wait...")
// dm := hfutils.ConcurrentDownloadManager{
// FileName: fileName,
// URL: downloadURL,
// Destination: modelPath,
// NumParts: 1,
// TempDir: tmpPath,
// }
// go dm.PrintProgress()
// if err := dm.Download(); err != nil {
// fmt.Println("Download failed:", err)
// } else {
// fmt.Println("Download successful!")
// }
// }
fileName = "sdxl_vae.safetensors"
downloadURL = "https://huggingface.co/stabilityai/sdxl-vae/resolve/main/sdxl_vae.safetensors"
modelPath = fmt.Sprintf("%s/sd/ComfyUI-master/models/vae/%s", config.DataPath, fileName)
if _, err := os.Stat(modelPath); err == nil {
pterm.Info.Printf("VAE model found: %s\n", modelPath)
} else {
// check if the llm folder exists
llmPath := fmt.Sprintf("%s/sd/ComfyUI-master/models/vae", config.DataPath)
if _, err := os.Stat(llmPath); err != nil {
if err := os.MkdirAll(llmPath, 0755); err != nil {
log.Errorf("Error creating llm directory: %v", err)
}
}
pterm.Info.Println("Downloading SDXL VAE, please wait...")
dm := hfutils.ConcurrentDownloadManager{
FileName: fileName,
URL: downloadURL,
Destination: modelPath,
NumParts: 1,
TempDir: tmpPath,
}
go dm.PrintProgress()
if err := dm.Download(); err != nil {
fmt.Println("Download failed:", err)
} else {
fmt.Println("Download successful!")
}
}
return nil
}