forked from juzeon/SydneyQt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
471 lines (452 loc) · 12.4 KB
/
app.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 (
"bytes"
"context"
_ "embed"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/PuerkitoBio/goquery"
goversion "github.com/hashicorp/go-version"
"github.com/life4/genesis/slices"
"github.com/microcosm-cc/bluemonday"
"github.com/pkoukk/tiktoken-go"
"github.com/samber/lo"
"github.com/wailsapp/wails/v2/pkg/runtime"
"log/slog"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sydneyqt/sydney"
"sydneyqt/util"
"sync"
"time"
)
//go:embed version.txt
var version string
// App struct
type App struct {
settings *Settings
ctx context.Context
logFile *os.File
logToStd bool
}
// NewApp creates a new App application struct
func NewApp(settings *Settings) *App {
return &App{settings: settings}
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
env := runtime.Environment(ctx)
a.logFile = os.Stderr
a.logToStd = true
if env.BuildType == "production" {
f, err := os.OpenFile(util.WithPath("log_" time.Now().Format("2006-01") ".log"),
os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
util.GracefulPanic(err)
}
a.logFile = f
a.logToStd = false
}
a.updateLogger(a.settings.config.Debug)
go func() {
for debug := range a.settings.DebugChangeSignal {
a.updateLogger(debug)
}
}()
}
func (a *App) shutdown(ctx context.Context) {
if !a.logToStd {
a.logFile.Close()
}
a.settings.Exit <- struct{}{}
os.Exit(0)
}
func (a *App) updateLogger(debug bool) {
slog.SetDefault(slog.New(slog.NewTextHandler(a.logFile, &slog.HandlerOptions{
AddSource: true,
Level: lo.Ternary(debug, slog.LevelDebug, slog.LevelInfo),
})))
slog.Info("Update logger", "debug", debug)
}
var tk *tiktoken.Tiktoken
var initTkFunc = sync.OnceFunc(func() {
slog.Info("Init tiktoken")
t, err := tiktoken.EncodingForModel("gpt-4")
if err != nil {
util.GracefulPanic(err)
}
tk = t
})
func (a *App) CountToken(text string) int {
initTkFunc()
return len(tk.Encode(text, nil, nil))
}
type UploadSydneyImageResult struct {
Base64URL string `json:"base64_url"`
BingURL string `json:"bing_url"`
Canceled bool `json:"canceled"`
}
func (a *App) UploadSydneyImage() (UploadSydneyImageResult, error) {
file, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Open an image to upload",
Filters: []runtime.FileFilter{{
DisplayName: "Image Files (*.jpg; *.jpeg; *.png; *.gif)",
Pattern: "*.jpg;*.jpeg;*.png;*.gif",
}},
})
if err != nil {
return UploadSydneyImageResult{}, err
}
if file == "" {
return UploadSydneyImageResult{Canceled: true}, nil
}
sydneyIns, err := a.createSydney()
if err != nil {
return UploadSydneyImageResult{}, err
}
v, err := os.ReadFile(file)
if err != nil {
return UploadSydneyImageResult{}, err
}
jpgData, err := util.ConvertImageToJpg(v)
if err != nil {
return UploadSydneyImageResult{}, err
}
url, err := sydneyIns.UploadImage(jpgData)
if err != nil {
return UploadSydneyImageResult{}, err
}
return UploadSydneyImageResult{
Base64URL: "data:image/jpeg;base64," base64.StdEncoding.EncodeToString(jpgData),
BingURL: url,
}, err
}
func (a *App) SelectUploadFile() (string, error) {
filePattern := strings.Join(lo.Map(sydney.BingAllowedFileExtensions, func(item string, index int) string {
return "*." item
}), ";")
file, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Open file to upload",
Filters: []runtime.FileFilter{{
DisplayName: "Custom Files (" filePattern ")",
Pattern: filePattern,
}},
})
if err != nil {
return "", err
}
return file, nil
}
type UploadSydneyDocumentResult struct {
Canceled bool `json:"canceled,omitempty"`
Text string `json:"text,omitempty"`
Ext string `json:"ext,omitempty"`
}
func (a *App) UploadDocument() (UploadSydneyDocumentResult, error) {
file, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Open a document to upload",
Filters: []runtime.FileFilter{{
DisplayName: "Document Files (*.pdf; *.pptx; *.docx; *.txt; *.md)",
Pattern: "*.pdf;*.pptx;*.docx;*.txt;*.md",
}},
})
if err != nil {
return UploadSydneyDocumentResult{}, err
}
if file == "" {
return UploadSydneyDocumentResult{Canceled: true}, nil
}
ext := filepath.Ext(file)
var docReader util.DocumentReader
switch ext {
case ".pdf":
docReader = util.PDFDocumentReader{}
case ".docx":
docReader = util.DocxDocumentReader{}
case ".pptx":
docReader = util.PptxDocumentReader{}
case ".txt", ".md":
docReader = util.PlainDocumentReader{}
default:
return UploadSydneyDocumentResult{}, errors.New("file type " ext " not implemented")
}
s, err := docReader.Read(file)
if err != nil {
return UploadSydneyDocumentResult{}, err
}
text := s
if !docReader.WillSkipPostprocess() {
text = strings.ReplaceAll(text, "\r", "")
text = regexp.MustCompile("(?m)^\r ").ReplaceAllString(text, "")
text = regexp.MustCompile("\n ").ReplaceAllString(text, "\n")
v, err := json.Marshal(&text)
if err != nil {
return UploadSydneyDocumentResult{}, err
}
text = string(v)
}
return UploadSydneyDocumentResult{
Text: text,
Ext: ext,
}, nil
}
type FetchWebpageResult struct {
Title string `json:"title"`
Content string `json:"content"`
}
func (a *App) FetchWebpage(url string) (FetchWebpageResult, error) {
empty := FetchWebpageResult{}
_, client, err := util.MakeHTTPClient(a.settings.config.Proxy, 15*time.Second)
if err != nil {
return empty, err
}
resp, err := client.R().Get(url)
if err != nil {
return empty, err
}
content := resp.String()
title := ""
if doc, err := goquery.NewDocumentFromReader(strings.NewReader(content)); err == nil {
title = doc.Find("title").Text()
doc.Find("script").Remove()
doc.Find("style").Remove()
text := bluemonday.StripTagsPolicy().Sanitize(doc.Text())
text = regexp.MustCompile(" {2,}").ReplaceAllString(text, " ")
lines := slices.Filter(strings.Split(text, "\n"), func(s string) bool {
return strings.TrimSpace(s) != ""
})
content = strings.Join(lines, "\n")
}
return FetchWebpageResult{
Title: title,
Content: content,
}, nil
}
func (a *App) GetUser() (string, error) {
sydneyIns, err := a.createSydney()
if err != nil {
return "", err
}
return sydneyIns.GetUser()
}
type CheckUpdateResult struct {
NeedUpdate bool `json:"need_update"`
CurrentVersion string `json:"current_version"`
LatestVersion string `json:"latest_version"`
ReleaseURL string `json:"release_url"`
ReleaseNote string `json:"release_note"`
}
func (a *App) CheckUpdate() (CheckUpdateResult, error) {
empty := CheckUpdateResult{}
_, client, err := util.MakeHTTPClient(a.settings.config.Proxy, 15*time.Second)
if err != nil {
return empty, err
}
resp, err := client.R().Get("https://api.github.com/repos/juzeon/SydneyQt/releases")
if err != nil {
return empty, err
}
var githubRelease []GithubReleaseResponse
err = json.Unmarshal(resp.Bytes(), &githubRelease)
if err != nil {
return empty, err
}
if len(githubRelease) == 0 {
return empty, errors.New("no release found")
}
currentVersion, err := goversion.NewVersion(strings.TrimSpace(version))
if err != nil {
return empty, err
}
latestVersionStr := githubRelease[0].TagName
latestVersionStr = strings.TrimPrefix(latestVersionStr, "v")
latestVersion, err := goversion.NewVersion(latestVersionStr)
if err != nil {
return empty, err
}
needUpdate := false
if latestVersion.GreaterThan(currentVersion) {
needUpdate = true
}
return CheckUpdateResult{
NeedUpdate: needUpdate,
CurrentVersion: currentVersion.String(),
LatestVersion: latestVersion.String(),
ReleaseURL: githubRelease[0].HtmlUrl,
ReleaseNote: githubRelease[0].Body,
}, nil
}
func (a *App) GenerateImage(generativeImage sydney.GenerativeImage) (sydney.GenerateImageResult, error) {
empty := sydney.GenerateImageResult{}
syd, err := a.createSydney()
if err != nil {
return empty, err
}
return syd.GenerateImage(generativeImage)
}
func (a *App) GenerateMusic(generativeMusic sydney.GenerativeMusic) (sydney.GenerateMusicResult, error) {
var empty sydney.GenerateMusicResult
syd, err := a.createSydney()
if err != nil {
return empty, err
}
return syd.GenerateMusic(generativeMusic)
}
func (a *App) SaveRemoteJPEGImage(url string) error {
if strings.Contains(url, "?") {
url = strings.Split(url, "?")[0]
}
filePath, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
Title: "Choose a destination to save the image",
Filters: []runtime.FileFilter{{
DisplayName: "JPEG Image Files (*.jpg, *.jpeg)",
Pattern: "*.jpg;*.jpeg",
}},
DefaultFilename: "image.jpg",
CanCreateDirectories: true,
})
if err != nil {
return err
}
if filePath == "" { // cancelled
return nil
}
_, client, err := util.MakeHTTPClient(a.settings.config.Proxy, 30*time.Second)
if err != nil {
return err
}
resp, err := client.R().Get(url)
if err != nil {
return err
}
if !strings.HasSuffix(filePath, ".jpg") && !strings.HasSuffix(filePath, ".jpeg") {
filePath = ".jpg"
}
return os.WriteFile(filePath, resp.Bytes(), 0644)
}
func (a *App) SaveRemoteFile(extWithoutDot, defaultFilenameWithoutExt, url string) error {
filePath, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
Title: "Choose a destination to save the file",
Filters: []runtime.FileFilter{{
DisplayName: "*." extWithoutDot,
Pattern: "*." extWithoutDot,
}},
DefaultFilename: lo.Ternary(defaultFilenameWithoutExt != "", defaultFilenameWithoutExt, "file")
"." extWithoutDot,
CanCreateDirectories: true,
})
if err != nil {
return err
}
if filePath == "" { // cancelled
return nil
}
_, client, err := util.MakeHTTPClient(a.settings.config.Proxy, 60*time.Second)
if err != nil {
return err
}
resp, err := client.R().Get(url)
if err != nil {
return err
}
if !strings.HasSuffix(filePath, "." extWithoutDot) {
filePath = "." extWithoutDot
}
return os.WriteFile(filePath, resp.Bytes(), 0644)
}
func (a *App) ExportWorkspace(id int) error {
workspace, ok := lo.Find(a.settings.config.Workspaces, func(item Workspace) bool {
return item.ID == id
})
if !ok {
return errors.New("workspace not exist by id: " strconv.Itoa(id))
}
filePath, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
Title: "Choose a destination to save the chat",
Filters: []runtime.FileFilter{{
DisplayName: "MarkDown Files (*.md)",
Pattern: "*.md",
}},
CanCreateDirectories: true,
DefaultFilename: workspace.Title ".md",
})
if err != nil {
return err
}
if filePath == "" {
return nil
}
if !strings.HasSuffix(filePath, ".md") {
filePath = ".md"
}
messages := util.GetChatMessage(workspace.Context)
var out bytes.Buffer
for _, msg := range messages {
out.WriteString(fmt.Sprintf("# \\[%s\\](#%s)\n%s\n\n", msg.Role, msg.Type, msg.Content))
}
input := strings.TrimSpace(workspace.Input)
if input != "" {
out.WriteString("# \\[user\\](#message)\n" workspace.Input "\n\n")
}
return os.WriteFile(filePath, out.Bytes(), 0644)
}
type ShareGPTRequest struct {
Title string `json:"title"`
Items []ShareGPTItem `json:"items"`
}
type ShareGPTItem struct {
From string `json:"from"`
Value string `json:"value"`
}
type ShareGPTResponse struct {
Message string `json:"message"` // on error
ID string `json:"id"` // on success
}
func (a *App) ShareWorkspace(id int) error {
workspace, ok := lo.Find(a.settings.config.Workspaces, func(item Workspace) bool {
return item.ID == id
})
if !ok {
return errors.New("workspace not exist by id: " strconv.Itoa(id))
}
_, client, err := util.MakeHTTPClient(a.settings.config.Proxy, 5*time.Second)
if err != nil {
return err
}
resp, err := client.R().SetBody(ShareGPTRequest{
Title: workspace.Title,
Items: lo.Map(util.GetChatMessage(workspace.Context), func(item util.ChatMessage, index int) ShareGPTItem {
from := "gpt"
if item.Role == "user" {
from = "human"
}
return ShareGPTItem{
From: from,
Value: fmt.Sprintf("[%s](#%s)\n%s", item.Role, item.Type, item.Content),
}
}),
}).Post("https://sharegpt.com/api/conversations")
if err != nil {
return err
}
if resp.IsErrorState() {
return errors.New("error status code: " resp.GetStatus())
}
var response ShareGPTResponse
err = json.Unmarshal(resp.Bytes(), &response)
if err != nil {
return err
}
if response.Message != "" {
return errors.New("error posting conversation: " response.Message)
}
err = util.OpenURL("https://sharegpt.com/c/" response.ID)
return nil
}