mkdocs-katex-ssr 1.0.4__tar.gz → 1.0.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mkdocs-katex-ssr
3
- Version: 1.0.4
3
+ Version: 1.0.6
4
4
  Summary: A MkDocs plugin for server-side rendering of KaTeX math.
5
5
  Author-email: RainPPR <2125773894@qq.com>
6
6
  License-Expression: MIT
@@ -38,6 +38,7 @@ Traditional client-side rendering relies on JavaScript in the browser to convert
38
38
  - **High Performance**: Uses a persistent Node.js process to render equations efficiently without spawning a new process for every item.
39
39
  - **Offline Support**: Optional "Offline Mode" copies all necessary CSS, fonts, and scripts to your site directory, removing external CDN dependencies.
40
40
  - **Smart Asset Management**: Separate configuration for server-side processing scripts (like `mhchem`) and client-side interactive scripts (like `copy-tex`).
41
+ - **Performance Monitoring**: Detailed build-time logging for each page tracking formula counts, cache hits, and processing speeds.
41
42
  - **Clean Output**: Aggressive warning suppression for a quieter build log.
42
43
 
43
44
  ## Installation
@@ -65,6 +66,7 @@ markdown_extensions:
65
66
  plugins:
66
67
  - katex-ssr:
67
68
  # --- Basic Configuration ---
69
+ verbose: true # Enable build logs for each page
68
70
  katex_dist: "https://cdn.jsdelivr.net/npm/katex@latest/dist/"
69
71
  add_katex_css: true
70
72
  katex_css_filename: "katex-swap.min.css" # Use swap version for better font-display behavior
@@ -107,6 +109,7 @@ plugins:
107
109
 
108
110
  | Option | Type | Default | Description |
109
111
  | :--- | :--- | :--- | :--- |
112
+ | `verbose` | bool | `false` | If true, logs the number of formulas, cache hits, and time spent processing each page. |
110
113
  | `katex_dist` | str | jsDelivr | Base URL for CDN, or local file path to KaTeX distribution. |
111
114
  | `add_katex_css` | bool | `true` | Whether to inject the CSS link tag. |
112
115
  | `katex_css_filename` | str | `katex.min.css` | The specific CSS file to load. `katex-swap.min.css` is recommended. |
@@ -22,6 +22,7 @@ Traditional client-side rendering relies on JavaScript in the browser to convert
22
22
  - **High Performance**: Uses a persistent Node.js process to render equations efficiently without spawning a new process for every item.
23
23
  - **Offline Support**: Optional "Offline Mode" copies all necessary CSS, fonts, and scripts to your site directory, removing external CDN dependencies.
24
24
  - **Smart Asset Management**: Separate configuration for server-side processing scripts (like `mhchem`) and client-side interactive scripts (like `copy-tex`).
25
+ - **Performance Monitoring**: Detailed build-time logging for each page tracking formula counts, cache hits, and processing speeds.
25
26
  - **Clean Output**: Aggressive warning suppression for a quieter build log.
26
27
 
27
28
  ## Installation
@@ -49,6 +50,7 @@ markdown_extensions:
49
50
  plugins:
50
51
  - katex-ssr:
51
52
  # --- Basic Configuration ---
53
+ verbose: true # Enable build logs for each page
52
54
  katex_dist: "https://cdn.jsdelivr.net/npm/katex@latest/dist/"
53
55
  add_katex_css: true
54
56
  katex_css_filename: "katex-swap.min.css" # Use swap version for better font-display behavior
@@ -91,6 +93,7 @@ plugins:
91
93
 
92
94
  | Option | Type | Default | Description |
93
95
  | :--- | :--- | :--- | :--- |
96
+ | `verbose` | bool | `false` | If true, logs the number of formulas, cache hits, and time spent processing each page. |
94
97
  | `katex_dist` | str | jsDelivr | Base URL for CDN, or local file path to KaTeX distribution. |
95
98
  | `add_katex_css` | bool | `true` | Whether to inject the CSS link tag. |
96
99
  | `katex_css_filename` | str | `katex.min.css` | The specific CSS file to load. `katex-swap.min.css` is recommended. |
@@ -1,11 +1,13 @@
1
1
  import os
2
2
  import json
3
+ import sqlite3
4
+ import hashlib
3
5
  import subprocess
4
6
  import threading
5
7
  import warnings
6
8
  import logging
7
- import requests
8
9
  import shutil
10
+ import time
9
11
  from mkdocs.plugins import BasePlugin
10
12
  from mkdocs.config import config_options
11
13
  from mkdocs.utils import get_relative_url
@@ -29,8 +31,11 @@ for logger_name in ["mkdocs", "mkdocs.plugins", "py.warnings", ""]:
29
31
 
30
32
  logging.captureWarnings(True)
31
33
 
34
+ log = logging.getLogger('mkdocs.plugins.katex-ssr')
35
+
32
36
  class KatexSsrPlugin(BasePlugin):
33
37
  config_scheme = (
38
+ ('verbose', config_options.Type(bool, default=False)),
34
39
  ('katex_dist', config_options.Type(str, default='https://cdn.jsdelivr.net/npm/katex@latest/dist/')),
35
40
  ('katex_css_filename', config_options.Type(str, default='katex.min.css')),
36
41
  ('add_katex_css', config_options.Type(bool, default=True)),
@@ -48,6 +53,8 @@ class KatexSsrPlugin(BasePlugin):
48
53
  self.lock = threading.Lock()
49
54
  self._asset_cache = {}
50
55
  self._local_dist_path = None
56
+ self.db_conn = None
57
+ self.db_path = None
51
58
 
52
59
  def _ensure_trailing_slash(self, path):
53
60
  if not path.endswith('/') and not path.endswith('\\'):
@@ -66,6 +73,21 @@ class KatexSsrPlugin(BasePlugin):
66
73
 
67
74
  project_dir = os.path.dirname(config['config_file_path'])
68
75
 
76
+ # Initialize Cache DB
77
+ try:
78
+ cache_dir = os.path.join(project_dir, '.cache', 'plugin', 'katex-ssr')
79
+ os.makedirs(cache_dir, exist_ok=True)
80
+ self.db_path = os.path.join(cache_dir, 'cache.db')
81
+ self.db_conn = sqlite3.connect(
82
+ self.db_path,
83
+ check_same_thread=False
84
+ )
85
+ with self.db_conn:
86
+ self.db_conn.execute('CREATE TABLE IF NOT EXISTS katex_cache (hash TEXT PRIMARY KEY, html TEXT)')
87
+ except Exception as e:
88
+ print(f"Warning: Failed to initialize KaTeX SSR cache: {e}")
89
+ self.db_conn = None
90
+
69
91
  # Merge legacy contrib_scripts into ssr_contribs if used
70
92
  if self.config['contrib_scripts']:
71
93
  # Append unique items
@@ -129,8 +151,24 @@ class KatexSsrPlugin(BasePlugin):
129
151
  return config
130
152
 
131
153
  def _render_latex(self, latex, display_mode=False):
154
+ # Check cache first
155
+ latex_trimmed = latex.strip()
156
+ cache_key = None
157
+ if self.db_conn:
158
+ try:
159
+ # Create a unique hash for the content AND display mode
160
+ content_to_hash = f"{latex_trimmed}::{display_mode}"
161
+ cache_key = hashlib.sha256(content_to_hash.encode('utf-8')).hexdigest()
162
+
163
+ cursor = self.db_conn.execute("SELECT html FROM katex_cache WHERE hash=?", (cache_key,))
164
+ row = cursor.fetchone()
165
+ if row:
166
+ return row[0], True
167
+ except Exception as e:
168
+ print(f"Error reading cache: {e}")
169
+
132
170
  if not self.process:
133
- return None
171
+ return None, False
134
172
 
135
173
  with self.lock:
136
174
  payload = {
@@ -146,11 +184,22 @@ class KatexSsrPlugin(BasePlugin):
146
184
 
147
185
  response_line = self.process.stdout.readline()
148
186
  if not response_line:
149
- return None
187
+ return None, False
150
188
 
151
189
  result = json.loads(response_line.decode('utf-8'))
152
190
  if result.get('status') == 'success':
153
- return result.get('html')
191
+ html = result.get('html')
192
+ # Save to cache
193
+ if self.db_conn and cache_key:
194
+ try:
195
+ with self.db_conn:
196
+ self.db_conn.execute(
197
+ "INSERT OR REPLACE INTO katex_cache (hash, html) VALUES (?, ?)",
198
+ (cache_key, html)
199
+ )
200
+ except Exception as e:
201
+ print(f"Error saving to cache: {e}")
202
+ return html, False
154
203
  else:
155
204
  print(f"KaTeX error: {result.get('message')}")
156
205
  except Exception as e:
@@ -158,12 +207,16 @@ class KatexSsrPlugin(BasePlugin):
158
207
  stderr_content = self.process.stderr.read()
159
208
  if stderr_content:
160
209
  print(f"Renderer died with: {stderr_content.decode('utf-8', errors='replace')}")
161
- return None
210
+ return None, False
162
211
 
163
212
  def on_post_page(self, output, page, config):
164
213
  if not self.process:
165
214
  return output
166
215
 
216
+ start_time = time.time()
217
+ formula_count = 0
218
+ cache_count = 0
219
+
167
220
  soup = BeautifulSoup(output, 'html.parser')
168
221
  math_elements = soup.find_all(class_='arithmatex')
169
222
  for el in math_elements:
@@ -183,11 +236,20 @@ class KatexSsrPlugin(BasePlugin):
183
236
  else:
184
237
  latex = content
185
238
 
186
- rendered_html = self._render_latex(latex, display_mode)
187
- new_soup = BeautifulSoup(rendered_html, 'html.parser')
239
+ rendered_html, from_cache = self._render_latex(latex, display_mode)
240
+
241
+ if rendered_html:
242
+ formula_count += 1
243
+ if from_cache:
244
+ cache_count += 1
245
+
246
+ new_soup = BeautifulSoup(rendered_html, 'html.parser')
247
+ el.clear()
248
+ el.append(new_soup)
188
249
 
189
- el.clear()
190
- el.append(new_soup)
250
+ if self.config['verbose']:
251
+ duration = (time.time() - start_time) * 1000
252
+ log.info(f"Katex-SSR processed {page.file.src_path} in {duration:.2f}ms: {formula_count} formulas ({cache_count} cached)")
191
253
 
192
254
  # Assets Injection
193
255
  css_file = self.config['katex_css_filename']
@@ -234,6 +296,13 @@ class KatexSsrPlugin(BasePlugin):
234
296
  self.process.terminate()
235
297
  self.process.wait()
236
298
 
299
+ if self.db_conn:
300
+ try:
301
+ self.db_conn.close()
302
+ except:
303
+ pass
304
+ self.db_conn = None
305
+
237
306
  # Copy assets if requested
238
307
  if self.config['embed_assets'] and self._local_dist_path:
239
308
  dest_dir = os.path.join(config['site_dir'], self.config['copy_assets_to'])
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mkdocs-katex-ssr
3
- Version: 1.0.4
3
+ Version: 1.0.6
4
4
  Summary: A MkDocs plugin for server-side rendering of KaTeX math.
5
5
  Author-email: RainPPR <2125773894@qq.com>
6
6
  License-Expression: MIT
@@ -38,6 +38,7 @@ Traditional client-side rendering relies on JavaScript in the browser to convert
38
38
  - **High Performance**: Uses a persistent Node.js process to render equations efficiently without spawning a new process for every item.
39
39
  - **Offline Support**: Optional "Offline Mode" copies all necessary CSS, fonts, and scripts to your site directory, removing external CDN dependencies.
40
40
  - **Smart Asset Management**: Separate configuration for server-side processing scripts (like `mhchem`) and client-side interactive scripts (like `copy-tex`).
41
+ - **Performance Monitoring**: Detailed build-time logging for each page tracking formula counts, cache hits, and processing speeds.
41
42
  - **Clean Output**: Aggressive warning suppression for a quieter build log.
42
43
 
43
44
  ## Installation
@@ -65,6 +66,7 @@ markdown_extensions:
65
66
  plugins:
66
67
  - katex-ssr:
67
68
  # --- Basic Configuration ---
69
+ verbose: true # Enable build logs for each page
68
70
  katex_dist: "https://cdn.jsdelivr.net/npm/katex@latest/dist/"
69
71
  add_katex_css: true
70
72
  katex_css_filename: "katex-swap.min.css" # Use swap version for better font-display behavior
@@ -107,6 +109,7 @@ plugins:
107
109
 
108
110
  | Option | Type | Default | Description |
109
111
  | :--- | :--- | :--- | :--- |
112
+ | `verbose` | bool | `false` | If true, logs the number of formulas, cache hits, and time spent processing each page. |
110
113
  | `katex_dist` | str | jsDelivr | Base URL for CDN, or local file path to KaTeX distribution. |
111
114
  | `add_katex_css` | bool | `true` | Whether to inject the CSS link tag. |
112
115
  | `katex_css_filename` | str | `katex.min.css` | The specific CSS file to load. `katex-swap.min.css` is recommended. |
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "mkdocs-katex-ssr"
7
- version = "1.0.4"
7
+ version = "1.0.6"
8
8
  description = "A MkDocs plugin for server-side rendering of KaTeX math."
9
9
  readme = "README.md"
10
10
  authors = [