-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
204 lines (167 loc) · 8.58 KB
/
Copy pathmain.py
File metadata and controls
204 lines (167 loc) · 8.58 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
import sys
import os
# === ВАЖНЫЙ ХАК ДЛЯ WINDOWS И PYINSTALLER ===
# Это должно быть ДО импорта weasyprint!
if os.name == 'nt':
gtk_path = r'C:\Program Files\GTK3-Runtime Win64\bin'
if os.path.exists(gtk_path):
# 1. Добавляем в PATH (классический способ)
os.environ['PATH'] = gtk_path + os.pathsep + os.environ.get('PATH', '')
# 2. Явно разрешаем загрузку DLL (обязательно для Python 3.8+ внутри exe)
if hasattr(os, 'add_dll_directory'):
os.add_dll_directory(gtk_path)
# ============================================
import re
import threading
import logging
from pathlib import Path
import tkinter as tk
from tkinter import filedialog
import eel
import markdown
from weasyprint import HTML, CSS
# ... дальше идет весь твой остальной код ...
# def resource_path... и так далее
# --- МАГИЯ PYINSTALLER ---
def resource_path(relative_path):
"""Возвращает абсолютный путь к ресурсам. Работает и для dev, и для .exe"""
try:
# PyInstaller создает временную папку _MEIPASS и кладет все туда
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
# Инициализация интерфейса (используем безопасный путь)
eel.init(resource_path('web'))
# --- Перехват логов WeasyPrint ---
class EelLogHandler(logging.Handler):
def emit(self, record):
log_entry = self.format(record)
eel.addLog(log_entry)()
logger = logging.getLogger('weasyprint')
logger.setLevel(logging.DEBUG)
eel_handler = EelLogHandler()
eel_handler.setFormatter(logging.Formatter('%(message)s'))
logger.addHandler(eel_handler)
# --- Диалоги Tkinter ---
def get_hidden_tk_root():
root = tk.Tk()
root.attributes('-topmost', True)
root.withdraw()
return root
@eel.expose
def pick_folder(current_path):
root = get_hidden_tk_root()
folder = filedialog.askdirectory(initialdir=current_path)
root.destroy()
return folder if folder else None
@eel.expose
def pick_file(current_path, is_md_mode):
root = get_hidden_tk_root()
# Меняем расширение в зависимости от тумблера
ext = ".md" if is_md_mode else ".pdf"
file_types = [("Markdown", "*.md")] if is_md_mode else [("PDF", "*.pdf")]
# Защита от пустых путей
init_dir = os.path.dirname(current_path) if current_path else os.path.expanduser("~")
if not os.path.exists(init_dir):
init_dir = os.path.expanduser("~")
file = filedialog.asksaveasfilename(
initialdir=init_dir,
defaultextension=ext,
filetypes=file_types
)
root.destroy()
return file if file else None
# --- Бизнес логика ---
def clean_markdown(text: str) -> str:
text = re.sub(r'!\[.*?\]\(.*?\)', '', text)
text = re.sub(r'!\[\[.*?\]\]', '', text)
text = re.sub(r'<img[^>]*>', '', text, flags=re.IGNORECASE)
text = re.sub(r'\[\[(.*?)\|(.*?)\]\]', r'[\2](\1)', text)
text = re.sub(r'\[\[(.*?)\]\]', r'[\1](\1)', text)
return text
def _conversion_task(notes_dir, out_file, generate_only_md):
try:
eel.addLog("> Сборка структуры файлов...")()
md_files = []
for root, _, files in os.walk(notes_dir):
for file in files:
if file.lower().endswith('.md'):
md_files.append(os.path.join(root, file))
md_files = sorted(md_files)
if not md_files:
raise ValueError("Markdown файлы не найдены.")
eel.addLog(f"> Найдено файлов: {len(md_files)}. Чтение...")()
md_blocks = []
html_blocks = []
md = markdown.Markdown(extensions=['tables', 'fenced_code'])
for i, file_path in enumerate(md_files):
with open(file_path, 'r', encoding='utf-8') as f:
content = clean_markdown(f.read())
filename = os.path.splitext(os.path.basename(file_path))[0]
note_md = f"# {filename}\n\n{content}"
md_blocks.append(note_md)
# Конвертируем в HTML только если нам НУЖЕН PDF
if not generate_only_md:
note_html = md.convert(note_md)
if i > 0: note_html = f'<div style="page-break-before: always;"></div>\n{note_html}'
html_blocks.append(note_html)
md.reset()
# === ЕСЛИ ВКЛЮЧЕН ТУМБЛЕР (Генерируем ТОЛЬКО .md) ===
if generate_only_md:
eel.addLog("> Режим ИИ: Собираем единый .md файл...")()
# Принудительно ставим расширение .md на всякий случай
out_md_path = os.path.splitext(out_file)[0] + ".md"
with open(out_md_path, 'w', encoding='utf-8') as f:
f.write("\n\n---\n\n".join(md_blocks))
eel.updateStatus("success", "Успешно завершено", "#10b981")()
eel.addLog(f"\n[SUCCESS] MD сохранен:\n{out_md_path}")()
return # <-- ВАЖНО: Выходим из функции, PDF рендериться НЕ БУДЕТ
# ====================================================
# ВСЁ ЧТО НИЖЕ СРАБОТАЕТ ТОЛЬКО ДЛЯ PDF
eel.addLog("> Подключение встроенных шрифтов...")()
fonts_info = []
fonts_dir = resource_path(os.path.join('web', 'fonts'))
if os.path.isdir(fonts_dir):
for file in os.listdir(fonts_dir):
if file.lower().endswith('.ttf'):
abs_path = os.path.abspath(os.path.join(fonts_dir, file))
file_uri = Path(abs_path).as_uri()
name = file.lower()
weight, style = "normal", "normal"
if "bold" in name and "italic" in name: weight, style = "bold", "italic"
elif "bold" in name: weight = "bold"
elif "italic" in name: style = "italic"
fonts_info.append((file_uri, weight, style))
combined_html = "\n".join(html_blocks)
final_html = f"<!DOCTYPE html><html><head><meta charset='utf-8'></head><body>{combined_html}</body></html>"
eel.addLog("> Генерация CSS стилей...")()
css_lines = []
for uri, weight, style in fonts_info:
css_lines.append(f"@font-face {{ font-family: 'AppCoreFont'; src: url('{uri}'); font-weight: {weight}; font-style: {style}; }}")
font_family = "'AppCoreFont', sans-serif" if fonts_info else "sans-serif"
css_lines.append(f"""
body, code, pre, table {{ font-family: {font_family}; line-height: 1.6; color: #333; }}
h1 {{ color: #111; border-bottom: 2px solid #ddd; padding-bottom: 5px; }}
table {{ width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 14px; }}
th, td {{ border: 1px solid #ddd; padding: 10px; text-align: left; }}
th {{ background-color: #f4f4f4; font-weight: bold; }}
pre {{ background-color: #f5f5f5; padding: 15px; border-radius: 5px; border: 1px solid #e0e0e0; overflow-x: auto; }}
code {{ background-color: #f5f5f5; padding: 2px 4px; border-radius: 3px; font-family: monospace, {font_family}; font-size: 0.9em; }}
""")
css_string = "\n".join(css_lines)
eel.updateStatus("pulsing", "Рендер через WeasyPrint...", "#eab308")()
HTML(string=final_html).write_pdf(out_file, stylesheets=[CSS(string=css_string)])
eel.updateStatus("success", "Успешно завершено", "#10b981")()
eel.addLog(f"\n[SUCCESS] PDF сохранен:\n{out_file}")()
except Exception as e:
eel.updateStatus("error", "Произошла ошибка", "#ef4444")()
eel.addLog(f"\n[ERROR] {str(e)}")()
finally:
eel.enableButton()()
@eel.expose
def start_conversion(notes_dir, out_pdf, generate_md): # <-- Добавили аргумент здесь
threading.Thread(target=_conversion_task, args=(notes_dir, out_pdf, generate_md), daemon=True).start()
if __name__ == '__main__':
# size(ширина, высота)
eel.start('index.html', size=(500, 750), port=0)