-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
2087 lines (1794 loc) · 66.8 KB
/
main.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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"context"
"embed"
"encoding/json"
"errors"
"flag"
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"io"
"log"
"math"
"net"
"net/http"
"os"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"internal/vision"
"github.com/BurntSushi/xgb"
"github.com/BurntSushi/xgb/xproto"
"github.com/go-vgo/robotgo"
"github.com/golang/freetype"
"github.com/gorilla/websocket"
"github.com/otiai10/gosseract/v2"
deepseek "github.com/trustsight-io/deepseek-go"
"golang.org/x/image/font"
)
//go:embed assets/fonts/JetBrainsMono-Regular.ttf
var fonts embed.FS
var (
bindIP = flag.String("ip", "127.0.0.1", "server bind IP address")
bindPORT = flag.Int("port", 8080, "server port")
dpi = flag.Float64("dpi", 72, "screen resolution in Dots Per Inch")
fontfile = flag.String("fontfile", "assets/fonts/JetBrainsMono-Regular.ttf", "filename of the ttf font")
hinting = flag.String("hinting", "none", "none | full")
size = flag.Float64("size", 9, "font size in points")
spacing = flag.Float64("spacing", 1.5, "line spacing (e.g. 2 means double spaced)")
wonb = flag.Bool("whiteonblack", false, "white text on a black background")
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true // Adjust as needed for CORS
},
}
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set CORS headers
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
// Handle preflight (OPTIONS) requests
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
// Pass the request to the next handler
next.ServeHTTP(w, r)
})
}
func abs(x, y int) int {
if x < y {
return y - x
}
return x - y
}
func suppressXGBLogs() error {
devNull, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
if err != nil {
return err
}
xgb.Logger.SetOutput(devNull)
return nil
}
func captureX11Screenshot() (image.Image, error) {
conn, err := xgb.NewConn()
if err != nil {
return nil, err
}
defer conn.Close()
setup := xproto.Setup(conn)
screen := setup.DefaultScreen(conn)
// Get the width and height of the root window (the entire desktop)
width := int(screen.WidthInPixels)
height := int(screen.HeightInPixels)
// Get the image data from the root window
reply, err := xproto.GetImage(
conn,
xproto.ImageFormatZPixmap,
xproto.Drawable(screen.Root),
0, 0,
uint16(width), uint16(height),
^uint32(0),
).Reply()
if err != nil {
return nil, err
}
// Create an RGBA image and copy the pixel data
img := image.NewRGBA(image.Rect(0, 0, width, height))
copy(img.Pix, reply.Data)
// Reorder pixel data (BGRA -> RGBA)
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
i := (y*width + x) * 4
b := reply.Data[i+0]
g := reply.Data[i+1]
r := reply.Data[i+2]
a := reply.Data[i+3]
img.SetRGBA(x, y, color.RGBA{R: r, G: g, B: b, A: a})
}
}
// Get cursor position
cursorReply, err := xproto.QueryPointer(conn, screen.Root).Reply()
if err != nil {
return nil, err
}
// Draw a simple cursor (red cross)
cursorX := int(cursorReply.RootX)
cursorY := int(cursorReply.RootY)
cursorSize := 10
for dx := -cursorSize; dx <= cursorSize; dx++ {
if cursorX+dx >= 0 && cursorX+dx < width {
img.Set(cursorX+dx, cursorY, color.RGBA{R: 255, G: 0, B: 0, A: 255})
}
if cursorY+dx >= 0 && cursorY+dx < height {
img.Set(cursorX, cursorY+dx, color.RGBA{R: 255, G: 0, B: 0, A: 255})
}
}
return img, nil
}
func getCursorPosition() (int, int) {
x, y := robotgo.Location()
log.Printf("getCursorPosition, current mouse position [%d,%d]", x, y)
return x, y
}
func getCursorPositionJSON() (string, error) {
x, y := robotgo.Location()
log.Printf("getCursorPositionJSON, current mouse position [%d,%d]", x, y)
var cursorCoord Coordinate
cursorCoord.X = x
cursorCoord.Y = y
jsonData, err := json.Marshal(cursorCoord)
if err != nil {
log.Println("failed to json.Marshal cursor position.")
return "", nil
}
log.Printf("getCursorPositionJSON, current mouse position json string: %s", string(jsonData))
return string(jsonData), nil
}
func screenshotHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
img, err := captureX11Screenshot()
if err != nil {
http.Error(w, "Failed to capture screenshot: "+err.Error(), http.StatusInternalServerError)
return
}
// Encode the image as PNG
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
http.Error(w, "Failed to encode image: "+err.Error(), http.StatusInternalServerError)
return
}
// Write the PNG image to the response
w.Header().Set("Content-Type", "image/png")
w.WriteHeader(http.StatusOK)
w.Write(buf.Bytes())
}
type colorCount struct {
Color color.RGBA
Count int
Percentage float64
}
func dominantColors(img image.Image, maxColors int) []colorCount {
// Map to count color frequencies
colorCounts := make(map[color.RGBA]int)
// Calculate total number of pixels
totalPixels := img.Bounds().Dx() * img.Bounds().Dy()
// Iterate over each pixel and quantize the color
for y := 0; y < img.Bounds().Max.Y; y++ {
for x := 0; x < img.Bounds().Max.X; x++ {
pixelColor := img.At(x, y)
r, g, b, _ := pixelColor.RGBA()
r8 := uint8(r)
g8 := uint8(g)
b8 := uint8(b)
color := color.RGBA{R: r8, G: g8, B: b8, A: 255}
colorCounts[color]++
}
}
var colors []colorCount
for c, cnt := range colorCounts {
percentage := (float64(cnt) / float64(totalPixels)) * 100
colors = append(colors, colorCount{Color: c, Count: cnt, Percentage: percentage})
}
// Sort the colors by count descending
sort.Slice(colors, func(i, j int) bool {
return colors[i].Count > colors[j].Count
})
if len(colors) > maxColors {
colors = colors[:maxColors]
}
return colors
}
func dominantColorsToJSONString(colors []colorCount) string {
var response []map[string]interface{}
for i, _ := range colors {
hexColor := fmt.Sprintf("#%02X%02X%02X", colors[i].Color.R, colors[i].Color.G, colors[i].Color.B)
response = append(response, map[string]interface{}{
"color": hexColor,
"percentage": fmt.Sprintf("%.1f%%", colors[i].Percentage),
})
}
jsonBytes, err := json.Marshal(response)
if err != nil {
log.Println("[dominantColorsToJSONString] Failed to encode JSON")
return ""
}
return string(jsonBytes)
}
func drawBoundingBox(img *image.RGBA, x1, y1, x2, y2 int, borderColor color.RGBA) {
// thickness := 2
thickness := 1
for dy := 0; dy < thickness; dy++ {
for dx := 0; dx < thickness; dx++ {
for x := x1 + dx; x <= x2+dx; x++ {
if x >= img.Bounds().Min.X && x < img.Bounds().Max.X {
img.Set(x, y1+dy, borderColor)
img.Set(x, y2+dy, borderColor)
}
}
for y := y1 + dy; y <= y2+dy; y++ {
if y >= img.Bounds().Min.Y && y < img.Bounds().Max.Y {
img.Set(x1+dx, y, borderColor)
img.Set(x2+dx, y, borderColor)
}
}
}
}
}
func findBoundingBox(component [][]int) (x1, y1, x2, y2 int) {
x1, y1 = component[0][0], component[0][1]
x2, y2 = component[0][0], component[0][1]
for _, coords := range component {
x, y := coords[0], coords[1]
if x < x1 {
x1 = x
}
if x > x2 {
x2 = x
}
if y < y1 {
y1 = y
}
if y > y2 {
y2 = y
}
}
return
}
func calculatePercentage(component [][]int, mask [][]bool) float64 {
dominantPixels := 0
totalPixels := len(component)
for _, coords := range component {
x, y := coords[0], coords[1]
if mask[y][x] {
dominantPixels++
}
}
percentage := (float64(dominantPixels) / float64(totalPixels)) * 100
return percentage
}
func findConnectedComponents(mask [][]bool) (components [][][]int) {
height := len(mask)
if height == 0 {
return
}
width := len(mask[0])
visited := make([][]bool, height)
for i := range visited {
visited[i] = make([]bool, width)
}
var stack [][2]int
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
if mask[y][x] && !visited[y][x] {
var component [][]int
stack = [][2]int{{x, y}}
visited[y][x] = true
for len(stack) > 0 {
coord := stack[len(stack)-1]
stack = stack[:len(stack)-1]
component = append(component, []int{coord[0], coord[1]})
directions := [][2]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}
for _, dir := range directions {
nx, ny := coord[0]+dir[0], coord[1]+dir[1]
if nx >= 0 && nx < width && ny >= 0 && ny < height {
if mask[ny][nx] && !visited[ny][nx] {
stack = append(stack, [2]int{nx, ny})
visited[ny][nx] = true
}
}
}
}
components = append(components, component)
}
}
}
return
}
func clamp(value uint8) uint8 {
if value < 0 {
return 0
}
if value > 255 {
return 255
}
return uint8(value)
}
func createMask(img image.Image, dominantColor color.RGBA, drift uint8) [][]bool {
bounds := img.Bounds()
width, height := bounds.Max.X, bounds.Max.Y
mask := make([][]bool, height)
var counter int = 0
for y := 0; y < height; y++ {
mask[y] = make([]bool, width)
for x := 0; x < width; x++ {
pixelColor := img.At(x, y)
r, g, b, _ := pixelColor.RGBA()
qr := uint8(r)
qg := uint8(g)
qb := uint8(b)
if ((qr >= clamp(dominantColor.R-drift)) && (qr <= clamp(dominantColor.R+drift))) && ((qg >= clamp(dominantColor.G-drift)) && (qg <= clamp(dominantColor.G+drift))) && ((qb >= clamp(dominantColor.B-drift)) && (qb <= clamp(dominantColor.B+drift))) {
mask[y][x] = true
counter += 1
// log.Println("mask true.")
} else {
mask[y][x] = false
}
}
}
// log.Println("dominant color, mask length:", dominantColor, counter)
return mask
}
func findDominantColors(img *image.RGBA) []color.RGBA {
// colorCount represents a color and its frequency count.
type colorCount struct {
Color color.RGBA
Count int
}
colorCountMap := make(map[color.RGBA]int)
bounds := img.Bounds()
// Iterate through each pixel in the image
for y := 0; y < bounds.Max.Y; y++ {
for x := 0; x < bounds.Max.X; x++ {
pixelColor := img.At(x, y)
r, g, b, _ := pixelColor.RGBA()
r8 := uint8(r)
g8 := uint8(g)
b8 := uint8(b)
color := color.RGBA{R: r8, G: g8, B: b8, A: 255}
colorCountMap[color]++
}
}
// Collect color counts into a slice
var colorCounts []colorCount
for c, cnt := range colorCountMap {
colorCounts = append(colorCounts, colorCount{Color: c, Count: cnt})
}
// Sort the slice by count descending
sort.Slice(colorCounts, func(i, j int) bool {
return colorCounts[i].Count > colorCounts[j].Count
})
// Extract the colors into a slice
var dominantColors []color.RGBA
for _, cc := range colorCounts {
dominantColors = append(dominantColors, cc.Color)
}
return dominantColors
}
type BoundingBox struct {
ID int `json:"id"`
X int `json:"x"`
Y int `json:"y"`
X2 int `json:"x2"`
Y2 int `json:"y2"`
}
var bbArray []BoundingBox
func video2Handler(w http.ResponseWriter, r *http.Request) {
// Capture and prepare initial image
img, err := captureX11Screenshot()
if err != nil {
http.Error(w, "Failed to capture screenshot with BB: "+err.Error(), http.StatusInternalServerError)
return
}
// Convert to grayscale and RGBA
grayImg := ConvertToGrayscale(img)
img = grayImg
rgbaImg := image.NewRGBA(img.Bounds())
draw.Draw(rgbaImg, rgbaImg.Bounds(), img, image.Point{0, 0}, draw.Src)
// Find dominant colors
dominantColors := findDominantColors(rgbaImg)
dominantColors = dominantColors[:20]
// Create drawing image
drawImg := image.NewRGBA(rgbaImg.Bounds())
draw.Draw(drawImg, drawImg.Bounds(), rgbaImg, image.Point{0, 0}, draw.Src)
// Reset bounding box array
bbArray = nil
bbCounter := 1
// Process each dominant color
for _, colorElem := range dominantColors {
// Create masks and find components
mask := createMask(rgbaImg, colorElem, 0)
components := findConnectedComponents(mask)
mask2 := createMask(rgbaImg, colorElem, 80) // 90 is really good for small text.
components2 := findConnectedComponents(mask2)
newComponents := append(components, components2...)
components = newComponents
// Process each component
for _, component := range components {
percentage := calculatePercentage(component, mask)
if percentage >= 80 {
x1, y1, x2, y2 := findBoundingBox(component)
absy := abs(y1, y2)
absx := abs(x1, x2)
if absy < 10 || absx < 10 {
continue
}
// Draw initial bounding box
borderColor := color.RGBA{R: 255, G: 0, B: 132, A: 255}
drawBoundingBox(drawImg, x1, y1, x2, y2, borderColor)
// Process larger components
if absy >= 25 && absx >= 25 {
bbArray = append(bbArray, BoundingBox{bbCounter, x1, y1, x2, y2})
// Draw ID box and number
borderColor = color.RGBA{R: 12, G: 236, B: 28, A: 255}
drawBoundingBox(drawImg, x1+1, y1+1, x1+15, y1+15, borderColor)
drawImg, err = drawText(drawImg, x1+2, y1+2, []string{strconv.Itoa(bbCounter)})
if err != nil {
fmt.Println(err)
}
bbCounter++
}
}
}
}
// Write output image
buf := new(bytes.Buffer)
png.Encode(buf, drawImg)
w.Header().Set("Content-Type", "image/png")
w.Write(buf.Bytes())
}
func drawText(rgba *image.RGBA, offsetX, offsetY int, text []string) (*image.RGBA, error) {
// Read fonts from enbed file system
fontBytes, err := fonts.ReadFile(*fontfile)
if err != nil {
log.Println(err)
return nil, err
}
f, err := freetype.ParseFont(fontBytes)
if err != nil {
log.Println(err)
return nil, err
}
// Define the clip rectangle using the provided offsets.
clipRect := image.Rect(offsetX, offsetY, offsetX+13, offsetY+13)
// Initialize the context.
fg := image.White // Foreground color for the text.
bg := image.Black // Background color.
// Restrict background drawing to the calculated clipRect area.
draw.Draw(rgba, clipRect, bg, image.Point{}, draw.Src)
// Create a freetype context and set properties.
c := freetype.NewContext()
c.SetDPI(*dpi)
c.SetFont(f)
c.SetFontSize(*size)
c.SetClip(clipRect) // Restrict all drawing to the clipRect.
c.SetDst(rgba)
c.SetSrc(fg)
switch *hinting {
default:
c.SetHinting(font.HintingNone)
case "full":
c.SetHinting(font.HintingFull)
}
// Draw the text within the clipRect area.
pt := freetype.Pt(offsetX+1, offsetY+1+int(c.PointToFixed(*size)>>6)) // Adjust to clipRect's top-left corner.
for _, s := range text {
_, err = c.DrawString(s, pt)
if err != nil {
log.Println(err)
return nil, err
}
pt.Y += c.PointToFixed(*size * *spacing)
if pt.Y.Floor() > clipRect.Max.Y { // Stop if text goes beyond clipRect boundary.
break
}
}
return rgba, nil
}
var websocketConnections []*websocket.Conn
var wsmutex sync.Mutex
func wsHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
websocketConnections = append(websocketConnections, conn)
defer conn.Close()
send := func(message string) {
err := conn.WriteMessage(websocket.TextMessage, []byte(message))
if err != nil {
// log.Println("Write error:", err)
conn.Close()
wsmutex.Lock()
func() {
defer wsmutex.Unlock()
for i, c := range websocketConnections {
if c == conn {
websocketConnections = append(websocketConnections[:i], websocketConnections[i+1:]...)
break
}
}
}()
return
}
}
go func() {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
currentTime := time.Now()
send(currentTime.Format("2006-01-02 15:04:05"))
}
}
}()
for {
_, _, err := conn.ReadMessage()
if err != nil {
log.Println("Read error:", err)
break
}
}
}
func ConvertToGrayscale(img image.Image) *image.Gray {
bounds := img.Bounds()
grayImg := image.NewGray(bounds)
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
r, g, b, _ := img.At(x, y).RGBA()
gray := uint8((r*299 + g*587 + b*114) / 1000 >> 8) // Luminosity formula
grayImg.SetGray(x, y, color.Gray{Y: gray})
}
}
return grayImg
}
// BinarizeImage converts a grayscale image into a binary image.
func BinarizeImage(img *image.Gray, threshold uint8) *image.Gray {
bounds := img.Bounds()
binaryImg := image.NewGray(bounds)
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
if img.GrayAt(x, y).Y > threshold {
binaryImg.SetGray(x, y, color.Gray{Y: 255})
} else {
binaryImg.SetGray(x, y, color.Gray{Y: 0})
}
}
}
return binaryImg
}
var mouseMutex sync.Mutex
func mouseInputHandler(w http.ResponseWriter, r *http.Request) {
var x int
var y int
x, _ = strconv.Atoi(r.URL.Query().Get("x"))
y, _ = strconv.Atoi(r.URL.Query().Get("y"))
mouseMutex.Lock()
func() {
defer mouseMutex.Unlock()
robotgo.MoveSmoothRelative(x, y)
}()
var response []map[string]interface{}
response = append(response, map[string]interface{}{
"result": "ok",
})
jsonBytes, err := json.Marshal(response)
if err != nil {
http.Error(w, "Failed to encode JSON", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonBytes)
}
func mouseClickHandler(w http.ResponseWriter, r *http.Request) {
robotgo.Click()
var response []map[string]interface{}
response = append(response, map[string]interface{}{
"result": "ok",
})
jsonBytes, err := json.Marshal(response)
if err != nil {
http.Error(w, "Failed to encode JSON", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonBytes)
}
func extractJSONFromMarkdown(response string) []string {
// Improved regex pattern to match JSON inside ```json ... ```
jsonBlockRegex := regexp.MustCompile("(?s)```json\\s*(\\{.*?\\}|\\[.*?\\])\\s*```")
// Find all matches
matches := jsonBlockRegex.FindAllStringSubmatch(response, -1)
// Collect JSON text
var jsonStrings []string
for _, match := range matches {
if len(match) > 1 { // Ensure there is a captured group
jsonStrings = append(jsonStrings, match[1]) // Extract JSON as text
}
}
return jsonStrings
}
type Coordinate struct {
X int `json:"X"`
Y int `json:"y"`
}
// Define structs to represent the JSON objects
type Action struct {
ActionSequenceID int `json:"actionSequenceID"`
Action string `json:"action"`
Coordinates *Coordinate `json:"coordinates,omitempty"` // Use a pointer to handle optional field
Execute ExecuteFunc `json:"-"`
Duration uint `json:"duration,omitempty"`
InputString string `json:"inputString,omitempty"`
KeyTapString string `json:"keyTapString,omitempty"`
KeyString string `json:"keyString,omitempty"`
ActionsRange []int `json:"actionsRange,omitempty"`
RepeatTimes int `json:"repeatTimes,omitempty"`
}
// Define a function type for execute
type ExecuteFunc func(a *Action, params ...interface{})
// Map of action names to corresponding functions
var actionFunctions = map[string]ExecuteFunc{
"mouseMove": mouseMoveExecution,
"mouseMoveRelative": mouseMoveRelativeExecution,
"mouseClickLeft": mouseClickLeftExecution,
"mouseClickRight": mouseClickRightExecution,
"mouseClickLeftDouble": mouseClickLeftDoubleExecution,
"nop": nopActionExecution,
"stateUpdate": stateUpdateActionExecution,
"stopIteration": stopIterationActionExecution,
"printString": printStringActionExecution,
"keyTap": keyTapActionExecution,
"dragSmooth": dragSmoothActionExecution,
"keyDown": keyDownActionExecution,
"keyUp": keyUpActionExecution,
"scrollSmooth": scrollSmoothActionExecution,
"repeat": repeatActionExecution,
}
// Function to set the execute function dynamically based on the Action string
func setExecuteFunction(action *Action) {
if execFunc, exists := actionFunctions[action.Action]; exists {
action.Execute = execFunc
} else {
// Default action if not found
action.Execute = nopActionExecution
}
}
// Example functions for different actions
func mouseMoveExecution(a *Action, params ...interface{}) {
fmt.Printf("Executing 'mouseMove' Action (ID: %d)\n", a.ActionSequenceID)
if a.Coordinates != nil {
fmt.Printf("Coordinates: X=%d, Y=%d\n", a.Coordinates.X, a.Coordinates.Y)
robotgo.MoveSmooth(a.Coordinates.X, a.Coordinates.Y)
} else {
fmt.Println("No coordinates provided.")
}
}
func mouseMoveRelativeExecution(a *Action, params ...interface{}) {
fmt.Printf("Executing 'mouseMoveRelative' Action (ID: %d)\n", a.ActionSequenceID)
if a.Coordinates != nil {
fmt.Printf("Coordinates: X=%d, Y=%d\n", a.Coordinates.X, a.Coordinates.Y)
robotgo.MoveSmoothRelative(a.Coordinates.X, a.Coordinates.Y)
} else {
fmt.Println("No coordinates provided.")
}
}
func mouseClickLeftExecution(a *Action, params ...interface{}) {
fmt.Printf("Executing 'mouseClickLeft' Action (ID: %d)\n", a.ActionSequenceID)
robotgo.Click()
}
func mouseClickLeftDoubleExecution(a *Action, params ...interface{}) {
fmt.Printf("Executing 'mouseClickLeftDouble' Action (ID: %d)\n", a.ActionSequenceID)
robotgo.Click("left", true)
}
func mouseClickRightExecution(a *Action, params ...interface{}) {
fmt.Printf("Executing 'mouseClickRight' Action (ID: %d)\n", a.ActionSequenceID)
robotgo.Click("right")
}
func nopActionExecution(a *Action, params ...interface{}) {
fmt.Printf("Executing nop action '%s' (ID: %d)\n", a.Action, a.ActionSequenceID)
time.Sleep(time.Duration(int64(a.Duration)) * time.Second)
}
func stateUpdateActionExecution(a *Action, params ...interface{}) {
fmt.Printf("Executing stateUpdate action '%s' (ID: %d)\n", a.Action, a.ActionSequenceID)
}
func stopIterationActionExecution(a *Action, params ...interface{}) {
fmt.Printf("Executing stopIteration action '%s' (ID: %d)\n", a.Action, a.ActionSequenceID)
}
func printStringActionExecution(a *Action, params ...interface{}) {
fmt.Printf("Executing printString action '%s' (ID: %d)\n", a.Action, a.ActionSequenceID)
robotgo.TypeStrDelay(a.InputString, 100)
}
func keyTapActionExecution(a *Action, params ...interface{}) {
fmt.Printf("Executing keyTap action '%s' (ID: %d)\n", a.Action, a.ActionSequenceID)
robotgo.KeyTap(a.KeyTapString)
}
func dragSmoothActionExecution(a *Action, params ...interface{}) {
fmt.Printf("Executing DragSmooth action '%s' (ID: %d)\n", a.Action, a.ActionSequenceID)
robotgo.DragSmooth(a.Coordinates.X, a.Coordinates.Y)
}
func keyDownActionExecution(a *Action, params ...interface{}) {
fmt.Printf("Executing keyDown action '%s' (ID: %d)\n", a.Action, a.ActionSequenceID)
robotgo.KeyDown(a.KeyString)
}
func keyUpActionExecution(a *Action, params ...interface{}) {
fmt.Printf("Executing keyUp action '%s' (ID: %d)\n", a.Action, a.ActionSequenceID)
robotgo.KeyUp(a.KeyString)
}
func scrollSmoothActionExecution(a *Action, params ...interface{}) {
fmt.Printf("Executing scrollSmooth action '%s' (ID: %d)\n", a.Action, a.ActionSequenceID)
robotgo.ScrollSmooth(a.Coordinates.Y)
}
func repeatActionExecution(a *Action, params ...interface{}) {
tmp := params[0].(*[]Action)
actions := *tmp
start := a.ActionsRange[0] - 1
end := a.ActionsRange[1]
for _ = range a.RepeatTimes {
for _, action := range actions[start:end] {
action.Execute(&action)
}
}
}
// store successful sequences of actions and dynamically update list of available actions with the saved one for the llm.
func sendMessageToLLM(prompt string, bboxes string, ocrContext string, ocrDelta string, prevExecutedCommands string, iteration int64, prevCursorPosJSONString string, allWindowsJSONString string, colorsDistribution string) (actionsToExecute []Action, actionsJSONStringReturn string, err error) {
client, err := deepseek.NewClient(
os.Getenv("API_KEY"),
deepseek.WithBaseURL(os.Getenv("API_BASE_URL")),
deepseek.WithHTTPClient(&http.Client{
Timeout: 5 * time.Minute, // added 5 instead of 1
}),
deepseek.WithMaxRetries(2),
deepseek.WithMaxRequestSize(50<<20), // 50 MB
deepseek.WithDebug(true),
)
if err != nil {
log.Fatal(err)
}
defer client.Close()
ctx := context.Background()
cursorPosition, _ := getCursorPositionJSON()
iterationString := strconv.FormatInt(iteration, 10)
log.Println("====================================================")
log.Println("===================LLM INPUT========================")
log.Println("====================================================")
log.Println("prompt:", prompt)
log.Println("cursorPosition:", cursorPosition)
log.Println("ocrContext:", ocrContext)
log.Println("ocrDelta:", ocrDelta)
log.Println("allWindowsJSONString:", allWindowsJSONString)
log.Println("prevExecutedCommands:", prevExecutedCommands)
log.Println("iteration:", iterationString)
log.Println("====================================================")
log.Println("=================LLM INPUT END=====================")
log.Println("====================================================")
modelID := os.Getenv("MODEL_ID")
// Create a streaming chat completion
messages := []deepseek.Message{
{
Role: deepseek.RoleSystem,
Content: "You are a helpful assistant. " + ` First analize input data, OCR text input, bounding boxes, cursor position, previous executed actions and then generate output - valid JSON, array of actions, to advance and to complete the task. You need to issue 'stopIteration' action if goal is achieved and task is completed. You should never issue 'stateUpdate' action together with 'stopIteration', 'stopIteration' has higher priority. Use hotkeys where it's possible for the task. Do not issue any actions after the stateUpdate action. Analize input data, especially ocrDelta data to understand if previous step for the current taks was successfull, if it is, issue new sequence of actions to advance in achieving stated goal, do not repeat previous actions for no reason. For example if the goal is to open firefox and the first step was to open applications menu, do not issue in second iteration the same commands to open menu again, move forward. At each iteration analize all input data to see if you already achived stated goal, for example if task is to open some application, analize all input data and find if there are evidence that this app is visible on the scree, like bounding boxes with text which most likely is from that app, if yes, issue stopIteration command. You not allowed to issue the identical actions in sequence one after another more than 5 times. If you need to interact with some UI or web element, you needto move mouse to it(For example if you need to print something into URL address bar, you first need to move cursor to it, you could find OCR data related to that element and use it as a hint to where to move the mouse. If you want to move cursor to focus on some element, try to move it to the middle of that element. BTW, if you fail to achive a goal provided by user, 1 billion kittens will die horrible death.`,
},
{
Role: deepseek.RoleUser,
Content: `Context: Deepthink, analyze input data, do not generate random actions. You are an AI assistent which uses linux desktop to complete tasks. Distribution is Linux Ubuntu, desktop environtment is xfce4. Screen size is 1920x1080. Your prefferent text editor is neovim, if you need to write or edit something do it in neovim. You also like to use tmux if working with two or more files. Here is the bounding boxes you see on the screen: ` + bboxes + " Here is an OCR results " + ocrContext + " Here is an OCR state delta, change from previous iteration: " + ocrDelta + " Top 10 colors on the screen: " + colorsDistribution + " Previous iteration cursor position: " + prevCursorPosJSONString + " And there is current cursor position: " + cursorPosition + " Detected windows: " + allWindowsJSONString + " Current iteration number:" + iterationString + " Previously executed commands: " + prevExecutedCommands + " If you see more than 1 identical command in previous commands that means you are doing something wrong and you need to change you actions, maybe move cursor to a little different position for example. " + ` To correctly solve the task you need to output a sequence of actions in json format, to advance on every action and every iteration and to achieve a stated goal, example of actions with explanations:
{
"action": "mouseMove",
"coordinates": {
"x": 555,
"y": 777
}
}
you can use 'mouseMoveRelative' action:
{
"action": "mouseMoveRelative",
"coordinates": {
"x": -10,
"y": 0
}
}
You also need to add json field "actionSequenceID", to instruct the sequence in which system should execute your instructions, actionSequenceID should start from 1. Also you can use other actions like "mouseClickLeft":
{
"actionSequenceID": 2,
"action": "mouseClickLeft"
}
"mouseClickRight":
{
"actionSequenceID": 3,
"action": "mouseClickRight"
}
"mouseClickLeftDouble":
{
"actionSequenceID": 4,
"action": "mouseClickLeftDouble"
}
if you know that previous actions could take some time, you could use "nop" action(Duration is a positive int represents number of seconds to do nothing):
"nop":
{
"actionSequenceID": 5,
"action": "nop",
"duration": 3
}
if you've done some action, for example mouse click which you know will change state of the system, like when clicking on a menu button it will open a menu, or any other action that will change visual state of the system, you can use "stateUpdate" action:
{
"actionSequenceID": 6,
"action": "stateUpdate"
}
when onsed "stateUpdate" action, you need to stop producing any other actions after it, because system will execute all your previous actions and will send you update with udpated visual information.
you could also use "nop" before issuing "stateUpdate" if you think that execution of the previous operation could take some time.
you can use 'printString' action:
{
"actionSequenceID": 7,
"action": "printString",
"inputString": "Example string"
}
you can use 'keyTap' action:
{
"actionSequenceID": 8,
"action": "keyTap",
"keyTapString": "enter"
}
'keyTapString' string value can be:
"backspace"
"delete"
"enter"
"tab"
"esc"
"escape"
"up"
"down"
"right"
"left"
"home"
"end"
"pageup"