-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcurrent_app.py
More file actions
1922 lines (1495 loc) · 70.5 KB
/
current_app.py
File metadata and controls
1922 lines (1495 loc) · 70.5 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
import os
import sys
import time
import json
import schedule
import requests
from bs4 import BeautifulSoup
from PyQt5.QtWidgets import (QApplication, QMainWindow, QLabel, QVBoxLayout, QPushButton, QWidget, QScrollArea)
from pystray import Icon, MenuItem, Menu
from PIL import Image
import win32com.client
import os
import json
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
# conda activate scrath_new
# === CONFIGURATION ===
CONFIG_FILE = 'config.json'
CACHE_FILE = 'cache.json'
# Load configuration
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'r') as f:
CONFIG = json.load(f)
else:
CONFIG = {"keywords": []}
# === MODULES ===
from modules.xiv_scrath import fetch_arxiv, fetch_biorxiv_medrxiv,fetch_huggingface
from modules.nature_series import fetch_nature_series,download_pdf
from modules.science_series import fetch_science
from utils.functions import generate_wordclouds, load_all_cache
from utils.recommendation import get_recommendations
#=== 处理nature系列期刊 ===
# 映射 journal_name 到期刊缩写
JOURNAL_MAPPING = {
'nature_biotechnology': 'nbt',
'nature_methods': 'nmeth',
'nature_machine_intelligence': 'natmachintell',
'nature': 'nature',
'nature_computer_science': 'natcomputsci',
'nature_communications': 'ncomms'
}
FAVORITES_FILE = 'favorites.json'
from PyQt5.QtCore import QThreadPool
from PyQt5.QtCore import Qt
import os
import json
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QVBoxLayout, QPushButton, QLabel, QScrollArea, QWidget, QMenu, QAction, QMessageBox
)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QPoint
from PyQt5.QtGui import QCursor
from PyQt5.QtWidgets import QMenu, QAction, QVBoxLayout, QWidget, QPushButton, QTextBrowser, QMainWindow
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget
import io
from PyQt5.QtCore import QThread, pyqtSignal, QTimer
import matplotlib.pyplot as plt
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import QBuffer, QIODevice
from PyQt5.QtWidgets import QGraphicsView, QGraphicsScene, QGraphicsPixmapItem, QVBoxLayout, QScrollArea, QWidget
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QPainter
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QPushButton, QMainWindow, QGraphicsView, QGraphicsScene, QGraphicsPixmapItem, QScrollArea, QWidget, QTextBrowser, QTextEdit, QLineEdit
import webbrowser
from threading import Lock
from PyQt5.QtWidgets import QInputDialog
from PyQt5.QtGui import QIcon
from utils.functions import generate_citation_plot,generate_github_stars_plot,generate_source_distribution
# === GUI ===
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# Apply a global stylesheet for the application
self.setStyleSheet("""
QMainWindow {
background-color: #f5f5f5;
}
QPushButton {
background-color: #0078d7;
color: white;
font-size: 16px;
border-radius: 5px;
padding: 8px 16px;
}
QPushButton:hover {
background-color: #005a9e;
}
QTextBrowser {
background-color: #ffffff;
color: #333333;
font-family: Arial, sans-serif;
font-size: 14px;
border: 1px solid #cccccc;
border-radius: 5px;
padding: 8px;
}
QLabel {
font-size: 16px;
color: #333333;
}
QScrollArea {
border: none;
}
""")
self.setWindowTitle("Article_taste")
# 设置窗口图标
self.setWindowIcon(QIcon('achat.png'))
self.setGeometry(100, 100, 2000, 1200)
self.favorites = self.load_favorites()
# 初始化聊天历史记录(用于多轮对话)
self.chat_history_messages = [] # 存储格式: [{"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]
self.current_chat_session_id = None # 当前聊天会话ID(用于保存)
# 创建主布局
main_layout = QHBoxLayout()
#layout默认在左边
button_scroll = QScrollArea()
button_scroll.setWidgetResizable(True)
# button_scroll.setStyleSheet("background-color: #f5f5f5; border: none;")
button_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) # 需要时显示滚动条
button_scroll.setMaximumHeight(600) # 增加高度限制,确保能看到更多按钮
button_scroll.setFixedWidth(300) # 设置固定宽度
button_container = QWidget()
layout = QVBoxLayout(button_container)
collections_rightoflayout = QVBoxLayout()
layout2 = QVBoxLayout()
# Buttons
# 创建arxiv与关键信息网站
self.arxiv_lock = Lock()
self.arxiv_button = QPushButton("ArXiv")
self.arxiv_button.clicked.connect(lambda: self.start_fetch_arxiv())
layout.addWidget(self.arxiv_button)
# self.huggingface_button = QPushButton("HuggingFace")
# self.huggingface_button.clicked.connect(lambda: self.start_fetch_huggingface())
# layout.addWidget(self.huggingface_button)
# 创建nature系列按钮
self.nbt_lock = Lock()
self.nbt_button = QPushButton("Nature Biotechnology")
self.nbt_button.clicked.connect(lambda: self.start_fetch('nature_biotechnology'))
layout.addWidget(self.nbt_button)
self.nmd_lock = Lock()
self.nmeth_button = QPushButton("Nature Methods")
self.nmeth_button.clicked.connect(lambda: self.start_fetch('nature_methods'))
layout.addWidget(self.nmeth_button)
self.nmachinetell_lock = Lock()
self.nmachintell_button = QPushButton("Nature Machine Intelligence")
self.nmachintell_button.clicked.connect(lambda: self.start_fetch('nature_machine_intelligence'))
layout.addWidget(self.nmachintell_button)
self.na_lock = Lock()
self.nature_button = QPushButton("Nature")
self.nature_button.clicked.connect(lambda: self.start_fetch('nature'))
layout.addWidget(self.nature_button)
self.ncomputersci_lock = Lock()
self.ncomputersci_button = QPushButton("Nature Computer Science")
self.ncomputersci_button.clicked.connect(lambda: self.start_fetch('nature_computer_science'))
layout.addWidget(self.ncomputersci_button)
self.ncomms_lock = Lock()
self.ncomms_button = QPushButton("Nature Communications")
self.ncomms_button.clicked.connect(lambda: self.start_fetch('nature_communications'))
layout.addWidget(self.ncomms_button)
#bioarxiv
self.bioarxiv_lock = Lock()
self.bioarxiv_button = QPushButton("Bioarxiv")
self.bioarxiv_button.clicked.connect(lambda: self.start_fetch_bioarxiv())
layout.addWidget(self.bioarxiv_button)
#medarxiv
self.medarxiv_lock = Lock()
self.medarxiv_button = QPushButton("Medarxiv")
self.medarxiv_button.clicked.connect(lambda: self.start_fetch_medarxiv())
layout.addWidget(self.medarxiv_button)
self.download_button = QPushButton("Download_papers_withhighlight")
self.download_button.clicked.connect(self.download)
layout.addWidget(self.download_button)
#science
self.science_lock = Lock()
self.science_button = QPushButton("Science")
self.science_button.clicked.connect(lambda: self.start_fetch_science())
layout.addWidget(self.science_button)
#cell
self.cell_lock = Lock()
self.cell_button = QPushButton("Cell")
self.cell_button.clicked.connect(lambda: self.start_fetch_cell())
layout.addWidget(self.cell_button)
#github
self.github_lock = Lock() # 添加锁
self.github_button = QPushButton("GitHub Search")
self.github_button.clicked.connect(self.start_fetch_github)
layout.addWidget(self.github_button)
#scholar
self.scholar_lock = Lock()
self.scholar_button = QPushButton("Google Scholar")
self.scholar_button.clicked.connect(self.start_fetch_scholar)
layout.addWidget(self.scholar_button)
self.update_button = QPushButton("更新")
self.update_button.clicked.connect(self.clear_cache)
layout.addWidget(self.update_button)
# ❤️ 收藏夹按钮
self.favorites_button = QPushButton("📁 查看收藏夹")
self.favorites_button.clicked.connect(self.show_favorites)
layout.addWidget(self.favorites_button)
# 🔥 新按钮触发词云生成
self.wordcloud_button = QPushButton("生成词云")
self.wordcloud_button.clicked.connect(self.start_generate_wordcloud)
layout.addWidget(self.wordcloud_button)
# 添加可视化按钮
self.vis_lock = Lock() # 添加可视化锁
self.visualization_button = QPushButton("引用量分布")
self.visualization_button.clicked.connect(self.show_citations_plot)
layout.addWidget(self.visualization_button)
self.github_vis_button = QPushButton("GitHub Stars分布")
self.github_vis_button.clicked.connect(self.show_github_plot)
layout.addWidget(self.github_vis_button)
self.source_vis_button = QPushButton("文章来源分布")
self.source_vis_button.clicked.connect(self.show_source_distribution)
layout.addWidget(self.source_vis_button)
# 推荐系统按钮
self.recommend_lock = Lock()
self.recommend_button = QPushButton("智能推荐")
self.recommend_button.clicked.connect(lambda: self.start_recommendation('auto'))
layout.addWidget(self.recommend_button)
self.recommend_keyword_button = QPushButton("推荐(关键词)")
self.recommend_keyword_button.clicked.connect(lambda: self.start_recommendation('keyword'))
layout.addWidget(self.recommend_keyword_button)
self.recommend_embedding_button = QPushButton("推荐(语义)")
self.recommend_embedding_button.clicked.connect(lambda: self.start_recommendation('embedding'))
layout.addWidget(self.recommend_embedding_button)
self.recommend_agent_button = QPushButton("推荐(AI)")
self.recommend_agent_button.clicked.connect(lambda: self.start_recommendation('agent'))
layout.addWidget(self.recommend_agent_button)
layout.addStretch()
button_scroll.setWidget(button_container)
# 用于展示自己所关注的重要网站
# 首先再创造一个layout,使得展示的网站在按钮区域的右边,充分利用空间
# 创建一个新的布局
layout_firstrow = QHBoxLayout()
# 创建一个标签用于展示网站
self.hotsite_area = QTextBrowser()
self.hotsite_area.setOpenExternalLinks(True)
# 添加网站信息内容
hotsite_html = self.load_hotsite_info()
self.hotsite_area.setHtml(hotsite_html)
self.hotsite_area.setOpenExternalLinks(True)
layout_firstrow.addWidget(button_scroll)
layout_firstrow.addWidget(self.hotsite_area)
# 设置样式
layout_firstrow.setContentsMargins(0, 0, 0, 0) # 去掉边距
layout_firstrow.setSpacing(0) # 去掉间距
#创建容器来包含布局
layout_firstrow_container = QWidget()
layout_firstrow_container.setLayout(layout_firstrow)
layout_firstrow_container.setFixedHeight(300) # 设置固定高度
# 添加按钮到布局
# layout2.addWidget(button_scroll)
layout2.addWidget(layout_firstrow_container)
# 结果展示区域
self.result_area = QTextBrowser()
self.result_area.setOpenExternalLinks(True)
self.result_area.setTextInteractionFlags(Qt.TextBrowserInteraction)
self.result_area.setContextMenuPolicy(Qt.CustomContextMenu)
self.result_area.customContextMenuRequested.connect(self.show_context_menu)
layout2.addWidget(self.result_area)
# 创建调试信息显示区域
self.debug_area = QTextBrowser()
self.debug_area.setMaximumHeight(150) # 限制高度
# 在 __init__ 中设置调试区域样式
self.debug_area.setStyleSheet("""
QTextBrowser {
background-color: #1e1e1e;
color: #dcdcdc;
font-family: Consolas, Monaco, monospace;
font-size: 12px;
border: 1px solid #444444;
border-radius: 5px;
padding: 5px;
}
""")
layout2.addWidget(self.debug_area)
# 设置输出重定向
self.output_redirector = OutputRedirector()
self.output_redirector.outputWritten.connect(self.append_debug_output)
sys.stdout = self.output_redirector
# 创建 QGraphicsView 和 QGraphicsScene
self.graphics_view = QGraphicsView(self)
self.graphics_scene = QGraphicsScene(self)
self.graphics_view.setScene(self.graphics_scene)
self.graphics_view.setRenderHint(QPainter.Antialiasing) # 启用抗锯齿
self.graphics_view.setRenderHint(QPainter.SmoothPixmapTransform) # 平滑缩放
# 创建一个垂直布局来容纳图形视图、聊天区域和会议信息
right_layout = QVBoxLayout()
# 添加图形视图
right_layout.addWidget(self.graphics_view)
# 创建聊天区域
chat_container = QWidget()
chat_layout = QVBoxLayout(chat_container)
chat_layout.setContentsMargins(2, 5, 5, 5) # 减少左边距
chat_layout.setSpacing(5)
# 聊天标题和操作按钮(水平布局)
title_layout = QHBoxLayout()
chat_title = QLabel("小A")
chat_title.setStyleSheet("""
QLabel {
font-size: 16px;
font-weight: bold;
color: #333333;
padding: 5px;
}
""")
title_layout.addWidget(chat_title)
# 新开聊天按钮
self.new_chat_button = QPushButton("新对话")
self.new_chat_button.setFixedWidth(70)
self.new_chat_button.setStyleSheet("""
QPushButton {
background-color: #28a745;
color: white;
font-size: 12px;
border-radius: 5px;
padding: 3px;
}
QPushButton:hover {
background-color: #218838;
}
""")
self.new_chat_button.clicked.connect(self.new_chat_session)
title_layout.addWidget(self.new_chat_button)
# 保存聊天记录按钮
self.save_chat_button = QPushButton("保存")
self.save_chat_button.setFixedWidth(60)
self.save_chat_button.setStyleSheet("""
QPushButton {
background-color: #17a2b8;
color: white;
font-size: 12px;
border-radius: 5px;
padding: 3px;
}
QPushButton:hover {
background-color: #138496;
}
""")
self.save_chat_button.clicked.connect(self.save_chat_history)
title_layout.addWidget(self.save_chat_button)
title_layout.addStretch() # 添加弹性空间
chat_layout.addLayout(title_layout)
# 对话历史显示区域
self.chat_history = QTextBrowser()
self.chat_history.setMaximumHeight(399)
self.chat_history.setStyleSheet("""
QTextBrowser {
background-color: #ffffff;
color: #333333;
font-family: Arial, sans-serif;
font-size: 28px;
border: 1px solid #cccccc;
border-radius: 5px;
padding: 5px 0px 5px 0px !important;
}
""")
# 设置文档边距为0,减少左侧空白
self.chat_history.document().setDocumentMargin(0)
# 设置默认样式表,消除body和html的默认边距
self.chat_history.document().setDefaultStyleSheet("""
body { margin: 0; padding: 0; }
html { margin: 0; padding: 0; }
p { margin: 0; padding: 0; margin-bottom: 10px; }
div { margin: 0; padding: 0; }
""")
self.chat_history.setHtml("<body style='margin: 0; padding: 0;'><p style='color:#666; margin: 0; padding: 0; margin-bottom: 10px;'>我是您的小助手!您可以问我关于文章、期刊、研究等相关问题。</p></body>")
chat_layout.addWidget(self.chat_history)
# 输入区域(水平布局)
input_layout = QHBoxLayout()
# 输入框
self.chat_input = QTextEdit()
self.chat_input.setMaximumHeight(60)
self.chat_input.setPlaceholderText("输入您的问题... (Ctrl+Enter发送)")
self.chat_input.setStyleSheet("""
QTextEdit {
background-color: #ffffff;
color: #333333;
font-family: Arial, sans-serif;
font-size: 28px;
border: 1px solid #cccccc;
border-radius: 5px;
padding: 5px;
}
""")
# 绑定Ctrl+Enter快捷键发送消息
from PyQt5.QtWidgets import QShortcut
from PyQt5.QtGui import QKeySequence
send_shortcut = QShortcut(QKeySequence("Ctrl+Return"), self.chat_input)
send_shortcut.activated.connect(self.send_chat_message)
input_layout.addWidget(self.chat_input)
# 发送按钮
self.send_button = QPushButton("发送")
self.send_button.setFixedWidth(60)
self.send_button.setStyleSheet("""
QPushButton {
background-color: #0078d7;
color: white;
font-size: 14px;
border-radius: 5px;
padding: 5px;
}
QPushButton:hover {
background-color: #005a9e;
}
QPushButton:pressed {
background-color: #004578;
}
""")
self.send_button.clicked.connect(self.send_chat_message)
input_layout.addWidget(self.send_button)
chat_layout.addLayout(input_layout)
# 将聊天区域添加到右侧布局
right_layout.addWidget(chat_container)
# 创建并添加会议信息面板
self.conference_info = QTextBrowser()
self.conference_info.setMaximumHeight(300)
self.conference_info.setStyleSheet("""
QTextBrowser {
background-color: #f8f9fa;
color: #495057;
font-family: Arial, sans-serif;
font-size: 14px;
border: 1px solid #dee2e6;
border-radius: 5px;
padding: 8px;
}
a {
color: #0066cc;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
""")
# 添加会议信息内容
conference_html = self.load_conference_info()
self.conference_info.setHtml(conference_html)
self.conference_info.setOpenExternalLinks(True)
right_layout.addWidget(self.conference_info)
# 创建一个容器 widget 来持有右侧布局
right_container = QWidget()
right_container.setLayout(right_layout)
# 创建 QScrollArea 并设置容器 widget
self.scroll_area = QScrollArea(self)
self.scroll_area.setWidgetResizable(True)
self.scroll_area.setWidget(right_container)
# 添加左侧布局到主布局
main_layout.addLayout(layout2)
# 添加右侧的 scroll_area 到主布局
main_layout.addWidget(self.scroll_area)
container = QWidget()
container.setLayout(main_layout)
self.setCentralWidget(container)
print("Welcome to Article_taste!")
#读取配置信息
def load_conference_info(self):
if os.path.exists('config.json'):
conference_info = json.load(open('config.json', 'r', encoding='utf-8'))['conference']
conference_info = [f"<p>• <a href='{info[1]}' style='font-size: 18px;'>{info[0]}</a></p>" for info in conference_info]
conference_info = "<h3 style='color: #333; margin-bottom: 10px;'>Conference board</h3><div style='margin-left: 10px;'>" + "".join(conference_info)+ "</div>"
return conference_info
def load_hotsite_info(self):
if os.path.exists('config.json'):
hotsite_info = json.load(open('config.json', 'r', encoding='utf-8'))['important_site']
hotsite_info = [f"<a href='{info[1]}' style='font-size: 18px;color:#332'>{info[0]}</a> <span style='color:#128; font-size: 18px'>|</span> " for info in hotsite_info]
hotsite_info = "<h3 style=' margin-bottom: 5px;'>Hotsite</h3><div style='margin-left: 10px;'>" + "".join(hotsite_info)+ "</div>"
return hotsite_info
#可视化函数
def show_plot(self, file_path):
"""通用显示图表方法"""
pixmap = QPixmap(file_path)
pixmap = pixmap.scaled(1800, 1200, Qt.KeepAspectRatio, Qt.SmoothTransformation)
pixmap_item = QGraphicsPixmapItem(pixmap)
self.graphics_scene.clear()
self.graphics_scene.addItem(pixmap_item)
def show_citations_plot(self):
if self.vis_lock.locked():
print("可视化正在进行中,请稍后...")
return
self.vis_lock.acquire()
print("正在生成引用量分布图...")
def on_vis_complete(file_path):
if file_path and os.path.exists(file_path):
self.show_plot(file_path)
print("引用量分布图生成完成!")
self.vis_lock.release()
self.vis_thread = VisualizationThread('citations')
self.vis_thread.finished.connect(on_vis_complete)
self.vis_thread.start()
def show_github_plot(self):
if self.vis_lock.locked():
print("可视化正在进行中,请稍后...")
return
self.vis_lock.acquire()
print("正在生成GitHub Stars分布图...")
def on_vis_complete(file_path):
if file_path and os.path.exists(file_path):
self.show_plot(file_path)
print("GitHub Stars分布图生成完成!")
self.vis_lock.release()
self.vis_thread = VisualizationThread('github')
self.vis_thread.finished.connect(on_vis_complete)
self.vis_thread.start()
def show_source_distribution(self):
if self.vis_lock.locked():
print("可视化正在进行中,请稍后...")
return
self.vis_lock.acquire()
print("正在生成文章来源分布图...")
def on_vis_complete(file_path):
if file_path and os.path.exists(file_path):
self.show_plot(file_path)
print("文章来源分布图生成完成!")
self.vis_lock.release()
self.vis_thread = VisualizationThread('source')
self.vis_thread.finished.connect(on_vis_complete)
self.vis_thread.start()
# 在 MainWindow 类中添加方法
def start_fetch_scholar(self):
if self.scholar_lock.locked():
print("Scholar 搜索正在进行中,请稍后")
return
# 创建输入对话框
keywords, ok = QInputDialog.getText(
self,
'Google Scholar Search',
'Enter keywords (separate multiple keywords with comma):'
)
if ok and keywords:
self.scholar_lock.acquire()
keywords_list = [k.strip() for k in keywords.split(',')]
print(f"开始搜索 Scholar: {keywords_list}")
def on_fetch_complete(results):
self.show_scholar_results(results) # 使用新的显示函数
print("Scholar 搜索完成!")
self.scholar_lock.release()
self.thread = FetchScholarThread(keywords_list)
self.thread.result_signal.connect(on_fetch_complete)
self.thread.start()
def show_scholar_results(self, results):
highlighted_results = []
for title, link, author_venue, citations in results:
title = insert_changeline(title)
# 创建带有引用数和作者信息的HTML
if any(keyword.lower() in title.lower() for keyword in CONFIG["keywords"]):
result_html = f'''
<div style="margin-bottom: 10px">
<b><a href="{link}" target="_blank" style="color:red;font-size:20px;">{title}</a></b>
<br>
<span style="color:#666;font-size:14px">{author_venue}</span>
<br>
<span style="color:#009688;font-size:14px">引用数: {citations}</span>
</div>
'''
else:
result_html = f'''
<div style="margin-bottom: 10px">
<a href="{link}" target="_blank" style="color:black;font-size:16px;">{title}</a>
<br>
<span style="color:#666;font-size:14px">{author_venue}</span>
<br>
<span style="color:#009688;font-size:14px">引用数: {citations}</span>
</div>
'''
highlighted_results.append(result_html)
self.result_area.setHtml("<br>".join(highlighted_results))
def append_debug_output(self, text):
self.debug_area.append(text.strip())
# 自动滚动到底部
self.debug_area.verticalScrollBar().setValue(
self.debug_area.verticalScrollBar().maximum()
)
def restore_stdout(self):
# 恢复标准输出(在需要时调用)
sys.stdout = sys.__stdout__
def wheelEvent(self, event):
"""实现缩放功能"""
# 获取当前缩放因子
factor = 1.1 if event.angleDelta().y() > 0 else 0.9
# 对 QGraphicsView 进行缩放
# self.graphics_view.scale(factor, factor)
def start_generate_wordcloud(self):
print("正在生成词云,请稍候...") # 显示提示信息
self.wordcloud_thread = WordCloudThread(set_column=3)
self.wordcloud_thread.finished.connect(self.on_wordcloud_finished)
self.wordcloud_thread.start()
def on_wordcloud_finished(self, file_path):
if file_path and os.path.exists(file_path):
# 加载图片
pixmap = QPixmap(file_path)
pixmap = pixmap.scaled(1800, 1200,transformMode=Qt.SmoothTransformation)
# 将图片添加到 QGraphicsScene
pixmap_item = QGraphicsPixmapItem(pixmap)
self.graphics_scene.clear() # 清除旧的图形项
self.graphics_scene.addItem(pixmap_item)
# 聊天相关方法
def send_chat_message(self):
"""发送聊天消息"""
message = self.chat_input.toPlainText().strip()
if not message:
return
message_lower = message.lower()
# 检查是否是推荐请求
is_recommend_request = any(word in message_lower for word in ['推荐', 'recommend', '推荐文章', '相关文章'])
# 显示用户消息
self.append_chat_message("用户", message)
# 将用户消息添加到历史记录
self.chat_history_messages.append({"role": "user", "content": message})
# 清空输入框
self.chat_input.clear()
# 如果是推荐请求,直接触发推荐功能
if is_recommend_request:
# 禁用发送按钮
self.send_button.setEnabled(False)
self.send_button.setText("推荐中...")
# 根据收藏数量自动选择方法
favorites_count = len(self.favorites)
if favorites_count < 3:
method = 'keyword'
elif favorites_count < 10:
method = 'embedding'
else:
method = 'agent'
# 显示AI响应
method_names = {'keyword': '关键词匹配', 'embedding': '语义相似度', 'agent': 'AI智能推荐'}
response_text = f"好的!我将使用{method_names.get(method, '自动选择')}方法为您推荐文章。\n\n根据您当前有{favorites_count}篇收藏,我选择了最适合的推荐方法。\n\n正在为您生成推荐..."
self.append_chat_message("AI助手", response_text)
# 将AI响应添加到历史记录
self.chat_history_messages.append({"role": "assistant", "content": response_text})
# 触发推荐
self.start_recommendation(method)
# 恢复发送按钮
self.send_button.setEnabled(True)
self.send_button.setText("发送")
return
# 禁用发送按钮,防止重复发送
self.send_button.setEnabled(False)
self.send_button.setText("思考中...")
# 启动AI响应线程(传入历史消息)
self.chat_thread = ChatAgentThread(message, self.get_chat_context(), self.chat_history_messages[:-1]) # 传入除当前消息外的历史
self.chat_thread.response_signal.connect(self.on_chat_response)
self.chat_thread.start()
def format_markdown_to_html(self, text):
"""将Markdown格式转换为美观的HTML"""
import re
if not text:
return ""
# 先保护代码块,避免被其他规则处理
code_blocks = []
def save_code_block(match):
code_blocks.append(match.group(0))
return f"__CODE_BLOCK_{len(code_blocks)-1}__"
text = re.sub(r'```[\s\S]*?```', save_code_block, text)
# 保护行内代码
inline_codes = []
def save_inline_code(match):
inline_codes.append(match.group(0))
return f"__INLINE_CODE_{len(inline_codes)-1}__"
text = re.sub(r'`[^`]+`', save_inline_code, text)
# 转义HTML特殊字符
text = text.replace('&', '&').replace('<', '<').replace('>', '>')
# 按行处理
lines = text.split('\n')
result_lines = []
in_ul = False
in_ol = False
for i, line in enumerate(lines):
stripped = line.strip()
# 处理标题(必须在行首)
if re.match(r'^#{1,3}\s+', stripped):
if in_ul:
result_lines.append('</ul>')
in_ul = False
if in_ol:
result_lines.append('</ol>')
in_ol = False
if stripped.startswith('###'):
title_text = re.sub(r'^###\s+', '', stripped)
result_lines.append(f'<h3 style="color: #0078d7; margin: 12px 0 6px 0; font-size: 18px; font-weight: bold;">{title_text}</h3>')
elif stripped.startswith('##'):
title_text = re.sub(r'^##\s+', '', stripped)
result_lines.append(f'<h2 style="color: #005a9e; margin: 14px 0 7px 0; font-size: 20px; font-weight: bold;">{title_text}</h2>')
elif stripped.startswith('#'):
title_text = re.sub(r'^#\s+', '', stripped)
result_lines.append(f'<h1 style="color: #004578; margin: 16px 0 8px 0; font-size: 22px; font-weight: bold;">{title_text}</h1>')
continue
# 处理无序列表
if re.match(r'^[-*]\s+', stripped):
if in_ol:
result_lines.append('</ol>')
in_ol = False
if not in_ul:
result_lines.append('<ul style="margin: 8px 0; padding-left: 25px; list-style-type: disc;">')
in_ul = True
item_text = re.sub(r'^[-*]\s+', '', stripped)
result_lines.append(f'<li style="margin: 4px 0; line-height: 1.5;">{item_text}</li>')
continue
# 处理有序列表
if re.match(r'^\d+\.\s+', stripped):
if in_ul:
result_lines.append('</ul>')
in_ul = False
if not in_ol:
result_lines.append('<ol style="margin: 8px 0; padding-left: 25px;">')
in_ol = True
item_text = re.sub(r'^\d+\.\s+', '', stripped)
result_lines.append(f'<li style="margin: 4px 0; line-height: 1.5;">{item_text}</li>')
continue
# 普通行
if in_ul:
result_lines.append('</ul>')
in_ul = False
if in_ol:
result_lines.append('</ol>')
in_ol = False
if stripped: # 非空行
result_lines.append(line)
else: # 空行作为段落分隔
result_lines.append('<br>')
# 关闭未关闭的列表
if in_ul:
result_lines.append('</ul>')
if in_ol:
result_lines.append('</ol>')
text = '\n'.join(result_lines)
# 处理粗体 **text** 或 __text__
text = re.sub(r'\*\*([^*]+)\*\*', r'<strong style="font-weight: bold; color: #333;">\1</strong>', text)
text = re.sub(r'__([^_]+)__', r'<strong style="font-weight: bold; color: #333;">\1</strong>', text)
# 处理斜体 *text*(不在粗体内部)
text = re.sub(r'(?<!\*)\*([^*\n]+)\*(?!\*)', r'<em style="font-style: italic;">\1</em>', text)
# 恢复代码块
for i, code_block in enumerate(code_blocks):
code_content = code_block.replace('```', '').strip()
text = text.replace(f'__CODE_BLOCK_{i}__',
f'<pre style="background-color: #f5f5f5; padding: 12px; border-radius: 5px; overflow-x: auto; margin: 8px 0; border-left: 3px solid #0078d7;"><code style="font-family: monospace; font-size: 13px;">{code_content}</code></pre>')
# 恢复行内代码
for i, inline_code in enumerate(inline_codes):
code_content = inline_code.replace('`', '')
text = text.replace(f'__INLINE_CODE_{i}__',
f'<code style="background-color: #f5f5f5; padding: 2px 6px; border-radius: 3px; font-family: monospace; font-size: 13px; color: #d63384;">{code_content}</code>')
# 处理换行:将连续换行转换为段落分隔
text = re.sub(r'<br>\s*<br>+', '</p><p style="margin: 8px 0; line-height: 1.6;">', text)
text = '<p style="margin: 5px 0; line-height: 1.6;">' + text + '</p>'
# 清理多余的段落标签和换行
text = re.sub(r'</p>\s*<p[^>]*>', '<br><br>', text)
text = re.sub(r'^<p[^>]*>', '', text)
text = re.sub(r'</p>$', '', text)
text = re.sub(r'<br>\s*<br>\s*<br>+', '<br><br>', text) # 限制连续换行
return text
def append_chat_message(self, sender, message):
"""添加聊天消息到历史记录"""
timestamp = datetime.now().strftime("%H:%M:%S")
# 格式化消息内容(如果是AI助手,转换Markdown)
if sender == "AI助手":
formatted_message = self.format_markdown_to_html(message)
else:
# 用户消息也做基本格式化(转义HTML)
formatted_message = message.replace('&', '&').replace('<', '<').replace('>', '>').replace('\n', '<br>')
if sender == "用户":
html = f'''<div style="margin: 0; padding: 0; margin-bottom: 15px; text-align: left;">
<div style="background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%); color: #333; padding: 12px 16px; border-radius: 12px; display: inline-block; max-width: 85%; word-wrap: break-word; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<div style="line-height: 1.6;">{formatted_message}</div>
</div>
<div style="margin-top: 4px;">
<span style="color: #999; font-size: 11px;">{timestamp}</span>
</div>
</div>'''
else:
html = f'''<div style="margin: 0; padding: 0; margin-bottom: 15px; text-align: left;">
<div style="background: linear-gradient(135deg, #f5f5f5 0%, #eeeeee 100%); color: #333; padding: 12px 16px; border-radius: 12px; display: inline-block; max-width: 85%; word-wrap: break-word; box-shadow: 0 2px 4px rgba(0,0,0,0.1); border-left: 4px solid #0078d7;">
<div style="margin-bottom: 6px;">
<b style="color: #0078d7; font-size: 14px;"> {sender}</b>
</div>
<div style="line-height: 1.6; color: #333;">{formatted_message}</div>
</div>
<div style="margin-top: 4px;">
<span style="color: #999; font-size: 11px;">{timestamp}</span>
</div>
</div>'''
# 使用moveCursor和insertHtml代替setHtml,避免重新解析整个HTML
cursor = self.chat_history.textCursor()
cursor.movePosition(cursor.End)
cursor.insertHtml(html)
# 自动滚动到底部
self.chat_history.verticalScrollBar().setValue(
self.chat_history.verticalScrollBar().maximum()
)
def on_chat_response(self, response):
"""处理AI响应"""