novel-downloader 1.1.0__py3-none-any.whl

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.
Files changed (115) hide show
  1. novel_downloader/__init__.py +14 -0
  2. novel_downloader/cli/__init__.py +14 -0
  3. novel_downloader/cli/clean.py +134 -0
  4. novel_downloader/cli/download.py +132 -0
  5. novel_downloader/cli/interactive.py +67 -0
  6. novel_downloader/cli/main.py +45 -0
  7. novel_downloader/cli/settings.py +177 -0
  8. novel_downloader/config/__init__.py +52 -0
  9. novel_downloader/config/adapter.py +153 -0
  10. novel_downloader/config/loader.py +177 -0
  11. novel_downloader/config/models.py +173 -0
  12. novel_downloader/config/site_rules.py +97 -0
  13. novel_downloader/core/__init__.py +25 -0
  14. novel_downloader/core/downloaders/__init__.py +22 -0
  15. novel_downloader/core/downloaders/base_async_downloader.py +157 -0
  16. novel_downloader/core/downloaders/base_downloader.py +187 -0
  17. novel_downloader/core/downloaders/common_asynb_downloader.py +207 -0
  18. novel_downloader/core/downloaders/common_downloader.py +191 -0
  19. novel_downloader/core/downloaders/qidian_downloader.py +208 -0
  20. novel_downloader/core/factory/__init__.py +33 -0
  21. novel_downloader/core/factory/downloader_factory.py +149 -0
  22. novel_downloader/core/factory/parser_factory.py +62 -0
  23. novel_downloader/core/factory/requester_factory.py +106 -0
  24. novel_downloader/core/factory/saver_factory.py +49 -0
  25. novel_downloader/core/interfaces/__init__.py +32 -0
  26. novel_downloader/core/interfaces/async_downloader_protocol.py +37 -0
  27. novel_downloader/core/interfaces/async_requester_protocol.py +68 -0
  28. novel_downloader/core/interfaces/downloader_protocol.py +37 -0
  29. novel_downloader/core/interfaces/parser_protocol.py +40 -0
  30. novel_downloader/core/interfaces/requester_protocol.py +65 -0
  31. novel_downloader/core/interfaces/saver_protocol.py +61 -0
  32. novel_downloader/core/parsers/__init__.py +28 -0
  33. novel_downloader/core/parsers/base_parser.py +96 -0
  34. novel_downloader/core/parsers/common_parser/__init__.py +14 -0
  35. novel_downloader/core/parsers/common_parser/helper.py +321 -0
  36. novel_downloader/core/parsers/common_parser/main_parser.py +86 -0
  37. novel_downloader/core/parsers/qidian_parser/__init__.py +20 -0
  38. novel_downloader/core/parsers/qidian_parser/browser/__init__.py +13 -0
  39. novel_downloader/core/parsers/qidian_parser/browser/chapter_encrypted.py +498 -0
  40. novel_downloader/core/parsers/qidian_parser/browser/chapter_normal.py +97 -0
  41. novel_downloader/core/parsers/qidian_parser/browser/chapter_router.py +70 -0
  42. novel_downloader/core/parsers/qidian_parser/browser/main_parser.py +110 -0
  43. novel_downloader/core/parsers/qidian_parser/session/__init__.py +13 -0
  44. novel_downloader/core/parsers/qidian_parser/session/chapter_encrypted.py +451 -0
  45. novel_downloader/core/parsers/qidian_parser/session/chapter_normal.py +119 -0
  46. novel_downloader/core/parsers/qidian_parser/session/chapter_router.py +67 -0
  47. novel_downloader/core/parsers/qidian_parser/session/main_parser.py +113 -0
  48. novel_downloader/core/parsers/qidian_parser/session/node_decryptor.py +164 -0
  49. novel_downloader/core/parsers/qidian_parser/shared/__init__.py +38 -0
  50. novel_downloader/core/parsers/qidian_parser/shared/book_info_parser.py +95 -0
  51. novel_downloader/core/parsers/qidian_parser/shared/helpers.py +133 -0
  52. novel_downloader/core/requesters/__init__.py +31 -0
  53. novel_downloader/core/requesters/base_async_session.py +297 -0
  54. novel_downloader/core/requesters/base_browser.py +210 -0
  55. novel_downloader/core/requesters/base_session.py +243 -0
  56. novel_downloader/core/requesters/common_requester/__init__.py +18 -0
  57. novel_downloader/core/requesters/common_requester/common_async_session.py +96 -0
  58. novel_downloader/core/requesters/common_requester/common_session.py +126 -0
  59. novel_downloader/core/requesters/qidian_requester/__init__.py +22 -0
  60. novel_downloader/core/requesters/qidian_requester/qidian_broswer.py +377 -0
  61. novel_downloader/core/requesters/qidian_requester/qidian_session.py +202 -0
  62. novel_downloader/core/savers/__init__.py +20 -0
  63. novel_downloader/core/savers/base_saver.py +169 -0
  64. novel_downloader/core/savers/common_saver/__init__.py +13 -0
  65. novel_downloader/core/savers/common_saver/common_epub.py +232 -0
  66. novel_downloader/core/savers/common_saver/common_txt.py +176 -0
  67. novel_downloader/core/savers/common_saver/main_saver.py +86 -0
  68. novel_downloader/core/savers/epub_utils/__init__.py +27 -0
  69. novel_downloader/core/savers/epub_utils/css_builder.py +68 -0
  70. novel_downloader/core/savers/epub_utils/initializer.py +98 -0
  71. novel_downloader/core/savers/epub_utils/text_to_html.py +132 -0
  72. novel_downloader/core/savers/epub_utils/volume_intro.py +61 -0
  73. novel_downloader/core/savers/qidian_saver.py +22 -0
  74. novel_downloader/locales/en.json +91 -0
  75. novel_downloader/locales/zh.json +91 -0
  76. novel_downloader/resources/config/rules.toml +196 -0
  77. novel_downloader/resources/config/settings.yaml +73 -0
  78. novel_downloader/resources/css_styles/main.css +104 -0
  79. novel_downloader/resources/css_styles/volume-intro.css +56 -0
  80. novel_downloader/resources/images/volume_border.png +0 -0
  81. novel_downloader/resources/js_scripts/qidian_decrypt_node.js +82 -0
  82. novel_downloader/resources/json/replace_word_map.json +4 -0
  83. novel_downloader/resources/text/blacklist.txt +22 -0
  84. novel_downloader/utils/__init__.py +0 -0
  85. novel_downloader/utils/cache.py +24 -0
  86. novel_downloader/utils/constants.py +158 -0
  87. novel_downloader/utils/crypto_utils.py +144 -0
  88. novel_downloader/utils/file_utils/__init__.py +43 -0
  89. novel_downloader/utils/file_utils/io.py +252 -0
  90. novel_downloader/utils/file_utils/normalize.py +68 -0
  91. novel_downloader/utils/file_utils/sanitize.py +77 -0
  92. novel_downloader/utils/fontocr/__init__.py +23 -0
  93. novel_downloader/utils/fontocr/ocr_v1.py +304 -0
  94. novel_downloader/utils/fontocr/ocr_v2.py +658 -0
  95. novel_downloader/utils/hash_store.py +288 -0
  96. novel_downloader/utils/hash_utils.py +103 -0
  97. novel_downloader/utils/i18n.py +41 -0
  98. novel_downloader/utils/logger.py +104 -0
  99. novel_downloader/utils/model_loader.py +72 -0
  100. novel_downloader/utils/network.py +287 -0
  101. novel_downloader/utils/state.py +156 -0
  102. novel_downloader/utils/text_utils/__init__.py +27 -0
  103. novel_downloader/utils/text_utils/chapter_formatting.py +46 -0
  104. novel_downloader/utils/text_utils/diff_display.py +75 -0
  105. novel_downloader/utils/text_utils/font_mapping.py +31 -0
  106. novel_downloader/utils/text_utils/text_cleaning.py +57 -0
  107. novel_downloader/utils/time_utils/__init__.py +22 -0
  108. novel_downloader/utils/time_utils/datetime_utils.py +146 -0
  109. novel_downloader/utils/time_utils/sleep_utils.py +49 -0
  110. novel_downloader-1.1.0.dist-info/METADATA +157 -0
  111. novel_downloader-1.1.0.dist-info/RECORD +115 -0
  112. novel_downloader-1.1.0.dist-info/WHEEL +5 -0
  113. novel_downloader-1.1.0.dist-info/entry_points.txt +2 -0
  114. novel_downloader-1.1.0.dist-info/licenses/LICENSE +21 -0
  115. novel_downloader-1.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ novel_downloader.core.parsers.qidian_parser.browser.main_parser
5
+ ---------------------------------------------------------------
6
+
7
+ Main parser class for handling Qidian chapters rendered via a browser environment.
8
+
9
+ This module defines `QidianBrowserParser`, a parser implementation that supports
10
+ content extracted from dynamically rendered Qidian HTML pages.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from pathlib import Path
16
+ from typing import TYPE_CHECKING, Any, Dict, Optional
17
+
18
+ from novel_downloader.config.models import ParserConfig
19
+ from novel_downloader.core.parsers.base_parser import BaseParser
20
+
21
+ from ..shared import (
22
+ is_encrypted,
23
+ parse_book_info,
24
+ )
25
+ from .chapter_router import parse_chapter
26
+
27
+ if TYPE_CHECKING:
28
+ from novel_downloader.utils.fontocr import FontOCR
29
+
30
+
31
+ class QidianBrowserParser(BaseParser):
32
+ """
33
+ Parser for Qidian site using a browser-rendered HTML workflow.
34
+ """
35
+
36
+ def __init__(self, config: ParserConfig):
37
+ """
38
+ Initialize the QidianBrowserParser with the given configuration.
39
+
40
+ :param config: ParserConfig object controlling:
41
+ """
42
+ super().__init__(config)
43
+
44
+ # Extract and store parser flags from config
45
+ self._decode_font: bool = config.decode_font
46
+ self._save_font_debug: bool = config.save_font_debug
47
+
48
+ self._fixed_font_dir: Path = self._base_cache_dir / "fixed_fonts"
49
+ self._fixed_font_dir.mkdir(parents=True, exist_ok=True)
50
+ self._font_debug_dir: Optional[Path] = None
51
+
52
+ self._font_ocr: Optional[FontOCR] = None
53
+ if self._decode_font:
54
+ from novel_downloader.utils.fontocr import FontOCR
55
+
56
+ self._font_ocr = FontOCR(
57
+ cache_dir=self._base_cache_dir,
58
+ use_freq=config.use_freq,
59
+ ocr_version=config.ocr_version,
60
+ use_ocr=config.use_ocr,
61
+ use_vec=config.use_vec,
62
+ batch_size=config.batch_size,
63
+ ocr_weight=config.ocr_weight,
64
+ vec_weight=config.vec_weight,
65
+ font_debug=config.save_font_debug,
66
+ )
67
+ self._font_debug_dir = self._base_cache_dir / "font_debug"
68
+ self._font_debug_dir.mkdir(parents=True, exist_ok=True)
69
+
70
+ def parse_book_info(self, html: str) -> Dict[str, Any]:
71
+ """
72
+ Parse a book info page and extract metadata and chapter structure.
73
+
74
+ :param html: Raw HTML of the book info page.
75
+ :return: Parsed metadata and chapter structure as a dictionary.
76
+ """
77
+ return parse_book_info(html)
78
+
79
+ def parse_chapter(self, html_str: str, chapter_id: str) -> Dict[str, Any]:
80
+ """
81
+ :param html: Raw HTML of the chapter page.
82
+ :param chapter_id: Identifier of the chapter being parsed.
83
+ :return: Cleaned chapter content as plain text.
84
+ """
85
+ return parse_chapter(self, html_str, chapter_id)
86
+
87
+ def is_encrypted(self, html_str: str) -> bool:
88
+ """
89
+ Return True if content is encrypted.
90
+
91
+ :param html: Raw HTML of the chapter page.
92
+ """
93
+ return is_encrypted(html_str)
94
+
95
+ def _init_cache_folders(self) -> None:
96
+ """
97
+ Prepare cache folders for plain/encrypted HTML and font debug data.
98
+ Folders are only created if corresponding debug/save flags are enabled.
99
+ """
100
+ base = self._base_cache_dir
101
+
102
+ # Font debug folder
103
+ if self._save_font_debug and self.book_id:
104
+ self._font_debug_dir = base / self.book_id / "font_debug"
105
+ self._font_debug_dir.mkdir(parents=True, exist_ok=True)
106
+ else:
107
+ self._font_debug_dir = None
108
+
109
+ def _on_book_id_set(self) -> None:
110
+ self._init_cache_folders()
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ novel_downloader.core.parsers.qidian_parser.session
5
+ ---------------------------------------------------------------
6
+
7
+ This package provides parsing components for handling Qidian
8
+ pages that have been rendered by a session.
9
+ """
10
+
11
+ from .main_parser import QidianSessionParser
12
+
13
+ __all__ = ["QidianSessionParser"]
@@ -0,0 +1,451 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ novel_downloader.core.parsers.qidian_parser.session.chapter_encrypted
5
+ ---------------------------------------------------------------------
6
+
7
+ Support for parsing encrypted chapters from Qidian using font OCR mapping,
8
+ CSS rules, and custom rendering logic.
9
+
10
+ Includes:
11
+ - Font downloading and caching
12
+ - Encrypted paragraph extraction
13
+ - Custom CSS parsing and layout restoration
14
+ - Font-based OCR decryption and mapping
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import logging
21
+ from pathlib import Path
22
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
23
+
24
+ import tinycss2
25
+ from bs4 import BeautifulSoup, Tag
26
+
27
+ from novel_downloader.utils.network import download_font_file
28
+ from novel_downloader.utils.text_utils import apply_font_mapping
29
+
30
+ from ..shared import (
31
+ extract_chapter_info,
32
+ find_ssr_page_context,
33
+ html_to_soup,
34
+ vip_status,
35
+ )
36
+ from .node_decryptor import QidianNodeDecryptor
37
+
38
+ if TYPE_CHECKING:
39
+ from .main_parser import QidianSessionParser
40
+
41
+ logger = logging.getLogger(__name__)
42
+ IGNORED_CLASS_LISTS = {"title", "review"}
43
+ _decryptor: Optional[QidianNodeDecryptor] = None
44
+
45
+
46
+ def _get_decryptor() -> QidianNodeDecryptor:
47
+ """
48
+ Return the singleton QidianNodeDecryptor, initializing it on first use.
49
+ """
50
+ global _decryptor
51
+ if _decryptor is None:
52
+ _decryptor = QidianNodeDecryptor()
53
+ return _decryptor
54
+
55
+
56
+ def parse_encrypted_chapter(
57
+ parser: QidianSessionParser,
58
+ soup: BeautifulSoup,
59
+ chapter_id: str,
60
+ fuid: str,
61
+ ) -> Dict[str, Any]:
62
+ """
63
+ Extract and return the formatted textual content of an encrypted chapter.
64
+
65
+ Steps:
66
+ 1. Load SSR JSON context for CSS, fonts, and metadata.
67
+ 3. Decode and save randomFont bytes; download fixedFont via download_font().
68
+ 4. Extract paragraph structures and save debug JSON.
69
+ 5. Parse CSS rules and save debug JSON.
70
+ 6. Render encrypted paragraphs, then run OCR font-mapping.
71
+ 7. Extracts paragraph texts and formats them.
72
+
73
+ :param html_str: Raw HTML content of the chapter page.
74
+ :return: Formatted chapter text or empty string if not parsable.
75
+ """
76
+ try:
77
+ if not (parser._decode_font and parser._font_ocr):
78
+ return {}
79
+ ssr_data = find_ssr_page_context(soup)
80
+ chapter_info = extract_chapter_info(ssr_data)
81
+ if not chapter_info:
82
+ logger.warning(
83
+ "[Parser] ssr_chapterInfo not found for chapter '%s'", chapter_id
84
+ )
85
+ return {}
86
+ debug_base_dir: Optional[Path] = None
87
+ if parser._font_debug_dir:
88
+ debug_base_dir = parser._font_debug_dir / chapter_id
89
+ debug_base_dir.mkdir(parents=True, exist_ok=True)
90
+
91
+ css_str = chapter_info["css"]
92
+ randomFont_str = chapter_info["randomFont"]
93
+ fixedFontWoff2_url = chapter_info["fixedFontWoff2"]
94
+
95
+ title = chapter_info.get("chapterName", "Untitled")
96
+ raw_html = chapter_info.get("content", "")
97
+ chapter_id = chapter_info.get("chapterId", "")
98
+ fkp = chapter_info.get("fkp", "")
99
+ author_say = chapter_info.get("authorSay", "")
100
+ update_time = chapter_info.get("updateTime", "")
101
+ update_timestamp = chapter_info.get("updateTimestamp", 0)
102
+ modify_time = chapter_info.get("modifyTime", 0)
103
+ word_count = chapter_info.get("wordsCount", 0)
104
+ vip = bool(chapter_info.get("vipStatus", 0))
105
+ is_buy = bool(chapter_info.get("isBuy", 0))
106
+ seq = chapter_info.get("seq", None)
107
+ order = chapter_info.get("chapterOrder", None)
108
+ volume = chapter_info.get("extra", {}).get("volumeName", "")
109
+
110
+ if not raw_html:
111
+ logger.warning("[Parser] raw_html not found for chapter '%s'", chapter_id)
112
+ return {}
113
+
114
+ # extract + save font
115
+ rf = json.loads(randomFont_str)
116
+ rand_path = parser._base_cache_dir / "randomFont.ttf"
117
+ rand_path.parent.mkdir(parents=True, exist_ok=True)
118
+ rand_path.write_bytes(bytes(rf["data"]))
119
+
120
+ fixed_path = download_font_file(
121
+ url=fixedFontWoff2_url, target_folder=parser._fixed_font_dir
122
+ )
123
+ if fixed_path is None:
124
+ raise ValueError("fixed_path is None: failed to download font")
125
+
126
+ # Extract and render paragraphs from HTML with CSS rules
127
+
128
+ if vip_status(soup):
129
+ try:
130
+ decryptor = _get_decryptor()
131
+ raw_html = decryptor.decrypt(
132
+ raw_html,
133
+ chapter_id,
134
+ fkp,
135
+ fuid,
136
+ )
137
+ except Exception as e:
138
+ logger.error("[Parser] decryption failed for '%s': %s", chapter_id, e)
139
+ return {}
140
+ main_paragraphs = extract_paragraphs_recursively(html_to_soup(raw_html))
141
+ if debug_base_dir:
142
+ main_paragraphs_path = debug_base_dir / "main_paragraphs_debug.json"
143
+ main_paragraphs_path.write_text(
144
+ json.dumps(main_paragraphs, ensure_ascii=False, indent=2),
145
+ encoding="utf-8",
146
+ )
147
+
148
+ paragraphs_rules = parse_rule(css_str)
149
+ if debug_base_dir:
150
+ paragraphs_rules_path = debug_base_dir / "paragraphs_rules_debug.json"
151
+ paragraphs_rules_path.write_text(
152
+ json.dumps(paragraphs_rules, ensure_ascii=False, indent=2),
153
+ encoding="utf-8",
154
+ )
155
+
156
+ paragraphs_str, refl_list = render_paragraphs(main_paragraphs, paragraphs_rules)
157
+ if debug_base_dir:
158
+ paragraphs_str_path = debug_base_dir / f"{chapter_id}_debug.txt"
159
+ paragraphs_str_path.write_text(paragraphs_str, encoding="utf-8")
160
+
161
+ # Run OCR + fallback mapping
162
+ char_set = set(c for c in paragraphs_str if c not in {" ", "\n", "\u3000"})
163
+ refl_set = set(refl_list)
164
+ char_set = char_set - refl_set
165
+ if debug_base_dir:
166
+ char_sets_path = debug_base_dir / "char_set_debug.txt"
167
+ temp = f"char_set:\n{char_set}\n\nrefl_set:\n{refl_set}"
168
+ char_sets_path.write_text(
169
+ temp,
170
+ encoding="utf-8",
171
+ )
172
+
173
+ mapping_result = parser._font_ocr.generate_font_map(
174
+ fixed_font_path=fixed_path,
175
+ random_font_path=rand_path,
176
+ char_set=char_set,
177
+ refl_set=refl_set,
178
+ chapter_id=chapter_id,
179
+ )
180
+ if debug_base_dir:
181
+ mapping_json_path = debug_base_dir / "font_mapping.json"
182
+ mapping_json_path.write_text(
183
+ json.dumps(mapping_result, ensure_ascii=False, indent=2),
184
+ encoding="utf-8",
185
+ )
186
+
187
+ # Reconstruct final readable text
188
+ original_text = apply_font_mapping(paragraphs_str, mapping_result)
189
+
190
+ final_paragraphs_str = "\n\n".join(
191
+ line.strip() for line in original_text.splitlines() if line.strip()
192
+ )
193
+ chapter_info = {
194
+ "id": str(chapter_id),
195
+ "title": title,
196
+ "content": final_paragraphs_str,
197
+ "author_say": author_say.strip() if author_say else "",
198
+ "updated_at": update_time,
199
+ "update_timestamp": update_timestamp,
200
+ "modify_time": modify_time,
201
+ "word_count": word_count,
202
+ "vip": vip,
203
+ "purchased": is_buy,
204
+ "order": order,
205
+ "seq": seq,
206
+ "volume": volume,
207
+ }
208
+ return chapter_info
209
+
210
+ except Exception as e:
211
+ logger.warning(
212
+ "[Parser] parse error for encrypted chapter '%s': %s", chapter_id, e
213
+ )
214
+ return {}
215
+
216
+
217
+ def extract_paragraphs_recursively(
218
+ soup: BeautifulSoup, chapter_id: int = -1
219
+ ) -> List[Dict[str, Any]]:
220
+ """
221
+ Extracts paragraph elements under <main id="c-{chapter_id}"> from HTML
222
+ and converts them to a nested data structure for further processing.
223
+
224
+ :param html_str: Full HTML content.
225
+ :param chapter_id: ID used to locate <main id="c-{chapter_id}">.
226
+
227
+ :return list: List of parsed <p> paragraph data.
228
+ """
229
+
230
+ def parse_element(elem: Any) -> Union[Dict[str, Any], None]:
231
+ if not isinstance(elem, Tag):
232
+ return None
233
+ result = {"tag": elem.name, "attrs": dict(elem.attrs), "data": []}
234
+ for child in elem.contents:
235
+ if isinstance(child, Tag):
236
+ parsed = parse_element(child)
237
+ if parsed:
238
+ result["data"].append(parsed)
239
+ else:
240
+ text = child
241
+ if text:
242
+ result["data"].append(text)
243
+ return result
244
+
245
+ if chapter_id > 0:
246
+ main_id = f"c-{chapter_id}"
247
+ main_tag = soup.find("main", id=main_id)
248
+ if not main_tag:
249
+ return []
250
+ else:
251
+ main_tag = soup
252
+
253
+ result = []
254
+ for p in main_tag.find_all("p"):
255
+ parsed_p = parse_element(p)
256
+ if parsed_p:
257
+ result.append(parsed_p)
258
+
259
+ return result
260
+
261
+
262
+ def parse_rule(css_str: str) -> Dict[str, Any]:
263
+ """
264
+ Parse a CSS string and extract style rules for rendering.
265
+
266
+ Handles:
267
+ - font-size:0 (mark for deletion)
268
+ - scaleX(-1) (mark as mirrored)
269
+ - ::before / ::after with content or attr()
270
+ - class + tag selector mapping
271
+ - custom rendering order via 'order'
272
+
273
+ :param css_str: Raw CSS stylesheet string.
274
+ :return: Dict with "rules" and "orders" for rendering.
275
+ """
276
+
277
+ rules: Dict[str, Any] = {}
278
+ orders = []
279
+
280
+ stylesheet = tinycss2.parse_stylesheet(
281
+ css_str, skip_comments=True, skip_whitespace=True
282
+ )
283
+
284
+ for rule in stylesheet:
285
+ if rule.type != "qualified-rule":
286
+ continue
287
+
288
+ selector = tinycss2.serialize(rule.prelude).strip()
289
+ declarations = tinycss2.parse_declaration_list(rule.content)
290
+
291
+ parsed = {}
292
+ order_val = None
293
+
294
+ for decl in declarations:
295
+ if decl.type != "declaration":
296
+ continue
297
+ name = decl.lower_name
298
+ value = tinycss2.serialize(decl.value).strip()
299
+
300
+ if name == "font-size" and value == "0":
301
+ if "::first-letter" in selector:
302
+ parsed["delete-first"] = True
303
+ else:
304
+ parsed["delete-all"] = True
305
+ elif name == "transform" and value.lower() == "scalex(-1)":
306
+ parsed["transform-x_-1"] = True
307
+ elif name == "order":
308
+ order_val = value
309
+ elif name == "content":
310
+ if "::after" in selector:
311
+ if "attr(" in value:
312
+ parsed["append-end-attr"] = value.split("attr(")[1].split(")")[
313
+ 0
314
+ ]
315
+ else:
316
+ parsed["append-end-char"] = value.strip("\"'")
317
+ elif "::before" in selector:
318
+ if "attr(" in value:
319
+ parsed["append-start-attr"] = value.split("attr(")[1].split(
320
+ ")"
321
+ )[0]
322
+ else:
323
+ parsed["append-start-char"] = value.strip("\"'")
324
+
325
+ # Store in structure
326
+ if selector.startswith(".sy-"):
327
+ rules.setdefault("sy", {})[selector[1:]] = parsed
328
+ elif selector.startswith(".p") and " " in selector:
329
+ class_str, tag_part = selector.split(" ", 1)
330
+ class_str = class_str.lstrip(".")
331
+ tag_part = tag_part.split("::")[0]
332
+ rules.setdefault(class_str, {}).setdefault(tag_part, {}).update(parsed)
333
+
334
+ if order_val:
335
+ orders.append((selector, order_val))
336
+
337
+ orders.sort(key=lambda x: int(x[1]))
338
+ return {"rules": rules, "orders": orders}
339
+
340
+
341
+ def render_paragraphs(
342
+ main_paragraphs: List[Dict[str, Any]], rules: Dict[str, Any]
343
+ ) -> Tuple[str, List[str]]:
344
+ """
345
+ Applies the parsed CSS rules to the paragraph structure and
346
+ reconstructs the visible text.
347
+
348
+ Handles special class styles like .sy-*, text order control,
349
+ mirrored characters, etc.
350
+
351
+ :param main_paragraphs: A list of paragraph dictionaries, each with 'attrs'
352
+ and 'data' fields representing structured content.
353
+ :param rules: A dictionary with keys 'orders' and 'rules', parsed from CSS.
354
+ - rules['orders']: List of (selector, id) tuples.
355
+ - rules['rules']: Nested dict containing transformation rules.
356
+
357
+ :return:
358
+ - A reconstructed paragraph string with line breaks.
359
+ - A list of mirrored (reflected) characters for later OCR processing.
360
+ """
361
+ orders: List[Tuple[str, str]] = rules.get("orders", [])
362
+ rules = rules.get("rules", {})
363
+ refl_list: List[str] = []
364
+
365
+ def apply_rule(data: Dict[str, Any], rule: Dict[str, Any]) -> str:
366
+ if rule.get("delete-all", False):
367
+ return ""
368
+
369
+ curr_str = ""
370
+ if isinstance(data.get("data"), list) and data["data"]:
371
+ first_data = data["data"][0]
372
+ if isinstance(first_data, str):
373
+ curr_str += first_data
374
+
375
+ if rule.get("delete-first", False):
376
+ if len(curr_str) <= 1:
377
+ curr_str = ""
378
+ else:
379
+ curr_str = curr_str[1:]
380
+
381
+ curr_str += rule.get("append-end-char", "")
382
+
383
+ attr_name = rule.get("append-end-attr", "")
384
+ if attr_name:
385
+ curr_str += data.get("attrs", {}).get(attr_name, "")
386
+
387
+ curr_str = rule.get("append-start-char", "") + curr_str
388
+
389
+ attr_name = rule.get("append-start-attr", "")
390
+ if attr_name:
391
+ curr_str = data.get("attrs", {}).get(attr_name, "") + curr_str
392
+
393
+ if rule.get("transform-x_-1", False):
394
+ refl_list.append(curr_str)
395
+ return curr_str
396
+
397
+ paragraphs_str = ""
398
+ for paragraph in main_paragraphs:
399
+ class_list = paragraph.get("attrs", {}).get("class", [])
400
+ p_class_str = next((c for c in class_list if c.startswith("p")), None)
401
+ curr_datas = paragraph.get("data", [])
402
+
403
+ ordered_cache = {}
404
+ for data in curr_datas:
405
+ # 文本节点直接加
406
+ if isinstance(data, str):
407
+ paragraphs_str += data
408
+ continue
409
+
410
+ if isinstance(data, dict):
411
+ tag = data.get("tag", "")
412
+ attrs = data.get("attrs", {})
413
+
414
+ # 跳过 span.review
415
+ if tag == "span" and "class" in attrs and "review" in attrs["class"]:
416
+ continue
417
+
418
+ # sy 类型标签处理
419
+ if tag == "y":
420
+ tag_class_list = attrs.get("class", [])
421
+ tag_class = next(
422
+ (c for c in tag_class_list if c.startswith("sy-")), None
423
+ )
424
+
425
+ if tag_class in rules.get("sy", {}):
426
+ curr_rule = rules["sy"][tag_class]
427
+ paragraphs_str += apply_rule(data, curr_rule)
428
+ continue
429
+
430
+ if not p_class_str:
431
+ if any(cls in IGNORED_CLASS_LISTS for cls in class_list):
432
+ continue
433
+ logger.debug(f"[parser] not find p_class_str: {class_list}")
434
+ continue
435
+ # 普通标签处理,根据 orders 顺序匹配
436
+ for ord_selector, ord_id in orders:
437
+ tag_name = f"{ord_selector}"
438
+ if data.get("tag") != tag_name:
439
+ continue
440
+ curr_rule = rules.get(p_class_str, {}).get(ord_selector)
441
+ curr_rule = curr_rule if curr_rule else {}
442
+ ordered_cache[ord_selector] = apply_rule(data, curr_rule)
443
+ break
444
+ # 最后按 orders 顺序拼接
445
+ for ord_selector, ord_id in orders:
446
+ if ord_selector in ordered_cache:
447
+ paragraphs_str += ordered_cache[ord_selector]
448
+
449
+ paragraphs_str += "\n\n"
450
+
451
+ return paragraphs_str, refl_list
@@ -0,0 +1,119 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ novel_downloader.core.parsers.qidian_parser.session.chapter_normal
5
+ ------------------------------------------------------------------
6
+
7
+ Provides `parse_normal_chapter`, which will:
8
+
9
+ 1. Extract SSR context from a “normal” (non-VIP) chapter page and format it.
10
+ 2. Detect VIP/encrypted chapters and fall back to Node-based decryption
11
+ via `QidianNodeDecryptor`.
12
+ """
13
+
14
+ import logging
15
+ from typing import Any, Dict, Optional
16
+
17
+ from bs4 import BeautifulSoup
18
+
19
+ from ..shared import (
20
+ extract_chapter_info,
21
+ find_ssr_page_context,
22
+ html_to_soup,
23
+ vip_status,
24
+ )
25
+ from .node_decryptor import QidianNodeDecryptor
26
+
27
+ logger = logging.getLogger(__name__)
28
+ _decryptor: Optional[QidianNodeDecryptor] = None
29
+
30
+
31
+ def _get_decryptor() -> QidianNodeDecryptor:
32
+ """
33
+ Return the singleton QidianNodeDecryptor, initializing it on first use.
34
+ """
35
+ global _decryptor
36
+ if _decryptor is None:
37
+ _decryptor = QidianNodeDecryptor()
38
+ return _decryptor
39
+
40
+
41
+ def parse_normal_chapter(
42
+ soup: BeautifulSoup,
43
+ chapter_id: str,
44
+ fuid: str,
45
+ ) -> Dict[str, Any]:
46
+ """
47
+ Extract structured chapter info from a normal Qidian page.
48
+
49
+ :param soup: A BeautifulSoup of the chapter HTML.
50
+ :param chapter_id: Chapter identifier (string).
51
+ :param fuid: Fock user ID parameter from the page.
52
+ :return: a dictionary with keys like 'id', 'title', 'content', etc.
53
+ """
54
+ try:
55
+ ssr_data = find_ssr_page_context(soup)
56
+ chapter_info = extract_chapter_info(ssr_data)
57
+ if not chapter_info:
58
+ logger.warning(
59
+ "[Parser] ssr_chapterInfo not found for chapter '%s'", chapter_id
60
+ )
61
+ return {}
62
+
63
+ title = chapter_info.get("chapterName", "Untitled")
64
+ raw_html = chapter_info.get("content", "")
65
+ chapter_id = chapter_info.get("chapterId", "")
66
+ fkp = chapter_info.get("fkp", "")
67
+ author_say = chapter_info.get("authorSay", "")
68
+ update_time = chapter_info.get("updateTime", "")
69
+ update_timestamp = chapter_info.get("updateTimestamp", 0)
70
+ modify_time = chapter_info.get("modifyTime", 0)
71
+ word_count = chapter_info.get("wordsCount", 0)
72
+ vip = bool(chapter_info.get("vipStatus", 0))
73
+ is_buy = bool(chapter_info.get("isBuy", 0))
74
+ seq = chapter_info.get("seq", None)
75
+ order = chapter_info.get("chapterOrder", None)
76
+ volume = chapter_info.get("extra", {}).get("volumeName", "")
77
+
78
+ if not raw_html:
79
+ logger.warning("[Parser] raw_html not found for chapter '%s'", chapter_id)
80
+ return {}
81
+
82
+ if vip_status(soup):
83
+ try:
84
+ decryptor = _get_decryptor()
85
+ raw_html = decryptor.decrypt(
86
+ raw_html,
87
+ chapter_id,
88
+ fkp,
89
+ fuid,
90
+ )
91
+ except Exception as e:
92
+ logger.error("[Parser] decryption failed for '%s': %s", chapter_id, e)
93
+ return {}
94
+
95
+ paras_soup = html_to_soup(raw_html)
96
+ paras = [p.get_text(strip=True) for p in paras_soup.find_all("p")]
97
+ chapter_text = "\n\n".join(paras)
98
+
99
+ return {
100
+ "id": str(chapter_id),
101
+ "title": title,
102
+ "content": chapter_text,
103
+ "author_say": author_say.strip() if author_say else "",
104
+ "updated_at": update_time,
105
+ "update_timestamp": update_timestamp,
106
+ "modify_time": modify_time,
107
+ "word_count": word_count,
108
+ "vip": vip,
109
+ "purchased": is_buy,
110
+ "order": order,
111
+ "seq": seq,
112
+ "volume": volume,
113
+ }
114
+
115
+ except Exception as e:
116
+ logger.warning(
117
+ "[Parser] parse error for normal chapter '%s': %s", chapter_id, e
118
+ )
119
+ return {}