-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpysharex.py
More file actions
9928 lines (8742 loc) · 429 KB
/
pysharex.py
File metadata and controls
9928 lines (8742 loc) · 429 KB
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
#!/usr/bin/env python3
"""
PyshareX - Cross-platform screen capture and recording tool
Inspired by ShareX, built with Python and PySide6
"""
import sys
import os
import json
import time
import threading
import subprocess
import tempfile
import platform
import math
import struct
import wave as wv
import io
from pathlib import Path
from datetime import datetime
import urllib.request # Potrzebne do otwierania z sieci
from PySide6.QtWidgets import (
QAbstractSpinBox, QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QLabel, QTableWidget, QTableWidgetItem, QHeaderView,
QSystemTrayIcon, QMenu, QFileDialog, QDialog, QLineEdit,
QComboBox, QCheckBox, QGroupBox, QScrollArea, QFrame,
QMessageBox, QListWidget, QListWidgetItem,
QDialogButtonBox, QSpinBox, QTabWidget, QRadioButton,
QTextEdit, QSizePolicy, QStackedWidget, QColorDialog, QInputDialog,
QGraphicsScene, QGraphicsView, QGraphicsItem, QGraphicsRectItem,
QGraphicsEllipseItem, QGraphicsLineItem, QGraphicsPathItem, QGraphicsTextItem
)
from PySide6.QtCore import (
QPointF, Qt, QThread, Signal, QTimer, QSize, QRect, QPoint,
QStandardPaths, QElapsedTimer, QLineF, QRectF, QSizeF
)
from PySide6.QtGui import (
QIcon, QKeySequence, QAction, QMouseEvent, QPixmap, QPainter, QColor,
QFont, QPen, QBrush, QCursor, QPainterPath, QImage, QPainterPathStroker,
QFontMetricsF
)
from PySide6.QtSvg import QSvgRenderer
from PySide6.QtGui import QShortcut
try:
from PIL import Image
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
try:
import mss
MSS_AVAILABLE = True
except ImportError:
MSS_AVAILABLE = False
try:
from pynput import keyboard as _pynput_kb
PYNPUT_AVAILABLE = True
except ImportError:
PYNPUT_AVAILABLE = False
try:
import cv2
import numpy as np
CV2_AVAILABLE = True
except ImportError:
CV2_AVAILABLE = False
try:
import easyocr as _easyocr
EASYOCR_AVAILABLE = True
except ImportError:
EASYOCR_AVAILABLE = False
# Must be set before paddleocr/paddlepaddle is imported — disables OneDNN/MKL-DNN
# which causes ConvertPirAttribute2RuntimeAttribute crash on Windows CPU
os.environ["PADDLE_PDX_ENABLE_MKLDNN_BYDEFAULT"] = "0"
try:
from paddleocr import PaddleOCR as _PaddleOCR
PADDLEOCR_AVAILABLE = True
except ImportError:
PADDLEOCR_AVAILABLE = False
try:
import qrcode as _qrcode
QRCODE_AVAILABLE = True
except ImportError:
QRCODE_AVAILABLE = False
_easyocr_reader = None # lazy singleton — first use initialises it
_paddleocr_reader = None # lazy singleton — first use initialises it
def _get_easyocr_reader():
global _easyocr_reader
if _easyocr_reader is None and EASYOCR_AVAILABLE:
try:
_easyocr_reader = _easyocr.Reader(["en", "pl"], gpu=False, verbose=False)
except Exception as e:
print(f"EasyOCR init error: {e}")
return _easyocr_reader
# Stores both the reader instance and which API generation it uses
_paddleocr_api_version = None # "v3" | "v2" | None
_paddleocr_init_error = None # last init error message, shown to user
def _get_paddleocr_reader():
global _paddleocr_reader, _paddleocr_api_version, _paddleocr_init_error
if _paddleocr_reader is None and PADDLEOCR_AVAILABLE:
# Disable OneDNN/MKL-DNN — causes ConvertPirAttribute crash on Windows
os.environ.setdefault("FLAGS_use_mkldnn", "0")
os.environ.setdefault("PADDLE_DISABLE_MKL", "1")
os.environ.setdefault("FLAGS_onednn_cpu_enable", "0")
# PaddleOCR 3.x removed use_angle_cls; try without it first.
# PaddleOCR 2.x requires use_angle_cls=True for best results.
# Build kwargs progressively — drop params that cause TypeError/unknown-arg errors
def _try_init_paddle(kwargs: dict):
"""Try to init PaddleOCR, stripping one unknown kwarg at a time."""
import copy
kw = copy.copy(kwargs)
removable = ["show_log", "use_angle_cls", "use_textline_orientation"]
tried = set()
while True:
try:
return _PaddleOCR(**kw)
except Exception as e:
msg = str(e)
removed = False
for param in removable:
if param in kw and param not in tried and (
"Unknown argument" in msg or param in msg
):
del kw[param]
tried.add(param)
removed = True
break
if not removed:
raise # nothing left to strip — real error
last_err = None
for ver, kwargs in [
("v3", {"lang": "en", "show_log": False}),
("v2", {"use_angle_cls": True, "lang": "en", "show_log": False}),
]:
try:
inst = _try_init_paddle(kwargs)
_paddleocr_reader = inst
_paddleocr_api_version = ver
break
except Exception as e:
last_err = e
continue
if _paddleocr_reader is None:
_paddleocr_init_error = str(last_err)
print(f"PaddleOCR init error: {last_err}")
if IS_LINUX:
print("[PyshareX] PaddleOCR may crash on Linux VMs or CPUs without AVX. "
"Switch to EasyOCR in Settings → OCR engine.")
return _paddleocr_reader
IS_WINDOWS = platform.system() == "Windows"
IS_LINUX = platform.system() == "Linux"
def _set_dialog_on_top(dlg):
"""Set dialog window flags so it appears above fullscreen overlays on all platforms.
On Linux, X11BypassWindowManagerHint is required to float above fullscreen windows."""
flags = Qt.WindowType.Window | Qt.WindowType.WindowStaysOnTopHint
if IS_LINUX:
flags |= Qt.WindowType.X11BypassWindowManagerHint
dlg.setWindowFlags(flags)
dlg.raise_()
dlg.activateWindow()
def _show_color_dialog(initial_color: QColor, parent=None,
alpha: bool = True, force_opaque: bool = False) -> QColor | None:
"""Show a QColorDialog that stays above fullscreen overlays on Linux.
Returns the selected QColor, or None if cancelled.
If force_opaque=True, alpha is forced to 255 regardless of user selection."""
color_to_show = QColor(initial_color)
if force_opaque:
color_to_show.setAlpha(255)
elif IS_LINUX and alpha and color_to_show.alpha() == 0:
# On Linux, QColorDialog defaults alpha to 0 if the initial color has
# alpha=0. Force it to 255 so the picker opens fully opaque by default.
color_to_show.setAlpha(255)
dlg = QColorDialog(color_to_show, parent)
dlg.setOption(QColorDialog.ColorDialogOption.ShowAlphaChannel, alpha)
dlg.setOption(QColorDialog.ColorDialogOption.DontUseNativeDialog, True)
if IS_LINUX:
dlg.setWindowFlags(
Qt.WindowType.Window |
Qt.WindowType.WindowStaysOnTopHint |
Qt.WindowType.X11BypassWindowManagerHint
)
# On Linux the alpha spin-box may still show 0 even after passing a
# color with alpha=255 to the constructor — set it explicitly.
if alpha:
dlg.setCurrentColor(color_to_show)
dlg.raise_()
dlg.activateWindow()
if dlg.exec():
c = dlg.selectedColor()
if c.isValid():
if force_opaque:
c.setAlpha(255)
return c
return None
# ── Hide console window on Windows ──────────────────────────────────────────
_NO_WINDOW = subprocess.CREATE_NO_WINDOW if IS_WINDOWS else 0
def _popen(cmd, **kw):
kw.setdefault("creationflags", _NO_WINDOW)
kw.setdefault("stdout", subprocess.DEVNULL)
kw.setdefault("stderr", subprocess.DEVNULL)
return subprocess.Popen(cmd, **kw)
def _run(cmd, **kw):
kw.setdefault("creationflags", _NO_WINDOW)
kw.setdefault("stdout", subprocess.DEVNULL)
kw.setdefault("stderr", subprocess.DEVNULL)
return subprocess.run(cmd, **kw)
# ─────────────────────────────────────────────
# MONITOR HELPER
# ─────────────────────────────────────────────
def _edid_model_name(edid: bytes) -> str:
"""Extract monitor model name from EDID bytes (descriptor block type 0xFC)."""
for d in range(4):
off = 54 + d * 18
if len(edid) >= off + 18:
desc = edid[off: off + 18]
if desc[0] == 0 and desc[1] == 0 and desc[2] == 0 and desc[3] == 0xFC:
raw = desc[5:].decode("ascii", errors="replace")
return raw.split("\n")[0].strip()
return ""
def _win_monitor_names() -> dict:
"""
Windows: return {mss_index: "Monitor Model Name"}.
Strategy (in order):
1. WMI via PowerShell Win32_DesktopMonitor
2. HKLM EDID registry
3. EnumDisplayDevices monitor-level DeviceString
"""
names = {}
# ── Method 1a: Get-PnpDevice -Class Monitor (Device Manager names) ─────────
# This is the most reliable — same names as Device Manager shows.
try:
ps_cmd = (
"(Get-PnpDevice -Class Monitor -Status OK "
"| Sort-Object -Property FriendlyName "
"| Select-Object -ExpandProperty FriendlyName)"
)
r = subprocess.run(
["powershell", "-NoProfile", "-NonInteractive", "-Command", ps_cmd],
capture_output=True, text=True, timeout=8,
creationflags=_NO_WINDOW,
)
if r.returncode == 0:
lines = [l.strip() for l in r.stdout.strip().splitlines()
if l.strip()
and "Generic" not in l
and "PnP" not in l
and "Default" not in l]
if lines:
for i, n in enumerate(lines):
names[i] = n
except Exception:
pass
if names:
return names
# ── Method 1b: WMI Win32_PnPEntity filtered to monitor class ─────────────
try:
ps_cmd = (
"Get-WmiObject -Query \"Select * From Win32_PnPEntity "
"Where PNPClass = 'Monitor'\" "
"| Where-Object {$_.Name -notlike '*Generic*' "
"-and $_.Name -notlike '*PnP*'} "
"| Select-Object -ExpandProperty Name"
)
r = subprocess.run(
["powershell", "-NoProfile", "-NonInteractive", "-Command", ps_cmd],
capture_output=True, text=True, timeout=8,
creationflags=_NO_WINDOW,
)
if r.returncode == 0:
lines = [l.strip() for l in r.stdout.strip().splitlines()
if l.strip()
and "Generic" not in l
and "PnP" not in l]
if lines:
for i, n in enumerate(lines):
names[i] = n
except Exception:
pass
if names:
return names
# ── Method 2: Registry EDID ───────────────────────────────────────────────
try:
import winreg
base = r"SYSTEM\CurrentControlSet\Enum\DISPLAY"
monitor_idx = 0
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, base) as disp:
mfr_i = 0
while True:
try:
mfr = winreg.EnumKey(disp, mfr_i); mfr_i += 1
with winreg.OpenKey(disp, mfr) as mk:
inst_i = 0
while True:
try:
inst = winreg.EnumKey(mk, inst_i); inst_i += 1
param = mfr + chr(92) + inst + chr(92) + "Device Parameters"
try:
with winreg.OpenKey(disp, param) as pk:
edid_data, _ = winreg.QueryValueEx(pk, "EDID")
model = _edid_model_name(bytes(edid_data))
if model:
names[monitor_idx] = model
monitor_idx += 1
except (FileNotFoundError, OSError):
monitor_idx += 1
except OSError:
break
except OSError:
break
except Exception:
pass
if names:
return names
# ── Method 3: EnumDisplayDevices ─────────────────────────────────────────
try:
import win32api
ai = 0
while True:
try:
adapter = win32api.EnumDisplayDevices(None, ai, 0)
if not adapter.DeviceName:
break
try:
mon = win32api.EnumDisplayDevices(adapter.DeviceName, 0, 0)
model = mon.DeviceString.strip()
if model and "Generic" not in model and "PnP" not in model:
names[ai] = model
except Exception:
pass
ai += 1
except Exception:
break
except Exception:
pass
return names
def _linux_monitor_names() -> list:
"""
Linux: parse EDID from xrandr --verbose to get real model names.
Returns ordered list matching mss connected-monitor order.
"""
port_model = {}
port_order = []
try:
out = subprocess.check_output(
["xrandr", "--verbose"], stderr=subprocess.DEVNULL, text=True, timeout=5)
current_port = None
edid_hex = ""
collecting = False
for line in out.splitlines():
stripped = line.strip()
if " connected" in line and not line[0].isspace():
# Save previous port EDID
if current_port and edid_hex:
try:
edid = bytes.fromhex(edid_hex)
for d in range(4):
off = 54 + d * 18
if len(edid) >= off + 18:
desc = edid[off:off+18]
if desc[0]==0 and desc[1]==0 and desc[2]==0 and desc[3]==0xFC:
raw = desc[5:].decode("ascii", errors="replace")
m = raw.split("\n")[0].strip()
if m:
port_model[current_port] = m
break
except Exception:
pass
current_port = line.split()[0]
port_order.append(current_port)
edid_hex = ""
collecting = False
elif stripped.lower() == "edid:":
collecting = True
elif collecting and stripped and all(c in "0123456789abcdefABCDEF" for c in stripped):
edid_hex += stripped
elif collecting and stripped:
collecting = False # end of EDID block
# Last port
if current_port and edid_hex:
try:
edid = bytes.fromhex(edid_hex)
for d in range(4):
off = 54 + d * 18
if len(edid) >= off + 18:
desc = edid[off:off+18]
if desc[0]==0 and desc[1]==0 and desc[2]==0 and desc[3]==0xFC:
raw = desc[5:].decode("ascii", errors="replace")
m = raw.split("\n")[0].strip()
if m:
port_model[current_port] = m
break
except Exception:
pass
except Exception:
pass
return [port_model.get(p, p) for p in port_order]
def get_monitors():
"""Returns list of {index, name, width, height, x, y}.
Name format: "1 (Main)" / "2 (Left)" / "3 (Right)" / "4 (Center)" etc.
"""
monitors = []
try:
with mss.MSS() as sct:
mons = sct.monitors[1:] # skip combined "all monitors" entry
# Find primary via Qt
primary_x, primary_y = 0, 0
try:
ps = QApplication.primaryScreen()
if ps:
primary_x, primary_y = ps.geometry().x(), ps.geometry().y()
except Exception:
pass
# Sort by X to determine Left/Center/Right order
sorted_by_x = sorted(enumerate(mons), key=lambda t: (t[1]["left"], t[1]["top"]))
positions = {} # mss_index → position_label
n = len(mons)
primary_mss_idx = None
for rank, (mss_idx, m) in enumerate(sorted_by_x):
if abs(m["left"] - primary_x) < 4 and abs(m["top"] - primary_y) < 4:
primary_mss_idx = mss_idx
for rank, (mss_idx, m) in enumerate(sorted_by_x):
if mss_idx == primary_mss_idx:
positions[mss_idx] = "Main"
elif n == 1:
positions[mss_idx] = "Main"
elif n == 2:
if rank == 0:
positions[mss_idx] = "Left" if primary_mss_idx != mss_idx else "Main"
else:
positions[mss_idx] = "Right" if primary_mss_idx != mss_idx else "Main"
else:
if rank == 0:
positions[mss_idx] = "Left"
elif rank == n - 1:
positions[mss_idx] = "Right"
else:
positions[mss_idx] = "Center"
for i, m in enumerate(mons):
pos = positions.get(i, f"Display {i+1}")
name = f"{i + 1} ({pos}) {m['width']}×{m['height']}"
monitors.append({"index": i, "name": name,
"width": m["width"], "height": m["height"],
"x": m["left"], "y": m["top"]})
except Exception:
monitors = [{"index": 0, "name": "1 (Main) 1920×1080",
"width": 1920, "height": 1080, "x": 0, "y": 0}]
return monitors
class FFmpegConverterThread(QThread):
log_signal = Signal(str)
finished_signal = Signal(int)
def __init__(self, cmd):
super().__init__()
self.cmd = cmd
self._is_cancelled = False
self.process = None
def run(self):
try:
# Flaga CREATE_NO_WINDOW ukrywa konsolę CMD na Windowsie
creationflags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
self.process = subprocess.Popen(
self.cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
creationflags=creationflags
)
for line in self.process.stdout:
if self._is_cancelled:
break
self.log_signal.emit(line.strip())
self.process.wait()
if self._is_cancelled:
self.finished_signal.emit(-99) # Znak, że anulowano
else:
self.finished_signal.emit(self.process.returncode)
except FileNotFoundError:
self.log_signal.emit("ERROR: ffmpeg not found. Make sure ffmpeg is installed and added to your PATH environment variables.")
self.finished_signal.emit(-1)
except Exception as e:
self.log_signal.emit(f"ERROR: {str(e)}")
self.finished_signal.emit(-1)
def cancel(self):
self._is_cancelled = True
if self.process:
self.process.terminate()
from PySide6.QtWidgets import (QGridLayout, QFormLayout, QProgressBar)
from PySide6.QtWidgets import QSlider
class VideoConverterDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Video Converter")
self.resize(750, 650)
self.thread = None
layout = QVBoxLayout(self)
# --- FILE PATHS ---
file_group = QGroupBox("File paths")
file_layout = QGridLayout()
self.input_edit = QLineEdit()
self.btn_browse_input = QPushButton("Browse...")
self.btn_browse_input.clicked.connect(self.browse_input)
self.output_dir_edit = QLineEdit()
self.btn_browse_output = QPushButton("Browse...")
self.btn_browse_output.clicked.connect(self.browse_output)
self.output_name_edit = QLineEdit()
file_layout.addWidget(QLabel("Input file:"), 0, 0)
file_layout.addWidget(self.input_edit, 0, 1)
file_layout.addWidget(self.btn_browse_input, 0, 2)
file_layout.addWidget(QLabel("Output folder:"), 1, 0)
file_layout.addWidget(self.output_dir_edit, 1, 1)
file_layout.addWidget(self.btn_browse_output, 1, 2)
file_layout.addWidget(QLabel("Output name:"), 2, 0)
file_layout.addWidget(self.output_name_edit, 2, 1)
file_group.setLayout(file_layout)
layout.addWidget(file_group)
# --- VIDEO OPTIONS ---
video_group = QGroupBox("Video options")
v_main_layout = QVBoxLayout()
video_form = QFormLayout()
self.video_codec_combo = QComboBox()
self.video_codec_combo.addItems([
"H.264/AVC (libx264)", "H.265/HEVC (libx265)",
"VP8 (libvpx)", "VP9 (libvpx-vp9)",
"AV1 (libaom-av1)", "Copy (no re-compression)", "None"
])
# 1. Quality Controls
self.quality_check = QCheckBox("Set custom video quality (CRF)")
quality_widget = QWidget()
quality_vbox = QVBoxLayout(quality_widget)
quality_vbox.setContentsMargins(0, 5, 0, 5)
self.quality_label = QLabel("Quality: Standard (CRF 23)")
self.quality_slider = QSlider(Qt.Orientation.Horizontal)
self.quality_slider.setRange(0, 51)
self.quality_slider.setValue(28) # Value 28 corresponds to CRF 23
quality_hint_layout = QHBoxLayout()
low_lbl = QLabel("Smaller file / Lower quality"); low_lbl.setStyleSheet("font-size: 10px; color: #888;")
high_lbl = QLabel("Higher quality / Bigger file"); high_lbl.setStyleSheet("font-size: 10px; color: #888;")
quality_hint_layout.addWidget(low_lbl)
quality_hint_layout.addStretch()
quality_hint_layout.addWidget(high_lbl)
quality_vbox.addWidget(self.quality_label)
quality_vbox.addWidget(self.quality_slider)
quality_vbox.addLayout(quality_hint_layout)
# Quality logic
def update_quality_ui(val):
crf = 51 - val
desc = "Standard"
if crf <= 17: desc = "Excellent"
elif crf <= 23: desc = "Standard"
elif crf <= 28: desc = "Medium"
else: desc = "Low"
self.quality_label.setText(f"Quality: {desc} (CRF {crf})")
self.quality_slider.valueChanged.connect(update_quality_ui)
self.quality_slider.setEnabled(False)
self.quality_label.setEnabled(False)
self.quality_check.toggled.connect(self.quality_slider.setEnabled)
self.quality_check.toggled.connect(self.quality_label.setEnabled)
# 2. Scale (Resize)
self.scale_combo = QComboBox()
self.scale_combo.addItems(["Original", "1920x1080", "1280x720", "854x480", "640x360"])
# 3. FPS Controls
self.fps_orig_check = QCheckBox("Use video’s original framerate")
self.fps_orig_check.setChecked(True)
self.fps_spin = QSpinBox()
self.fps_spin.setRange(1, 240)
self.fps_spin.setValue(60)
self.fps_spin.setEnabled(False)
self.fps_orig_check.toggled.connect(lambda checked: self.fps_spin.setEnabled(not checked))
# 4. Assemble the Form (NO DUPLICATES)
video_form.addRow("Video codec:", self.video_codec_combo)
video_form.addRow(self.quality_check)
video_form.addRow(quality_widget)
video_form.addRow("Scale (Resize):", self.scale_combo)
video_form.addRow(self.fps_orig_check)
video_form.addRow("Custom FPS:", self.fps_spin)
v_main_layout.addLayout(video_form)
video_group.setLayout(v_main_layout)
# --- AUDIO & FORMAT ---
audio_group = QGroupBox("Audio & Format")
audio_form = QFormLayout()
self.audio_codec_combo = QComboBox()
self.audio_codec_combo.addItems([
"AAC (aac)", "MP3 (libmp3lame)", "Opus (libopus)",
"Vorbis (libvorbis)", "Copy (no re-compression)", "None"
])
self.format_combo = QComboBox()
self.format_combo.addItems(["MP4", "WebM", "MKV", "AVI", "GIF"])
audio_form.addRow("Audio codec:", self.audio_codec_combo)
audio_form.addRow("Output format:", self.format_combo)
audio_group.setLayout(audio_form)
settings_layout = QHBoxLayout()
settings_layout.addWidget(video_group)
settings_layout.addWidget(audio_group)
layout.addLayout(settings_layout)
# --- LOGS & BUTTONS ---
self.log_text = QTextEdit()
self.log_text.setReadOnly(True)
self.log_text.setFont(QFont("Consolas", 9) if sys.platform=="win32" else QFont("Monospace", 9))
layout.addWidget(self.log_text)
button_layout = QHBoxLayout()
self.btn_start = QPushButton("Start encoding")
self.btn_start.clicked.connect(self.start_conversion)
self.btn_cancel = QPushButton("Cancel")
self.btn_cancel.setEnabled(False)
self.btn_cancel.clicked.connect(self.cancel_conversion)
button_layout.addStretch()
button_layout.addWidget(self.btn_start)
button_layout.addWidget(self.btn_cancel)
layout.addLayout(button_layout)
def browse_input(self):
file_path, _ = QFileDialog.getOpenFileName(self, "Select video file", "", "Video Files (*.mp4 *.mkv *.avi *.webm *.mov);;All Files (*)")
if file_path:
self.input_edit.setText(file_path)
p = Path(file_path)
self.output_dir_edit.setText(str(p.parent))
self.output_name_edit.setText(f"{p.stem}_converted")
def browse_output(self):
dir_path = QFileDialog.getExistingDirectory(self, "Select output folder")
if dir_path:
self.output_dir_edit.setText(dir_path)
def get_ffmpeg_args(self):
v_codecs = {"H.264/AVC (libx264)": "libx264", "H.265/HEVC (libx265)": "libx265",
"VP8 (libvpx)": "libvpx", "VP9 (libvpx-vp9)": "libvpx-vp9",
"AV1 (libaom-av1)": "libaom-av1", "Copy (no re-compression)": "copy"}
a_codecs = {"AAC (aac)": "aac", "MP3 (libmp3lame)": "libmp3lame",
"Opus (libopus)": "libopus", "Vorbis (libvorbis)": "libvorbis",
"Copy (no re-compression)": "copy"}
v_val = self.video_codec_combo.currentText()
a_val = self.audio_codec_combo.currentText()
args = ["-map", "0:v:0", "-map", "0:a?"]
# --- VIDEO ---
# --- VIDEO ---
if v_val == "None":
args.append("-vn")
else:
codec = v_codecs.get(v_val, "libx264")
args.extend(["-c:v", codec])
if codec != "copy":
args.extend(["-pix_fmt", "yuv420p"])
# --- Quality Logic ---
if self.quality_check.isChecked():
# Invert the slider value back to FFmpeg CRF
real_crf = 51 - self.quality_slider.value()
args.extend(["-crf", str(real_crf)])
# Resizing
scale = self.scale_combo.currentText()
if scale != "Original":
w, h = scale.split('x')
args.extend(["-vf", f"scale={w}:{h}:force_original_aspect_ratio=decrease,pad={w}:{h}:(ow-iw)/2:(oh-ih)/2"])
# --- Update FPS Logic ---
if not self.fps_orig_check.isChecked():
args.extend(["-r", str(self.fps_spin.value())])
# --- AUDIO ---
if a_val == "None":
args.append("-an")
else:
codec = a_codecs.get(a_val, "aac")
args.extend(["-c:a", codec])
if codec != "copy":
args.extend(["-b:a", "128k"])
if self.format_combo.currentText().lower() == "mp4":
args.extend(["-movflags", "+faststart"])
return args
def start_conversion(self):
input_file = self.input_edit.text().strip()
output_dir = self.output_dir_edit.text().strip()
output_name = self.output_name_edit.text().strip()
ext = self.format_combo.currentText().lower()
if not input_file or not os.path.exists(input_file):
QMessageBox.warning(self, "Error", "Invalid input file!")
return
output_path = os.path.join(output_dir, f"{output_name}.{ext}")
cmd = ["ffmpeg", "-y", "-i", input_file] + self.get_ffmpeg_args() + [output_path]
self.log_text.clear()
self.log_text.append(f"Command: {' '.join(cmd)}\n")
self.btn_start.setEnabled(False)
self.btn_cancel.setEnabled(True)
self.thread = FFmpegConverterThread(cmd)
self.thread.log_signal.connect(self.append_log)
self.thread.finished_signal.connect(self.conversion_finished)
self.thread.start()
def append_log(self, text):
self.log_text.append(text)
self.log_text.verticalScrollBar().setValue(self.log_text.verticalScrollBar().maximum())
def cancel_conversion(self):
if self.thread and self.thread.isRunning():
self.thread.cancel()
def conversion_finished(self, code):
self.btn_start.setEnabled(True)
self.btn_cancel.setEnabled(False)
msg = "[✓] Done!" if code == 0 else "[✗] Failed or Cancelled."
self.log_text.append(f"\n{msg}")
# ─────────────────────────────────────────────
# CONFIG
# ─────────────────────────────────────────────
class Config:
DEFAULT_SHORTCUTS = [
{"name": "Capture region", "action": "capture_region", "shortcut": "Ctrl+Alt+Print Screen", "enabled": True},
{"name": "Capture active monitor", "action": "capture_active_monitor", "shortcut": "Alt+Print Screen", "enabled": True},
{"name": "Capture active window", "action": "capture_active_window", "shortcut": "Ctrl+Print Screen", "enabled": True},
{"name": "Capture selected monitor", "action": "capture_selected_monitor", "shortcut": "Ctrl+Alt+M", "enabled": True},
{"name": "Scrolling capture", "action": "capture_scrolling", "shortcut": "Shift+Print Screen", "enabled": True},
{"name": "Start/Stop recording", "action": "toggle_recording", "shortcut": "Ctrl+Shift+Print Screen","enabled": True},
{"name": "Record GIF", "action": "record_gif", "shortcut": "Ctrl+Shift+G", "enabled": True},
{"name": "Recognize text", "action": "ocr_text", "shortcut": "Ctrl+Alt+O", "enabled": True},
{"name": "Recognize QR code", "action": "ocr_code", "shortcut": "Ctrl+Alt+K", "enabled": True},
{"name": "OCR/QR Toolbox", "action": "ocr_qr_toolbox", "shortcut": "Ctrl+Alt+Q", "enabled": True},
]
DEFAULT_AFTER = {"copy_to_clipboard": True, "save_to_file": True,
"show_in_explorer": False, "scan_qr": False, "ocr_recognize": False,
"open_in_editor": False}
DEFAULT_NOTIF = {"enabled": True, "sound": True, "thumbnail": True,
"show_path": True, "click_open_file": True, "click_open_folder": False}
def __init__(self):
cfg_dir = Path(QStandardPaths.writableLocation(
QStandardPaths.StandardLocation.AppConfigLocation))
cfg_dir.mkdir(parents=True, exist_ok=True)
self.path = cfg_dir / "pysharex.json"
self.data = self._load()
def _defaults(self):
pics = Path(QStandardPaths.writableLocation(
QStandardPaths.StandardLocation.PicturesLocation))
return {
"shortcuts": self.DEFAULT_SHORTCUTS.copy(),
"save_folder": str(pics / "PyshareX"),
"after_capture": self.DEFAULT_AFTER.copy(),
"notifications": self.DEFAULT_NOTIF.copy(),
"image_format": "png",
"jpeg_quality": 90,
"show_cursor": False,
"delay": 0,
"gif_fps": 10,
"gif_duration": 5,
"record_audio": False,
"selected_monitor": 0,
"ocr_engine": "paddleocr",
}
def _load(self):
if self.path.exists():
try:
with open(self.path, "r", encoding="utf-8") as f:
d = json.load(f)
for k, v in self._defaults().items():
d.setdefault(k, v)
# Auto-migrate: reset shortcuts to English if any Polish names found
scs = d.get("shortcuts", [])
if scs and any(
any(pl in s.get("name", "")
for pl in ("Przechwyt", "Nagryw", "Rozpoznaj", "Rozpocz"))
for s in scs
):
d["shortcuts"] = self.DEFAULT_SHORTCUTS.copy()
try:
with open(self.path, "w", encoding="utf-8") as fw:
json.dump(d, fw, indent=2, ensure_ascii=False)
except Exception:
pass
# Auto-migrate: force paddleocr as default if not explicitly set to a known engine
valid_engines = {"paddleocr", "easyocr", "tesseract"}
if d.get("ocr_engine") not in valid_engines:
d["ocr_engine"] = "paddleocr"
try:
with open(self.path, "w", encoding="utf-8") as fw:
json.dump(d, fw, indent=2, ensure_ascii=False)
except Exception:
pass
return d
except Exception:
pass
return self._defaults()
def save(self):
try:
with open(self.path, "w", encoding="utf-8") as f:
json.dump(self.data, f, indent=2, ensure_ascii=False)
except Exception as e:
print(f"Config save error: {e}")
def get(self, key, default=None):
return self.data.get(key, default)
def set(self, key, value):
self.data[key] = value
self.save()
# ─────────────────────────────────────────────
# BEEP / NOTIFICATION
# ─────────────────────────────────────────────
def _play_beep():
try:
if IS_WINDOWS:
import winsound
winsound.MessageBeep(winsound.MB_ICONASTERISK)
else:
sr, dur, freq = 22050, 0.12, 880
samples = [int(32767 * math.sin(2 * math.pi * freq * t / sr))
for t in range(int(sr * dur))]
buf = io.BytesIO()
with wv.open(buf, "w") as wf:
wf.setnchannels(1); wf.setsampwidth(2); wf.setframerate(sr)
wf.writeframes(b"".join(struct.pack("<h", s) for s in samples))
tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
tmp.write(buf.getvalue()); tmp.close()
for player in ("paplay", "aplay", "play"):
if _run(["which", player], timeout=1).returncode == 0:
_popen([player, tmp.name])
break
except Exception:
pass
class NotificationToast(QWidget):
def __init__(self, title, message, pixmap=None, filepath=None, on_click_open=True, on_click_folder=False):
super().__init__(None,
Qt.WindowType.Tool |
Qt.WindowType.FramelessWindowHint |
Qt.WindowType.WindowStaysOnTopHint |
Qt.WindowType.BypassWindowManagerHint)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
self._opacity = 1.0
self._filepath = filepath
self._on_click_open = on_click_open
self._on_click_folder = on_click_folder
self.setStyleSheet("""
QWidget#MainFrame {
background-color: #1f1f1f;
border: 1px solid #3a3a3a;
}
QLabel#Title {
color: #00a2ed;
font-weight: bold;
font-size: 14px;
}
QLabel#Message {
color: #bbbbbb;
font-size: 12px;
}
QWidget#AccentBar {
background-color: #00a2ed;
}
""")
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
# Niebieski pasek
self.accent = QFrame()
self.accent.setObjectName("AccentBar")
self.accent.setFixedWidth(4)
layout.addWidget(self.accent)
# Główny kontener
self.frame = QFrame()
self.frame.setObjectName("MainFrame")
layout.addWidget(self.frame)
f_layout = QHBoxLayout(self.frame)
f_layout.setContentsMargins(5, 5, 15, 5) # Bardzo małe marginesy dla obrazka
f_layout.setSpacing(15)
# DUŻA MINIATURKA - teraz 125x125
self.img_label = QLabel()
tsize = 125
self.img_label.setFixedSize(tsize, tsize)
if pixmap and not pixmap.isNull():
# Skalowanie wypełniające całe pole (Crop)
scaled = pixmap.scaled(tsize, tsize, Qt.AspectRatioMode.KeepAspectRatioByExpanding, Qt.TransformationMode.SmoothTransformation)
self.img_label.setPixmap(scaled)
else:
self.img_label.setStyleSheet("background-color: #2a2a2a;")
f_layout.addWidget(self.img_label)
# Tekst
t_layout = QVBoxLayout()
t_layout.setSpacing(2)
self.l_title = QLabel(title); self.l_title.setObjectName("Title")
self.l_msg = QLabel(message); self.l_msg.setObjectName("Message"); self.l_msg.setWordWrap(True)
t_layout.addStretch()