-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart_gui.py
More file actions
864 lines (678 loc) · 30.7 KB
/
start_gui.py
File metadata and controls
864 lines (678 loc) · 30.7 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
import os
import shutil
import webbrowser
import subprocess
import sys
import datetime
import requests
import threading
import io
from urllib.parse import urljoin, urlparse, unquote
from bs4 import BeautifulSoup
from PIL import Image
import openpyxl # <--- ADDED for Excel handling
from openpyxl import Workbook, load_workbook
# Force XCB if on Linux/Unix to avoid Wayland issues
os.environ["QT_QPA_PLATFORM"] = "xcb"
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QTextEdit, QPushButton, QLabel, QTabWidget, QSplitter,
QListWidget, QLineEdit, QMessageBox, QProgressBar, QFileDialog,
QScrollArea, QGridLayout, QFrame, QSizePolicy
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QSize
from PyQt6.QtGui import QFont, QPixmap, QIcon
# --- MOCK IMPORTS FOR RUNNABILITY IF FILES MISSING ---
try:
from get_info_from_rss import get_articles
except ImportError:
# Mock return: list of dicts with 'name' and 'url'
def get_articles(names):
return [{'name': n, 'url': f'http://example.com/{n}'} for n in names]
try:
from autotrans import translate_file
except ImportError:
def translate_file(path): print(f"Translating {path}...")
# -----------------------------------------------------
import os
import datetime
import pandas as pd
from openpyxl import Workbook, load_workbook
class ExcelManager:
def __init__(self, filepath="AI Translations/Master.xlsx"):
self.filepath = filepath
self.headers = [
"Date", "Chinese Name", "English Name (WeChat, 64 limit)",
"English Name (Website, 80 Limit)", "Website Link",
"Translated", "WeChat", "Website"
]
self._ensure_file_exists()
def _ensure_file_exists(self):
"""Creates the directory and file with headers if they don't exist."""
directory = os.path.dirname(self.filepath)
if directory and not os.path.exists(directory):
os.makedirs(directory)
if not os.path.exists(self.filepath):
wb = Workbook()
ws = wb.active
ws.append(self.headers)
wb.save(self.filepath)
def log_new_article(self, chinese_name, url):
"""Adds a new row with 'Awaiting Approval'."""
try:
wb = load_workbook(self.filepath)
ws = wb.active
date_str = datetime.datetime.now().strftime("%Y-%m-%d")
# Simple append is fine for logging new rows
row = [
date_str,
str(chinese_name).strip(),
None,
None,
url,
"Awaiting Approval",
None,
None
]
ws.append(row)
wb.save(self.filepath)
print(f"Logged to Excel: {chinese_name}")
except PermissionError:
print("Error: Could not write to Excel file. Is it open?")
except Exception as e:
print(f"Excel Error: {e}")
def update_to_approved(self, chinese_name):
"""
Updates the status to 'Approved' for the given Chinese Name.
Uses Pandas to find the row (robust text matching) and OpenPyXL to write.
"""
try:
# 1. READ with Pandas to find the correct row index
# This handles Chinese encoding better than iterating cells manually
df = pd.read_excel(self.filepath)
clean_name = str(chinese_name).strip()
# Create a mask to find the row (handle NaNs and whitespace)
# We treat everything as string to ensure safe comparison
mask = df['Chinese Name'].astype(str).str.strip() == clean_name
if not mask.any():
print(f"Could not find entry for '{chinese_name}'")
return
# Get the dataframe index of the first match
df_index = df.index[mask][0]
# 2. WRITE with OpenPyXL using the index found by Pandas
wb = load_workbook(self.filepath)
ws = wb.active
# Calculate Excel Row Number:
# Pandas index starts at 0.
# Excel header is row 1. Data starts at row 2.
# So: Excel Row = Pandas Index + 2
excel_row_num = df_index + 2
# Find the 'Translated' column dynamically
translated_col_idx = None
for col in range(1, ws.max_column + 1):
if ws.cell(row=1, column=col).value == "Translated":
translated_col_idx = col
break
if translated_col_idx:
ws.cell(row=excel_row_num, column=translated_col_idx, value="Approved")
wb.save(self.filepath)
print(f"Updated Excel status to Approved: {chinese_name}")
else:
print("Error: 'Translated' column not found in Excel file.")
except PermissionError:
print("Error: Could not update Excel file. Is it open?")
except Exception as e:
print(f"Excel Update Error: {e}")
# --- EXAMPLE USAGE ---
if __name__ == "__main__":
manager = ExcelManager()
# 1. Test Logging
# manager.log_new_article("测试文章", "http://example.com")
# 2. Test Updating (Using the new Pandas logic)
# manager.update_to_approved("测试文章")
# --- IMAGE DOWNLOADING HELPER FUNCTIONS ---
def sanitize_filename(url_or_name):
if "http" in url_or_name:
parsed = urlparse(url_or_name)
path = unquote(parsed.path)
filename = os.path.basename(path)
else:
filename = url_or_name
if not filename or len(filename) < 3:
filename = "image"
name_part, _ = os.path.splitext(filename)
return "".join(c for c in name_part if c.isalnum() or c in (' ', '-', '_')).strip()
def get_unique_filepath(directory, base_name):
counter = 0
while True:
suffix = f"_{counter}" if counter > 0 else ""
filename = f"{base_name}{suffix}.png"
filepath = os.path.join(directory, filename)
if not os.path.exists(filepath):
return filepath
counter += 1
def download_images_from_soup(soup, article_url, folder_name):
base_dir = "AI Translations/temp_images"
if not os.path.exists(base_dir):
os.makedirs(base_dir)
safe_folder_name = sanitize_filename(folder_name)
save_dir = os.path.join(base_dir, safe_folder_name)
os.makedirs(save_dir, exist_ok=True)
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
}
img_tags = soup.find_all('img')
print(f" [Images] Found {len(img_tags)} images for '{folder_name}'")
for img in img_tags:
img_url = img.get('data-src') or img.get('data-original') or img.get('src')
if not img_url:
continue
full_url = urljoin(article_url, img_url)
try:
img_headers = headers.copy()
img_headers['Referer'] = article_url
img_resp = requests.get(full_url, headers=img_headers, timeout=10)
img_data = io.BytesIO(img_resp.content)
pil_img = Image.open(img_data)
if pil_img.width < 50 or pil_img.height < 50:
continue
original_name_clean = sanitize_filename(full_url)
save_path = get_unique_filepath(save_dir, original_name_clean)
pil_img = pil_img.convert("RGB")
pil_img.save(save_path, "PNG")
except Exception as e:
continue
# --- COMBINED SCRAPING FUNCTION ---
def process_url_and_download_images(url):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
"Accept-Language": "en-US,en;q=0.9",
}
try:
response = requests.get(url, headers=headers, timeout=15)
response.raise_for_status()
response.encoding = response.apparent_encoding
soup = BeautifulSoup(response.content, 'html.parser')
for element in soup(['script', 'style', 'header', 'footer', 'nav', 'noscript']):
element.decompose()
text = soup.get_text(separator='\n', strip=True)
lines = text.splitlines()
non_empty_lines = [line for line in lines if line.strip()]
folder_name = "Unknown_Article"
if non_empty_lines:
folder_name = non_empty_lines[0][:100]
else:
folder_name = sanitize_filename(url)
try:
download_images_from_soup(soup, url, folder_name)
except Exception as img_e:
print(f"Error downloading images for {url}: {img_e}")
return text
except Exception as e:
return f"Error accessing {url}: {e}"
# --- WORKER THREAD ---
class ScraperThread(QThread):
finished = pyqtSignal(list)
error = pyqtSignal(str)
def __init__(self, raw_text):
super().__init__()
self.raw_text = raw_text
self.excel_manager = ExcelManager() # Initialize Excel Manager
def run(self):
try:
chinese_names = [line.strip() for line in self.raw_text.splitlines() if line.strip()]
print(f"Processing names: {chinese_names}")
# Expecting get_articles to return list of dicts: [{'name': '...', 'url': '...'}, ...]
title_url_pairs = get_articles(chinese_names)
scraped_data = []
for item in title_url_pairs:
url = item.get("url")
# Try to get the original search name, fallback to title or Unknown
original_name = item.get("name", item.get("chinese_name"))
if not url:
continue
# --- EXCEL LOGGING (Start) ---
self.excel_manager.log_new_article(original_name, url)
# -----------------------------
full_text = process_url_and_download_images(url)
lines = full_text.splitlines()
non_empty_lines = [line for line in lines if line.strip()]
if non_empty_lines:
first_line = non_empty_lines[0]
body = "\n".join(non_empty_lines)
else:
first_line = url
body = full_text
scraped_data.append({
'list_display': first_line[:50] + "..." if len(first_line) > 50 else first_line,
'title': first_line,
'body': body,
'url': url,
'original_search_term': original_name # Store this to update Excel later
})
self.finished.emit(scraped_data)
except Exception as e:
self.error.emit(str(e))
# --- NEW IMAGE SELECTOR TAB CLASS ---
class ImageSelectorTab(QWidget):
def __init__(self):
super().__init__()
self.temp_base_dir = "AI Translations/temp_images"
self.final_base_dir = "AI Translations/Images"
self.current_folder_path = None
self.current_image_path = None
self.init_ui()
self.refresh_folders()
def init_ui(self):
main_layout = QHBoxLayout(self)
# --- Left Side: Folder Selector ---
left_layout = QVBoxLayout()
left_layout.addWidget(QLabel("Select Article Folder:"))
self.folder_list = QListWidget()
self.folder_list.setFixedWidth(250)
self.folder_list.itemClicked.connect(self.on_folder_selected)
left_layout.addWidget(self.folder_list)
self.btn_refresh = QPushButton("Refresh List")
self.btn_refresh.clicked.connect(self.refresh_folders)
left_layout.addWidget(self.btn_refresh)
main_layout.addLayout(left_layout)
# --- Right Side: Image Viewer & Gallery ---
right_layout = QVBoxLayout()
# 1. Top Half: Large Image Viewer
self.image_viewer = QLabel("Select an image from the gallery below")
self.image_viewer.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.image_viewer.setStyleSheet("background-color: #f0f0f0; border: 1px solid #ccc;")
self.image_viewer.setMinimumHeight(300)
right_layout.addWidget(self.image_viewer, stretch=2)
# 2. Middle: Controls
control_layout = QHBoxLayout()
self.lbl_selected_info = QLabel("No image selected")
control_layout.addWidget(self.lbl_selected_info)
control_layout.addStretch()
self.btn_skip = QPushButton("Skip / Delete Folder")
self.btn_skip.setStyleSheet("background-color: #d9534f; color: white;")
self.btn_skip.clicked.connect(self.skip_folder)
control_layout.addWidget(self.btn_skip)
self.btn_save = QPushButton("Save Image")
self.btn_save.setStyleSheet("background-color: #5cb85c; color: white;")
self.btn_save.clicked.connect(self.save_image)
control_layout.addWidget(self.btn_save)
right_layout.addLayout(control_layout)
# 3. Bottom Half: Gallery
right_layout.addWidget(QLabel("Gallery (Click to Preview):"))
self.scroll_area = QScrollArea()
self.scroll_area.setWidgetResizable(True)
self.scroll_area.setMinimumHeight(200)
self.gallery_widget = QWidget()
self.gallery_layout = QGridLayout(self.gallery_widget)
self.gallery_layout.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)
self.scroll_area.setWidget(self.gallery_widget)
right_layout.addWidget(self.scroll_area, stretch=1)
main_layout.addLayout(right_layout)
def refresh_folders(self):
self.folder_list.clear()
self.clear_gallery()
self.image_viewer.clear()
self.image_viewer.setText("Select an image from the gallery below")
self.current_folder_path = None
self.current_image_path = None
if not os.path.exists(self.temp_base_dir):
return
folders = [f for f in os.listdir(self.temp_base_dir)
if os.path.isdir(os.path.join(self.temp_base_dir, f))]
for folder in sorted(folders):
self.folder_list.addItem(folder)
def on_folder_selected(self, item):
folder_name = item.text()
self.current_folder_path = os.path.join(self.temp_base_dir, folder_name)
self.load_gallery(self.current_folder_path)
def clear_gallery(self):
while self.gallery_layout.count():
item = self.gallery_layout.takeAt(0)
widget = item.widget()
if widget:
widget.deleteLater()
def load_gallery(self, folder_path):
self.clear_gallery()
self.current_image_path = None
self.image_viewer.setText("Select an image below")
images = [f for f in os.listdir(folder_path)
if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
if not images:
self.image_viewer.setText("No images found in this folder.")
return
row, col = 0, 0
max_cols = 5
for img_name in images:
full_path = os.path.join(folder_path, img_name)
btn = QPushButton()
btn.setFixedSize(100, 100)
btn.setIconSize(QSize(90, 90))
pixmap = QPixmap(full_path)
if not pixmap.isNull():
btn.setIcon(QIcon(pixmap))
btn.setToolTip(img_name)
btn.clicked.connect(lambda checked, path=full_path: self.display_large_image(path))
self.gallery_layout.addWidget(btn, row, col)
col += 1
if col >= max_cols:
col = 0
row += 1
def display_large_image(self, image_path):
self.current_image_path = image_path
self.lbl_selected_info.setText(f"Selected: {os.path.basename(image_path)}")
pixmap = QPixmap(image_path)
if not pixmap.isNull():
w = self.image_viewer.width()
h = self.image_viewer.height()
scaled_pixmap = pixmap.scaled(w, h, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
self.image_viewer.setPixmap(scaled_pixmap)
else:
self.image_viewer.setText("Error loading image")
def save_image(self):
if not self.current_folder_path:
QMessageBox.warning(self, "Warning", "No folder selected.")
return
if not self.current_image_path:
QMessageBox.warning(self, "Warning", "No image selected. Please click an image in the gallery.")
return
if not os.path.exists(self.final_base_dir):
os.makedirs(self.final_base_dir)
folder_name = os.path.basename(self.current_folder_path)
dest_filename = f"{folder_name}.png"
dest_path = os.path.join(self.final_base_dir, dest_filename)
try:
shutil.copy2(self.current_image_path, dest_path)
shutil.rmtree(self.current_folder_path)
self.refresh_folders()
except Exception as e:
QMessageBox.critical(self, "Error", f"Failed to save or delete:\n{e}")
def skip_folder(self):
if not self.current_folder_path:
QMessageBox.warning(self, "Warning", "No folder selected.")
return
confirm = QMessageBox.question(self, "Confirm Skip",
"Are you sure you want to delete this folder without saving an image?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
if confirm == QMessageBox.StandardButton.Yes:
try:
shutil.rmtree(self.current_folder_path)
self.refresh_folders()
except Exception as e:
QMessageBox.critical(self, "Error", f"Failed to delete folder:\n{e}")
# --- MAIN GUI CLASS ---
class ArticleApp(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Article Scraper & Editor")
self.resize(1200, 850)
self.articles_data = []
self.current_index = -1
self.excel_manager = ExcelManager() # Initialize Excel Manager for Main Thread
self.apply_styles()
main_widget = QWidget()
self.setCentralWidget(main_widget)
layout = QVBoxLayout(main_widget)
# Tabs
self.tabs = QTabWidget()
self.tabs.setStyleSheet("QTabBar::tab { height: 40px; width: 150px; font-size: 14px; }")
layout.addWidget(self.tabs)
# Tab 1: Input
self.tab_input = QWidget()
self.setup_input_tab()
self.tabs.addTab(self.tab_input, "Input Chinese Names")
# Tab 2: Editor
self.tab_editor = QWidget()
self.setup_editor_tab()
self.tabs.addTab(self.tab_editor, "Editor")
self.tabs.setTabEnabled(1, False)
# Tab 3: Image Selector
self.tab_images = ImageSelectorTab()
self.tabs.addTab(self.tab_images, "Image Selector")
# Tab 4: File Viewer
self.tab_viewer = QWidget()
self.setup_file_viewer_tab()
self.tabs.addTab(self.tab_viewer, "File Viewer")
def apply_styles(self):
style = """
QLabel { font-size: 16px; font-weight: bold; padding: 5px; }
QPushButton {
font-size: 16px; padding: 12px;
background-color: #E0E0E0; border: 1px solid #A0A0A0; border-radius: 4px;
}
QPushButton:hover { background-color: #D0D0D0; }
QTextEdit, QLineEdit { font-size: 14px; padding: 5px; border: 1px solid #CCCCCC; }
QListWidget { font-size: 14px; }
QListWidget::item { padding: 8px; border-bottom: 1px solid #EEEEEE; }
QListWidget::item:selected { background-color: #0078D7; color: white; }
"""
self.setStyleSheet(style)
def setup_input_tab(self):
layout = QVBoxLayout(self.tab_input)
layout.setSpacing(15)
lbl = QLabel("Enter text below (separate items with new lines):")
layout.addWidget(lbl)
self.input_text = QTextEdit()
self.input_text.setFontPointSize(14)
layout.addWidget(self.input_text)
self.process_btn = QPushButton("Get Content")
self.process_btn.setCursor(Qt.CursorShape.PointingHandCursor)
self.process_btn.setMinimumHeight(60)
self.process_btn.clicked.connect(self.start_processing)
layout.addWidget(self.process_btn)
self.progress_bar = QProgressBar()
self.progress_bar.setFixedHeight(20)
self.progress_bar.setRange(0, 0)
self.progress_bar.hide()
layout.addWidget(self.progress_bar)
def setup_editor_tab(self):
layout = QVBoxLayout(self.tab_editor)
splitter = QSplitter(Qt.Orientation.Horizontal)
splitter.setHandleWidth(10)
layout.addWidget(splitter)
# -- Left Side: Article List --
left_widget = QWidget()
left_layout = QVBoxLayout(left_widget)
left_layout.setContentsMargins(0, 0, 5, 0)
left_layout.addWidget(QLabel("Select Article:"))
self.article_list = QListWidget()
self.article_list.currentRowChanged.connect(self.on_article_select)
left_layout.addWidget(self.article_list)
left_widget.setMinimumWidth(300)
splitter.addWidget(left_widget)
# -- Right Side: Editor --
right_widget = QWidget()
right_layout = QVBoxLayout(right_widget)
right_layout.setContentsMargins(10, 0, 0, 0)
right_layout.setSpacing(10)
# --- Button: Open in Browser ---
self.btn_open_link = QPushButton("Open Original Link in Browser ↗")
self.btn_open_link.setCursor(Qt.CursorShape.PointingHandCursor)
self.btn_open_link.setStyleSheet("""
QPushButton {
background-color: #f0f8ff; border: 1px solid #0078D7; color: #0078D7;
}
QPushButton:hover { background-color: #e6f2ff; }
""")
self.btn_open_link.clicked.connect(self.open_browser_link)
right_layout.addWidget(self.btn_open_link)
# -------------------------------
right_layout.addWidget(QLabel("Edit Title:"))
self.title_edit = QLineEdit()
self.title_edit.setMinimumHeight(40)
self.title_edit.textEdited.connect(self.save_temp_state)
right_layout.addWidget(self.title_edit)
right_layout.addWidget(QLabel("Edit Body Text:"))
self.body_edit = QTextEdit()
self.body_edit.setFontPointSize(14)
self.body_edit.textChanged.connect(self.save_temp_state)
right_layout.addWidget(self.body_edit)
save_btn = QPushButton("Save All to File (.txt)")
save_btn.setStyleSheet("""
QPushButton {
background-color: #4CAF50; color: white; font-weight: bold;
font-size: 16px; padding: 15px;
}
QPushButton:hover { background-color: #45a049; }
""")
save_btn.setCursor(Qt.CursorShape.PointingHandCursor)
save_btn.clicked.connect(self.save_to_file)
right_layout.addWidget(save_btn)
splitter.addWidget(right_widget)
splitter.setStretchFactor(1, 1)
def open_browser_link(self):
"""Opens the URL of the currently selected article."""
if self.current_index < 0 or self.current_index >= len(self.articles_data):
QMessageBox.warning(self, "No Selection", "Please select an article first.")
return
url = self.articles_data[self.current_index].get('url')
if not url:
QMessageBox.information(self, "No URL", "This article does not have a valid URL.")
return
if not url.startswith(('http://', 'https://')):
url = 'http://' + url
if sys.platform.startswith('linux'):
try:
subprocess.Popen(['xdg-open', url],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
return
except Exception as e:
print(f"xdg-open failed: {e}, falling back to webbrowser...")
try:
webbrowser.open(url)
except Exception as e:
QMessageBox.critical(self, "Error", f"Failed to open browser: {e}")
def setup_file_viewer_tab(self):
layout = QVBoxLayout(self.tab_viewer)
layout.setSpacing(15)
# Top Bar: File Selection
top_bar = QHBoxLayout()
self.btn_select_file = QPushButton("Select .txt File")
self.btn_select_file.setCursor(Qt.CursorShape.PointingHandCursor)
self.btn_select_file.clicked.connect(self.open_file_dialog)
top_bar.addWidget(self.btn_select_file)
self.lbl_current_file = QLabel("No file selected")
self.lbl_current_file.setStyleSheet("color: #555; font-weight: normal;")
top_bar.addWidget(self.lbl_current_file)
top_bar.addStretch()
layout.addLayout(top_bar)
# Preview Area
layout.addWidget(QLabel("File Preview:"))
self.file_preview = QTextEdit()
self.file_preview.setReadOnly(True)
self.file_preview.setFontPointSize(14)
self.file_preview.setPlaceholderText("File contents will appear here...")
layout.addWidget(self.file_preview)
# Bottom Bar: Actions
self.btn_print_console = QPushButton("Translate")
self.btn_print_console.setCursor(Qt.CursorShape.PointingHandCursor)
self.btn_print_console.setStyleSheet("""
QPushButton {
background-color: #008CBA; color: white; font-weight: bold;
font-size: 16px; padding: 15px;
}
QPushButton:hover { background-color: #007B9E; }
""")
self.btn_print_console.clicked.connect(self.translate_file)
layout.addWidget(self.btn_print_console)
def open_file_dialog(self):
file_name, _ = QFileDialog.getOpenFileName(
self,
"Open Text File",
os.getcwd(),
"Text Files (*.txt);;All Files (*)"
)
if file_name:
self.lbl_current_file.setText(file_name)
try:
with open(file_name, 'r', encoding='utf-8') as f:
content = f.read()
self.file_preview.setPlainText(content)
except Exception as e:
QMessageBox.critical(self, "Error", f"Could not read file:\n{e}")
def translate_file(self):
content = self.file_preview.toPlainText()
if not content:
QMessageBox.warning(self, "Empty", "No content to print. Select a file first.")
return
translate_file(self.lbl_current_file.text())
def start_processing(self):
raw_text = self.input_text.toPlainText()
if not raw_text.strip():
QMessageBox.warning(self, "Warning", "Please enter some text first.")
return
self.process_btn.setEnabled(False)
self.input_text.setEnabled(False)
self.progress_bar.show()
self.thread = ScraperThread(raw_text)
self.thread.finished.connect(self.on_processing_finished)
self.thread.error.connect(self.on_processing_error)
self.thread.start()
def on_processing_finished(self, data):
self.articles_data = data
self.progress_bar.hide()
self.process_btn.setEnabled(True)
self.input_text.setEnabled(True)
self.article_list.clear()
for item in self.articles_data:
self.article_list.addItem(item['list_display'])
self.tabs.setTabEnabled(1, True)
self.tabs.setCurrentIndex(1)
if self.articles_data:
self.article_list.setCurrentRow(0)
self.tab_images.refresh_folders()
def on_processing_error(self, error_msg):
self.progress_bar.hide()
self.process_btn.setEnabled(True)
self.input_text.setEnabled(True)
QMessageBox.critical(self, "Error", f"An error occurred:\n{error_msg}")
def on_article_select(self, index):
if index < 0 or index >= len(self.articles_data):
return
self.title_edit.blockSignals(True)
self.body_edit.blockSignals(True)
self.current_index = index
data = self.articles_data[index]
self.title_edit.setText(data['title'])
self.body_edit.setPlainText(data['body'])
self.title_edit.blockSignals(False)
self.body_edit.blockSignals(False)
def save_temp_state(self):
if self.current_index >= 0:
self.articles_data[self.current_index]['title'] = self.title_edit.text()
self.articles_data[self.current_index]['body'] = self.body_edit.toPlainText()
def save_to_file(self):
self.save_temp_state()
date_str = datetime.datetime.now().strftime("%Y-%m-%d")
if not os.path.exists("AI Translations"):
os.makedirs("AI Translations")
filename = f"AI Translations/{date_str}.txt"
try:
with open(filename, "w", encoding="utf-8") as f:
for article in self.articles_data:
stripped_body = article['body'].rstrip()
f.write(article['title'] + "\n")
f.write(stripped_body + "\n")
f.write("\n")
# --- EXCEL UPDATE (Start) ---
# Update status to 'Approved' for all saved articles
try:
for article in self.articles_data:
original_name = article.get('original_search_term')
if original_name and original_name != "Unknown":
self.excel_manager.update_to_approved(original_name)
except Exception as excel_e:
print(f"Failed to update Excel status: {excel_e}")
# ----------------------------
QMessageBox.information(self, "Success", f"Saved to {filename}\nExcel updated.")
except Exception as e:
QMessageBox.critical(self, "Error Saving", str(e))
if __name__ == "__main__":
app = QApplication(sys.argv)
default_font = QFont()
default_font.setPointSize(12)
app.setFont(default_font)
window = ArticleApp()
window.show()
sys.exit(app.exec())