-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathocr.go
1630 lines (1386 loc) · 40.3 KB
/
ocr.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
// Copyright (c) 2022-2024 Winlin
//
// SPDX-License-Identifier: MIT
package main
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path"
"strings"
"sync"
"time"
// From ossrs.
"github.com/ossrs/go-oryx-lib/errors"
ohttp "github.com/ossrs/go-oryx-lib/http"
"github.com/ossrs/go-oryx-lib/logger"
// Use v8 because we use Go 1.16+, while v9 requires Go 1.18+
"github.com/go-redis/redis/v8"
"github.com/google/uuid"
"github.com/sashabaranov/go-openai"
)
// The total segments in callback HLS.
const maxCallbackSegments = 9
var ocrWorker *OCRWorker
type OCRWorker struct {
cancel context.CancelFunc
wg sync.WaitGroup
// The global OCR task, only support one OCR task.
task *OCRTask
// Use async goroutine to process on_hls messages.
msgs chan *SrsOnHlsMessage
// Got message from SRS, a new TS segment file is generated.
tsfiles chan *SrsOnHlsObject
}
func NewOCRWorker() *OCRWorker {
v := &OCRWorker{
// Message on_hls.
msgs: make(chan *SrsOnHlsMessage, 1024),
// TS files.
tsfiles: make(chan *SrsOnHlsObject, 1024),
}
v.task = NewOCRTask()
v.task.ocrWorker = v
return v
}
func (v *OCRWorker) Handle(ctx context.Context, handler *http.ServeMux) error {
ep := "/terraform/v1/ai/ocr/query"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
var token string
if err := ParseBody(ctx, r.Body, &struct {
Token *string `json:"token"`
}{
Token: &token,
}); err != nil {
return errors.Wrapf(err, "parse body")
}
apiSecret := envApiSecret()
if err := Authenticate(ctx, apiSecret, token, r.Header); err != nil {
return errors.Wrapf(err, "authenticate")
}
config := NewOCRConfig()
if err := config.Load(ctx); err != nil {
return errors.Wrapf(err, "load config")
}
type QueryResponse struct {
Config *OCRConfig `json:"config"`
Task struct {
UUID string `json:"uuid"`
} `json:"task"`
}
resp := &QueryResponse{
Config: config,
}
resp.Task.UUID = v.task.UUID
ohttp.WriteData(ctx, w, r, resp)
logger.Tf(ctx, "ocr query ok, config=<%v>, uuid=%v, token=%vB",
config, v.task.UUID, len(token))
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
ep = "/terraform/v1/ai/ocr/apply"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
var token string
var uuid string
var config OCRConfig
if err := ParseBody(ctx, r.Body, &struct {
Token *string `json:"token"`
UUID *string `json:"uuid"`
*OCRConfig
}{
Token: &token,
UUID: &uuid, OCRConfig: &config,
}); err != nil {
return errors.Wrapf(err, "parse body")
}
apiSecret := envApiSecret()
if err := Authenticate(ctx, apiSecret, token, r.Header); err != nil {
return errors.Wrapf(err, "authenticate")
}
// Not required yet.
if uuid != v.task.UUID {
logger.Wf(ctx, "ocr ignore uuid mismatch, query=%v, task=%v", uuid, v.task.UUID)
}
if err := config.Save(ctx); err != nil {
return errors.Wrapf(err, "save config")
}
if err := v.task.restart(ctx); err != nil {
return errors.Wrapf(err, "restart task %v", config.String())
}
type ApplyResponse struct {
UUID string `json:"uuid"`
}
ohttp.WriteData(ctx, w, r, &ApplyResponse{
UUID: v.task.UUID,
})
logger.Tf(ctx, "ocr apply ok, config=<%v>, uuid=%v, token=%vB",
config, v.task.UUID, len(token))
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
ep = "/terraform/v1/ai/ocr/check"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
var token string
var ocrConfig OCRConfig
if err := ParseBody(ctx, r.Body, &struct {
Token *string `json:"token"`
*OCRConfig
}{
Token: &token,
OCRConfig: &ocrConfig,
}); err != nil {
return errors.Wrapf(err, "parse body")
}
apiSecret := envApiSecret()
if err := Authenticate(ctx, apiSecret, token, r.Header); err != nil {
return errors.Wrapf(err, "authenticate")
}
// Query whisper-1 model detail.
var config openai.ClientConfig
config = openai.DefaultConfig(ocrConfig.AISecretKey)
config.BaseURL = ocrConfig.AIBaseURL
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
client := openai.NewClientWithConfig(config)
model, err := client.GetModel(ctx, "whisper-1")
if err != nil {
return errors.Wrapf(err, "query model whisper-1")
}
// Start a chat, to check whether the billing is expired.
resp, err := client.CreateChatCompletion(
ctx, openai.ChatCompletionRequest{
Model: openai.GPT4o,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleUser,
Content: "Hello!",
},
},
MaxTokens: 50,
},
)
if err != nil {
return errors.Wrapf(err, "create chat")
}
ohttp.WriteData(ctx, w, r, nil)
logger.Tf(ctx, "ocr check ok, config=<%v>, model=<%v>, msg=<%v>, token=%vB",
ocrConfig, model.ID, resp.Choices[0].Message.Content, len(token))
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
ep = "/terraform/v1/ai/ocr/reset"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
var token string
var uuid string
if err := ParseBody(ctx, r.Body, &struct {
Token *string `json:"token"`
UUID *string `json:"uuid"`
}{
Token: &token,
UUID: &uuid,
}); err != nil {
return errors.Wrapf(err, "parse body")
}
apiSecret := envApiSecret()
if err := Authenticate(ctx, apiSecret, token, r.Header); err != nil {
return errors.Wrapf(err, "authenticate")
}
if uuid != v.task.UUID {
return errors.Errorf("invalid uuid %v", uuid)
}
if err := v.task.reset(ctx); err != nil {
return errors.Wrapf(err, "restart task %v", uuid)
}
type ResetResponse struct {
UUID string `json:"uuid"`
}
ohttp.WriteData(ctx, w, r, &ResetResponse{
UUID: v.task.UUID,
})
logger.Tf(ctx, "ocr reset ok, uuid=%v, new=%v, token=%vB", uuid, v.task.UUID, len(token))
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
ep = "/terraform/v1/ai/ocr/live-queue"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
var token string
if err := ParseBody(ctx, r.Body, &struct {
Token *string `json:"token"`
}{
Token: &token,
}); err != nil {
return errors.Wrapf(err, "parse body")
}
apiSecret := envApiSecret()
if err := Authenticate(ctx, apiSecret, token, r.Header); err != nil {
return errors.Wrapf(err, "authenticate")
}
type Segment struct {
TsID string `json:"tsid"`
SeqNo uint64 `json:"seqno"`
URL string `json:"url"`
Duration float64 `json:"duration"`
Size uint64 `json:"size"`
}
type LiveQueueResponse struct {
Segments []*Segment `json:"segments"`
Count int `json:"count"`
}
res := &LiveQueueResponse{}
segments := v.task.liveSegments()
for _, segment := range segments {
res.Segments = append(res.Segments, []*Segment{&Segment{
TsID: segment.TsFile.TsID,
SeqNo: segment.TsFile.SeqNo,
URL: segment.TsFile.URL,
Duration: segment.TsFile.Duration,
Size: segment.TsFile.Size,
}}...)
}
res.Count = len(res.Segments)
ohttp.WriteData(ctx, w, r, res)
logger.Tf(ctx, "ocr query live ok, token=%vB", len(token))
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
ep = "/terraform/v1/ai/ocr/ocr-queue"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
var token string
if err := ParseBody(ctx, r.Body, &struct {
Token *string `json:"token"`
}{
Token: &token,
}); err != nil {
return errors.Wrapf(err, "parse body")
}
apiSecret := envApiSecret()
if err := Authenticate(ctx, apiSecret, token, r.Header); err != nil {
return errors.Wrapf(err, "authenticate")
}
type Segment struct {
TsID string `json:"tsid"`
SeqNo uint64 `json:"seqno"`
URL string `json:"url"`
Duration float64 `json:"duration"`
Size uint64 `json:"size"`
// The source ts file.
SourceTsID string `json:"stsid"`
// The cost in ms to extract image.
ExtractImageCost int32 `json:"eic"`
}
type OCRQueueResponse struct {
Segments []*Segment `json:"segments"`
Count int `json:"count"`
}
res := &OCRQueueResponse{}
segments := v.task.ocrSegments()
for _, segment := range segments {
res.Segments = append(res.Segments, []*Segment{&Segment{
TsID: segment.ImageFile.TsID,
SeqNo: segment.ImageFile.SeqNo,
URL: segment.ImageFile.File,
Duration: segment.ImageFile.Duration,
Size: segment.ImageFile.Size,
// The source ts file.
SourceTsID: segment.TsFile.TsID,
// The cost in ms to extract image.
ExtractImageCost: int32(segment.CostExtractImage.Milliseconds()),
}}...)
}
res.Count = len(res.Segments)
ohttp.WriteData(ctx, w, r, res)
logger.Tf(ctx, "ocr query ocr ok, token=%vB", len(token))
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
ep = "/terraform/v1/ai/ocr/callback-queue"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
var token string
if err := ParseBody(ctx, r.Body, &struct {
Token *string `json:"token"`
}{
Token: &token,
}); err != nil {
return errors.Wrapf(err, "parse body")
}
apiSecret := envApiSecret()
if err := Authenticate(ctx, apiSecret, token, r.Header); err != nil {
return errors.Wrapf(err, "authenticate")
}
type Segment struct {
TsID string `json:"tsid"`
SeqNo uint64 `json:"seqno"`
URL string `json:"url"`
Duration float64 `json:"duration"`
Size uint64 `json:"size"`
// The source ts file.
SourceTsID string `json:"stsid"`
// The cost in ms to extract image.
ExtractImageCost int32 `json:"eic"`
// The OCR text result.
OCRText string `json:"ocr"`
// The cost in ms to do OCR.
OCRCost int32 `json:"ocrc"`
}
type OCRQueueResponse struct {
Segments []*Segment `json:"segments"`
Count int `json:"count"`
}
res := &OCRQueueResponse{}
segments := v.task.callbackSegments()
for _, segment := range segments {
res.Segments = append(res.Segments, []*Segment{&Segment{
TsID: segment.ImageFile.TsID,
SeqNo: segment.ImageFile.SeqNo,
URL: segment.ImageFile.File,
Duration: segment.ImageFile.Duration,
Size: segment.ImageFile.Size,
// The source ts file.
SourceTsID: segment.TsFile.TsID,
// The cost in ms to extract image.
ExtractImageCost: int32(segment.CostExtractImage.Milliseconds()),
// The OCR text result.
OCRText: segment.OCRText,
// The cost in ms to do OCR.
OCRCost: int32(segment.CostOCR.Milliseconds()),
}}...)
}
res.Count = len(res.Segments)
ohttp.WriteData(ctx, w, r, res)
logger.Tf(ctx, "ocr query callback ok, token=%vB", len(token))
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
ep = "/terraform/v1/ai/ocr/cleanup-queue"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
var token string
if err := ParseBody(ctx, r.Body, &struct {
Token *string `json:"token"`
}{
Token: &token,
}); err != nil {
return errors.Wrapf(err, "parse body")
}
apiSecret := envApiSecret()
if err := Authenticate(ctx, apiSecret, token, r.Header); err != nil {
return errors.Wrapf(err, "authenticate")
}
type Segment struct {
TsID string `json:"tsid"`
SeqNo uint64 `json:"seqno"`
URL string `json:"url"`
Duration float64 `json:"duration"`
Size uint64 `json:"size"`
// The source ts file.
SourceTsID string `json:"stsid"`
// The cost in ms to extract image.
ExtractImageCost int32 `json:"eic"`
// The OCR text result.
OCRText string `json:"ocr"`
// The cost in ms to do OCR.
OCRCost int32 `json:"ocrc"`
// The cost in ms to do callback.
CallbackCost int32 `json:"cbc"`
}
type OCRQueueResponse struct {
Segments []*Segment `json:"segments"`
Count int `json:"count"`
}
res := &OCRQueueResponse{}
segments := v.task.cleanupSegments()
for _, segment := range segments {
res.Segments = append(res.Segments, []*Segment{&Segment{
TsID: segment.ImageFile.TsID,
SeqNo: segment.ImageFile.SeqNo,
URL: segment.ImageFile.File,
Duration: segment.ImageFile.Duration,
Size: segment.ImageFile.Size,
// The source ts file.
SourceTsID: segment.TsFile.TsID,
// The cost in ms to extract image.
ExtractImageCost: int32(segment.CostExtractImage.Milliseconds()),
// The OCR text result.
OCRText: segment.OCRText,
// The cost in ms to do OCR.
OCRCost: int32(segment.CostOCR.Milliseconds()),
// The cost in msg to do callback.
CallbackCost: int32(segment.CostCallback.Milliseconds()),
}}...)
}
res.Count = len(res.Segments)
ohttp.WriteData(ctx, w, r, res)
logger.Tf(ctx, "ocr query cleanup ok, token=%vB", len(token))
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
ep = "/terraform/v1/ai/ocr/image/"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
// Format is /image/:uuid.jpg
filename := r.URL.Path[len("/terraform/v1/ai/ocr/image/"):]
// Format is :uuid.jpg
uuid := filename[:len(filename)-len(path.Ext(filename))]
if len(uuid) == 0 {
return errors.Errorf("invalid uuid %v from %v of %v", uuid, filename, r.URL.Path)
}
imageFilePath := path.Join("ocr", fmt.Sprintf("%v.jpg", uuid))
if _, err := os.Stat(imageFilePath); err != nil {
return errors.Wrapf(err, "no image file %v", imageFilePath)
}
if tsFile, err := os.Open(imageFilePath); err != nil {
return errors.Wrapf(err, "open file %v", imageFilePath)
} else {
defer tsFile.Close()
w.Header().Set("Content-Type", "image/jpeg")
io.Copy(w, tsFile)
}
logger.Tf(ctx, "ocr preview image ok, uuid=%v", uuid)
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
return nil
}
func (v *OCRWorker) Enabled() bool {
return v.task.enabled()
}
func (v *OCRWorker) OnHlsTsMessage(ctx context.Context, msg *SrsOnHlsMessage) error {
select {
case <-ctx.Done():
case v.msgs <- msg:
}
return nil
}
func (v *OCRWorker) OnHlsTsMessageImpl(ctx context.Context, msg *SrsOnHlsMessage) error {
// Ignore if not natch the task config.
if !v.task.match(msg) {
return nil
}
// Copy the ts file to temporary cache dir.
tsid := fmt.Sprintf("%v-org-%v", msg.SeqNo, uuid.NewString())
tsfile := path.Join("ocr", fmt.Sprintf("%v.ts", tsid))
// Always use execFile when params contains user inputs, see https://auth0.com/blog/preventing-command-injection-attacks-in-node-js-apps/
// Note that should never use fs.copyFileSync(file, tsfile, fs.constants.COPYFILE_FICLONE_FORCE) which fails in macOS.
if err := exec.CommandContext(ctx, "cp", "-f", msg.File, tsfile).Run(); err != nil {
return errors.Wrapf(err, "copy file %v to %v", msg.File, tsfile)
}
// Get the file size.
stats, err := os.Stat(msg.File)
if err != nil {
return errors.Wrapf(err, "stat file %v", msg.File)
}
// Create a local ts file object.
tsFile := &TsFile{
TsID: tsid,
URL: msg.URL,
SeqNo: msg.SeqNo,
Duration: msg.Duration,
Size: uint64(stats.Size()),
File: tsfile,
}
// Notify worker asynchronously.
// TODO: FIXME: Should cleanup the temporary file when restart.
go func() {
select {
case <-ctx.Done():
case v.tsfiles <- &SrsOnHlsObject{Msg: msg, TsFile: tsFile}:
}
}()
return nil
}
func (v *OCRWorker) Close() error {
if v.cancel != nil {
v.cancel()
}
v.wg.Wait()
return nil
}
func (v *OCRWorker) Start(ctx context.Context) error {
wg := &v.wg
ctx, cancel := context.WithCancel(ctx)
v.cancel = cancel
ctx = logger.WithContext(ctx)
logger.Tf(ctx, "ocr start a worker")
// Load task from redis and continue to run the task.
if objs, err := rdb.HGetAll(ctx, SRS_OCR_TASK).Result(); err != nil && err != redis.Nil {
return errors.Wrapf(err, "hgetall %v", SRS_OCR_TASK)
} else if len(objs) != 1 {
// Only support one task right now.
if err = rdb.Del(ctx, SRS_OCR_TASK).Err(); err != nil && err != redis.Nil {
return errors.Wrapf(err, "del %v", SRS_OCR_TASK)
}
} else {
for uuid, obj := range objs {
logger.Tf(ctx, "Load task %v object %v", uuid, obj)
if err = json.Unmarshal([]byte(obj), v.task); err != nil {
return errors.Wrapf(err, "unmarshal %v %v", uuid, obj)
}
break
}
}
// Start global ocr task.
wg.Add(1)
go func() {
defer wg.Done()
task := v.task
for ctx.Err() == nil {
var duration time.Duration
if err := task.Run(ctx); err != nil {
logger.Wf(ctx, "ocr: run task %v err %+v", task.String(), err)
duration = 10 * time.Second
} else {
duration = 3 * time.Second
}
select {
case <-ctx.Done():
case <-time.After(duration):
}
}
}()
// Consume all on_hls messages.
wg.Add(1)
go func() {
defer wg.Done()
for ctx.Err() == nil {
select {
case <-ctx.Done():
case msg := <-v.msgs:
if err := v.OnHlsTsMessageImpl(ctx, msg); err != nil {
logger.Wf(ctx, "ocr: handle on hls message %v err %+v", msg.String(), err)
}
}
}
}()
// Consume all ts files by task.
wg.Add(1)
go func() {
defer wg.Done()
task := v.task
for ctx.Err() == nil {
select {
case <-ctx.Done():
case msg := <-v.tsfiles:
if err := task.OnTsSegment(ctx, msg); err != nil {
logger.Wf(ctx, "ocr: task %v on hls ts message %v err %+v", task.String(), msg.String(), err)
}
}
}
}()
// Watch for new stream.
wg.Add(1)
go func() {
defer wg.Done()
task := v.task
for ctx.Err() == nil {
var duration time.Duration
if err := task.WatchNewStream(ctx); err != nil {
logger.Wf(ctx, "ocr: task %v watch new stream err %+v", task.String(), err)
duration = 10 * time.Second
} else {
duration = 200 * time.Millisecond
}
select {
case <-ctx.Done():
case <-time.After(duration):
}
}
}()
// Drive the live queue to OCR.
wg.Add(1)
go func() {
defer wg.Done()
task := v.task
for ctx.Err() == nil {
var duration time.Duration
if err := task.DriveLiveQueue(ctx); err != nil {
logger.Wf(ctx, "ocr: task %v drive live queue err %+v", task.String(), err)
duration = 10 * time.Second
} else {
duration = 200 * time.Millisecond
}
select {
case <-ctx.Done():
case <-time.After(duration):
}
}
}()
// Drive the OCR queue to correct queue.
wg.Add(1)
go func() {
defer wg.Done()
task := v.task
for ctx.Err() == nil {
var duration time.Duration
if err := task.DriveOCRQueue(ctx); err != nil {
logger.Wf(ctx, "ocr: task %v drive ocr queue err %+v", task.String(), err)
duration = 10 * time.Second
} else {
duration = 200 * time.Millisecond
}
select {
case <-ctx.Done():
case <-time.After(duration):
}
}
}()
// Drive the callback queue, notify user's service.
wg.Add(1)
go func() {
defer wg.Done()
task := v.task
for ctx.Err() == nil {
var duration time.Duration
if err := task.DriveCallbackQueue(ctx); err != nil {
logger.Wf(ctx, "ocr: task %v drive callback queue err %+v", task.String(), err)
duration = 10 * time.Second
} else {
duration = 200 * time.Millisecond
}
select {
case <-ctx.Done():
case <-time.After(duration):
}
}
}()
// Drive the cleanup queue, remove old files.
wg.Add(1)
go func() {
defer wg.Done()
task := v.task
for ctx.Err() == nil {
var duration time.Duration
if err := task.DriveCleanupQueue(ctx); err != nil {
logger.Wf(ctx, "ocr: task %v drive cleanup queue err %+v", task.String(), err)
duration = 10 * time.Second
} else {
duration = 200 * time.Millisecond
}
select {
case <-ctx.Done():
case <-time.After(duration):
}
}
}()
return nil
}
type OCRConfig struct {
// Whether ocr all streams.
All bool `json:"all"`
// The AI service provider.
SrsAssistantProvider
// The AI chat configuration.
SrsAssistantChat
}
func NewOCRConfig() *OCRConfig {
v := &OCRConfig{}
v.All = false
v.AIChatEnabled = true
return v
}
func (v OCRConfig) String() string {
return fmt.Sprintf("all=%v, provider=<%v>, chat=<%v>",
v.All, v.SrsAssistantProvider.String(), v.SrsAssistantChat.String(),
)
}
func (v *OCRConfig) Load(ctx context.Context) error {
if b, err := rdb.HGet(ctx, SRS_OCR_CONFIG, "global").Result(); err != nil && err != redis.Nil {
return errors.Wrapf(err, "hget %v global", SRS_OCR_CONFIG)
} else if len(b) > 0 {
if err := json.Unmarshal([]byte(b), v); err != nil {
return errors.Wrapf(err, "unmarshal %v", b)
}
}
return nil
}
func (v *OCRConfig) Save(ctx context.Context) error {
if b, err := json.Marshal(v); err != nil {
return errors.Wrapf(err, "marshal conf %v", v)
} else if err := rdb.HSet(ctx, SRS_OCR_CONFIG, "global", string(b)).Err(); err != nil && err != redis.Nil {
return errors.Wrapf(err, "hset %v global %v", SRS_OCR_CONFIG, string(b))
}
return nil
}
type OCRSegment struct {
// The SRS callback message msg.
Msg *SrsOnHlsMessage `json:"msg,omitempty"`
// The original source TS file.
TsFile *TsFile `json:"tsfile,omitempty"`
// The extracted image file.
ImageFile *TsFile `json:"image,omitempty"`
// The ocr result, by AI service.
OCRText string `json:"ocr,omitempty"`
// The callback video file.
CallbackFile *TsFile `json:"callback,omitempty"`
// The cost to transcode the TS file to image file.
CostExtractImage time.Duration `json:"eic,omitempty"`
// The cost to do OCR, converting speech to text.
CostOCR time.Duration `json:"ocrc,omitempty"`
// The cost to callback the OCR result.
CostCallback time.Duration `json:"olc,omitempty"`
}
func (v OCRSegment) String() string {
var sb strings.Builder
if v.Msg != nil {
sb.WriteString(fmt.Sprintf("msg=%v, ", v.Msg.String()))
}
if v.TsFile != nil {
sb.WriteString(fmt.Sprintf("ts=%v, ", v.TsFile.String()))
}
if v.ImageFile != nil {
sb.WriteString(fmt.Sprintf("image=%v, ", v.ImageFile.String()))
sb.WriteString(fmt.Sprintf("eac=%v, ", v.CostExtractImage))
}
if v.OCRText != "" {
sb.WriteString(fmt.Sprintf("ocr=%v, ", v.OCRText))
sb.WriteString(fmt.Sprintf("ocrc=%v, ", v.CostOCR))
}
if v.CallbackFile != nil {
sb.WriteString(fmt.Sprintf("callback=%v, ", v.CallbackFile.String()))
sb.WriteString(fmt.Sprintf("olc=%v, ", v.CostCallback))
}
return sb.String()
}
func (v *OCRSegment) Dispose() error {
// Remove the original ts file.
if v.TsFile != nil {
if _, err := os.Stat(v.TsFile.File); err == nil {
os.Remove(v.TsFile.File)
}
}
// Remove the extracted image file.
if v.ImageFile != nil {
if _, err := os.Stat(v.ImageFile.File); err == nil {
os.Remove(v.ImageFile.File)
}
}
// Remove the callback video file.
if v.CallbackFile != nil {
if _, err := os.Stat(v.CallbackFile.File); err == nil {
os.Remove(v.CallbackFile.File)
}
}
return nil
}
type OCRQueue struct {
// The ocr segments in the queue.
Segments []*OCRSegment `json:"segments,omitempty"`
// To protect the queue.
lock sync.Mutex
}
func NewOCRQueue() *OCRQueue {
return &OCRQueue{}
}
func (v *OCRQueue) String() string {
return fmt.Sprintf("segments=%v", len(v.Segments))
}
func (v *OCRQueue) count() int {
v.lock.Lock()
defer v.lock.Unlock()
return len(v.Segments)
}
func (v *OCRQueue) enqueue(segment *OCRSegment) {
v.lock.Lock()
defer v.lock.Unlock()
v.Segments = append(v.Segments, segment)
}
func (v *OCRQueue) first() *OCRSegment {
v.lock.Lock()
defer v.lock.Unlock()
if len(v.Segments) == 0 {
return nil
}
return v.Segments[0]
}
func (v *OCRQueue) dequeue(segment *OCRSegment) {
v.lock.Lock()
defer v.lock.Unlock()
for i, s := range v.Segments {
if s == segment {
v.Segments = append(v.Segments[:i], v.Segments[i+1:]...)
return
}
}
}
func (v *OCRQueue) reset(ctx context.Context) error {
var segments []*OCRSegment
func() {
v.lock.Lock()
defer v.lock.Unlock()
segments = v.Segments
v.Segments = nil
}()
for _, segment := range segments {
segment.Dispose()
}
return nil
}
type OCRTask struct {
// The ID for task.
UUID string `json:"uuid,omitempty"`
// The input url.
Input string `json:"input,omitempty"`
// The input stream object, select the active stream.
inputStream *SrsStream
// The chat history, to use as prompt for next chat.
histories []openai.ChatCompletionMessage