Repository navigation
Expand file tree
/
Copy pathgui.py
More file actions
230 lines (197 loc) · 10.2 KB
/
Copy pathgui.py
File metadata and controls
230 lines (197 loc) · 10.2 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
"""Графическое приложение CrossReference для Windows."""
import datetime
import os
import sys
import threading
import sv_ttk
import tkinter as tk
from pathlib import Path
from tkinter import filedialog, messagebox, ttk
# В собранном приложении Chromium хранится рядом с Playwright.
if getattr(sys, "frozen", False):
os.environ.setdefault("PLAYWRIGHT_BROWSERS_PATH", "0")
from main import APP_VERSION, run
class CrossReferenceApp(tk.Tk):
def __init__(self):
super().__init__()
self.title(f"CrossReference v{APP_VERSION}")
self.minsize(720, 560)
sv_ttk.set_theme("light")
self.columnconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
# В собранном приложении папка по умолчанию — рядом с .exe
if getattr(sys, "frozen", False):
app_dir = Path(sys.executable).parent
else:
app_dir = Path.cwd()
self.articles_file = tk.StringVar()
self.output_dir = tk.StringVar(value=str(app_dir / "output"))
self.status = tk.StringVar(value="Выберите файл с артикулами и папку для результатов.")
self.debug_network = tk.BooleanVar(value=False)
self.show_browser = tk.BooleanVar(value=False)
self.current = tk.StringVar(value="—")
self.loaded = tk.StringVar(value="Загружено: —")
self.processed = tk.StringVar(value="Обработано: —")
self._log_file = None
self._build_form()
self._build_status()
self.protocol("WM_DELETE_WINDOW", self._on_close)
def _build_form(self):
frame = ttk.LabelFrame(self, text=f"CrossReference v{APP_VERSION}", padding=16)
frame.grid(row=0, column=0, sticky="ew", padx=16, pady=(16, 8))
frame.columnconfigure(1, weight=1)
ttk.Label(frame, text="Сайт:").grid(row=0, column=0, sticky="w", pady=(0, 12))
site = ttk.Combobox(frame, values=["Noitech"], state="readonly", width=30)
site.current(0)
site.grid(row=0, column=1, columnspan=2, sticky="ew", pady=(0, 12))
ttk.Label(frame, text="Файл с артикулами:").grid(row=1, column=0, sticky="w", pady=6)
ttk.Entry(frame, textvariable=self.articles_file).grid(row=1, column=1, sticky="ew", pady=6)
ttk.Button(frame, text="Обзор…", command=self._choose_articles).grid(row=1, column=2, padx=(8, 0), pady=6)
ttk.Label(frame, text="Папка для сохранения:").grid(row=2, column=0, sticky="w", pady=6)
ttk.Entry(frame, textvariable=self.output_dir).grid(row=2, column=1, sticky="ew", pady=6)
ttk.Button(frame, text="Обзор…", command=self._choose_output).grid(row=2, column=2, padx=(8, 0), pady=6)
self.start_button = ttk.Button(frame, text="Запустить", command=self._start)
self.start_button.grid(row=3, column=1, pady=(16, 0))
ttk.Checkbutton(
frame,
text="Показывать браузер?",
variable=self.show_browser,
).grid(row=4, column=1, sticky="w", pady=(8, 0))
ttk.Checkbutton(
frame,
text="Сохранять API-ответы для отладки",
variable=self.debug_network,
).grid(row=5, column=1, sticky="w", pady=(4, 0))
def _build_status(self):
frame = ttk.LabelFrame(self, text="Статус", padding=16)
frame.grid(row=1, column=0, sticky="nsew", padx=16, pady=(8, 16))
frame.columnconfigure(0, weight=1)
frame.rowconfigure(4, weight=1)
ttk.Label(frame, textvariable=self.status).grid(row=0, column=0, sticky="w")
ttk.Label(frame, textvariable=self.loaded).grid(row=1, column=0, sticky="w", pady=(12, 0))
ttk.Label(frame, textvariable=self.processed).grid(row=2, column=0, sticky="w", pady=(4, 0))
ttk.Label(frame, text="Сейчас:").grid(row=3, column=0, sticky="w", pady=(12, 0))
ttk.Label(frame, textvariable=self.current).grid(row=4, column=0, sticky="nw", pady=(4, 8))
ttk.Label(frame, text="Лог:").grid(row=5, column=0, sticky="w")
self.log = tk.Text(frame, height=8, state="disabled", wrap="word")
self.log.grid(row=6, column=0, sticky="nsew", pady=(4, 0))
frame.rowconfigure(6, weight=1)
def _choose_articles(self):
filename = filedialog.askopenfilename(
title="Выберите файл с артикулами",
filetypes=[
("Поддерживаемые файлы", "*.txt *.xlsx"),
("Текстовые файлы", "*.txt"),
("Excel файлы", "*.xlsx"),
("Все файлы", "*.*"),
],
)
if filename:
self.articles_file.set(filename)
def _choose_output(self):
folder = filedialog.askdirectory(title="Выберите папку для результатов")
if folder:
self.output_dir.set(folder)
def _start(self):
articles = Path(self.articles_file.get())
if not articles.is_file():
messagebox.showerror("Нет файла", "Выберите существующий файл с артикулами.")
return
if not self.output_dir.get().strip():
messagebox.showerror("Нет папки", "Выберите папку для сохранения результатов.")
return
self.start_button.configure(state="disabled")
self.status.set("Выполняется поиск аналогов…")
self.log.configure(state="normal")
self.log.delete("1.0", tk.END)
self.log.configure(state="disabled")
# Открываем лог-файл в папке output
out_path = Path(self.output_dir.get())
out_path.mkdir(parents=True, exist_ok=True)
log_path = out_path / "log.txt"
try:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self._log_file = open(log_path, "w", encoding="utf-8")
self._log_file.write(f"=== CrossReference v{APP_VERSION} — {timestamp} ===\n")
self._log_file.flush()
except OSError:
self._log_file = None
threading.Thread(
target=self._run_worker,
args=(str(articles), self.output_dir.get(), self.debug_network.get(), self.show_browser.get()),
daemon=True,
).start()
def _run_worker(self, articles_file: str, output_dir: str, debug_network: bool, show_browser: bool):
try:
run(
articles_file,
output_dir,
headless=not show_browser,
debug_network=debug_network,
progress_callback=self._report_progress,
)
except Exception as error:
self.after(0, self._fatal_error, str(error))
def _report_progress(self, event: str, details: dict):
self.after(0, self._handle_progress, event, details)
def _handle_progress(self, event: str, details: dict):
if event == "loaded":
self.loaded.set(f"Загружено: {details['total']} артикулов")
self._write_log(f"Загружено артикулов: {details['total']}")
elif event == "processing":
self.current.set(details["article"])
self.processed.set(f"Обработано: {details['current'] - 1} из {details['total']}")
elif event == "processed":
self.processed.set(f"Обработано: {details['current']} из {details['total']}")
self._write_log(f"{details['article']}: найдено аналогов — {details['analogs']}")
elif event == "error":
self.processed.set(f"Обработано: {details['current']} из {details['total']}")
self._write_log(f"{details['article']}: ошибка — {details['message']}")
elif event == "retry":
self.status.set(
f"Повторное подключение к Noitech: {details['attempt'] + 1} из {details['total']}…"
)
self._write_log("Страница Noitech загружается дольше обычного, повторяем попытку.")
elif event == "debug":
self._write_log(details["message"])
elif event == "empty":
self.status.set("Файл с артикулами пуст.")
self._write_log("Файл с артикулами пуст — обработка не производилась.")
self._close_log_file()
self.start_button.configure(state="normal")
elif event == "complete":
self.current.set("—")
self.status.set("Обработка завершена.")
self._write_log(f"Готово. Записей: {details['records']}; ошибок: {details['errors']}.")
self._close_log_file()
self.start_button.configure(state="normal")
messagebox.showinfo("CrossReference", f"Готово. Результат сохранён:\n{details['output']}")
def _fatal_error(self, error: str):
self.status.set("Работа остановлена из-за ошибки.")
self._write_log(f"Критическая ошибка: {error}")
self._close_log_file()
self.start_button.configure(state="normal")
messagebox.showerror("Ошибка", error)
def _write_log(self, message: str):
self.log.configure(state="normal")
self.log.insert(tk.END, message + "\n")
self.log.see(tk.END)
self.log.configure(state="disabled")
if self._log_file is not None:
try:
self._log_file.write(message + "\n")
self._log_file.flush()
except OSError:
pass
def _close_log_file(self):
if self._log_file is not None:
try:
self._log_file.close()
except OSError:
pass
self._log_file = None
def _on_close(self):
self._close_log_file()
self.destroy()
if __name__ == "__main__":
CrossReferenceApp().mainloop()