-
Notifications
You must be signed in to change notification settings - Fork 96
/
CoreModels.py
5795 lines (5266 loc) · 286 KB
/
CoreModels.py
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
# -*- coding: utf-8 -*-
# @Author : Fandes
# @FileName: test.py
# @Software: PyCharm
# 项目地址:https://github.com/fandesfyf/JamTools
import hashlib
import json
import socket
import gc
import sys
import cv2
import os, re
from Logger import Logger
import numpy as np
Jamtools_logger = Logger(os.path.join(os.path.expanduser('~'), ".jamtools.log"))
sys.stdout = Jamtools_logger
from jampublic import Commen_Thread, OcrimgThread, Transparent_windows, APP_ID, API_KEY, \
SECRECT_KEY, PLATFORM_SYS, mutilocr,gethtml,CONFIG_DICT,get_request_session
from jamWidgets import FramelessEnterSendQTextEdit,EnterSendQTextEdit,ShortcutSettingWidget
import http.client
import random
import shutil
import subprocess
import time
from urllib.parse import quote
from PIL import Image
import qrcode
import requests
from PyQt5.QtCore import QRect, Qt, QThread, pyqtSignal, QStandardPaths, QTimer, QSettings, QFileInfo, \
QUrl, QObject, QSize,pyqtSlot
from PyQt5.QtGui import QPixmap, QPainter, QPen, QIcon, QFont, QImage, QTextCursor, QColor, QDesktopServices, QMovie,\
QBrush
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton, QToolTip, QAction, QTextEdit, QLineEdit, \
QMessageBox, QFileDialog, QMenu, QSystemTrayIcon, QGroupBox, QComboBox, QCheckBox, QSpinBox, QTabWidget, \
QDoubleSpinBox, QLCDNumber, QScrollArea, QWidget, QToolBox, QRadioButton, QTimeEdit, QListWidget, QDialog, \
QProgressBar, QTextBrowser,QListWidgetItem,QVBoxLayout, QHBoxLayout,QStackedWidget,QSizePolicy,QAbstractItemView
from PyQt5.QtNetwork import QLocalSocket, QLocalServer
from qt_material import apply_stylesheet,list_themes
import qt_material
from jamscreenshot import Slabel
# from aip import AipOcr
# from fbs_runtime.application_context.PyQt5 import ApplicationContext
from pynput import keyboard, mouse
from jamcontroller import ActionController, ActionCondition
from WEBFilesTransmitter import WebFilesTransmitter, WebFilesTransmitterBox, apppath
from jamspeak import Speaker
from clientFilesTransmitter import ClientFilesTransmitterGroupbox
from jam_transtalater import Translator
import jamresourse
from pynput.mouse import Controller
from ClipboardManager import ClipboardManager
if PLATFORM_SYS == "win32":
import win32con
import win32api
import ctypes, ctypes.wintypes
try:# win7 don't have SetProcessDpiAwareness
ctypes.windll.shcore.SetProcessDpiAwareness(2)
except Exception as e:
print("SetProcessDpiAwareness error ",e)
import pynput.keyboard._win32
import pynput.mouse._win32
if PLATFORM_SYS == "darwin":
import pynput.keyboard._darwin
import pynput.mouse._darwin
elif PLATFORM_SYS == "linux":
import pynput.keyboard._xorg
import pynput.mouse._xorg
VERSON = "0.14.5B"
class JHotkey(QThread):
ss_signal = pyqtSignal()
ocr_signal = pyqtSignal()
recordchange_signal = pyqtSignal()
record_setarea_signal = pyqtSignal()
listening_change_signal = pyqtSignal()
running_change_signal = pyqtSignal()
showm_signal = pyqtSignal(str)
def __init__(self):
super().__init__()
self.settings = QSettings('Fandes', 'jamtools')
self.hoykey_name,self.hoykey_str = self.get_dicts()
self.hotkeys = dict(zip(self.hoykey_name,self.hoykey_str))
self.stop_flag = False
def get_dicts(self):
if PLATFORM_SYS == "darwin":
ss = self.settings.value('hotkey_ss', "alt<+>Ω", type=str)
ocr = self.settings.value('hotkey_ocr', "alt<+>≈", type=str)
rc = self.settings.value('hotkey_rc', "alt<+>ç", type=str)
rcs = self.settings.value('hotkey_rcs', "ctrl<+>alt<+>ç", type=str)
a1 = self.settings.value('hotkey_a1', "alt<+>¡", type=str)
a2 = self.settings.value('hotkey_a2', "alt<+>™", type=str)
else:
ss = self.settings.value('hotkey_ss', "alt<+>z", type=str)
ocr = self.settings.value('hotkey_ocr', "alt<+>x", type=str)
rc = self.settings.value('hotkey_rc', "alt<+>c", type=str)
rcs = self.settings.value('hotkey_rcs', "ctrl<+>alt<+>c", type=str)
a1 = self.settings.value('hotkey_a1', "alt<+>1", type=str)
a2 = self.settings.value('hotkey_a2', "alt<+>2", type=str)
return ["ss","ocr","rc","rcs","a1","a2"],[ss,ocr,rc,rcs,a1,a2]
def set_hotkeys(self,keys):
names = ["hotkey_ss",'hotkey_ocr','hotkey_rc',"hotkey_rcs",'hotkey_a1','hotkey_a2']
for i,name in enumerate(names):
self.settings.setValue(name,keys[i])
self.hoykey_name,self.hoykey_str = self.get_dicts()
self.hotkeys = dict(zip(self.hoykey_name,self.hoykey_str))
def judge_hotkey(self,keylist):
fault_id = []
available_keys = []
for i,keystr in enumerate(keylist):
if len(keystr) == 0:
keystr = self.hoykey_str[i]
print("使用默认快捷键",i,keystr)
else:
keystr = keystr.replace("+","<+>")
available_keys.append(keystr)
if PLATFORM_SYS == "win32":
for i,keystr in enumerate(available_keys):
if self.win32_registerhotkey(100+i,keystr):
print(keystr,"success")
else:
fault_id.append(i)
print(keystr,"快捷键设置失败")
self.win32hotkey_unregister()
else:
fault_id = self.pynputhotkey_start(check = True)
# fault_id = self.pynputhotkey_start(check = True)
if len(fault_id) == 0:
self.set_hotkeys(available_keys)
return fault_id
def run(self):
if PLATFORM_SYS == "win32":
self.win32hotkey()
else:
self.pynputhotkey_start()
# self.pynputhotkey_start()
def stop(self):
if PLATFORM_SYS == "win32":
self.win32hotkey_unregister()
else:
self.pynputhotkey_stop()
# self.pynputhotkey_stop()
self.terminate()
def generate_hotkey_str(self,hotkey_ss):
mod = ""
ss_vk = None
hotkey_ss = hotkey_ss.split("<+>")
for i,k in enumerate(hotkey_ss):
if i == len(hotkey_ss)-1:
ss_vk = k
else:
mod = mod+"<{}>+".format(k)
mod = mod.rstrip("+")
return mod,ss_vk
def pynputhotkey_start(self,check=False):
try:
releaser = keyboard.Controller()
def ssf():
self.ss_signal.emit()
releaser.release(self.generate_hotkey_str(self.hotkeys["ss"])[-1])
def ocrf():
self.ocr_signal.emit()
releaser.release(self.generate_hotkey_str(self.hotkeys["ocr"])[-1])
def srf():
self.recordchange_signal.emit()
releaser.release(self.generate_hotkey_str(self.hotkeys["rc"])[-1])
def a1f():
self.listening_change_signal.emit()
releaser.release(self.generate_hotkey_str(self.hotkeys["a1"])[-1])
def a2f():
self.running_change_signal.emit()
releaser.release(self.generate_hotkey_str(self.hotkeys["a2"])[-1])
def sr_setarea():
print("record_setarea_signal")
self.record_setarea_signal.emit()
releaser.release(self.generate_hotkey_str(self.hotkeys["rcs"])[-1])
dd ={
"+".join(self.generate_hotkey_str(self.hotkeys["ss"])): ssf,
"+".join(self.generate_hotkey_str(self.hotkeys["ocr"])): ocrf,
"+".join(self.generate_hotkey_str(self.hotkeys["rc"])): srf,
"+".join(self.generate_hotkey_str(self.hotkeys["a1"])): a1f,
"+".join(self.generate_hotkey_str(self.hotkeys["a2"])): a2f,
"+".join(self.generate_hotkey_str(self.hotkeys["rcs"])): sr_setarea,
}
self.pynputhotkey = keyboard.GlobalHotKeys(
dd
)
self.pynputhotkey.start()
print("hotkey start")
except Exception as e:
print("设置快捷键错误",e)
if check:
return list(range(6))
else:
if check:
return []
while not self.stop_flag:
time.sleep(0.1)
# self.pynputhotkey.wait()
# self.pynputhotkey.join()
def pynputhotkey_stop(self):
print("pynputhotkey_stopping")
self.stop_flag=False
self.pynputhotkey.stop()
self.pynputhotkey.wait()
self.pynputhotkey.join()
print("pynputhotkey_stoped")
def win32_registerhotkey(self,callbackid,keys):
key_names = {
'f1': 0x70, 'f2': 0x71, 'f3': 0x72, 'f4': 0x73, 'f5': 0x74, 'f6': 0x75, 'f7': 0x76, 'f8': 0x77, 'f9': 0x78, 'f10': 0x79, 'f11': 0x7A, 'f12': 0x7B, '0': 0x30, '1': 0x31, '2': 0x32, '3': 0x33, '4': 0x34, '5': 0x35, '6': 0x36, '7': 0x37, '8': 0x38, '9': 0x39, 'num0': 0x60, 'num1': 0x61, 'num2': 0x62, 'num3': 0x63, 'num4': 0x64, 'num5': 0x65, 'num6': 0x66, 'num7': 0x67, 'num8': 0x68, 'num9': 0x69, 'a': 0x41, 'b': 0x42, 'c': 0x43, 'd': 0x44, 'e': 0x45, 'f': 0x46, 'g': 0x47, 'h': 0x48, 'i': 0x49, 'j': 0x4A, 'k': 0x4B, 'l': 0x4C, 'm': 0x4D, 'n': 0x4E, 'o': 0x4F, 'p': 0x50, 'q': 0x51, 'r': 0x52, 's': 0x53, 't': 0x54, 'u': 0x55, 'v': 0x56, 'w': 0x57, 'x': 0x58, 'y': 0x59, 'z': 0x5A, 'enter': 0x0D, 'space': 0x20, 'tab': 0x09, 'delete': 0x2E, 'up': 0x26, 'down': 0x28, 'left': 0x25, 'right': 0x27, 'pageup': 0x21, 'pagedown': 0x22, 'home': 0x24, 'end': 0x23, 'escape': 0x1B, 'semicolon': 0xBA, 'plus': 0xBB, 'comma': 0xBC, 'minus': 0xBD, 'period': 0xBE, 'slash': 0xBF, 'backslash': 0xDC,
"alt" : 1,
"ctrl" : 2,"shift" : 4,"win" : 8}
try:
keys=keys.lower()
hotkey_ss = keys.split("<+>")
ss_vk = 0
mod = 0
for i,k in enumerate(hotkey_ss):
if k not in key_names:
raise Exception('无法识别快捷键:{}'.format(k))
if i == len(hotkey_ss)-1:
ss_vk = key_names[k]
else:
mod = mod|key_names[k]
if not self.user32.RegisterHotKey(None, callbackid,mod, ss_vk):
self.showm_signal.emit('无法注册快捷键!{}'.format(keys))
raise Exception('无法注册快捷键!{}'.format(keys))
except Exception as e:
print(e)
return False
return True
def win32hotkey_unregister_id(self,id):
self.user32.UnregisterHotKey(None, id)
def win32hotkey_unregister(self):
print("win32hotkey_unregister")
for i in range(100,106):
self.user32.UnregisterHotKey(None, i)
print("win32hotkey_unregistered")
def win32hotkey(self):
self.user32 = ctypes.windll.user32
self.win32_registerhotkey(100,self.hotkeys["ss"])
self.win32_registerhotkey(101,self.hotkeys["ocr"])
self.win32_registerhotkey(102,self.hotkeys["rc"])
self.win32_registerhotkey(103,self.hotkeys["a1"])
self.win32_registerhotkey(104,self.hotkeys["a2"])
self.win32_registerhotkey(105,self.hotkeys["rcs"])
# if not self.user32.RegisterHotKey(None, 100, win32con.MOD_ALT, 0x5A):
# print('RuntimeError')
# self.showm_signal.emit('无法注册截屏快捷键!Alt+z')
# if not self.user32.RegisterHotKey(None, 101, win32con.MOD_ALT, 0x58):
# print('RuntimeError')
# self.showm_signal.emit('无法注册文字识别快捷键!Alt+x')
# if not self.user32.RegisterHotKey(None, 102, win32con.MOD_ALT, 0x43):
# print('RuntimeError')
# self.showm_signal.emit('无法注册录屏快捷键!Alt+c')
# if not self.user32.RegisterHotKey(None, 103, win32con.MOD_ALT, 0x31):
# print('RuntimeError')
# self.showm_signal.emit('无法注册动作录制快捷键!Alt+1')
# if not self.user32.RegisterHotKey(None, 104, win32con.MOD_ALT, 0x32):
# print('RuntimeError')
# self.showm_signal.emit('无法注册动作播放快捷键!Alt+2')
try:
msg = ctypes.wintypes.MSG()
while self.user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0: # GetMessageA 堵塞
print(msg.message, msg.wParam)
if msg.message == win32con.WM_HOTKEY:
id = msg.wParam
if id == 100:
print('alt+z')
self.ss_signal.emit()
elif id == 101:
print('alt+x')
self.ocr_signal.emit()
elif id == 102:
print('alt+c')
self.recordchange_signal.emit()
elif id == 103:
print('Alt+1')
self.listening_change_signal.emit()
elif id == 104:
print('Alt+2')
self.running_change_signal.emit()
elif id == 105:
print("record_setarea_signal")
self.record_setarea_signal.emit()
self.user32.TranslateMessage(ctypes.byref(msg))
self.user32.DispatchMessageA(ctypes.byref(msg))
finally:
# pass
print('end hotkey')
self.user32.UnregisterHotKey(None, 1)
class Recordingthescreen(QObject):
showm_signal = pyqtSignal(str)
counter_display_signal = pyqtSignal(str)
def __init__(self, parent):
super(Recordingthescreen, self).__init__()
self.parent = parent
self.init_arearecord_thread = Commen_Thread(self.init_arearecord)
self.init_arearecord_thread.start()
self.timer = QTimer()
self.timer.timeout.connect(self.count)
self.showrect = Transparent_windows()
self.reset_area()
def reset_area(self):
self.x = 0
self.y = 0
self.using_area = False
self.w = self.maxw = QApplication.desktop().width() // 2 * 2
self.h = self.maxh = QApplication.desktop().height() // 2 * 2
def init_arearecord(self):
self.recording = False
self.record = None
self.time = None
self.t_fps = 30
self.gif = False
self.waiting = False
self.stop_wait = False
self.name = '_'
self.file_format = 'mp4'
self.mouse = 1
self.fps = 30
self.codec = 'libx264 '
self.preset = ' ultrafast '
self.delay = 0
self.Nondestructive = ' -qp 5 '
self.scale = 1
self.c = 0
display_evn = ":0"
if sys.platform == "linux":
display_evn = os.environ['DISPLAY']
if "." in display_evn:
display_evn = display_evn.split(".")[0]
self.display = display_evn if ":" in display_evn else ":0"
if not os.path.exists(QStandardPaths.writableLocation(
QStandardPaths.MoviesLocation) + "/Jam_screenrecord"):
os.mkdir(QStandardPaths.writableLocation(
QStandardPaths.MoviesLocation) + "/Jam_screenrecord")
def area_recording(self):
screen_number = 0
if not self.using_area:
if QApplication.desktop().screenCount()>1:
screen=self.search_in_which_screen()
else:
screen=QApplication.primaryScreen()
ssize = screen.geometry()
self.x = ssize.x() // 2*2
self.y = ssize.y() // 2*2
self.w = self.maxw = ssize.width() // 2 * 2
self.h = self.maxh = ssize.height() // 2 * 2
desktop = QApplication.desktop()
screen_number = desktop.screenNumber(desktop.cursor().pos())
print("screen_number",screen_number)
self.codec = 'libx264 '
profile = ' high444 -level 5.1 '
try:
self.mouse = int(self.parent.mouse_rec.isChecked())
if self.parent.hide_rec.isChecked():
self.parent.hide()
self.scale = self.parent.scale.value()
self.file_format = self.parent.file_format.currentText()
au_divice = self.parent.soundsourse.currentText()
vi_divice = self.parent.videosourse.currentText()
if self.gif and self.file_format != 'gif':
self.gif = False
self.parent.comboBox_2.setValue(self.t_fps)
self.fps = self.parent.comboBox_2.value()
self.preset = self.parent.preset.currentText()
qp = self.parent.qp_rec.value()
if qp == -1:
self.Nondestructive = ' '
else:
self.Nondestructive = ' -qp {0} '.format(qp)
self.delay = self.parent.delay_t.value()
if self.parent.sp_rec.isChecked():
profile = ' baseline -level 3.0 '
if self.parent.hardware_rec.isChecked() and PLATFORM_SYS == "win32":
profile = ' high '
self.codec = ' h264_nvenc '
except:
self.init_arearecord()
profile = ' high444 -level 5.1 '
au_divice = '无'
vi_divice = '抓屏'
if len(self.parent.audio_divice) != 0:
au_divice = self.parent.audio_divice[0]
print(sys.exc_info(), 273)
self.recording = True
print(self.x, self.y, self.w, self.h)
if not (
self.w >= self.maxw and self.h >= self.maxh) and "camera" not in vi_divice.lower() and "摄像头" not in vi_divice.lower():
self.showrect.setGeometry(self.x, self.y, self.w, self.h)
self.showrect.show()
if self.delay != 0:
print('delay')
self.parent.pushButton.setStyleSheet("QPushButton{background-color:rgb(200,180,10)}")
self.waiting = True
self.wait_()
self.waiting = False
if self.stop_wait:
self.stop_wait = False
print('stopwait')
self.recording = False
try:
self.parent.pushButton.setStyleSheet("QPushButton{color:rgb(200,100,100)}"
"QPushButton:hover{background-color:rgb(200,10,10)}"
"QPushButton:!hover{background-color:rgb(200,200,200)}"
"QPushButton{background-color:rgb(239,239,239)}"
"QPushButton{border:6px solid rgb(50, 50, 50)}"
"QPushButton{border-radius:60px}")
except:
print(sys.exc_info())
self.showm_signal.emit('录屏等待中止!')
self.showrect.hide()
return
try:
self.parent.pushButton.setStyleSheet("QPushButton{background-color:rgb(200,10,10)}"
"QPushButton{color:rgb(200,100,100)}"
"QPushButton{border:6px solid rgb(50, 50, 50)}"
)
except:
print(sys.exc_info(), 308)
self.c = 0
self.counter_display_signal.emit('00:00')
self.timer.start(1000)
f_path = '"' + ffmpeg_path + '/ffmpeg" '
self.name = str(time.strftime("%Y-%m-%d_%H.%M.%S", time.localtime()))
w = str(int(self.w * self.scale // 2) * 2)
area = ' -draw_mouse {} -offset_x {} -offset_y {} -video_size {}x{} '.format(self.mouse,
self.x,
self.y,
self.w,
self.h)
audio = ' '
video = ' -thread_queue_size 16 -f gdigrab -rtbufsize 500M ' + area + ' -i desktop '
if self.file_format == 'gif':
if self.parent.comboBox_2.value() == 30:
self.fps = 12
self.gif = True
f = self.parent.comboBox_2.value()
if f != 30:
self.t_fps = f
self.parent.comboBox_2.setValue(12)
print('rearea')
vf = ' -vf scale=' + w + ':-2 '
if vi_divice == '抓屏':
if PLATFORM_SYS == "win32":
area = ' -draw_mouse {} -offset_x {} -offset_y {} -video_size {}x{} '.format(
self.mouse,
self.x,
self.y,
self.w,
self.h)
video = ' -thread_queue_size 16 -f gdigrab -rtbufsize 500M ' + area + ' -i desktop '
else:
video = " -video_size {}x{} -f x11grab -draw_mouse {} -i {}.0+{},{} ".format(self.w, self.h,
self.mouse, self.display, self.x,
self.y)
else:
vf = ' -vf crop={}:{}:{}:{} '.format(self.w, self.h, self.x, self.y)
if PLATFORM_SYS == "win32":
video = ' -thread_queue_size 16 -f dshow -rtbufsize 500M -i video="{}" '.format(vi_divice)
elif PLATFORM_SYS == "darwin":
video = ' -thread_queue_size 16 -f avfoundation -rtbufsize 500M -i {}: '.format(
self.parent.video_divice.index(vi_divice))
self.Nondestructive = ' '
out_file = self.Nondestructive + vf + ' -r {} -profile:v '.format(
self.fps) + profile + ' -pix_fmt yuv420p ' \
'-preset:v ultrafast -vcodec libx264 ' + \
' "' + temp_path + '/j_temp/temp_video.mp4"'
elif self.file_format == 'mp3': # 音频
video = ' '
if au_divice != '无':
adv = au_divice
else:
adv = self.parent.audio_divice[0]
if PLATFORM_SYS == "win32":
audio += ' -thread_queue_size 16 -f dshow -rtbufsize 50M -i audio="{0}" '.format(adv)
elif PLATFORM_SYS == "darwin":
audio += ' -thread_queue_size 16 -f avfoundation -rtbufsize 50M -i :{} '.format(
self.parent.audio_divice.index(adv))
out_file = ' -preset:a ' + self.preset + ' ' + QStandardPaths.writableLocation(
QStandardPaths.MoviesLocation) + "/Jam_screenrecord/" + self.name + '.mp3'
else: # 视频
try:
if au_divice != '无':
adv = au_divice
if PLATFORM_SYS == "win32":
audio += ' -thread_queue_size 16 -f dshow -rtbufsize 50M -i audio="{0}" '.format(adv)
# elif PLATFORM_SYS == "darwin":
# audio += ' -thread_queue_size 16 -f avfoundation -rtbufsize 50M -i :{} '.format(
# self.parent.audio_divice.index(adv))
else:
adv = 0
video = " "
except:
print(sys.exc_info(), 408)
vf = ' -vf scale=' + w + ':-2 '
if vi_divice == '抓屏':
if PLATFORM_SYS == "win32":
video = ' -thread_queue_size 16 -f gdigrab -rtbufsize 500M ' + area + ' -i desktop '
else:
audio = " " # linux 暂不支持录音
video = " -video_size {}x{} -f x11grab -draw_mouse {} -i {}.0+{},{} ".format(self.w, self.h,
self.mouse, self.display, self.x,
self.y)
else:
if "camera" in vi_divice.lower() or "摄像头" in vi_divice.lower(): # 摄像头
vf = ' '
else:
vf = ' -vf crop={}:{}:{}:{} '.format(self.w, self.h, self.x, self.y)
if PLATFORM_SYS == "win32":
video = ' -thread_queue_size 16 -f dshow -rtbufsize 500M -i video="{}" '.format(vi_divice)
elif PLATFORM_SYS == "darwin":
video = ' -thread_queue_size 16 -f avfoundation -rtbufsize 500M -i {}:{} '.format(
self.parent.video_divice.index(vi_divice),
self.parent.audio_divice.index(adv) if au_divice != '无' else "")
self.Nondestructive = ' '
# -vf crop=1920:500:500:0
out_file = self.Nondestructive + vf + ' -r {} -profile:v '.format(
self.fps) + profile + ' -pix_fmt yuv420p ' \
'-preset:v ' + self.preset + \
' -preset:a ' + self.preset + ' -vcodec ' + \
self.codec + ' ' + QStandardPaths.writableLocation(
QStandardPaths.MoviesLocation) + "/Jam_screenrecord/" + self.name + '.' + self.file_format
self.record = subprocess.Popen(
f_path + video
+ audio
+ out_file
+ ' -y',
shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
print(f_path + video
+ audio
+ out_file
+ ' -y')
def search_in_which_screen(self):
mousepos=Controller().position
screens = QApplication.screens()
targetscreen = QApplication.primaryScreen()
for i in screens:
rect=i.geometry().getRect()
if mousepos[0]in range(rect[0],rect[0]+rect[2]) and mousepos[1]in range(rect[1],rect[1]+rect[3]):
targetscreen = i
break
return targetscreen
# -framerate 5 -draw_mouse 1 -show_region 1 显示截取区域 -i title={窗口名称} 用-framerate在macos下报错 用-r代替
def recordchange(self):
if self.waiting:
self.stop_wait = True
self.recording_trayicon.setVisible(False)
elif self.recording:
self.recording_trayicon.setVisible(False)
if not QSettings('Fandes', 'jamtools').value("S_SIMPLE_MODE", False, bool):
self.parent.show()
self.stop_recording()
self.showrect.hide()
else:
self.recording_trayicon = Recording_trayicon()
self.recording_trayicon.show()
self.area_recording()
def wait_(self):
# self.parent.pushButton.setCheckable(False)
# self.delay += 1
while self.delay > 0 and not self.stop_wait:
time_text = '%02d:%02d' % (int((self.delay + 0.9) // 60), int((self.delay + 0.9) % 60))
self.counter_display_signal.emit(time_text)
QApplication.processEvents()
time.sleep(0.1)
# print(self.delay)
self.delay -= 0.1
self.parent.delay_t.setValue(self.delay)
def count(self):
self.c += 1
time_text = '%02d:%02d' % (self.c // 60, self.c % 60)
self.counter_display_signal.emit(time_text)
def stop_recording(self):
self.timer.stop()
self.recording = False
self.stop_record()
try:
self.parent.pushButton.setStyleSheet("QPushButton{color:rgb(200,100,100)}"
"QPushButton:hover{background-color:rgb(200,10,10)}"
"QPushButton:!hover{background-color:rgb(200,200,200)}"
"QPushButton{background-color:rgb(239,239,239)}"
"QPushButton{border:6px solid rgb(50, 50, 50)}"
"QPushButton{border-radius:60px}")
except:
pass
if self.file_format != 'gif':
self.showm_signal.emit("录屏结束,文件保存于:视频/Jam_screenrecord/" + self.name + '文件夹中\n点击此处可打开')
self.parent.trayicon.recorded_open = True
self.time = time.time()
if not QSettings('Fandes', 'jamtools').value("S_SIMPLE_MODE", False, bool):
self.parent.statusBar().showMessage(
"录屏结束,文件保存于:视频/Jam_screenrecord/" + self.name + '.' + self.file_format)
else:
self.showm_signal.emit('录屏结束,正在生成gif文件,请耐心等待...')
vds = [str(temp_path + '/j_temp/temp_video.mp4')]
self.Tr = Commen_Thread(transformater.t_video, vds, True)
self.Tr.start()
QApplication.processEvents()
# transformater.t_video(vds, recording=True)
def stop_record(self):
self.record.stdin.write('q'.encode("GBK"))
self.record.communicate()
self.record.kill()
# *'XVID'MPEG-4编码 *'mp4v' *'PIMI' MPEG-1编码 *'I420'(无损压缩avi
def Tulin(text):
print("start chat")
if len(text) == 0:
text = "空文本"
info = text.encode('utf-8')
url = 'https://api.ownthink.com/bot'
data = {u"appid": jamtools.botappid, "spoken": info, "userid": jamtools.userid}
try:
response = requests.get(url, data)
print(response.text)
res = response.json()
s = res['data']['info']['text']
except:
print('聊天出错', sys.exc_info())
s = "聊天出错!请确保网络畅通!"
return s
class Recording_trayicon(QSystemTrayIcon):
def __init__(self, parent=None):
super(Recording_trayicon, self).__init__(parent)
self.activated.connect(self.iconClied)
self.setToolTip('正在录屏,点击此处结束!')
self.setIcon(QIcon(":/recording.png"))
def iconClied(self, e):
print('clicked')
jamtools.recorder.recordchange()
# print('change')
class TrayIcon(QSystemTrayIcon): # 系统托盘
def __init__(self, parent=None):
super(TrayIcon, self).__init__(parent)
self.parent = parent
self.showMenu()
self.init_trayicon_thread = Commen_Thread(self.init_trayicon)
self.init_trayicon_thread.start()
self.show()
def init_trayicon(self):
self.recorded_open = False
self.tran_open = False
self.small_windows = []
self.open_path = QStandardPaths.writableLocation(
QStandardPaths.PicturesLocation)
self.getscreen.triggered.connect(self.parent.screenshot_slot)
self.recordscreen.triggered.connect(self.connect_record_fun)
self.setarea.triggered.connect(self.parent.set_area)
self.Tray_tra.triggered.connect(self.BaiduTRA)
self.quitAction.triggered.connect(self.jquit)
self.OCR.triggered.connect(self.parent.BaiduOCR)
self.chatbot.triggered.connect(self.chat)
self.mulocr.triggered.connect(self.parent.multiocr)
self.changesimple.setCheckable(True)
self.changesimple.triggered.connect(self.parent.changesimple)
self.addsimplewin.triggered.connect(self.add_simple_window)
def connect_record_fun(self):
self.parent.recorder.recordchange()
def showMenu(self):
"设计托盘的菜单,这里实现了一个二级菜单"
self.menu = QMenu()
self.menu1 = QMenu()
self.menu2 = QMenu()
self.getscreen = QAction("酱截屏", self)
self.recordscreen = QAction("录屏", self)
self.setarea = QAction("设定区域", self)
self.Tray_tra = QAction("酱翻译", self)
# self.control = QAction("酱控制", self)
self.quitAction = QAction("退出", self)
# self.Bdcla = QAction("图像主体识别", self)
self.screenrecord = QAction("酱录屏", self)
# self.screenrecord.triggered.connect(self.parent.recordscreen)
self.OCR = QAction("截屏文字识别", self)
self.chatbot = QAction("酱聊天", self)
self.mulocr = QAction("批量文字提取", self)
self.changesimple = QAction("小窗模式", self)
self.addsimplewin = QAction("添加小窗", self)
self.menu1.addAction(self.OCR)
self.menu1.addAction(self.mulocr)
# self.menu1.addAction(self.Bdcla)
self.menu.addMenu(self.menu1)
self.menu2.addAction(self.recordscreen)
self.menu2.addAction(self.setarea)
self.menu.addMenu(self.menu2)
self.menu.addAction(self.chatbot)
self.menu.addAction(self.Tray_tra)
self.menu.addAction(self.getscreen)
self.menu.addAction(self.changesimple)
self.menu.addAction(self.addsimplewin)
self.menu.addAction(self.quitAction)
self.menu1.setTitle("酱识图")
self.menu2.setTitle("酱录屏")
self.setContextMenu(self.menu)
self.activated.connect(self.iconClied)
# # 把鼠标点击图标的信号和槽连接
self.messageClicked.connect(self.open_file)
# 把鼠标点击弹出消息的信号和槽连接xccxxzcx
self.setIcon(QIcon(":/ico.png"))
self.icon = self.MessageIcon()
# 设置图标
def add_simple_window(self):
simplemodebox = FramelessEnterSendQTextEdit(enter_tra=True, autoresetid=len(self.small_windows) + 1)
simplemodebox.show()
simplemodebox.del_myself_signal.connect(self.small_windows.pop)
self.small_windows.append(simplemodebox)
def iconClied(self, e):
"鼠标点击icon传递的信号会带有一个整形的值,1是表示单击右键,2是双击,3是单击左键,4是用鼠标中键点击"
if e == 3:
self.parent.changesimple()
def open_file(self):
now = time.time()
if self.tran_open and transformater.open_path is not None and (now - transformater.time) < 7:
# print(transformater.time - now)
self.tran_open = False
p = transformater.open_path
QDesktopServices.openUrl(QUrl.fromLocalFile(p))
transformater.open_path = None
if self.recorded_open and (now - self.parent.recorder.time) < 7:
self.recorded_open = False
record_name = QStandardPaths.writableLocation(
QStandardPaths.MoviesLocation) + "/Jam_screenrecord/" + self.parent.recorder.name + '.' + self.parent.recorder.file_format
QDesktopServices.openUrl(QUrl.fromLocalFile(record_name))
def BaiduTRA(self):
if QSettings('Fandes', 'jamtools').value("S_SIMPLE_MODE", False, bool):
self.parent.simplemodebox.show()
else:
self.parent.show()
self.parent.setup_ui_translater()
def chat(self):
if QSettings('Fandes', 'jamtools').value("S_SIMPLE_MODE", False, bool):
QSettings('Fandes', 'jamtools').setValue("S_SIMPLE_MODE", False)
self.parent.show()
self.parent.setup_ui_Tulinchat()
def JP(self):
self.showMessage("图像数据已复制到剪切板", "可在聊天界面或画板粘贴", self.NoIcon, )
def showM(self, message):
if self.parent.settings.value('close_notice', False, type=bool):
return
self.showMessage("JamTools", message, self.icon)
def jquit(self):
"保险起见,为了完整的退出"
self.parent.close_clean()
class StraThread(QThread): # 右键画屏翻译线程
signal = pyqtSignal(float, str, str)
def __init__(self, w):
super(QThread, self).__init__()
self.w = w
self.signal.connect(jamtools.word_extraction)
self.textresult = ""
self.traresult = ""
def run(self):
self.signal.emit(self.w, '正在识别...', '正在翻译...')
with open("j_temp/sdf.png", 'rb') as i:
img_bytes = i.read()
np_array = np.frombuffer(img_bytes, np.uint8)
img = cv2.imdecode(np_array, cv2.IMREAD_COLOR)
text0 = ''
self.textresult = ""
try:
self.ocrthread = OcrimgThread(img)
self.ocrthread.start()
self.ocrthread.wait()
self.textresult = self.ocrthread.ocr_result
if len(self.textresult):
text0 = self.textresult
else:
raise Exception("识别出错!")
except Exception as e:
print("Unexpected error:", sys.exc_info()[0],e)
self.signal.emit(self.w, 'Unexpected error...', str(e))
return
else:
self.signal.emit(self.w, text0, '正在翻译...')
try:
text1 = ''
self.traresult = ""
n = 0
for i in text0:
if self.is_alphabet(i):
n += 1
if n / len(text0) > 0.4:
print("is en")
fr = "英语"
to = "中文"
else:
fr = "中文"
to = "英语"
self.translator = Translator()
self.translator.translate(text0, fr, to)
self.translator.wait()
if self.translator.tra_result:
self.traresult = self.translator.tra_result
else:
raise Exception("翻译出错")
except Exception as e:
print(e)
text1 = str(e)
else:
text1 = self.traresult
self.signal.emit(self.w, text0, text1)
def is_alphabet(self, uchar):
"""判断一个unicode是否是英文字母"""
if (u'\u0041' <= uchar <= u'\u005a') or (u'\u0061' <= uchar <= u'\u007a'):
return True
else:
return False
class Draw_grab_width(QLabel):
# 划屏提字设置界面
def __init__(self, parent):
super(Draw_grab_width, self).__init__(parent)
self.h = 18
self.painter = QPainter(self)
def paintEvent(self, event):
self.painter.setPen(QPen(Qt.green, 1, Qt.SolidLine))
self.painter.drawLine(0, 0, self.width(), 0)
self.painter.drawLine(0, self.h, self.width(), self.h)
self.painter.setPen(QPen(Qt.red, 1, Qt.SolidLine))
self.painter.drawLine(self.width() / 2, 0, self.width() / 2, self.h)
self.painter.drawLine(0, self.h / 2, self.width(), self.h / 2)
self.painter.end()
super().paintEvent(event)
class Small_Ocr(QLabel):
def __init__(self):
super().__init__()
self.small_show = QTextEdit(self)
self.smalltra = QTextEdit(self)
self.search_botton = QPushButton('', self)
self.close_botton=QPushButton('X',self)
self.pix = QPixmap()
self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.SplashScreen)
self.setAlignment(Qt.AlignTop)
self.init_small_ocr_thread = Commen_Thread(self.init_small_ocr)
self.init_small_ocr_thread.start()
self.h = QSettings('Fandes', 'jamtools').value('grab_height', 28)
self.sx = self.sy = self.ex = self.ey = 0
self.moving =False
self.setMouseTracking(True)
self.autoclose =True
def init_small_ocr(self):
time.sleep(1)
self.search_botton.resize(28, 28)
self.close_botton.resize(28, 28)
self.small_show.setPlaceholderText('文字框...')
self.smalltra.setPlaceholderText('翻译框...')
self.setToolTip('显示不全可向下滚动...')
self.search_botton.clicked.connect(self.baidusearch)
self.search_botton.setIcon(QIcon(":/search.png"))
self.search_botton.setToolTip('跳转百度搜索')
self.close_botton.clicked.connect(self.clearandreset)
self.close_botton.setToolTip("关闭这个贴纸")
self.setWindowOpacity(0.9)
# self.setStyleSheet("QPushButton{color:black;background-color:rgb(239,239,239);padding:1px 4px;}"
# "QPushButton:hover{color:green;background-color:rgb(200,200,100);}"
# """QTextEdit{border:1px solid gray;
# width:300px;
# border-radius:5px;
# padding:2px 4px;
# background-color:rgb(250,250,250);}"""
# "QScrollBar{background-color:rgb(200,100,100);width: 4px;}")
# self.close_botton.setStyleSheet("QPushButton{color:white;background-color:rgb(200,50,50);padding:1px 4px;}"
# "QPushButton:hover{color:green;background-color:rgb(200,200,100);}")
def baidusearch(self, a=1):
url = """https://www.baidu.com/s?wd={0}&rsv_spt=1&rsv_iqid=0xe12177a6000c90b8&issp=1&f=8&rsv_
bp=1&rsv_idx=2&ie=utf-8&tn=94819464_hao_pg&rsv_enter=1&rsv_dl=tb&rsv_sug3=4&rsv_sug1=3
&rsv_sug7=101&rsv_sug2=0&inputT=1398&rsv_sug4=2340""".format(self.small_show.toPlainText())
QDesktopServices.openUrl(QUrl(url))
def show_extrat_res(self, w, text=None, text1=None):
self.autoclose = True
self.close_botton.hide()
self.small_show.clear()
self.smalltra.clear()
self.smalltra.hide()
grabheight = self.h
self.setPixmap(self.pix)
self.small_show.setText(text)
self.smalltra.setText(text1)
self.adjustSize(w)
self.move(self.sx, self.sy)
font = QFont('黑体' if PLATFORM_SYS == "win32" else "", )
self.small_show.move(0, grabheight)
self.smalltra.move(0, self.small_show.y() + self.small_show.height())
self.search_botton.move(w, 0)
# font.setBold(True)
self.small_show.setFont(font)
self.smalltra.setFont(font)
if text1 is not None:
self.smalltra.show()
self.show()
self.small_show.show()
self.search_botton.show()
QApplication.processEvents()
def adjustSize(self, w) -> None:
td = self.smalltra.document()
td.adjustSize()
sd = self.small_show.document()
sd.adjustSize()
show_width=trawidth = td.size().width()
traheight = td.size().height() + 5
show_height = sd.size().height() + 5
self.small_show.resize(w, show_height)
self.smalltra.resize(w, traheight)
self.resize(w + 28, self.h + traheight + show_height)
self.small_show.setDocument(sd)
self.smalltra.setDocument(td)
# super(Small_Ocr, self).adjustSize()