-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodern_gui.py
More file actions
1305 lines (1045 loc) · 51.6 KB
/
modern_gui.py
File metadata and controls
1305 lines (1045 loc) · 51.6 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 sys
import os
import requests
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QFileDialog, QMessageBox, QFrame
from PySide6.QtCore import Qt, Signal, QThread, QUrl
from PySide6.QtGui import QIcon, QPixmap, QDesktopServices
from qfluentwidgets import (
FluentWindow,
SubtitleLabel, BodyLabel, CaptionLabel, StrongBodyLabel,
SearchLineEdit, ComboBox, PrimaryPushButton, HyperlinkButton, PushButton,
CardWidget, ScrollArea, setTheme, Theme,
FlowLayout, IconWidget, ImageLabel,
NavigationItemPosition, ToolButton, Pivot, SegmentedWidget,
InfoBar, InfoBarPosition, RoundMenu, Action
)
from qfluentwidgets import FluentIcon as FIF
from qframelesswindow import FramelessWindow, StandardTitleBar
# Add Matplotlib backend for Qt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from recommender import InternshipRecommender
from user_context import UserManager
def resource_path(relative_path):
"""Get absolute resource path for source run and PyInstaller run."""
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, relative_path)
APP_ICON_PATH = resource_path("app_icon.ico")
if not os.path.exists(APP_ICON_PATH):
APP_ICON_PATH = resource_path("app_icon.svg")
class ScrollableCanvas(FigureCanvas):
"""Custom Canvas that propagates wheel events to parent for scrolling."""
def wheelEvent(self, event):
event.ignore()
class JobCard(CardWidget):
cardClicked = Signal(dict)
bookmarkToggled = Signal(dict, bool) # job_data, is_bookmarked
def __init__(self, job_data, user_manager, parent=None):
super().__init__(parent)
self.job_data = job_data
self.user_manager = user_manager
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setFixedHeight(120) # Make it a bit compact
layout = QVBoxLayout(self)
layout.setContentsMargins(16, 16, 16, 16)
# Header: Job Title + Wage + Bookmark
header_layout = QHBoxLayout()
title_label = SubtitleLabel("Title", self)
title_label.setText(job_data.get('job_title', 'Unknown'))
# Truncate title if too long
font_metrics = title_label.fontMetrics()
elided_title = font_metrics.elidedText(title_label.text(), Qt.TextElideMode.ElideRight, 300)
title_label.setText(elided_title)
# Bookmark Button
self.bookmark_btn = ToolButton(FIF.HEART, self)
self.bookmark_btn.setFixedSize(32, 32)
# Check initial state
# Logic is handled by update_bookmark_icon
self.update_bookmark_icon()
self.bookmark_btn.clicked.connect(self.toggle_bookmark)
wage_label = BodyLabel("Wage", self)
wage_label.setText(job_data.get('wage', 'Negotiable'))
wage_label.setStyleSheet("color: #009faa; font-weight: bold;") # Teal color for wage
header_layout.addWidget(title_label)
header_layout.addWidget(self.bookmark_btn) # Add bookmark button
header_layout.addStretch()
header_layout.addWidget(wage_label)
# Sub-header: Company + City
sub_layout = QHBoxLayout()
# Use icon for company
company_layout = QHBoxLayout()
company_layout.setSpacing(4)
# FIF usage fix: use IconWidget or QLabel with pixmap from .icon()
company_icon_widget = IconWidget(FIF.MARKET)
company_icon_widget.setFixedSize(16, 16)
company_name = BodyLabel("Company", self)
company_name.setText(job_data.get('com_fullname', 'Unknown Company'))
company_layout.addWidget(company_icon_widget)
company_layout.addWidget(company_name)
city_label = CaptionLabel("City", self)
city_label.setText(job_data.get('city', 'Unknown City'))
sub_layout.addLayout(company_layout)
sub_layout.addStretch()
sub_layout.addWidget(city_label)
# Footer: Tags
tags_text = f"Tags: {job_data.get('tag', '')} | Industry: {job_data.get('industry', '')}"
tags_label = CaptionLabel("Tags", self)
tags_label.setText(tags_text)
tags_label.setTextColor("#808080", "#808080") # Custom gray color
layout.addLayout(header_layout)
layout.addLayout(sub_layout)
layout.addStretch() # Push everything up
layout.addWidget(tags_label)
def update_bookmark_icon(self):
job_id = self.job_data.get('job_id')
if job_id and self.user_manager.is_bookmarked(job_id):
self.bookmark_btn.setIcon(FIF.HEART)
self.bookmark_btn.setStyleSheet("ToolButton { color: #FF4D4F; background-color: #333333; border-radius: 4px; }")
else:
self.bookmark_btn.setIcon(FIF.HEART)
self.bookmark_btn.setStyleSheet("ToolButton { color: #cccccc; background-color: transparent; }")
def toggle_bookmark(self):
job_id = self.job_data.get('job_id')
if job_id:
is_saved = self.user_manager.toggle_bookmark(job_id)
self.update_bookmark_icon()
self.bookmarkToggled.emit(self.job_data, is_saved)
def mousePressEvent(self, event):
# Only left click opens details. Right click is reserved for context menu.
if event.button() != Qt.MouseButton.LeftButton:
super().mousePressEvent(event)
return
# Prevent card click when clicking bookmark button
click_pos = event.position().toPoint()
if self.childAt(click_pos) == self.bookmark_btn:
super().mousePressEvent(event)
return
self.cardClicked.emit(self.job_data)
super().mousePressEvent(event)
class ImageLoader(QThread):
loaded = Signal(QPixmap)
def __init__(self, url):
super().__init__()
self.url = url
def run(self):
try:
if not self.url or not isinstance(self.url, str) or not self.url.startswith('http'):
return
# Add headers and disable verify to handle some company sites with strict anti-bot or bad certs
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}
response = requests.get(self.url, timeout=5, headers=headers, verify=False)
if response.status_code == 200:
pixmap = QPixmap()
pixmap.loadFromData(response.content)
if not pixmap.isNull():
self.loaded.emit(pixmap)
except Exception as e:
print(f"Image load error: {e}")
class DetailWindow(FramelessWindow):
def __init__(self, job_data, user_manager, on_bookmark_changed=None, app_icon=None):
super().__init__()
self.user_manager = user_manager
self.job_data = job_data
self.on_bookmark_changed = on_bookmark_changed
self.setWindowTitle(job_data.get('job_title'))
self.resize(900, 700) # Slightly larger
if app_icon is not None and not app_icon.isNull():
self.setWindowIcon(app_icon)
# Center Window
desktop = QApplication.primaryScreen().availableGeometry()
w, h = desktop.width(), desktop.height()
self.move(w//2 - self.width()//2, h//2 - self.height()//2)
# Use StandardTitleBar for modern look
self.setTitleBar(StandardTitleBar(self))
self.titleBar.raise_()
# Main container with distinct background
self.setStyleSheet("DetailWindow { background-color: #272727; }")
# Content Layout
self.main_layout = QVBoxLayout(self)
self.main_layout.setContentsMargins(0, 32, 0, 0) # Top margin for title bar
# Scroll Area for the whole page content
self.page_scroll = ScrollArea(self)
self.page_scroll.setWidgetResizable(True)
self.page_scroll.setStyleSheet("background-color: transparent; border: none;")
self.page_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.content_widget = QWidget()
self.content_layout = QVBoxLayout(self.content_widget)
self.content_layout.setContentsMargins(30, 20, 30, 30)
self.content_layout.setSpacing(20)
# --- 1. Header Section ---
header_container = QWidget()
header_layout = QHBoxLayout(header_container)
header_layout.setContentsMargins(0, 0, 0, 0)
# Company Logo
self.logo_label = ImageLabel()
self.logo_label.setFixedSize(80, 80)
self.logo_label.setBorderRadius(8, 8, 8, 8)
self.logo_label.setStyleSheet("background-color: #333333; border-radius: 8px;") # Placeholder
# Load Logo
logo_url = job_data.get('com_logo')
if logo_url:
self.loader = ImageLoader(logo_url)
self.loader.loaded.connect(self.set_logo)
self.loader.start()
# Title & Company Info
title_info = QVBoxLayout()
title_info.setSpacing(5)
job_title = SubtitleLabel("Title", self)
job_title.setText(job_data.get('job_title'))
job_title.setStyleSheet("font-size: 24px; font-weight: bold; color: #569cd6;")
company_name = BodyLabel("Company", self)
company_name.setText(job_data.get('com_fullname'))
company_name.setStyleSheet("font-size: 16px; color: #cccccc;")
title_info.addWidget(job_title)
title_info.addWidget(company_name)
title_info.addStretch()
# Wage & Action Buttons
action_layout = QVBoxLayout()
action_layout.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop)
wage_lbl = SubtitleLabel(job_data.get('wage', 'Negotiable'), self)
wage_lbl.setStyleSheet("color: #009faa; font-weight: bold; font-size: 20px;")
btns_layout = QHBoxLayout()
# Check websites
com_site = job_data.get('com_website')
if com_site and isinstance(com_site, str) and (com_site.startswith('http') or com_site.startswith('www')):
btn_site = HyperlinkButton(url=com_site, text="公司官网", parent=self)
btns_layout.addWidget(btn_site)
# Internship Link (com_links per user request)
intern_link = job_data.get('com_links')
if intern_link and isinstance(intern_link, str) and intern_link.startswith('http'):
# Apply Button
btn_link = PrimaryPushButton("投递/查看详情", self)
btn_link.setFixedWidth(120)
btn_link.clicked.connect(self.apply_job)
btns_layout.addWidget(btn_link)
# Bookmark
self.btn_bookmark = ToolButton(FIF.HEART, self)
self.btn_bookmark.setFixedSize(32, 32)
self.btn_bookmark.clicked.connect(self.toggle_bookmark)
self.update_bookmark_state()
btns_layout.addWidget(self.btn_bookmark)
action_layout.addWidget(wage_lbl, 0, Qt.AlignmentFlag.AlignRight)
action_layout.addLayout(btns_layout)
header_layout.addWidget(self.logo_label)
header_layout.addSpacing(15)
header_layout.addLayout(title_info, 1) # Stretch factor 1
header_layout.addLayout(action_layout)
self.content_layout.addWidget(header_container)
# --- 2. Meta Info Tags (Flow Layout) ---
meta_card = CardWidget(self)
meta_layout = FlowLayout(meta_card)
meta_layout.setContentsMargins(16, 16, 16, 16)
def create_badge(icon_enum, text, label=""):
if not text: return None
container = QWidget()
l = QHBoxLayout(container)
l.setContentsMargins(0, 0, 16, 0) # Spacing between items
l.setSpacing(6)
ic = IconWidget(icon_enum)
ic.setFixedSize(16, 16)
txt_lbl = BodyLabel(f"{text}", container)
l.addWidget(ic)
l.addWidget(txt_lbl)
return container
# Add all metadata
meta_items = [
(FIF.GLOBE, job_data.get('city'), "City"),
(FIF.EDUCATION, job_data.get('job_academic'), "Academic"),
(FIF.DATE_TIME, job_data.get('day_per_week'), "Days/Week"),
(FIF.UPDATE, job_data.get('time_span'), "Duration"),
(FIF.PEOPLE, str(job_data.get('num_employee')) + "人", "Scale"),
(FIF.RINGER, job_data.get('job_deadline'), "Deadline"), # Deadline DATE_TIME
(FIF.MARKET, job_data.get('industry'), "Industry"),
(FIF.HISTORY, job_data.get('est_date'), "Established"),
(FIF.ALBUM, job_data.get('auth_capital'), "Capital"), # Added auth_capital
# Newly added fields
(FIF.CERTIFICATE, job_data.get('com_class'), "Type"), # Company Type
(FIF.PIN, job_data.get('com_location'), "Address"), # Exact Location
(FIF.TAG, job_data.get('tag'), "Category"), # Job Tag
(FIF.STOP_WATCH, job_data.get('released_time'), "Released"), # Released Time
]
for icon, val, _ in meta_items:
w = create_badge(icon, str(val) if val else "")
if w: meta_layout.addWidget(w)
self.content_layout.addWidget(meta_card)
# --- 3. Welfare Tags ---
welfare_raw = job_data.get('com_welfare')
if welfare_raw:
# Parse string list like "['a', 'b']"
try:
import ast
welfare_list = ast.literal_eval(welfare_raw)
if isinstance(welfare_list, list) and len(welfare_list) > 0:
welfare_layout = FlowLayout()
welfare_layout.setContentsMargins(0, 0, 0, 0)
welfare_layout.setSpacing(8)
for tag in welfare_list:
# Simple pill/badge style
pill = QLabel(tag)
pill.setStyleSheet("""
background-color: #3e3e42;
color: #ffffff;
padding: 4px 12px;
border-radius: 12px;
border: 1px solid #555;
""")
welfare_layout.addWidget(pill)
self.content_layout.addLayout(welfare_layout)
except:
pass # Ignore parse errors
# --- 4. Description Sections ---
def add_section(title, text):
if not text: return
self.content_layout.addSpacing(10)
lbl = StrongBodyLabel(title, self)
lbl.setStyleSheet("font-size: 18px; color: #ffffff;")
self.content_layout.addWidget(lbl)
desc_card = CardWidget(self)
desc_l = QVBoxLayout(desc_card)
desc_body = BodyLabel(text, self)
desc_body.setWordWrap(True)
desc_body.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
desc_body.setStyleSheet("font-size: 14px; line-height: 1.6; color: #d4d4d4;")
desc_l.addWidget(desc_body)
self.content_layout.addWidget(desc_card)
# Job Detail
clean_detail = job_data.get('job_detail', '')
add_section("职位详情", clean_detail)
# Company Intro (Prioritize detailed_intro, fallback to com_intro)
intro = job_data.get('detailed_intro')
if not intro:
intro = job_data.get('com_intro')
add_section("公司介绍", intro)
self.content_layout.addStretch()
# Set Scroll content
self.page_scroll.setWidget(self.content_widget)
self.main_layout.addWidget(self.page_scroll)
def apply_job(self):
"""Open link and track application"""
intern_link = self.job_data.get('com_links')
if intern_link:
QDesktopServices.openUrl(QUrl(intern_link))
# Track
job_id = self.job_data.get('job_id')
if job_id:
self.user_manager.add_application(job_id)
# Provide feedback?
# No easy toast in base Qt, maybe just console log or update UI
def toggle_bookmark(self):
job_id = self.job_data.get('job_id')
if job_id:
is_saved = self.user_manager.toggle_bookmark(job_id)
self.update_bookmark_state()
if callable(self.on_bookmark_changed):
self.on_bookmark_changed(self.job_data, is_saved)
def update_bookmark_state(self):
job_id = self.job_data.get('job_id')
if job_id and self.user_manager.is_bookmarked(job_id):
self.btn_bookmark.setStyleSheet("ToolButton { color: #FF4D4F; background-color: #444; border-radius: 4px; }")
else:
self.btn_bookmark.setStyleSheet("ToolButton { color: #ccc; background-color: transparent; }")
def set_logo(self, pixmap):
scaled = pixmap.scaled(80, 80, Qt.AspectRatioMode.KeepAspectRatioByExpanding, Qt.TransformationMode.SmoothTransformation)
self.logo_label.setImage(scaled)
class AboutWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("aboutInterface")
# Main layout for the widget
self.main_layout = QVBoxLayout(self)
self.main_layout.setContentsMargins(0, 0, 0, 0)
# Scroll Area to ensure it fits small screens
self.scroll = ScrollArea(self)
self.scroll.setWidgetResizable(True)
self.scroll.setStyleSheet("background-color: transparent; border: none;")
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.container = QWidget()
self.vBoxLayout = QVBoxLayout(self.container)
self.vBoxLayout.setContentsMargins(36, 36, 36, 36)
self.vBoxLayout.setSpacing(20)
# --- 1. Header Card ---
self.headerCard = CardWidget(self.container)
self.headerLayout = QVBoxLayout(self.headerCard)
self.headerLayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.headerLayout.setContentsMargins(0, 40, 0, 40)
self.headerLayout.setSpacing(16)
# App Icon
self.appIcon = IconWidget(FIF.EDUCATION)
self.appIcon.setFixedSize(80, 80)
# Title
self.appTitle = SubtitleLabel("InternHub", self.headerCard)
self.appTitle.setStyleSheet("font-size: 32px; font-weight: bold;")
# Version
self.appVer = CaptionLabel("版本 v0.1.0 Beta", self.headerCard)
self.appVer.setTextColor("#aaaaaa", "#aaaaaa")
title_row = QHBoxLayout()
title_row.setAlignment(Qt.AlignmentFlag.AlignCenter)
title_row.setSpacing(12)
title_row.addWidget(self.appIcon)
title_row.addWidget(self.appTitle)
self.headerLayout.addLayout(title_row)
self.headerLayout.addWidget(self.appVer, 0, Qt.AlignmentFlag.AlignHCenter)
# --- 2. Introduction Card ---
self.introCard = CardWidget(self.container)
self.introLayout = QVBoxLayout(self.introCard)
self.introLayout.setContentsMargins(24, 24, 24, 24)
self.introLayout.setSpacing(12)
self.introTitle = StrongBodyLabel("关于项目", self.introCard)
self.introTitle.setStyleSheet("font-size: 18px;")
self.introText = BodyLabel(
"InternHub 是一款基于 Python 与 PySide6 (QFluentWidgets) 开发的现代化实习岗位推荐系统。\n"
"本项目利用 TF-IDF 与余弦相似度算法,挖掘数据中的潜在价值,为大学生精准匹配最适合的实习机会。\n"
"我们致力于提供简洁、高效、美观的用户体验,帮助你在求职路上快人一步。",
self.introCard
)
self.introText.setWordWrap(True)
self.introText.setStyleSheet("color: #cccccc; line-height: 1.6; font-size: 14px;")
self.introLayout.addWidget(self.introTitle)
self.introLayout.addWidget(self.introText)
# --- 3. Developer & Links Card ---
self.devCard = CardWidget(self.container)
self.devLayout = QVBoxLayout(self.devCard)
self.devLayout.setContentsMargins(24, 24, 24, 24)
self.devLayout.setSpacing(16)
self.devBlockTitle = StrongBodyLabel("开发者信息", self.devCard)
self.devBlockTitle.setStyleSheet("font-size: 18px;")
# Developer Row
devRow = QHBoxLayout()
# Developer Avatar
devAvatar = ImageLabel(resource_path("developer.jpg"), self.devCard)
devAvatar.setFixedSize(60, 60)
devAvatar.setBorderRadius(30, 30, 30, 30)
devAvatar.setScaledContents(True)
devInfoLayout = QVBoxLayout() # Vertical layout for name and role
devInfoLayout.setSpacing(4)
devName = BodyLabel("MathCraft", self.devCard)
devName.setStyleSheet("font-size: 16px; font-weight: bold;")
devRole = CaptionLabel("全栈开发工程师 & 算法工程师", self.devCard)
devRole.setTextColor("#aaaaaa", "#aaaaaa")
devInfoLayout.addWidget(devName)
devInfoLayout.addWidget(devRole)
devRow.addWidget(devAvatar)
devRow.addSpacing(16)
devRow.addLayout(devInfoLayout)
devRow.addStretch()
# Link Row
linkRow = QHBoxLayout()
linkIcon = IconWidget(FIF.GITHUB)
linkIcon.setFixedSize(16, 16) # GITHUB icon usually exists
linkBtn = HyperlinkButton("https://github.com/SakuraMathcraft/InternHub", "GitHub 项目主页", self.devCard)
linkRow.addWidget(linkIcon)
linkRow.addWidget(linkBtn)
linkRow.addStretch()
self.devLayout.addWidget(self.devBlockTitle)
self.devLayout.addLayout(devRow)
self.devLayout.addLayout(linkRow)
# Assemble
self.vBoxLayout.addWidget(self.headerCard)
self.vBoxLayout.addWidget(self.introCard)
self.vBoxLayout.addWidget(self.devCard)
self.vBoxLayout.addStretch()
self.scroll.setWidget(self.container)
self.main_layout.addWidget(self.scroll)
class ProfileWidget(QWidget):
"""
User Profile & Resume Parsing & Context Recommendation
"""
def __init__(self, user_manager, recommender, main_window, parent=None):
super().__init__(parent)
self.setObjectName("profileInterface")
self.user_manager = user_manager
self.recommender = recommender
self.main_window = main_window # To trigger tab switch or search
self.scroll = ScrollArea(self)
self.scroll.setWidgetResizable(True)
self.scroll.setStyleSheet("background-color: transparent; border: none;")
self.container = QWidget()
self.vbox = QVBoxLayout(self.container)
self.vbox.setContentsMargins(36, 36, 36, 36)
self.vbox.setSpacing(20)
self.init_header()
self.init_resume_section()
self.init_context_recommend()
self.vbox.addStretch()
self.scroll.setWidget(self.container)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.scroll)
def init_header(self):
title = SubtitleLabel("我的简历 & 个人画像", self.container)
title.setStyleSheet("font-size: 24px; font-weight: bold;")
self.vbox.addWidget(title)
def init_resume_section(self):
card = CardWidget(self.container)
layout = QVBoxLayout(card)
layout.setContentsMargins(24, 24, 24, 24)
# Title
t = StrongBodyLabel("简历解析", card)
layout.addWidget(t)
# Upload Button
btn_layout = QHBoxLayout()
self.upload_btn = PrimaryPushButton("上传 PDF 简历", card)
self.upload_btn.setIcon(FIF.ADD)
self.upload_btn.clicked.connect(self.upload_resume)
btn_layout.addWidget(self.upload_btn)
btn_layout.addStretch()
layout.addLayout(btn_layout)
# Extracted Info Display
self.info_label = BodyLabel("暂无简历信息,请上传简历。", card)
self.info_label.setWordWrap(True)
self.info_label.setStyleSheet("color: #cccccc; margin-top: 10px;")
layout.addWidget(self.info_label)
self.update_info_display()
self.vbox.addWidget(card)
def update_info_display(self):
p = self.user_manager.profile
if p.get('resume_text'):
txt = f"<b>学校:</b> {p.get('school', '未识别')}<br>" \
f"<b>邮箱:</b> {p.get('email', '未识别')}<br>" \
f"<b>电话:</b> {p.get('phone', '未识别')}<br>" \
f"<b>技能标签:</b> {', '.join(p.get('skills', []))}"
self.info_label.setText(txt)
else:
self.info_label.setText("暂无简历信息,请上传简历以解锁个性化推荐。")
def upload_resume(self):
file_path, _ = QFileDialog.getOpenFileName(self, "选择简历 PDF", "", "PDF Files (*.pdf)")
if file_path:
self.upload_btn.setText("解析中...")
self.upload_btn.setEnabled(False)
QApplication.processEvents()
success, msg = self.user_manager.parse_resume(file_path)
self.upload_btn.setText("上传 PDF 简历")
self.upload_btn.setEnabled(True)
if success:
self.update_info_display()
InfoBar.success(
title='成功',
content="简历解析成功!技能标签已提取。",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP_RIGHT,
duration=2000,
parent=self
)
else:
InfoBar.error(
title='识别失败',
content=f"简历解析失败: {msg}",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP_RIGHT,
duration=2000,
parent=self
)
def init_context_recommend(self):
card = CardWidget(self.container)
layout = QVBoxLayout(card)
layout.setContentsMargins(24, 24, 24, 24)
t = StrongBodyLabel("智能匹配推荐 (Context-Aware)", card)
sub = CaptionLabel("根据您的简历技能和教育背景,直接匹配最适合的岗位,无需搜索。", card)
sub.setTextColor("#aaaaaa", "#aaaaaa")
layout.addWidget(t)
layout.addWidget(sub)
self.rec_btn = PrimaryPushButton("一键获取个性化推荐", card)
self.rec_btn.setIcon(FIF.SEARCH)
self.rec_btn.clicked.connect(self.trigger_recommendation)
layout.addWidget(self.rec_btn)
self.vbox.addWidget(card)
def trigger_recommendation(self):
# Construct query from profile
query = self.user_manager.get_recommendation_query()
if not query:
QMessageBox.warning(self, "提示", "请先上传简历,或补充个人信息。")
return
# Switch to Home and search
# We need to access MainWindow methods.
# This is a bit coupled but fine for MVP.
# Assuming MainWindow has perform_search(query)
self.main_window.switch_to_home_and_search(query)
class ApplicationsWidget(QWidget):
"""
Manages Bookmarks and Application History
"""
def __init__(self, user_manager, recommender, main_window, parent=None):
super().__init__(parent)
self.setObjectName("applicationsInterface")
self.user_manager = user_manager
self.recommender = recommender
self.main_window = main_window # To open details
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 20, 20, 0)
title = SubtitleLabel("投递管理 & 收藏", self)
layout.addWidget(title)
# Pivot (Tabs)
self.pivot = Pivot(self)
self.pivot.addItem("bookmarks", "我的收藏")
self.pivot.addItem("applied", "投递记录")
self.pivot.setCurrentItem("bookmarks")
self.pivot.currentItemChanged.connect(lambda k: self.refresh_list())
layout.addWidget(self.pivot)
# Scroll Area for list
self.scroll = ScrollArea(self)
self.scroll.setWidgetResizable(True)
self.scroll.setStyleSheet("background-color: transparent; border: none;")
self.container = QWidget()
self.list_layout = QVBoxLayout(self.container)
self.list_layout.setAlignment(Qt.AlignmentFlag.AlignTop)
self.list_layout.setSpacing(10)
self.scroll.setWidget(self.container)
layout.addWidget(self.scroll)
# self.refresh_list() # Moved to showEvent
def showEvent(self, event):
self.refresh_list()
super().showEvent(event)
def _is_bookmark_mode(self):
current_item = self.pivot.currentItem()
if current_item is None:
return True
mode_text = current_item.text()
return mode_text in ("我的收藏", "bookmarks")
def show_bookmark_context_menu(self, job_data, card, pos):
menu = RoundMenu(parent=self)
remove_action = Action(FIF.DELETE, "取消收藏", self)
remove_action.triggered.connect(lambda: self.remove_bookmark(job_data))
menu.addAction(remove_action)
menu.exec(card.mapToGlobal(pos), ani=True)
def remove_bookmark(self, job_data):
job_id = job_data.get('job_id') if isinstance(job_data, dict) else None
if not job_id:
return
if self.user_manager.remove_bookmark(job_id):
self.main_window.on_bookmark_changed(job_data, False, show_tip=False)
InfoBar.success(
title='已取消收藏',
content='岗位已从收藏夹移除',
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP_RIGHT,
duration=1500,
parent=self
)
else:
InfoBar.warning(
title='操作未生效',
content='该岗位不在收藏夹中',
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP_RIGHT,
duration=1500,
parent=self
)
def refresh_list(self):
# Clear list
while self.list_layout.count():
item = self.list_layout.takeAt(0)
if item.widget():
item.widget().deleteLater()
# Get current route key
# In this widget, the current item text is likely "我的收藏" or "bookmarks" depending on initialization
mode_text = self.pivot.currentItem().text()
# Get Job IDs
job_ids = []
# Check against the displayed text
if self._is_bookmark_mode():
job_ids = self.user_manager.bookmarks
else: # applied
job_ids = list(self.user_manager.applications.keys())
# Normalize + de-duplicate IDs while keeping order.
normalized_job_ids = []
seen_ids = set()
for jid in job_ids:
key = str(jid).strip()
if not key or key in seen_ids:
continue
seen_ids.add(key)
normalized_job_ids.append(key)
if not normalized_job_ids:
lbl = BodyLabel("暂无数据", self.container)
lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.list_layout.addWidget(lbl)
return
# Fetch job data from recommender df
# Recommender DF has job_id column now
df = self.recommender.df
if df is None:
return
# Find rows
subset = df[df['job_id'].astype(str).isin(normalized_job_ids)]
subset = subset.drop_duplicates(subset=['job_id'], keep='first')
for _, row in subset.iterrows():
job_data = row.to_dict()
card = JobCard(job_data, self.user_manager)
card.cardClicked.connect(self.main_window.open_detail)
card.bookmarkToggled.connect(self.main_window.on_bookmark_changed)
if self._is_bookmark_mode():
card.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
card.customContextMenuRequested.connect(
lambda pos, jd=job_data, c=card: self.show_bookmark_context_menu(jd, c, pos)
)
# If applied mode, add status label
if not self._is_bookmark_mode():
app_info = self.user_manager.applications.get(str(job_data['job_id'])) or \
self.user_manager.applications.get(job_data['job_id'])
if app_info:
status_lbl = CaptionLabel(f"{app_info['status']} on {app_info['date']}", card)
status_lbl.setStyleSheet("color: #009faa;")
card.layout().addWidget(status_lbl) # Hacky append
self.list_layout.addWidget(card)
class AnalyticsWidget(QWidget):
def __init__(self, recommender, parent=None):
super().__init__(parent)
self.setObjectName("analyticsInterface")
self.recommender = recommender
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 40, 20, 20)
title = SubtitleLabel("岗位数据洞察", self)
title.setStyleSheet("font-size: 24px; font-weight: bold;")
layout.addWidget(title)
self.scroll = ScrollArea()
self.scroll.setWidgetResizable(True)
self.scroll.setStyleSheet("background-color: transparent; border: none;")
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) # Fix syntax
container = QWidget()
self.vbox = QVBoxLayout(container)
self.vbox.setSpacing(20)
self.create_charts()
self.scroll.setWidget(container)
layout.addWidget(self.scroll)
def create_charts(self):
df = self.recommender.df
if df is None or df.empty:
self.vbox.addWidget(BodyLabel("No data available for analysis."))
return
# Enable Chinese font support
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'SimSun']
plt.rcParams['axes.unicode_minus'] = False
# Chart 1: Top 10 Cities
self.add_city_distribution(df)
# Chart 2: Top Industries
self.add_industry_distribution(df)
# Chart 3: Weekly Days Requirement
self.add_days_distribution(df)
def add_plot(self, fig, title_str):
card = CardWidget(self)
l = QVBoxLayout(card)
l.setContentsMargins(24, 24, 24, 24) # More breathable
lbl = StrongBodyLabel(title_str, card)
lbl.setStyleSheet("font-size: 20px; color: #ffffff; margin-bottom: 16px; font-weight: bold;")
l.addWidget(lbl)
# Use ScrollableCanvas instead of FigureCanvas
canvas = ScrollableCanvas(fig)
canvas.setFixedHeight(450) # Higher chart
canvas.setStyleSheet("background-color: transparent;")
l.addWidget(canvas)
self.vbox.addWidget(card)
def _setup_dark_ax(self, ax, title=""):
"""Helper to style axes for enterprise dark theme"""
ax.set_facecolor('none') # Transparent chart bg
# Spines
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_color('#555555')
ax.spines['left'].set_color('#555555')
ax.spines['bottom'].set_linewidth(1.5)
ax.spines['left'].set_linewidth(1.5)
# Ticks
ax.tick_params(axis='x', colors='#cccccc', labelsize=10)
ax.tick_params(axis='y', colors='#cccccc', labelsize=10)
# Grid
ax.grid(axis='y', linestyle='--', alpha=0.3, color='#888888')
def add_city_distribution(self, df):
try:
city_counts = df['city'].value_counts().head(10)
# Use a slightly transparent background for the figure to blend in
fig = Figure(figsize=(8, 5), dpi=100)
fig.patch.set_alpha(0) # Transparent figure background
ax = fig.add_subplot(111)
self._setup_dark_ax(ax)
# Enterprise Blue/Teal Gradient simulation with bar colors
bars = ax.bar(city_counts.index, city_counts.values, width=0.6, color='#009faa', zorder=3)
# Add value labels on top
for rect in bars:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., height + 0.5,
'%d' % int(height),
ha='center', va='bottom', color='#ffffff', fontsize=10, fontweight='bold')
ax.tick_params(axis='x', rotation=30)
fig.tight_layout()
self.add_plot(fig, "热门实习城市 Top 10")
except Exception as e:
print(f"Error creating city chart: {e}")
def add_industry_distribution(self, df):
try:
ind_counts = df['industry'].value_counts().head(5)
fig = Figure(figsize=(8, 5), dpi=100)
fig.patch.set_alpha(0)
ax = fig.add_subplot(111)
# Enterprise Color Palette
colors = ['#0078d4', '#009faa', '#ffaa44', '#b4009e', '#ea4300']
# Donut Chart style
wedges, texts, autotexts = ax.pie(ind_counts, labels=ind_counts.index,
autopct='%1.1f%%',
startangle=140,
colors=colors,
pctdistance=0.85,
textprops=dict(color="w", fontsize=11),
wedgeprops=dict(width=0.4, edgecolor='#272727'))
# Make label text clearer
for t in texts:
t.set_color('#cccccc')
t.set_fontsize(11)
ax.set_facecolor('none')
# Center info? Maybe just total
# ax.text(0, 0, f"Total\n{ind_counts.sum()}", ha='center', va='center', color='white', fontsize=12)
fig.tight_layout()
self.add_plot(fig, "热门行业分布 (Top 5)")
except Exception as e:
print(f"Error creating industry chart: {e}")
def add_days_distribution(self, df):
try:
days_counts = df['day_per_week'].value_counts().sort_index()
fig = Figure(figsize=(8, 5), dpi=100)