Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
316 lines (256 loc) · 10.1 KB
/
Copy pathmain.py
File metadata and controls
316 lines (256 loc) · 10.1 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
import sys
import os
import time
from PySide6.QtCore import Qt, QUrl, QTimer, QObject, Slot, Signal, Property, QAbstractListModel, QModelIndex, QByteArray
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
from subtitle_parser import parse_subtitle
class PlaylistModel(QAbstractListModel):
NameRole = Qt.ItemDataRole.UserRole + 1
PathRole = Qt.ItemDataRole.UserRole + 2
def __init__(self, parent=None):
super().__init__(parent)
self._playlist = []
def rowCount(self, parent=QModelIndex()):
return len(self._playlist)
def data(self, index, role=Qt.ItemDataRole.DisplayRole):
if not index.isValid():
return None
if 0 <= index.row() < self.rowCount():
item = self._playlist[index.row()]
if role == self.NameRole:
return item['name']
elif role == self.PathRole:
return item['path']
return None
def roleNames(self):
return {
self.NameRole: QByteArray(b"name"),
self.PathRole: QByteArray(b"path")
}
def load_directory(self, directory):
self.beginResetModel()
self._playlist.clear()
video_extensions = ('.mp4', '.mkv', '.avi', '.webm')
try:
files = [f for f in os.listdir(directory) if f.lower().endswith(video_extensions)]
files.sort()
for file in files:
full_path = os.path.normpath(os.path.join(directory, file))
self._playlist.append({
"name": file,
"path": QUrl.fromLocalFile(full_path).toString()
})
except FileNotFoundError:
pass
self.endResetModel()
class SubtitleModel(QAbstractListModel):
TextRole = Qt.ItemDataRole.UserRole + 1
StartRole = Qt.ItemDataRole.UserRole + 2
EndRole = Qt.ItemDataRole.UserRole + 3
def __init__(self, parent=None):
super().__init__(parent)
self._subtitles = []
def rowCount(self, parent=QModelIndex()):
return len(self._subtitles)
def data(self, index, role=Qt.ItemDataRole.DisplayRole):
if not index.isValid():
return None
if 0 <= index.row() < self.rowCount():
item = self._subtitles[index.row()]
if role == self.TextRole:
return item['text'].strip()
elif role == self.StartRole:
return item['start']
elif role == self.EndRole:
return item['end']
return None
def roleNames(self):
return {
self.TextRole: QByteArray(b"text"),
self.StartRole: QByteArray(b"start"),
self.EndRole: QByteArray(b"end")
}
def load_subtitles(self, filepath):
self.beginResetModel()
self._subtitles.clear()
base_name = os.path.splitext(filepath)[0]
sub_path = None
for ext in ['.srt', '.vtt']:
if os.path.exists(base_name + ext):
sub_path = base_name + ext
break
if sub_path:
self._subtitles = parse_subtitle(sub_path)
self.endResetModel()
return len(self._subtitles) > 0
def get_subtitle_at(self, position_ms):
# Could be binary search for large files, but linear is fine for normal subs
for i, sub in enumerate(self._subtitles):
if sub["start"] <= position_ms <= sub["end"]:
return sub["text"].strip(), i
return "", -1
class PlayerBackend(QObject):
# Signals to update QML
currentVideoUrlChanged = Signal()
currentSubtitleTextChanged = Signal()
activeSubtitleIndexChanged = Signal()
def __init__(self, parent=None):
super().__init__(parent)
self._currentVideoUrl = QUrl()
self._currentSubtitleText = ""
self._activeSubtitleIndex = -1
self.playlistModel = PlaylistModel(self)
self.subtitleModel = SubtitleModel(self)
# --- Properties ---
@Property(QUrl, notify=currentVideoUrlChanged)
def currentVideoUrl(self):
return self._currentVideoUrl
@Property(str, notify=currentSubtitleTextChanged)
def currentSubtitleText(self):
return self._currentSubtitleText
@Property(int, notify=activeSubtitleIndexChanged)
def activeSubtitleIndex(self):
return self._activeSubtitleIndex
# --- Slots callable from QML ---
@Slot(str)
def loadVideo(self, filepath):
if filepath.startswith("file://"):
filepath = QUrl(filepath).toLocalFile()
# On Windows, sometimes an extra leading slash remains (e.g. /E:/path)
if os.name == 'nt' and filepath.startswith('/') and len(filepath) > 2 and filepath[2] == ':':
filepath = filepath[1:]
self._currentVideoUrl = QUrl.fromLocalFile(filepath)
self.currentVideoUrlChanged.emit()
# Load associated directories into models
directory = os.path.dirname(filepath)
self.playlistModel.load_directory(directory)
self.subtitleModel.load_subtitles(filepath)
# Reset current subtitle
self.updateSubtitle(0)
@Slot(int)
def updateSubtitle(self, position_ms):
text, index = self.subtitleModel.get_subtitle_at(position_ms)
if self._currentSubtitleText != text:
self._currentSubtitleText = text
self.currentSubtitleTextChanged.emit()
if self._activeSubtitleIndex != index:
self._activeSubtitleIndex = index
self.activeSubtitleIndexChanged.emit()
import json
class ConfigManager(QObject):
def __init__(self, parent=None):
super().__init__(parent)
self.config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
self._config = {
"windowWidth": 1200,
"windowHeight": 800,
"rightPanelWidth": 400,
"subtitlesHeight": 400,
"rightPanelVisible": True,
"playlistVisible": True
}
self.load()
def load(self):
if os.path.exists(self.config_path):
try:
with open(self.config_path, 'r') as f:
self._config.update(json.load(f))
except Exception:
pass
def save(self):
try:
with open(self.config_path, 'w') as f:
json.dump(self._config, f, indent=4)
except Exception:
pass
windowWidthChanged = Signal()
windowHeightChanged = Signal()
rightPanelWidthChanged = Signal()
subtitlesHeightChanged = Signal()
lastVideoPathChanged = Signal()
lastVideoPositionChanged = Signal()
rightPanelVisibleChanged = Signal()
playlistVisibleChanged = Signal()
@Property(bool, notify=rightPanelVisibleChanged)
def rightPanelVisible(self):
return self._config.get("rightPanelVisible", True)
@rightPanelVisible.setter
def rightPanelVisible(self, v):
self._config["rightPanelVisible"] = v
self.save()
self.rightPanelVisibleChanged.emit()
@Property(bool, notify=playlistVisibleChanged)
def playlistVisible(self):
return self._config.get("playlistVisible", True)
@playlistVisible.setter
def playlistVisible(self, v):
self._config["playlistVisible"] = v
self.save()
self.playlistVisibleChanged.emit()
@Property(int, notify=lastVideoPositionChanged)
def lastVideoPosition(self):
return self._config.get("lastVideoPosition", 0)
@lastVideoPosition.setter
def lastVideoPosition(self, v):
self._config["lastVideoPosition"] = v
self.save()
self.lastVideoPositionChanged.emit()
@Property(str, notify=lastVideoPathChanged)
def lastVideoPath(self):
return self._config.get("lastVideoPath", "")
@lastVideoPath.setter
def lastVideoPath(self, v):
self._config["lastVideoPath"] = v
self.save()
self.lastVideoPathChanged.emit()
@Property(int, notify=windowWidthChanged)
def windowWidth(self):
return self._config.get("windowWidth", 1200)
@windowWidth.setter
def windowWidth(self, v):
self._config["windowWidth"] = v
self.save()
self.windowWidthChanged.emit()
@Property(int, notify=windowHeightChanged)
def windowHeight(self):
return self._config.get("windowHeight", 800)
@windowHeight.setter
def windowHeight(self, v):
self._config["windowHeight"] = v
self.save()
self.windowHeightChanged.emit()
@Property(int, notify=rightPanelWidthChanged)
def rightPanelWidth(self):
return self._config.get("rightPanelWidth", 400)
@rightPanelWidth.setter
def rightPanelWidth(self, v):
self._config["rightPanelWidth"] = v
self.save()
self.rightPanelWidthChanged.emit()
@Property(int, notify=subtitlesHeightChanged)
def subtitlesHeight(self):
return self._config.get("subtitlesHeight", 400)
@subtitlesHeight.setter
def subtitlesHeight(self, v):
self._config["subtitlesHeight"] = v
self.save()
self.subtitlesHeightChanged.emit()
if __name__ == "__main__":
app = QGuiApplication(sys.argv)
# We use QQmlApplicationEngine to load the heavily aesthetic QML UI
engine = QQmlApplicationEngine()
# Instantiate our python backend controller
backend = PlayerBackend()
config = ConfigManager()
# Expose the backend and models to the QML context
engine.rootContext().setContextProperty("backend", backend)
engine.rootContext().setContextProperty("playlistModel", backend.playlistModel)
engine.rootContext().setContextProperty("subtitleModel", backend.subtitleModel)
engine.rootContext().setContextProperty("config", config)
# Load the main.qml file which we are about to create
qml_file = os.path.join(os.path.dirname(__file__), "main.qml")
engine.load(QUrl.fromLocalFile(qml_file))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec())