-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmain.py
More file actions
7886 lines (6632 loc) · 355 KB
/
main.py
File metadata and controls
7886 lines (6632 loc) · 355 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 python
# -*- coding: utf-8 -*-
"""
YouTube 转录工具 PyQt6 版本
基于原始 youtube_transcriber.py 代码实现的图形界面版本
"""
import sys
import os
# 将 src/ 目录加入模块搜索路径
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "src"))
import threading
import time
import subprocess
import platform
from datetime import datetime
from pathlib import Path
# 导入 PyQt6 相关模块
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QLabel, QLineEdit, QTextEdit, QComboBox,
QCheckBox, QTabWidget, QFileDialog, QMessageBox, QProgressBar,
QGroupBox, QRadioButton, QScrollArea, QSplitter, QListWidget,
QListWidgetItem, QButtonGroup, QSpinBox, QStatusBar, QDialog,
QDialogButtonBox, QInputDialog, QMenu, QFontComboBox, QDoubleSpinBox,
QFrame, QColorDialog
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QSize, QUrl, QTimer, QObject
from PyQt6.QtGui import (QIcon, QPixmap, QFont, QDesktopServices, QTextCursor,
QAction, QClipboard, QEnterEvent, QColor, QPainter,
QPen, QPainterPath)
# 导入原始代码中的功能模块
import yt_dlp
import whisper
import torch
from dotenv import load_dotenv
from openai import OpenAI
import requests
import html
import subprocess
import json
# 导入抖音下载模块
try:
from douyin import DouyinDownloader, DouyinConfig, DouyinUtils
DOUYIN_AVAILABLE = True
print("✅ 抖音模块导入成功")
except ImportError as e:
print(f"⚠️ 抖音模块未找到: {e}")
DouyinDownloader = None
DouyinConfig = None
DouyinUtils = None
DOUYIN_AVAILABLE = False
# DouyinUtils 安全调用函数
def safe_douyin_utils():
"""安全获取 DouyinUtils,确保模块可用"""
global DOUYIN_AVAILABLE, DouyinUtils
try:
print(f"[安全调用] 检查状态 - DOUYIN_AVAILABLE: {DOUYIN_AVAILABLE}, DouyinUtils: {DouyinUtils}")
# 检查当前状态
if DOUYIN_AVAILABLE and DouyinUtils is not None:
print("[安全调用] 使用现有的 DouyinUtils")
return DouyinUtils
# 尝试重新导入
print("[安全调用] 尝试重新导入 DouyinUtils...")
from douyin.utils import DouyinUtils as _DouyinUtils
DouyinUtils = _DouyinUtils
DOUYIN_AVAILABLE = True
print("[安全调用] DouyinUtils 重新导入成功")
return DouyinUtils
except ImportError as e:
print(f"[安全调用] DouyinUtils 导入失败: {e}")
DOUYIN_AVAILABLE = False
DouyinUtils = None
return None
except Exception as e:
print(f"[安全调用] DouyinUtils 获取异常: {e}")
import traceback
traceback.print_exc()
DOUYIN_AVAILABLE = False
DouyinUtils = None
return None
# 自定义抖音输入框类
class DouyinLineEdit(QLineEdit):
"""支持智能粘贴的抖音URL输入框"""
def __init__(self, parent=None):
super().__init__(parent)
self.main_window = parent
def keyPressEvent(self, event):
"""处理键盘事件,支持Ctrl+V智能粘贴"""
try:
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QKeySequence
# 检查是否是Ctrl+V
if event.matches(QKeySequence.StandardKey.Paste):
print("[键盘] 检测到Ctrl+V,执行智能粘贴")
self.smart_paste()
return
# 其他键盘事件按正常处理
super().keyPressEvent(event)
except Exception as e:
print(f"[键盘] 处理键盘事件错误: {e}")
super().keyPressEvent(event)
def contextMenuEvent(self, event):
"""自定义右键菜单"""
menu = self.createStandardContextMenu()
# 添加智能粘贴选项
if menu.actions():
paste_action = None
for action in menu.actions():
if "粘贴" in action.text() or "Paste" in action.text():
paste_action = action
break
if paste_action:
# 移除原来的粘贴操作
menu.removeAction(paste_action)
# 添加智能粘贴
smart_paste_action = menu.addAction("🎯 智能粘贴")
smart_paste_action.triggered.connect(self.smart_paste)
# 添加普通粘贴
normal_paste_action = menu.addAction("📋 普通粘贴")
normal_paste_action.triggered.connect(self.paste)
menu.exec(event.globalPos())
def smart_paste(self):
"""智能粘贴功能"""
try:
from PyQt6.QtWidgets import QApplication
clipboard = QApplication.clipboard()
clipboard_text = clipboard.text()
print(f"[智能粘贴] 剪贴板内容: {clipboard_text[:100] if clipboard_text else '空'}...")
if clipboard_text:
# 安全获取 DouyinUtils
utils = safe_douyin_utils()
if utils is None:
print("[智能粘贴] DouyinUtils 不可用")
if hasattr(self.main_window, 'douyin_status_label'):
self.main_window.douyin_status_label.setText("❌ 抖音模块不可用")
self.main_window.douyin_status_label.setStyleSheet("color: #f44336;")
self.paste()
return
try:
print("[智能粘贴] 开始处理分享文本...")
extracted_url = utils.parse_share_text(clipboard_text)
print(f"[智能粘贴] 提取结果: {extracted_url}")
if extracted_url:
self.setText(extracted_url)
# 记录是否为用户主页分享,供解析线程使用
is_user_profile = utils.is_user_profile_share_text(clipboard_text)
# 记录是否为用户主页分享,供解析线程使用
if self.main_window is not None:
self.main_window._pending_douyin_url_is_user = is_user_profile
if hasattr(self.main_window, 'douyin_status_label'):
if is_user_profile:
self.main_window.douyin_status_label.setText("✅ 已提取用户主页链接")
self.main_window.douyin_status_label.setStyleSheet("color: #2196F3;")
else:
self.main_window.douyin_status_label.setText("✅ 已从剪贴板提取有效链接")
self.main_window.douyin_status_label.setStyleSheet("color: #4CAF50;")
print("[智能粘贴] 设置URL成功")
else:
print("[智能粘贴] 未找到有效链接,使用普通粘贴")
if hasattr(self.main_window, 'douyin_status_label'):
self.main_window.douyin_status_label.setText("⚠️ 未检测到抖音链接,已使用普通粘贴")
self.main_window.douyin_status_label.setStyleSheet("color: #FF9800;")
# 没有找到有效链接,使用普通粘贴
self.paste()
except Exception as e:
print(f"[智能粘贴] 处理出错: {e}")
import traceback
traceback.print_exc()
if hasattr(self.main_window, 'douyin_status_label'):
self.main_window.douyin_status_label.setText(f"❌ 处理出错: {str(e)}")
self.main_window.douyin_status_label.setStyleSheet("color: #f44336;")
self.paste()
else:
print("[智能粘贴] 剪贴板为空")
if hasattr(self.main_window, 'douyin_status_label'):
self.main_window.douyin_status_label.setText("ℹ️ 剪贴板为空")
self.main_window.douyin_status_label.setStyleSheet("color: #666;")
self.paste()
except Exception as e:
print(f"[智能粘贴] 总体错误: {e}")
import traceback
traceback.print_exc()
if hasattr(self.main_window, 'douyin_status_label'):
self.main_window.douyin_status_label.setText(f"❌ 智能粘贴失败: {str(e)}")
self.main_window.douyin_status_label.setStyleSheet("color: #f44336;")
self.paste()
class DouyinTextEdit(QTextEdit):
"""支持智能粘贴的抖音批量输入框"""
def __init__(self, parent=None):
super().__init__(parent)
self.main_window = parent
def keyPressEvent(self, event):
"""处理键盘事件,支持Ctrl+V智能粘贴"""
try:
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QKeySequence
# 检查是否是Ctrl+V
if event.matches(QKeySequence.StandardKey.Paste):
print("[键盘] 检测到Ctrl+V,执行批量智能粘贴")
self.smart_paste()
return
# 其他键盘事件按正常处理
super().keyPressEvent(event)
except Exception as e:
print(f"[键盘] 处理键盘事件错误: {e}")
super().keyPressEvent(event)
def contextMenuEvent(self, event):
"""自定义右键菜单"""
menu = self.createStandardContextMenu()
# 添加智能粘贴选项
if menu.actions():
paste_action = None
for action in menu.actions():
if "粘贴" in action.text() or "Paste" in action.text():
paste_action = action
break
if paste_action:
# 移除原来的粘贴操作
menu.removeAction(paste_action)
# 添加智能粘贴
smart_paste_action = menu.addAction("🎯 智能粘贴")
smart_paste_action.triggered.connect(self.smart_paste)
# 添加普通粘贴
normal_paste_action = menu.addAction("📋 普通粘贴")
normal_paste_action.triggered.connect(self.paste)
menu.exec(event.globalPos())
def smart_paste(self):
"""智能粘贴功能"""
try:
from PyQt6.QtWidgets import QApplication
clipboard = QApplication.clipboard()
clipboard_text = clipboard.text()
print(f"[批量智能粘贴] 剪贴板内容: {clipboard_text[:100] if clipboard_text else '空'}...")
if clipboard_text:
# 安全获取 DouyinUtils
utils = safe_douyin_utils()
if utils is None:
print("[批量智能粘贴] DouyinUtils 不可用")
if hasattr(self.main_window, 'douyin_status_label'):
self.main_window.douyin_status_label.setText("❌ 抖音模块不可用")
self.main_window.douyin_status_label.setStyleSheet("color: #f44336;")
self.paste()
return
try:
print("[批量智能粘贴] 开始处理分享文本...")
# 提取所有有效URL
all_urls = utils.extract_urls_from_text(clipboard_text)
valid_urls = []
print(f"[批量智能粘贴] 发现URL: {all_urls}")
# 验证每个URL
for url in all_urls:
if utils.validate_url(url):
valid_urls.append(url)
# 如果没有直接链接,尝试从分享文本提取
if not valid_urls:
extracted = utils.parse_share_text(clipboard_text)
print(f"[批量智能粘贴] 分享文本提取结果: {extracted}")
if extracted:
valid_urls.append(extracted)
print(f"[批量智能粘贴] 有效链接: {valid_urls}")
if valid_urls:
# 获取当前文本内容
current_text = self.toPlainText()
# 准备要添加的内容
new_lines = []
for url in valid_urls:
if url not in current_text: # 避免重复
new_lines.append(url)
if new_lines:
# 如果当前有内容且不是空行结尾,添加换行
if current_text and not current_text.endswith('\n'):
current_text += '\n'
# 添加新链接
new_content = current_text + '\n'.join(new_lines)
self.setPlainText(new_content)
# 更新状态提示
if hasattr(self.main_window, 'douyin_status_label'):
self.main_window.douyin_status_label.setText(f"✅ 已添加 {len(new_lines)} 个有效链接")
self.main_window.douyin_status_label.setStyleSheet("color: #4CAF50;")
print(f"[批量智能粘贴] 成功添加 {len(new_lines)} 个链接")
else:
# 所有链接已存在
if hasattr(self.main_window, 'douyin_status_label'):
self.main_window.douyin_status_label.setText("ℹ️ 所有链接已存在")
self.main_window.douyin_status_label.setStyleSheet("color: #FF9800;")
print("[批量智能粘贴] 所有链接已存在")
else:
print("[批量智能粘贴] 未找到有效链接,使用普通粘贴")
if hasattr(self.main_window, 'douyin_status_label'):
self.main_window.douyin_status_label.setText("⚠️ 未检测到抖音链接,已使用普通粘贴")
self.main_window.douyin_status_label.setStyleSheet("color: #FF9800;")
# 没有找到有效链接,使用普通粘贴
self.paste()
except Exception as e:
print(f"[批量智能粘贴] 处理出错: {e}")
import traceback
traceback.print_exc()
if hasattr(self.main_window, 'douyin_status_label'):
self.main_window.douyin_status_label.setText(f"❌ 处理出错: {str(e)}")
self.main_window.douyin_status_label.setStyleSheet("color: #f44336;")
self.paste()
else:
print("[批量智能粘贴] 剪贴板为空")
if hasattr(self.main_window, 'douyin_status_label'):
self.main_window.douyin_status_label.setText("ℹ️ 剪贴板为空")
self.main_window.douyin_status_label.setStyleSheet("color: #666;")
self.paste()
except Exception as e:
print(f"[批量智能粘贴] 总体错误: {e}")
import traceback
traceback.print_exc()
if hasattr(self.main_window, 'douyin_status_label'):
self.main_window.douyin_status_label.setText(f"❌ 智能粘贴失败: {str(e)}")
self.main_window.douyin_status_label.setStyleSheet("color: #f44336;")
self.paste()
# 加载环境变量(指定 main.py 所在目录的 .env 文件)
_env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env")
load_dotenv(_env_path, override=True) # override=True 确保总是从.env文件中加载最新的值
print(f"✅ 已加载环境变量: {_env_path}")
def _save_env_key(env_path: str, key: str, value: str):
"""向 .env 文件写入或更新单个 key=value,保留其他行不变。"""
lines = []
found = False
if os.path.exists(env_path):
with open(env_path, "r", encoding="utf-8") as f:
for line in f:
stripped = line.rstrip("\n")
if stripped.startswith(f"{key}=") or stripped == key:
lines.append(f"{key}={value}\n")
found = True
else:
lines.append(line if line.endswith("\n") else line + "\n")
if not found:
lines.append(f"{key}={value}\n")
with open(env_path, "w", encoding="utf-8") as f:
f.writelines(lines)
# 创建模板目录
TEMPLATES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates")
os.makedirs(TEMPLATES_DIR, exist_ok=True)
# 创建日志目录
LOGS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
os.makedirs(LOGS_DIR, exist_ok=True)
# 日志文件路径
COMMAND_LOG_FILE = os.path.join(LOGS_DIR, "command_history.log")
VIDEO_LIST_FILE = os.path.join(LOGS_DIR, "downloaded_videos.json")
# 默认模板
DEFAULT_TEMPLATE = """请将以下文本改写成一篇完整、连贯、专业的文章。
要求:
1. 你是一名资深科技领域编辑,同时具备优秀的文笔,文本转为一篇文章,确保段落清晰,文字连贯,可读性强,必要修改调整段落结构,确保内容具备良好的逻辑性。
2. 添加适当的小标题来组织内容
3. 以markdown格式输出,充分利用标题、列表、引用等格式元素
4. 如果原文有技术内容,确保准确表达并提供必要的解释
原文内容:
{content}
"""
# 创建默认模板文件
DEFAULT_TEMPLATE_PATH = os.path.join(TEMPLATES_DIR, "default.txt")
if not os.path.exists(DEFAULT_TEMPLATE_PATH):
with open(DEFAULT_TEMPLATE_PATH, "w", encoding="utf-8") as f:
f.write(DEFAULT_TEMPLATE)
# 从原始代码导入工具函数
from youtube_transcriber import (
sanitize_filename, translate_text, format_timestamp, log_command,
log_downloaded_video, list_downloaded_videos, download_youtube_video,
download_youtube_audio, extract_audio_from_video, transcribe_audio_to_text,
transcribe_only, create_bilingual_subtitles, embed_subtitles_to_video,
process_local_audio, process_local_video, process_local_videos_batch, summarize_text, TextSummaryComposite,
check_cookies_file, process_youtube_video, show_download_history,
process_youtube_videos_batch, process_local_text, create_template,
list_templates, clean_markdown_formatting, load_template,
is_youtube_playlist_url, process_youtube_playlist, normalize_youtube_video_url
)
# 统一的工作目录与子目录
from paths_config import (
WORKSPACE_DIR,
VIDEOS_DIR,
DOWNLOADS_DIR,
SUBTITLES_DIR,
TRANSCRIPTS_DIR,
SUMMARIES_DIR,
VIDEOS_WITH_SUBTITLES_DIR,
NATIVE_SUBTITLES_DIR,
TWITTER_DOWNLOADS_DIR,
BILIBILI_DOWNLOADS_DIR,
DOUYIN_DOWNLOADS_DIR,
LIVE_DOWNLOADS_DIR,
KOUSHARE_DOWNLOADS_DIR,
DIRECTORY_MAP,
DEFAULT_SUMMARY_DIR,
)
# 自定义URL输入框类,支持右键直接粘贴
class URLLineEdit(QLineEdit):
"""支持右键直接粘贴和鼠标悬停显示视频信息的URL输入框"""
def __init__(self, parent=None):
super().__init__(parent)
self.cookies_file = None
self.hover_timer = QTimer()
self.hover_timer.setSingleShot(True)
self.hover_timer.timeout.connect(self.fetch_video_info)
self.last_url = ""
def set_cookies_file(self, cookies_file):
"""设置cookies文件路径"""
self.cookies_file = cookies_file
def enterEvent(self, event: QEnterEvent):
"""鼠标进入事件"""
super().enterEvent(event)
current_url = self.text().strip()
# 只有当URL是YouTube链接且与上次不同时才获取信息
if (current_url and
('youtube.com/watch' in current_url or 'youtu.be/' in current_url) and
current_url != self.last_url):
# 延迟800ms再获取信息,避免频繁请求
self.hover_timer.start(800)
self.last_url = current_url
def leaveEvent(self, event):
"""鼠标离开事件"""
super().leaveEvent(event)
# 停止计时器
self.hover_timer.stop()
# 清除工具提示
self.setToolTip("")
def fetch_video_info(self):
"""获取视频信息并设置工具提示"""
current_url = self.text().strip()
if not current_url:
return
try:
# 导入必要的函数
from youtube_transcriber import get_youtube_video_title, format_video_tooltip
# 显示加载提示
self.setToolTip("🔄 正在获取视频信息...")
# 获取视频信息
video_info = get_youtube_video_title(current_url, self.cookies_file)
# 格式化并设置工具提示
if video_info:
tooltip_text = format_video_tooltip(video_info)
self.setToolTip(tooltip_text)
else:
self.setToolTip("❌ 无法获取视频信息")
except Exception as e:
self.setToolTip(f"❌ 获取视频信息时出错: {str(e)}")
def textChanged(self, text):
"""文本改变时重置状态"""
super().textChanged(text)
self.last_url = "" # 重置URL缓存
self.setToolTip("") # 清除工具提示
def contextMenuEvent(self, event):
"""重写右键菜单事件"""
# 获取剪贴板内容
clipboard = QApplication.clipboard()
clipboard_text = clipboard.text()
# 如果剪贴板中有内容,智能处理
if clipboard_text:
# 优先检查抖音分享内容,使用智能提取
if '抖音' in clipboard_text or 'douyin' in clipboard_text.lower():
# 尝试使用DouyinUtils智能提取
utils = safe_douyin_utils()
if utils:
try:
# 使用智能解析从分享文本提取链接
extracted_url = utils.parse_share_text(clipboard_text)
if extracted_url:
self.clear()
self.setText(extracted_url)
# 记录是否为用户主页分享,供 WorkerThread 使用
main_win = self.window()
if main_win is not None:
main_win._pending_douyin_url_is_user = utils.is_user_profile_share_text(clipboard_text)
event.accept()
return
except Exception as e:
print(f"[URL输入框] DouyinUtils提取失败: {e}")
# 备用方案:简单正则提取
import re
douyin_pattern = r'https?://[^\s]*douyin\.com[^\s]*'
matches = re.findall(douyin_pattern, clipboard_text)
if matches:
self.clear()
self.setText(matches[0])
event.accept()
return
# 检查是否是简单的直接URL(排除复杂分享文本)
clipboard_lines = clipboard_text.strip().split('\n')
if len(clipboard_lines) == 1 and any(keyword in clipboard_text.lower() for keyword in ['youtube', 'youtu.be', 'twitter.com', 'x.com', 'bilibili', 'tiktok.com', 'koushare.com']):
self.clear()
self.setText(clipboard_text.strip())
event.accept()
return
# 如果剪贴板中没有内容或不像URL,显示标准右键菜单
menu = self.createStandardContextMenu()
# 添加自定义"直接粘贴"动作
if clipboard_text:
menu.addSeparator()
paste_action = QAction("直接粘贴并清空", self)
paste_action.triggered.connect(lambda: self.paste_and_clear(clipboard_text))
menu.addAction(paste_action)
menu.exec(event.globalPos())
event.accept()
def paste_and_clear(self, text):
"""粘贴文本并清空原内容"""
self.clear()
self.setText(text.strip())
# 自定义文本编辑框类,支持右键直接粘贴多个URL
class URLTextEdit(QTextEdit):
"""支持右键直接粘贴的多行URL输入框"""
def __init__(self, parent=None):
super().__init__(parent)
def contextMenuEvent(self, event):
"""重写右键菜单事件"""
# 获取剪贴板内容
clipboard = QApplication.clipboard()
clipboard_text = clipboard.text()
# 如果剪贴板中有内容,检查是否包含URL
if clipboard_text:
# 检查是否看起来像包含URL
if any(keyword in clipboard_text.lower() for keyword in ['http', 'youtube', 'youtu.be', 'twitter.com', 'x.com', 'bilibili', 'tiktok.com', 'www.']):
# 如果当前文本框为空,直接粘贴
if not self.toPlainText().strip():
self.clear()
self.setPlainText(clipboard_text.strip())
event.accept()
return
else:
# 如果已有内容,添加到新行
current_text = self.toPlainText().strip()
new_text = current_text + '\n' + clipboard_text.strip()
self.setPlainText(new_text)
event.accept()
return
# 如果剪贴板中没有内容或不像URL,显示标准右键菜单
menu = self.createStandardContextMenu()
# 添加自定义动作
if clipboard_text:
menu.addSeparator()
if not self.toPlainText().strip():
paste_action = QAction("直接粘贴", self)
paste_action.triggered.connect(lambda: self.paste_direct(clipboard_text))
else:
paste_action = QAction("添加到新行", self)
paste_action.triggered.connect(lambda: self.paste_append(clipboard_text))
menu.addAction(paste_action)
clear_paste_action = QAction("清空并粘贴", self)
clear_paste_action.triggered.connect(lambda: self.paste_and_clear_text(clipboard_text))
menu.addAction(clear_paste_action)
menu.exec(event.globalPos())
event.accept()
def paste_direct(self, text):
"""直接粘贴文本"""
self.setPlainText(text.strip())
def paste_append(self, text):
"""添加文本到新行"""
current_text = self.toPlainText().strip()
new_text = current_text + '\n' + text.strip()
self.setPlainText(new_text)
def paste_and_clear_text(self, text):
"""清空并粘贴文本"""
self.clear()
self.setPlainText(text.strip())
# 可折叠的分组框组件
class CollapsibleGroupBox(QWidget):
"""可折叠的分组框组件,用于节省界面空间"""
def __init__(self, title="", parent=None, collapsed=True):
"""
初始化可折叠分组框
:param title: 标题文字
:param parent: 父组件
:param collapsed: 是否默认折叠
"""
super().__init__(parent)
self.is_collapsed = collapsed
# 创建主布局
self.main_layout = QVBoxLayout(self)
self.main_layout.setContentsMargins(0, 0, 0, 2)
self.main_layout.setSpacing(2)
# 创建标题栏容器
self.title_frame = QFrame()
self.title_frame.setFrameShape(QFrame.Shape.NoFrame)
self.title_frame.setFixedHeight(24) # 固定标题栏高度为24像素
self.title_frame.setStyleSheet("""
QFrame {
background-color: #f5f5f5;
border-radius: 0px;
padding: 0px;
}
QFrame:hover {
background-color: #eeeeee;
}
""")
title_layout = QHBoxLayout(self.title_frame)
title_layout.setContentsMargins(4, 0, 4, 0)
title_layout.setSpacing(4)
# 创建蓝色竖线(高度为标题栏的2/3)
blue_line = QFrame()
blue_line.setFixedWidth(3)
blue_line.setFixedHeight(12) # 调整为更短
blue_line.setStyleSheet("background-color: #2196F3; border: none;")
title_layout.addWidget(blue_line)
# 折叠/展开指示器
self.toggle_button = QPushButton()
self.toggle_button.setFixedSize(12, 12)
self.toggle_button.setFlat(True)
self.toggle_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.toggle_button.setStyleSheet("""
QPushButton {
background: transparent;
border: none;
font-size: 10px;
color: #2196F3;
}
""")
self.toggle_button.clicked.connect(self.toggle_collapsed)
self.update_toggle_icon()
# 标题文字
self.title_label = QLabel(title)
self.title_label.setStyleSheet("font-weight: bold; font-size: 11px; color: #333;")
title_layout.addWidget(self.toggle_button)
title_layout.addWidget(self.title_label)
title_layout.addStretch()
# 让整个标题栏可点击
self.title_frame.mousePressEvent = lambda event: self.toggle_collapsed()
# 创建内容容器
self.content_widget = QWidget()
self.content_widget.setStyleSheet("""
QWidget {
background-color: white;
border: 1px solid #e0e0e0;
border-radius: 3px;
}
""")
self.content_layout = QVBoxLayout(self.content_widget)
self.content_layout.setContentsMargins(15, 10, 15, 10)
self.content_layout.setSpacing(8)
# 添加到主布局
self.main_layout.addWidget(self.title_frame)
self.main_layout.addWidget(self.content_widget)
# 设置初始折叠状态
self.content_widget.setVisible(not collapsed)
def update_toggle_icon(self):
"""更新折叠/展开图标"""
if self.is_collapsed:
self.toggle_button.setText("▶") # 折叠状态,显示右箭头
else:
self.toggle_button.setText("▼") # 展开状态,显示下箭头
def toggle_collapsed(self):
"""切换折叠/展开状态"""
self.is_collapsed = not self.is_collapsed
self.content_widget.setVisible(not self.is_collapsed)
self.update_toggle_icon()
def set_collapsed(self, collapsed):
"""设置折叠状态"""
self.is_collapsed = collapsed
self.content_widget.setVisible(not collapsed)
self.update_toggle_icon()
def add_layout(self, layout):
"""添加布局到内容区域"""
self.content_layout.addLayout(layout)
def add_widget(self, widget):
"""添加组件到内容区域"""
self.content_layout.addWidget(widget)
# 工作线程类,用于执行耗时操作
class WorkerThread(QThread):
"""工作线程,用于执行耗时操作,避免界面卡顿"""
update_signal = pyqtSignal(str) # 更新信息信号
progress_signal = pyqtSignal(int) # 进度信号
finished_signal = pyqtSignal(str, bool) # 完成信号,参数:结果路径,是否成功
def __init__(self, task_type, params):
"""
初始化工作线程
:param task_type: 任务类型
:param params: 任务参数
"""
super().__init__()
self.task_type = task_type
self.params = params
self.is_running = True
self.stopped = False
def run(self):
"""执行任务"""
try:
# 根据任务类型执行不同的操作
if not self.stopped and self.task_type == "youtube":
self.process_youtube()
elif not self.stopped and self.task_type == "twitter":
self.process_twitter()
elif not self.stopped and self.task_type == "bilibili":
self.process_bilibili()
elif not self.stopped and self.task_type == "koushare":
self.process_koushare()
elif not self.stopped and self.task_type == "local_audio":
self.process_local_audio()
elif not self.stopped and self.task_type == "local_video":
self.process_local_video()
elif not self.stopped and self.task_type == "local_video_batch":
self.process_local_video_batch()
elif not self.stopped and self.task_type == "local_text":
self.process_local_text()
elif not self.stopped and self.task_type == "batch":
self.process_batch()
except Exception as e:
if not self.stopped: # 只有在非停止状态下才报告错误
import traceback
error_msg = f"执行任务时出错: {str(e)}\n{traceback.format_exc()}"
self.update_signal.emit(error_msg)
self.finished_signal.emit("", False)
def process_youtube(self):
"""处理YouTube视频"""
self.update_signal.emit("开始处理YouTube视频...")
# 从参数中获取值
youtube_url = self.params.get("youtube_url", "")
model = self.params.get("model", None)
api_key = self.params.get("api_key", None)
base_url = self.params.get("base_url", None)
whisper_model_size = self.params.get("whisper_model_size", "medium")
stream = self.params.get("stream", True)
summary_dir = self.params.get("summary_dir", DEFAULT_SUMMARY_DIR)
download_video = self.params.get("download_video", False)
custom_prompt = self.params.get("custom_prompt", None)
template_path = self.params.get("template_path", None)
generate_subtitles = self.params.get("generate_subtitles", False)
translate_to_chinese = self.params.get("translate_to_chinese", True)
embed_subtitles = self.params.get("embed_subtitles", False)
cookies_file = self.params.get("cookies_file", None)
enable_transcription = self.params.get("enable_transcription", True)
generate_article = self.params.get("generate_article", True)
prefer_native_subtitles = self.params.get("prefer_native_subtitles", True)
show_translation_logs = self.params.get("show_translation_logs", True)
# 重定向print输出到信号
original_print = print
def custom_print(*args, **kwargs):
text = " ".join(map(str, args))
self.update_signal.emit(text)
original_print(*args, **kwargs)
# 替换全局print函数
import builtins
builtins.print = custom_print
# 控制翻译日志详细程度
try:
from youtube_transcriber import set_translation_verbose
set_translation_verbose(show_translation_logs)
except Exception:
pass
try:
# 检查是否为抖音URL
if DOUYIN_AVAILABLE and DouyinUtils.validate_url(youtube_url):
self.update_signal.emit(f"检测到抖音视频,开始下载...")
# 使用抖音下载器处理
try:
# 创建下载器
downloader = DouyinDownloader()
# 检查是否为用户主页链接:优先读粘贴时记录的标记,否则展开短链判断
self.update_signal.emit("正在判断链接类型...")
is_user_profile = self.params.get("is_user_profile", False) or DouyinUtils.is_user_profile_url(youtube_url)
if is_user_profile:
self.update_signal.emit("检测到用户主页链接,开始批量下载...")
def user_progress(message, progress):
self.update_signal.emit(f"[{progress}%] {message}")
result = downloader.download_user_videos(youtube_url, progress_callback=user_progress)
if result.get("success"):
s = result.get("successful_count", 0)
f = result.get("failed_count", 0)
self.update_signal.emit(f"✅ 批量下载完成:成功 {s} 个,失败 {f} 个")
self.finished_signal.emit("", True)
else:
self.update_signal.emit(f"❌ 批量下载失败: {result.get('error', '未知错误')}")
self.finished_signal.emit("", False)
return
# 单视频:获取视频信息
self.update_signal.emit("正在获取视频信息...")
video_info = downloader.get_video_info(youtube_url)
if not video_info:
self.update_signal.emit("❌ 无法获取抖音视频信息")
self.update_signal.emit("可能原因:")
self.update_signal.emit("1. 视频链接已失效或被删除")
self.update_signal.emit("2. douyinVd 服务器暂时不可用")
self.update_signal.emit("3. 网络连接问题")
self.update_signal.emit("建议:尝试使用其他抖音链接或稍后重试")
self.finished_signal.emit("抖音视频信息获取失败", False)
return
# 显示视频信息
summary = DouyinUtils.get_video_info_summary(video_info)
self.update_signal.emit(f"视频信息:\n{summary}")
# 下载视频
self.update_signal.emit("开始下载抖音视频...")
def progress_callback(message, progress):
self.update_signal.emit(f"[{progress}%] {message}")
result = downloader.download_video(youtube_url, progress_callback=progress_callback)
if result.get("success"):
downloaded_files = result.get("downloaded_files", [])
if downloaded_files:
video_file = None
for file_info in downloaded_files:
if file_info.get("type") == "video":
video_file = file_info.get("path")
break
if video_file:
self.update_signal.emit(f"✅ 抖音视频下载完成: {video_file}")
# 检查是否需要执行转录和摘要
if enable_transcription or generate_article:
self.process_douyin_transcription_and_summary(
video_file, model, api_key, base_url, whisper_model_size,
stream, summary_dir, custom_prompt, template_path,
generate_subtitles, translate_to_chinese, embed_subtitles,
enable_transcription, generate_article
)
else:
self.finished_signal.emit(video_file, True)
else:
self.update_signal.emit("✅ 抖音视频处理完成")
self.finished_signal.emit("", True)
else:
self.update_signal.emit("✅ 抖音视频处理完成")
self.finished_signal.emit("", True)
else:
error_msg = result.get("error", "未知错误")
self.update_signal.emit(f"❌ 抖音视频下载失败: {error_msg}")
self.finished_signal.emit("", False)
return
except Exception as e:
self.update_signal.emit(f"❌ 抖音视频处理异常: {str(e)}")
self.finished_signal.emit("", False)
return
# 检查是否为播放列表URL
elif is_youtube_playlist_url(youtube_url):
self.update_signal.emit(f"检测到YouTube播放列表,开始批量处理...")
# 调用播放列表处理函数
results = process_youtube_playlist(
youtube_url, model, api_key, base_url, whisper_model_size,
stream, summary_dir, download_video, custom_prompt,
template_path, generate_subtitles, translate_to_chinese,
embed_subtitles, cookies_file, enable_transcription, generate_article,
prefer_native_subtitles
)
if results:
success_count = sum(1 for result in results.values() if result.get("status") == "success")
total_count = len(results)
self.update_signal.emit(f"播放列表处理完成! 成功处理 {success_count}/{total_count} 个视频")
# 返回第一个成功的结果作为主要结果
first_success = None
for result in results.values():
if result.get("status") == "success":
first_success = result.get("summary_path")
break
self.finished_signal.emit(first_success or "", success_count > 0)
else:
self.update_signal.emit("播放列表处理失败,请检查错误信息。")
self.finished_signal.emit("", False)
else:
# 调用原始代码中的处理函数
result = process_youtube_video(
youtube_url, model, api_key, base_url, whisper_model_size,
stream, summary_dir, download_video, custom_prompt,
template_path, generate_subtitles, translate_to_chinese,
embed_subtitles, cookies_file, enable_transcription, generate_article,
prefer_native_subtitles
)