repdf 0.1.0__tar.gz → 0.1.1__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.
Files changed (37) hide show
  1. {repdf-0.1.0 → repdf-0.1.1}/PKG-INFO +7 -4
  2. {repdf-0.1.0 → repdf-0.1.1}/README.md +5 -2
  3. {repdf-0.1.0 → repdf-0.1.1}/pyproject.toml +2 -2
  4. {repdf-0.1.0 → repdf-0.1.1}/pyproject.toml.orig +2 -2
  5. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/app.py +28 -2
  6. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/icons.py +6 -1
  7. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/ocr.py +112 -24
  8. repdf-0.1.1/src/repdf/ocr_languages.py +219 -0
  9. repdf-0.1.1/src/repdf/ocr_models.py +82 -0
  10. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/packaging_smoke.py +19 -0
  11. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/render_worker.py +13 -4
  12. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/renderer.py +3 -1
  13. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/strings.py +25 -0
  14. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/theme.py +8 -0
  15. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/toolbar.py +39 -0
  16. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/__init__.py +0 -0
  17. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/__main__.py +0 -0
  18. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/assets/check-dark.svg +0 -0
  19. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/assets/check.svg +0 -0
  20. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/assets/partial-dark.svg +0 -0
  21. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/assets/partial.svg +0 -0
  22. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/assets/repdf.ico +0 -0
  23. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/assets/repdf.png +0 -0
  24. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/core.py +0 -0
  25. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/entrypoint.py +0 -0
  26. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/images.py +0 -0
  27. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/navigation.py +0 -0
  28. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/page_view.py +0 -0
  29. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/pdf_navigation.py +0 -0
  30. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/preferences.py +0 -0
  31. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/preview.py +0 -0
  32. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/print_preview.py +0 -0
  33. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/printing.py +0 -0
  34. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/search.py +0 -0
  35. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/search_panel.py +0 -0
  36. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/widgets.py +0 -0
  37. {repdf-0.1.0 → repdf-0.1.1}/src/repdf/workers.py +0 -0
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: repdf
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: RePDF (Read the PDF): a desktop PDF reader with printing, search, bookmarks, OCR and page rearrangement.
5
5
  Requires-Dist: onnxruntime>=1.31.0,<2
6
6
  Requires-Dist: pillow>=11.0,<13
7
7
  Requires-Dist: pypdf[crypto]>=5.0,<7
8
8
  Requires-Dist: pypdfium2>=4.30,<6
9
9
  Requires-Dist: pyside6>=6.8,<7
10
- Requires-Dist: rapidocr==3.10.0
10
+ Requires-Dist: rapidocr[rtl]==3.10.0
11
11
  Requires-Dist: regex>=2024.11.6
12
12
  Requires-Python: >=3.11
13
13
  Project-URL: Homepage, https://github.com/codemee/repdf
@@ -36,7 +36,7 @@ RePDF 代表 **Read the PDF**,命令與 Python 套件名稱為 `repdf`。這
36
36
  - **macOS Apple Silicon(arm64)**:下載 `repdf-<版本>-macos-arm64.dmg`,開啟後將 `RePDF.app` 拖入 Applications,再從 Applications 啟動。
37
37
 
38
38
  - Release 同時提供 SHA256 校驗檔。
39
- - 桌面套件已包含 OCR 執行環境與模型,不需要額外安裝。
39
+ - 桌面套件已包含 OCR 執行環境與內建多語言模型;其他語言可在首次選用時下載,之後離線辨識。
40
40
  - 目前未設定 Windows 程式碼簽章或 macOS Developer ID 簽章/公證,下載後可能出現系統安全提示。
41
41
 
42
42
  ### 2. 使用 uv tool 安裝
@@ -214,7 +214,10 @@ repdf
214
214
  - 輸出完整內嵌圖片,不套用頁面上的旋轉或裁切,也不包含周圍文字與向量圖形。
215
215
  - 點到空白處會顯示提示;同一位置有多張圖片時,選取最後繪製的圖片。
216
216
  - 掃描頁面通常會擷取整張掃描圖,無法從中直接分離照片或圖表。
217
- - OCR 支援繁體中文、簡體中文、英文、日文及多種拉丁字母語言,不支援韓文;辨識後請校對結果。完整操作與限制見 [OCR 說明](docs/OCR.md)。
217
+ - OCR 預設支援繁體中文、簡體中文、英文、日文及多種拉丁字母語言。點「區域 OCR」旁的箭頭,可選韓文、泰文、俄文/烏克蘭文、阿拉伯文與印地文/尼泊爾文;另提供希臘文、泰米爾文與泰盧固文。
218
+ - 選「自動+已下載模型」可共用內建與已下載模型,逐行選擇辨識結果,不會自行下載其他模型。
219
+ - 語言選單以分隔線區分自動選項、已下載與未下載三組,不顯示群組標題;已下載的模型名稱後會標記「已下載」。模型下載、遺失或損壞後,分組與標記會自動更新。
220
+ - 額外模型會先顯示下載確認,下載完成才切換語言;取消或失敗保留原設定。語言設定會記住,並套用於區域 OCR 及損壞文字備援。辨識後請校對結果。完整操作與限制見 [OCR 說明](docs/OCR.md)。
218
221
 
219
222
  ## 語言與配色
220
223
 
@@ -19,7 +19,7 @@ RePDF 代表 **Read the PDF**,命令與 Python 套件名稱為 `repdf`。這
19
19
  - **macOS Apple Silicon(arm64)**:下載 `repdf-<版本>-macos-arm64.dmg`,開啟後將 `RePDF.app` 拖入 Applications,再從 Applications 啟動。
20
20
 
21
21
  - Release 同時提供 SHA256 校驗檔。
22
- - 桌面套件已包含 OCR 執行環境與模型,不需要額外安裝。
22
+ - 桌面套件已包含 OCR 執行環境與內建多語言模型;其他語言可在首次選用時下載,之後離線辨識。
23
23
  - 目前未設定 Windows 程式碼簽章或 macOS Developer ID 簽章/公證,下載後可能出現系統安全提示。
24
24
 
25
25
  ### 2. 使用 uv tool 安裝
@@ -197,7 +197,10 @@ repdf
197
197
  - 輸出完整內嵌圖片,不套用頁面上的旋轉或裁切,也不包含周圍文字與向量圖形。
198
198
  - 點到空白處會顯示提示;同一位置有多張圖片時,選取最後繪製的圖片。
199
199
  - 掃描頁面通常會擷取整張掃描圖,無法從中直接分離照片或圖表。
200
- - OCR 支援繁體中文、簡體中文、英文、日文及多種拉丁字母語言,不支援韓文;辨識後請校對結果。完整操作與限制見 [OCR 說明](docs/OCR.md)。
200
+ - OCR 預設支援繁體中文、簡體中文、英文、日文及多種拉丁字母語言。點「區域 OCR」旁的箭頭,可選韓文、泰文、俄文/烏克蘭文、阿拉伯文與印地文/尼泊爾文;另提供希臘文、泰米爾文與泰盧固文。
201
+ - 選「自動+已下載模型」可共用內建與已下載模型,逐行選擇辨識結果,不會自行下載其他模型。
202
+ - 語言選單以分隔線區分自動選項、已下載與未下載三組,不顯示群組標題;已下載的模型名稱後會標記「已下載」。模型下載、遺失或損壞後,分組與標記會自動更新。
203
+ - 額外模型會先顯示下載確認,下載完成才切換語言;取消或失敗保留原設定。語言設定會記住,並套用於區域 OCR 及損壞文字備援。辨識後請校對結果。完整操作與限制見 [OCR 說明](docs/OCR.md)。
201
204
 
202
205
  ## 語言與配色
203
206
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "repdf"
3
- version = "0.1.0"
3
+ version = "0.1.1"
4
4
  description = "RePDF (Read the PDF): a desktop PDF reader with printing, search, bookmarks, OCR and page rearrangement."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -10,7 +10,7 @@ dependencies = [
10
10
  "pypdf[crypto]>=5.0,<7",
11
11
  "pypdfium2>=4.30,<6",
12
12
  "pyside6>=6.8,<7",
13
- "rapidocr==3.10.0",
13
+ "rapidocr[rtl]==3.10.0",
14
14
  "regex>=2024.11.6",
15
15
  ]
16
16
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "repdf"
3
- version = "0.1.0"
3
+ version = "0.1.1"
4
4
  description = "RePDF (Read the PDF): a desktop PDF reader with printing, search, bookmarks, OCR and page rearrangement."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -11,7 +11,7 @@ dependencies = [
11
11
  "pypdf[crypto]>=5.0,<7",
12
12
  "pypdfium2>=4.30,<6",
13
13
  "pyside6>=6.8,<7",
14
- "rapidocr==3.10.0",
14
+ "rapidocr[rtl]==3.10.0",
15
15
  "regex>=2024.11.6",
16
16
  ]
17
17
 
@@ -10,7 +10,7 @@ from importlib.resources import files
10
10
  from pathlib import Path
11
11
  from shiboken6 import isValid
12
12
 
13
- from PySide6.QtCore import QEvent, QSettings, QSize, Qt, QThreadPool, QTimer, Slot
13
+ from PySide6.QtCore import QEvent, QPointF, QSettings, QSize, Qt, QThreadPool, QTimer, Slot
14
14
  from PySide6.QtGui import (
15
15
  QCloseEvent,
16
16
  QAction,
@@ -66,6 +66,7 @@ from repdf.search_panel import SearchController
66
66
  from repdf.page_view import PageViewport, PreviewCache
67
67
  from repdf.navigation import NavigationController
68
68
  from repdf.printing import PrintController
69
+ from repdf.ocr_languages import OcrLanguageController
69
70
 
70
71
 
71
72
  class DocumentView(QWidget):
@@ -383,6 +384,7 @@ class MainWindow(QMainWindow):
383
384
  self._next_generation = 0
384
385
  self._render_documents = {}
385
386
  self._text_requests = {}
387
+ self._ocr_generations = {}
386
388
  self._image_requests = {}
387
389
  self._active_tasks = set()
388
390
  self._load_batches = {}
@@ -714,8 +716,11 @@ class MainWindow(QMainWindow):
714
716
  self.region_ocr_action.setCheckable(True)
715
717
  self.region_ocr_action.setToolTip(tr('區域 OCR:框選頁面或圖片中的區域,放開滑鼠後辨識並複製文字。'))
716
718
  self.region_ocr_action.toggled.connect(self._set_region_ocr_mode)
717
- self.toolbar.addAction(self.region_ocr_action)
719
+ self.ocr_languages = OcrLanguageController(self)
720
+ self.ocr_language_button = self.toolbar.add_action_menu_group(self.region_ocr_action, self.ocr_languages.menu)
718
721
  self.toolbar.widgetForAction(self.region_ocr_action).setObjectName('regionOcrTool')
722
+ self.ocr_language_button.setToolTip(tr('OCR 辨識語言'))
723
+ self.ocr_language_button.setAccessibleName(tr('OCR 辨識語言'))
719
724
  self.extract_image_action = QAction(tr('擷取圖片'), self)
720
725
  self.extract_image_action.setCheckable(True)
721
726
  self.extract_image_action.setEnabled(False)
@@ -808,6 +813,8 @@ class MainWindow(QMainWindow):
808
813
  button.setFixedSize(34, 34)
809
814
 
810
815
  def _refresh_toolbar_icons(self) -> None:
816
+ if hasattr(self, 'ocr_language_button'):
817
+ self.ocr_language_button.setIcon(toolbar_icon('chevron_down'))
811
818
  for action, kind in ((self.open_action, "open"), (self.export_action, "export"),
812
819
  (self.split_action, "split"), (self.copy_text_action, "copy_text"),
813
820
  (self.region_ocr_action, "ocr_region"),
@@ -868,6 +875,7 @@ class MainWindow(QMainWindow):
868
875
  self._update_preference_actions()
869
876
  self.search_controller.retranslate()
870
877
  self.navigation.retranslate()
878
+ self.ocr_languages.refresh()
871
879
 
872
880
  def changeEvent(self, event: QEvent) -> None:
873
881
  super().changeEvent(event)
@@ -930,6 +938,7 @@ class MainWindow(QMainWindow):
930
938
  for label in self._fullscreen_preview.labels.values():
931
939
  label.set_text_mode(enabled, region=region, image=image)
932
940
  self._text_requests.clear()
941
+ self._ocr_generations.clear()
933
942
  self._image_requests.clear()
934
943
 
935
944
  def _copy_text_selection(self, doc, page_index, label, start, end, *, copy=True) -> None:
@@ -950,12 +959,14 @@ class MainWindow(QMainWindow):
950
959
  if document_id == doc.document_id:
951
960
  self._text_requests.pop(previous)
952
961
  self._text_requests[generation] = (doc.document_id, label, copy)
962
+ self._ocr_generations[doc.document_id] = generation
953
963
  self.render_service.request_text(
954
964
  doc.source_path, page_index,
955
965
  (start.x() / label.width(), start.y() / label.height()),
956
966
  (end.x() / label.width(), end.y() / label.height()),
957
967
  generation, -1_000_000 - doc.document_id,
958
968
  allow_ocr=copy, region_ocr=region, password=doc.password,
969
+ ocr_profile=self.ocr_languages.profile,
959
970
  )
960
971
  if copy:
961
972
  self.statusBar().showMessage(tr('正在辨識選取區域…') if region else tr('正在擷取文字…'))
@@ -1305,6 +1316,7 @@ class MainWindow(QMainWindow):
1305
1316
  if document_id == doc.document_id:
1306
1317
  self._render_documents.pop(generation)
1307
1318
  self.documents.pop(doc.document_id, None)
1319
+ self._ocr_generations.pop(doc.document_id, None)
1308
1320
  self.search_controller.remove_document(doc.document_id)
1309
1321
  self.navigation.remove_document(doc)
1310
1322
  self.tabs.removeTab(index)
@@ -1340,6 +1352,19 @@ class MainWindow(QMainWindow):
1340
1352
  if generation in self._text_requests:
1341
1353
  document_id, label, copy = self._text_requests[generation]
1342
1354
  if document_id in self.documents and not self._closing:
1355
+ retry = payload.get('ocr_retry')
1356
+ if payload.get('ocr_model_missing') and copy and retry:
1357
+ def retry_selection(document_id=document_id, label=label, retry=retry, generation=generation):
1358
+ doc = self.documents.get(document_id)
1359
+ if (doc is None or not isValid(label) or self._closing or not label.text_mode
1360
+ or self._ocr_generations.get(document_id) != generation
1361
+ or self.ocr_languages.profile != retry['ocr_profile']
1362
+ or label.region_mode != (retry['type'] == 'ocr_region')):
1363
+ return
1364
+ self._copy_text_selection(doc, retry['page'], label,
1365
+ QPointF(retry['start'][0] * label.width(), retry['start'][1] * label.height()),
1366
+ QPointF(retry['end'][0] * label.width(), retry['end'][1] * label.height()))
1367
+ self.ocr_languages.ensure(retry['ocr_profile'], retry_selection)
1343
1368
  if payload.get('type') == 'ocr' and copy:
1344
1369
  self.statusBar().showMessage(tr('選取文字疑似損壞,正在進行 OCR…'))
1345
1370
  elif payload.get('type') == 'text':
@@ -1478,6 +1503,7 @@ class MainWindow(QMainWindow):
1478
1503
 
1479
1504
  def closeEvent(self, event: QCloseEvent) -> None:
1480
1505
  self._closing = True
1506
+ self.ocr_languages.close()
1481
1507
  self.print_controller.close()
1482
1508
  self.search_controller.stop()
1483
1509
  self._password_queue.clear()
@@ -20,7 +20,12 @@ def toolbar_icon(kind: str) -> QIcon:
20
20
  painter.setPen(QPen(QApplication.palette().color(group, role),
21
21
  1.0, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap,
22
22
  Qt.PenJoinStyle.RoundJoin))
23
- if kind == "more":
23
+ if kind == 'chevron_down':
24
+ pen = painter.pen()
25
+ pen.setWidthF(2)
26
+ painter.setPen(pen)
27
+ painter.drawPolyline(QPolygonF([QPointF(6, 9), QPointF(12, 15), QPointF(18, 9)]))
28
+ elif kind == "more":
24
29
  painter.setBrush(painter.pen().color())
25
30
  for x in (5, 12, 19):
26
31
  painter.drawEllipse(QRectF(x - 1, 11, 2, 2))
@@ -2,6 +2,7 @@
2
2
  from __future__ import annotations
3
3
 
4
4
  import hashlib
5
+ import math
5
6
  import re
6
7
  import time
7
8
  import unicodedata
@@ -10,12 +11,17 @@ from importlib.util import find_spec
10
11
  from pathlib import Path
11
12
 
12
13
  from PIL import ImageOps
14
+ from repdf.ocr_models import PROFILES, installed_profiles, model_available, model_path
13
15
 
14
16
 
15
17
  class OcrError(RuntimeError):
16
18
  pass
17
19
 
18
20
 
21
+ class OcrModelMissing(OcrError):
22
+ pass
23
+
24
+
19
25
  def _clean_line(text: str) -> str:
20
26
  # Remove OCR segmentation spaces within CJK text; keep English word spaces.
21
27
  cjk = r'\u3400-\u9fff\uf900-\ufaff\U00020000-\U000323af'
@@ -37,28 +43,39 @@ DETECTION_SHA256 = '090f04abcd9d9a7498bc4ebf677e4cb9bdce1fe4197ddb7e529f1ef44e1f
37
43
 
38
44
 
39
45
  @lru_cache(maxsize=1)
40
- def _engine():
46
+ def _engine(profile='builtin'):
41
47
  """Load only on first damaged selection, in the existing background process."""
42
48
  try:
43
49
  spec = find_spec('rapidocr')
44
50
  if spec is None or spec.origin is None:
45
51
  raise OcrError('RapidOCR is not installed. Run uv sync.')
46
- model = Path(spec.origin).parent / 'models' / MODEL_NAME
52
+ if profile not in PROFILES:
53
+ raise OcrError('Unknown OCR language.')
54
+ bundled = Path(spec.origin).parent / 'models'
55
+ model = bundled / MODEL_NAME
56
+ if profile != 'builtin':
57
+ if not model_available(profile):
58
+ raise OcrModelMissing('OCR language model is missing or damaged.')
59
+ model = model_path(profile)
47
60
  if not model.is_file():
48
61
  raise OcrError('Bundled OCR model is missing. Reinstall RapidOCR 3.10.0.')
49
- if hashlib.sha256(model.read_bytes()).hexdigest() != MODEL_SHA256:
62
+ if profile == 'builtin' and hashlib.sha256(model.read_bytes()).hexdigest() != MODEL_SHA256:
50
63
  raise OcrError('Bundled OCR model checksum mismatch.')
51
- from rapidocr import RapidOCR
52
- engine = RapidOCR(params={
64
+ from rapidocr import ModelType, OCRVersion, RapidOCR
65
+ params = {
53
66
  'Global.use_det': False,
54
67
  'Global.use_cls': False,
55
68
  'Global.use_preprocess_img': False,
56
69
  'Global.log_level': 'error',
57
70
  'Rec.model_path': str(model), # Explicit local path disables model downloads.
58
- 'Det.model_path': str(model.parent / DETECTION_MODEL),
71
+ 'Det.model_path': str(bundled / DETECTION_MODEL),
59
72
  'EngineConfig.onnxruntime.intra_op_num_threads': 2,
60
73
  'EngineConfig.onnxruntime.inter_op_num_threads': 1,
61
- })
74
+ }
75
+ if profile != 'builtin':
76
+ params.update({'Rec.ocr_version': OCRVersion.PPOCRV5, 'Rec.model_type': ModelType.MOBILE,
77
+ 'Rec.lang_type': profile})
78
+ engine = RapidOCR(params=params)
62
79
  return engine
63
80
  except OcrError:
64
81
  raise
@@ -92,18 +109,13 @@ def _line_regions(rects: list[list[float]]) -> list[list[float]]:
92
109
  return lines
93
110
 
94
111
 
95
- def recognize_selection(page, rects: list[list[float]]) -> str:
96
- """Render selected glyphs at 400 DPI; do not OCR arbitrary/image-only regions."""
97
- if not rects:
98
- raise OcrError('No selected text bounds are available.')
112
+ def _recognize_candidates(page, lines, profile, deadline, *, tolerate_errors=False):
99
113
  width, height = page.get_size()
100
114
  scale = 400 / 72
101
- lines = _line_regions(rects)
102
- if len(lines) > 30:
103
- raise OcrError('Please select at most 30 lines for OCR.')
104
- engine = _engine()
115
+ if time.monotonic() >= deadline:
116
+ raise OcrError('OCR time limit reached.')
117
+ engine = _engine() if profile == 'builtin' else _engine(profile)
105
118
  output = []
106
- deadline = time.monotonic() + 60
107
119
  for left, top, right, bottom in lines:
108
120
  # Small padding preserves antialiased glyph edges without adding neighbours.
109
121
  x0, y0 = max(0, left * width - 0.5), max(0, top * height - 0.5)
@@ -120,19 +132,94 @@ def recognize_selection(page, rects: list[list[float]]) -> str:
120
132
  try:
121
133
  result = engine(image, use_det=False, use_cls=False, use_rec=True)
122
134
  except Exception as exc:
135
+ if time.monotonic() >= deadline:
136
+ raise OcrError('OCR time limit reached.') from exc
137
+ if tolerate_errors:
138
+ output.append(None)
139
+ continue
123
140
  raise OcrError(f'RapidOCR failed: {exc}') from exc
141
+ if time.monotonic() >= deadline:
142
+ raise OcrError('OCR time limit reached.')
124
143
  if not result.txts or not result.scores:
125
- raise OcrError('OCR did not return usable text.')
144
+ output.append(None)
145
+ continue
126
146
  text = result.txts[0].strip()
127
- if not text or suspicious_text(text) or min(result.scores) < 0.8:
147
+ score = min(result.scores)
148
+ if not text or suspicious_text(text) or not math.isfinite(score) or not .8 <= score <= 1:
149
+ output.append(None)
150
+ else:
151
+ output.append((_clean_line(text), score))
152
+ return output
153
+
154
+
155
+ _SCRIPT_NAMES = {'korean': ('HANGUL',), 'th': ('THAI',), 'cyrillic': ('CYRILLIC',),
156
+ 'arabic': ('ARABIC',), 'devanagari': ('DEVANAGARI',), 'el': ('GREEK',),
157
+ 'ta': ('TAMIL',), 'te': ('TELUGU',)}
158
+
159
+
160
+ def _choose_candidate(candidates):
161
+ """Conservative heuristics, not calibrated cross-model probabilities."""
162
+ baseline = candidates.get('builtin')
163
+ alternatives = []
164
+ for profile, candidate in candidates.items():
165
+ if profile == 'builtin' or candidate is None:
166
+ continue
167
+ text, score = candidate
168
+ letters = [char for char in text if unicodedata.category(char).startswith('L')]
169
+ matching = sum(any(script in unicodedata.name(char, '') for script in _SCRIPT_NAMES[profile])
170
+ for char in letters)
171
+ # A specialist returning Latin gibberish must not replace multilingual text.
172
+ if not letters or matching / len(letters) < .6:
173
+ continue
174
+ if baseline is not None and score < .9:
175
+ continue
176
+ alternatives.append((score, text))
177
+ alternatives.sort(reverse=True)
178
+ if alternatives:
179
+ score, text = alternatives[0]
180
+ # Conflicting scripts with nearly equal evidence remain uncertain.
181
+ ambiguous = len(alternatives) > 1 and score - alternatives[1][0] < .03
182
+ if not ambiguous and (baseline is None or score + .04 > baseline[1] + .02):
183
+ return text
184
+ if baseline is not None:
185
+ return baseline[0]
186
+ raise OcrError('OCR result is empty, damaged, ambiguous or low confidence.')
187
+
188
+
189
+ def recognize_selection(page, rects: list[list[float]], *, profile='builtin') -> str:
190
+ """Recognize each line, optionally comparing only already installed models."""
191
+ if not rects:
192
+ raise OcrError('No selected text bounds are available.')
193
+ lines = _line_regions(rects)
194
+ if len(lines) > 30:
195
+ raise OcrError('Please select at most 30 lines for OCR.')
196
+ deadline = time.monotonic() + 60
197
+ if profile != 'auto':
198
+ candidates = _recognize_candidates(page, lines, profile, deadline)
199
+ if any(candidate is None for candidate in candidates):
128
200
  raise OcrError('OCR result is empty, damaged or low confidence.')
129
- output.append(_clean_line(text))
130
- return '\n'.join(output)
201
+ return '\n'.join(candidate[0] for candidate in candidates)
202
+ results = {'builtin': _recognize_candidates(page, lines, 'builtin', deadline, tolerate_errors=True)}
203
+ # Model-major order loads each engine once per request, rather than once per line.
204
+ # Rendering one crop at a time also avoids retaining thirty large line images.
205
+ for installed in installed_profiles():
206
+ if time.monotonic() >= deadline:
207
+ raise OcrError('OCR time limit reached.')
208
+ try:
209
+ results[installed] = _recognize_candidates(page, lines, installed, deadline, tolerate_errors=True)
210
+ except OcrError:
211
+ # A model removed/damaged after discovery must not trigger a download.
212
+ if time.monotonic() >= deadline:
213
+ raise OcrError('OCR time limit reached.')
214
+ continue
215
+ if time.monotonic() >= deadline:
216
+ raise OcrError('OCR time limit reached.')
217
+ return '\n'.join(_choose_candidate({name: values[index] for name, values in results.items()})
218
+ for index in range(len(lines)))
131
219
 
132
220
 
133
- def recognize_region(page, start, end) -> dict[str, object]:
221
+ def recognize_region(page, start, end, *, profile='builtin') -> dict[str, object]:
134
222
  """OCR the displayed page rectangle, including image-only PDF content."""
135
- import math
136
223
  if len(start) != 2 or len(end) != 2:
137
224
  raise OcrError('Invalid OCR region.')
138
225
  values = [float(value) for value in (*start, *end)]
@@ -158,7 +245,8 @@ def recognize_region(page, start, end) -> dict[str, object]:
158
245
  finally:
159
246
  bitmap.close()
160
247
  try:
161
- result = _engine()(image, use_det=True, use_cls=False, use_rec=False)
248
+ engine = _engine() if profile in ('builtin', 'auto') else _engine(profile)
249
+ result = engine(image, use_det=True, use_cls=False, use_rec=False)
162
250
  except OcrError:
163
251
  raise
164
252
  except Exception as exc:
@@ -173,4 +261,4 @@ def recognize_region(page, start, end) -> dict[str, object]:
173
261
  x0 + max(xs) / image.width * (x1 - x0),
174
262
  y0 + max(ys) / image.height * (y1 - y0)])
175
263
  rects = _line_regions(rects)
176
- return {'text': recognize_selection(page, rects), 'rects': rects, 'ocr_used': True}
264
+ return {'text': recognize_selection(page, rects, profile=profile), 'rects': rects, 'ocr_used': True}
@@ -0,0 +1,219 @@
1
+ """Language selection and cancellable downloads for source and frozen applications."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+
6
+ from PySide6.QtCore import QObject, QIODevice, QSaveFile, QTimer, Qt, QUrl
7
+ from PySide6.QtGui import QAction, QActionGroup
8
+ from PySide6.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest
9
+ from PySide6.QtWidgets import (QDialog, QDialogButtonBox, QLabel, QMenu,
10
+ QProgressBar, QVBoxLayout)
11
+
12
+ from repdf.ocr_models import PROFILES, installed_profiles, model_available, model_path
13
+ from repdf.strings import tr
14
+
15
+
16
+ class OcrModelDialog(QDialog):
17
+ def __init__(self, profile, parent=None):
18
+ super().__init__(parent)
19
+ self.profile = profile
20
+ self.reply = None
21
+ self.file = None
22
+ self.network = QNetworkAccessManager(self)
23
+ self.setWindowTitle(tr('下載 OCR 語言模型'))
24
+ self.setWindowModality(Qt.WindowModality.WindowModal)
25
+ self.resize(460, 250)
26
+ layout = QVBoxLayout(self)
27
+ self.message = QLabel(tr('「{language}」需要額外下載模型。確認後將從 RapidOCR 官方模型來源下載至使用者資料目錄;完成後可離線使用,不會上傳 PDF。',
28
+ language=tr(PROFILES[profile]['label'])))
29
+ self.message.setWordWrap(True)
30
+ layout.addWidget(self.message)
31
+ source = QLabel('https://www.modelscope.cn/models/RapidAI/RapidOCR')
32
+ source.setWordWrap(True)
33
+ source.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
34
+ layout.addWidget(source)
35
+ self.status = QLabel(tr('下載完成後才會切換辨識語言;取消則保留原設定。'))
36
+ self.status.setWordWrap(True)
37
+ self.status.setTextFormat(Qt.TextFormat.PlainText)
38
+ layout.addWidget(self.status)
39
+ self.progress = QProgressBar()
40
+ self.progress.setRange(0, 100)
41
+ layout.addWidget(self.progress)
42
+ buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel)
43
+ self.download_button = buttons.addButton(tr('下載並使用'), QDialogButtonBox.ButtonRole.ActionRole)
44
+ self.download_button.clicked.connect(self.start)
45
+ buttons.rejected.connect(self.reject)
46
+ layout.addWidget(buttons)
47
+ self.timer = QTimer(self)
48
+ self.timer.setSingleShot(True)
49
+ self.timer.setInterval(180_000)
50
+ self.timer.timeout.connect(lambda: self._fail(tr('下載逾時,請稍後重試。')))
51
+
52
+ def start(self):
53
+ if self.reply is not None:
54
+ return
55
+ try:
56
+ destination = model_path(self.profile)
57
+ destination.parent.mkdir(parents=True, exist_ok=True)
58
+ self.file = QSaveFile(str(destination))
59
+ if not self.file.open(QIODevice.OpenModeFlag.WriteOnly):
60
+ raise OSError(self.file.errorString())
61
+ except OSError as exc:
62
+ self._fail(str(exc))
63
+ return
64
+ self.digest = hashlib.sha256()
65
+ self.received = 0
66
+ self.download_button.setEnabled(False)
67
+ self.status.setText(tr('正在下載模型…'))
68
+ self.progress.setRange(0, 0)
69
+ request = QNetworkRequest(QUrl(PROFILES[self.profile]['url']))
70
+ request.setTransferTimeout(30_000)
71
+ self.reply = self.network.get(request)
72
+ self.reply.readyRead.connect(self._read)
73
+ self.reply.downloadProgress.connect(self._progress)
74
+ self.reply.finished.connect(self._finished)
75
+ self.timer.start()
76
+
77
+ def _progress(self, received, total):
78
+ if total > 0:
79
+ self.progress.setRange(0, 100)
80
+ self.progress.setValue(int(received * 100 / total))
81
+
82
+ def _read(self):
83
+ if self.reply is None:
84
+ return
85
+ data = bytes(self.reply.readAll())
86
+ self.received += len(data)
87
+ if self.received > 100_000_000:
88
+ self._fail(tr('下載檔案大小異常。'))
89
+ elif self.file.write(data) != len(data):
90
+ self._fail(self.file.errorString())
91
+ else:
92
+ self.digest.update(data)
93
+
94
+ def _finished(self):
95
+ if self.reply is None:
96
+ return
97
+ self._read()
98
+ if self.reply is None:
99
+ return
100
+ if self.reply.error() != QNetworkReply.NetworkError.NoError:
101
+ self._fail(self.reply.errorString())
102
+ return
103
+ if self.digest.hexdigest() != PROFILES[self.profile]['sha256']:
104
+ self._fail(tr('模型校驗失敗,請重新下載。'))
105
+ return
106
+ if not self.file.commit():
107
+ self._fail(self.file.errorString())
108
+ return
109
+ self.file = None
110
+ self._cleanup()
111
+ self.accept()
112
+
113
+ def _cleanup(self):
114
+ self.timer.stop()
115
+ reply, self.reply = self.reply, None
116
+ if reply is not None:
117
+ reply.abort()
118
+ reply.deleteLater()
119
+ if self.file is not None:
120
+ self.file.cancelWriting()
121
+ self.file = None
122
+
123
+ def _fail(self, reason):
124
+ self._cleanup()
125
+ self.progress.setRange(0, 100)
126
+ self.progress.setValue(0)
127
+ self.status.setText(tr('下載未完成:{reason}', reason=reason))
128
+ self.download_button.setEnabled(True)
129
+
130
+ def reject(self):
131
+ self._cleanup()
132
+ super().reject()
133
+
134
+
135
+ class OcrLanguageController(QObject):
136
+ def __init__(self, owner):
137
+ super().__init__(owner)
138
+ self.owner = owner
139
+ saved = owner.settings.value('ocr/language', 'builtin')
140
+ self.profile = saved if saved in PROFILES else 'builtin'
141
+ self.dialog = None
142
+ self.callbacks = []
143
+ self.menu = QMenu(owner)
144
+ self.group = QActionGroup(self)
145
+ self.actions = {}
146
+ self._menu_signature = None
147
+ for profile, info in PROFILES.items():
148
+ action = QAction(tr(info['label']), self)
149
+ action.setCheckable(True)
150
+ self.group.addAction(action)
151
+ action.triggered.connect(lambda _checked=False, profile=profile: self.choose(profile))
152
+ self.actions[profile] = action
153
+ self.menu.aboutToShow.connect(self.refresh)
154
+ self.refresh()
155
+
156
+ def refresh(self):
157
+ installed = installed_profiles()
158
+ signature = installed
159
+ if signature != self._menu_signature:
160
+ self.menu.clear()
161
+ self.menu.addAction(self.actions['builtin'])
162
+ self.menu.addAction(self.actions['auto'])
163
+ self.menu.addSeparator()
164
+ for profile in installed:
165
+ self.menu.addAction(self.actions[profile])
166
+ self.menu.addSeparator()
167
+ for profile, info in PROFILES.items():
168
+ if 'url' in info and profile not in installed:
169
+ self.menu.addAction(self.actions[profile])
170
+ self._menu_signature = signature
171
+ for profile, action in self.actions.items():
172
+ label = tr(PROFILES[profile]['label'])
173
+ action.setText(tr('{language}(已下載)', language=label) if profile in installed else label)
174
+ action.setChecked(profile == self.profile)
175
+ self.menu.setTitle(tr('OCR 辨識語言'))
176
+ self.owner.region_ocr_action.setToolTip(tr('區域 OCR:框選頁面或圖片中的文字。辨識語言:{language};按旁邊箭頭切換。',
177
+ language=tr(PROFILES[self.profile]['label'])))
178
+
179
+ def choose(self, profile):
180
+ def apply():
181
+ self.profile = profile
182
+ self.owner.settings.setValue('ocr/language', profile)
183
+ # Results from an older language must not overwrite a newer selection.
184
+ self.owner._text_requests.clear()
185
+ self.owner._ocr_generations.clear()
186
+ self.refresh()
187
+ self.ensure(profile, apply)
188
+ self.refresh()
189
+
190
+ def ensure(self, profile, callback):
191
+ if self.owner._closing:
192
+ return
193
+ if model_available(profile):
194
+ callback()
195
+ return
196
+ if self.dialog is not None:
197
+ if self.dialog.profile == profile:
198
+ self.callbacks.append(callback)
199
+ self.dialog.raise_()
200
+ self.dialog.activateWindow()
201
+ return
202
+ self.callbacks = [callback]
203
+ self.dialog = OcrModelDialog(profile, self.owner._fullscreen_preview or self.owner)
204
+ self.dialog.finished.connect(self._finished)
205
+ self.dialog.open()
206
+
207
+ def _finished(self, result):
208
+ dialog, self.dialog = self.dialog, None
209
+ callbacks, self.callbacks = self.callbacks, []
210
+ dialog.deleteLater()
211
+ if result == QDialog.DialogCode.Accepted and not self.owner._closing:
212
+ for callback in callbacks:
213
+ callback()
214
+ self.refresh()
215
+
216
+ def close(self):
217
+ self.callbacks.clear()
218
+ if self.dialog is not None:
219
+ self.dialog.reject()
@@ -0,0 +1,82 @@
1
+ """OCR model catalog pinned to the official RapidOCR 3.10.0 manifest."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import os
6
+ from pathlib import Path
7
+ import sys
8
+
9
+ PROFILES = {
10
+ 'auto': {'label': '自動+已下載模型'},
11
+ 'builtin': {'label': '自動'},
12
+ 'korean': {
13
+ 'label': '韓文',
14
+ 'url': 'https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv5/rec/korean_PP-OCRv5_rec_mobile.onnx',
15
+ 'sha256': 'cd6e2ea50f6943ca7271eb8c56a877a5a90720b7047fe9c41a2e541a25773c9b',
16
+ },
17
+ 'th': {
18
+ 'label': '泰文',
19
+ 'url': 'https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv5/rec/th_PP-OCRv5_rec_mobile.onnx',
20
+ 'sha256': 'de541dd83161c241ff426f7ecfd602a0ba77d686cf3ab9a6c255ea82fd08006e',
21
+ },
22
+ 'cyrillic': {
23
+ 'label': '俄文/烏克蘭文(西里爾字母)',
24
+ 'url': 'https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv5/rec/cyrillic_PP-OCRv5_rec_mobile.onnx',
25
+ 'sha256': '90f761b4bfcce0c8c561c0cb5c887b0971d3ec01c32164bdf7374a35b0982711',
26
+ },
27
+ 'arabic': {
28
+ 'label': '阿拉伯文',
29
+ 'url': 'https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv5/rec/arabic_PP-OCRv5_rec_mobile.onnx',
30
+ 'sha256': 'c1192e632d0baa9146ae5b756a0e635e3dc63c1733737ebfd1629e87144e9295',
31
+ },
32
+ 'devanagari': {
33
+ 'label': '印地文/尼泊爾文(天城文)',
34
+ 'url': 'https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv5/rec/devanagari_PP-OCRv5_rec_mobile.onnx',
35
+ 'sha256': 'd6f0a906580e3fa6b324a318718f1f31f268b6ea8ef985f91c2012a37f52c91e',
36
+ },
37
+ 'el': {
38
+ 'label': '希臘文',
39
+ 'url': 'https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv5/rec/el_PP-OCRv5_rec_mobile.onnx',
40
+ 'sha256': 'b4368bccd557123c702b7549fee6cd1e94b581337d1c9b65310f109131542b7f',
41
+ },
42
+ 'ta': {
43
+ 'label': '泰米爾文',
44
+ 'url': 'https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv5/rec/ta_PP-OCRv5_rec_mobile.onnx',
45
+ 'sha256': 'a42448808b7dea87597336f12438935f40353f1949e8360acd9e06b4da21bfe1',
46
+ },
47
+ 'te': {
48
+ 'label': '泰盧固文',
49
+ 'url': 'https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv5/rec/te_PP-OCRv5_rec_mobile.onnx',
50
+ 'sha256': 'a3690451b50028a09a3316a1274f7c05728151ea3f8fd392696397a7fefcbd92',
51
+ },
52
+ }
53
+
54
+
55
+ def model_directory():
56
+ # Never write to site-packages, a frozen bundle, or PyInstaller's extraction dir.
57
+ if sys.platform == 'win32':
58
+ base = Path(os.environ.get('LOCALAPPDATA', Path.home() / 'AppData/Local'))
59
+ elif sys.platform == 'darwin':
60
+ base = Path.home() / 'Library/Application Support'
61
+ else:
62
+ base = Path(os.environ.get('XDG_DATA_HOME', Path.home() / '.local/share'))
63
+ return base / 'RePDF/ocr/models'
64
+
65
+
66
+ def model_path(profile):
67
+ return model_directory() / PROFILES[profile]['url'].rsplit('/', 1)[1]
68
+
69
+
70
+ def model_available(profile):
71
+ if profile in ('auto', 'builtin'):
72
+ return True
73
+ path = model_path(profile)
74
+ try:
75
+ return hashlib.sha256(path.read_bytes()).hexdigest() == PROFILES[profile]['sha256']
76
+ except OSError:
77
+ return False
78
+
79
+
80
+ def installed_profiles():
81
+ return tuple(profile for profile, info in PROFILES.items()
82
+ if 'url' in info and model_available(profile))
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import json
4
4
  import os
5
+ import sys
5
6
  import tempfile
6
7
  import traceback
7
8
  from contextlib import ExitStack
@@ -29,6 +30,10 @@ def main(report_path: str) -> int:
29
30
  from repdf.strings import tr
30
31
  from repdf.theme import ThemeController
31
32
  from repdf.ocr import _engine, recognize_region
33
+ from repdf.ocr_languages import OcrModelDialog
34
+ from repdf.ocr_models import PROFILES, model_path
35
+ from PySide6.QtNetwork import QSslSocket
36
+ from bidi.algorithm import get_display
32
37
  from repdf.search import compile_query
33
38
  import pypdfium2 as pdfium
34
39
  from PIL import Image, ImageDraw, ImageFont
@@ -44,6 +49,17 @@ def main(report_path: str) -> int:
44
49
  language.close()
45
50
  if load_app_icon().isNull():
46
51
  raise RuntimeError("Application icon is missing")
52
+ if not QSslSocket.supportsSsl():
53
+ raise RuntimeError('HTTPS support for optional OCR model downloads is missing')
54
+ if get_display('abc') != 'abc' or 'korean' not in PROFILES:
55
+ raise RuntimeError('Optional OCR language runtime is missing')
56
+ frozen_root = getattr(sys, '_MEIPASS', None)
57
+ if frozen_root and model_path('korean').is_relative_to(Path(frozen_root)):
58
+ raise RuntimeError('Optional OCR models must be stored outside the bundle')
59
+ download_dialog = OcrModelDialog('korean')
60
+ if download_dialog.reply is not None:
61
+ raise RuntimeError('OCR downloads must require explicit confirmation')
62
+ download_dialog.reject()
47
63
  if not compile_query(r'sm.ke', regular_expression=True).search('SMOKE', timeout=1):
48
64
  raise RuntimeError('Search regular expression runtime failed')
49
65
  ocr_image = Image.new('RGB', (500, 100), 'white')
@@ -61,12 +77,15 @@ def main(report_path: str) -> int:
61
77
  ocr_page = ocr_document[0]
62
78
  try:
63
79
  region_result = recognize_region(ocr_page, [0, 0], [1, 1])
80
+ auto_result = recognize_region(ocr_page, [0, 0], [1, 1], profile='auto')
64
81
  finally:
65
82
  ocr_page.close()
66
83
  finally:
67
84
  ocr_document.close()
68
85
  if region_result['text'] != 'Copy this text':
69
86
  raise RuntimeError(f"Packaged region OCR failed: {region_result['text']}")
87
+ if auto_result['text'] != 'Copy this text':
88
+ raise RuntimeError(f"Packaged automatic OCR failed: {auto_result['text']}")
70
89
  source = root / "source.pdf"
71
90
  writer = PdfWriter()
72
91
  for width in (200, 300):
@@ -10,7 +10,7 @@ from typing import TextIO
10
10
 
11
11
  import pypdfium2 as pdfium
12
12
 
13
- from repdf.ocr import OcrError, recognize_region, recognize_selection, suspicious_text
13
+ from repdf.ocr import OcrError, OcrModelMissing, recognize_region, recognize_selection, suspicious_text
14
14
  from repdf.images import extract_clicked_image
15
15
  from repdf.pdf_navigation import read_bookmarks, read_page_label, read_page_links, resolve_destination
16
16
 
@@ -98,7 +98,7 @@ def render_document(
98
98
 
99
99
  def extract_selection_result(source: Path, page_index: int, start: list[float],
100
100
  end: list[float], *, allow_ocr: bool = False,
101
- on_ocr=None, password: str | None = None) -> dict[str, object]:
101
+ on_ocr=None, password: str | None = None, ocr_profile='builtin') -> dict[str, object]:
102
102
  """Return copied text and the matching glyph bounds in rendered-page coordinates."""
103
103
  document = pdfium.PdfDocument(str(source), password=password)
104
104
  try:
@@ -169,10 +169,12 @@ def extract_selection_result(source: Path, page_index: int, start: list[float],
169
169
  if on_ocr is not None:
170
170
  on_ocr()
171
171
  try:
172
- result['text'] = recognize_selection(page, rects)
172
+ result['text'] = (recognize_selection(page, rects) if ocr_profile == 'builtin'
173
+ else recognize_selection(page, rects, profile=ocr_profile))
173
174
  result['ocr_used'] = True
174
175
  except OcrError as exc:
175
176
  result['ocr_error'] = str(exc)
177
+ result['ocr_model_missing'] = isinstance(exc, OcrModelMissing)
176
178
  return result
177
179
  finally:
178
180
  textpage.close()
@@ -228,7 +230,8 @@ def serve(
228
230
  raise ValueError('Invalid OCR page index')
229
231
  page = document[page_index]
230
232
  try:
231
- extracted = recognize_region(page, request['start'], request['end'])
233
+ extracted = recognize_region(page, request['start'], request['end'],
234
+ profile=request.get('ocr_profile', 'builtin'))
232
235
  finally:
233
236
  page.close()
234
237
  finally:
@@ -239,8 +242,11 @@ def serve(
239
242
  extracted = extract_selection_result(Path(request["source"]), int(request["page"]),
240
243
  request["start"], request["end"], allow_ocr=bool(request.get('allow_ocr', False)),
241
244
  password=request.get('password'),
245
+ ocr_profile=request.get('ocr_profile', 'builtin'),
242
246
  on_ocr=lambda: print(json.dumps({'type': 'ocr', 'generation': int(request['generation'])}),
243
247
  file=output_stream, flush=True))
248
+ if extracted.get('ocr_model_missing'):
249
+ extracted['ocr_retry'] = {key: request[key] for key in ('type', 'page', 'start', 'end', 'ocr_profile')}
244
250
  print(json.dumps({"type": "text", "generation": int(request["generation"]),
245
251
  **extracted}), file=output_stream, flush=True)
246
252
  else:
@@ -263,6 +269,9 @@ def serve(
263
269
  "message": str(exc),
264
270
  "document_id": request.get('document_id') if isinstance(request, dict) else None,
265
271
  "timeout": isinstance(exc, TimeoutError),
272
+ "ocr_model_missing": isinstance(exc, OcrModelMissing),
273
+ "ocr_retry": ({key: request[key] for key in ('type', 'page', 'start', 'end', 'ocr_profile')}
274
+ if isinstance(exc, OcrModelMissing) else None),
266
275
  }), file=output_stream, flush=True)
267
276
  finally:
268
277
  # Release credential references before waiting for the next request.
@@ -125,11 +125,13 @@ class RenderService(QObject):
125
125
 
126
126
  def request_text(self, source: Path, page: int, start: tuple[float, float],
127
127
  end: tuple[float, float], generation: int, document_id: int,
128
- *, allow_ocr: bool = False, region_ocr: bool = False, password: str | None = None) -> None:
128
+ *, allow_ocr: bool = False, region_ocr: bool = False, password: str | None = None,
129
+ ocr_profile: str = 'builtin') -> None:
129
130
  payload: dict[str, object] = {
130
131
  "type": "ocr_region" if region_ocr else "copy_text", "source": str(source), "page": page,
131
132
  "start": start, "end": end, "generation": generation,
132
133
  "allow_ocr": allow_ocr,
134
+ "ocr_profile": ocr_profile,
133
135
  }
134
136
  if password is not None:
135
137
  payload['password'] = password
@@ -5,6 +5,31 @@ from string import Formatter
5
5
 
6
6
  LANGUAGE = "zh"
7
7
  ENGLISH = {
8
+ "{language}(已下載)": "{language} (downloaded)",
9
+ "自動+已下載模型": "Automatic + downloaded models",
10
+ "未下載": "Not downloaded",
11
+ "無": "None",
12
+ "已下載": "Downloaded",
13
+ "韓文": "Korean",
14
+ "泰文": "Thai",
15
+ "俄文/烏克蘭文(西里爾字母)": "Russian / Ukrainian (Cyrillic)",
16
+ "阿拉伯文": "Arabic",
17
+ "印地文/尼泊爾文(天城文)": "Hindi / Nepali (Devanagari)",
18
+ "希臘文": "Greek",
19
+ "泰米爾文": "Tamil",
20
+ "泰盧固文": "Telugu",
21
+ "其他語言": "Other languages",
22
+ "OCR 辨識語言": "OCR recognition language",
23
+ "下載 OCR 語言模型": "Download OCR language model",
24
+ "「{language}」需要額外下載模型。確認後將從 RapidOCR 官方模型來源下載至使用者資料目錄;完成後可離線使用,不會上傳 PDF。": "{language} needs an additional model. Confirm to download it from RapidOCR's official model source to your user data directory. Recognition works offline afterward; no PDF is uploaded.",
25
+ "下載完成後才會切換辨識語言;取消則保留原設定。": "The recognition language changes only after the download succeeds. Cancel keeps your current setting.",
26
+ "下載並使用": "Download and use",
27
+ "正在下載模型…": "Downloading model…",
28
+ "下載逾時,請稍後重試。": "The download timed out. Please try again later.",
29
+ "下載檔案大小異常。": "The download exceeds the expected size limit.",
30
+ "模型校驗失敗,請重新下載。": "Model verification failed. Please download again.",
31
+ "下載未完成:{reason}": "Download incomplete: {reason}",
32
+ "區域 OCR:框選頁面或圖片中的文字。辨識語言:{language};按旁邊箭頭切換。": "Region OCR: select text on a page or image. Language: {language}; use the arrow to change it.",
8
33
  "PDF 檔案": "PDF file",
9
34
  "列印:設定範圍、印表機並即時預覽": "Print: choose pages and printer with a live preview",
10
35
  "印表機": "Printer",
@@ -74,6 +74,8 @@ class ThemeController(QObject):
74
74
  slider_handle = "#ff9d45" if dark else "#0b57d0"
75
75
  hover = "#3b2a56" if dark else "#e7ebf0"
76
76
  pressed = "#4d376e" if dark else "#d8e3f3"
77
+ menu_background = hover if dark else card
78
+ menu_hover = pressed if dark else hover
77
79
  mark_suffix = "-dark" if dark else ""
78
80
  check = files("repdf").joinpath("assets", f"check{mark_suffix}.svg").as_posix()
79
81
  partial = files("repdf").joinpath("assets", f"partial{mark_suffix}.svg").as_posix()
@@ -85,6 +87,12 @@ class ThemeController(QObject):
85
87
  QToolBar {{ background: palette(window); border: none;
86
88
  border-bottom: 1px solid {border}; padding: 4px; spacing: 4px; }}
87
89
  QToolBar::separator {{ background: {border}; width: 1px; margin: 5px 4px; }}
90
+ QMenu {{ background: {menu_background}; color: palette(window-text);
91
+ border: 1px solid {border}; padding: 4px; }}
92
+ QMenu::item {{ padding: 5px 20px 5px 24px; }}
93
+ QMenu::item:selected {{ background: {menu_hover}; color: palette(window-text); }}
94
+ QMenu::item:disabled {{ color: {disabled}; }}
95
+ QMenu::separator {{ height: 1px; background: {border}; margin: 4px 6px; }}
88
96
  QTabWidget::pane {{ border: none; }}
89
97
  QTabBar::tab {{ background: transparent; color: palette(window-text);
90
98
  border: none; border-bottom: 2px solid transparent;
@@ -40,6 +40,8 @@ class OverflowToolBar(QToolBar):
40
40
  self.overflow_button.setAccessibleName(tr("更多工具"))
41
41
  self.overflow_menu = QMenu(self)
42
42
  self._overflow_controls = {}
43
+ self._action_groups = {}
44
+ self._group_buttons = {}
43
45
  self.overflow_button.setMenu(self.overflow_menu)
44
46
  self.overflow_button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
45
47
  self.overflow_menu.aboutToShow.connect(self._populate_overflow)
@@ -73,6 +75,37 @@ class OverflowToolBar(QToolBar):
73
75
  self._overflow_controls[action] = controls
74
76
  return action
75
77
 
78
+ def widgetForAction(self, action):
79
+ return self._group_buttons.get(action) or super().widgetForAction(action)
80
+
81
+ def add_action_menu_group(self, action, menu):
82
+ group = QWidget()
83
+ layout = QHBoxLayout(group)
84
+ layout.setContentsMargins(0, 0, 0, 0)
85
+ layout.setSpacing(2)
86
+ button = QToolButton(group)
87
+ button.setDefaultAction(action)
88
+ button.setFixedSize(34, 34)
89
+ button.setIconSize(QSize(20, 20))
90
+ button.setProperty('stateButton', action.isCheckable())
91
+ button.setAttribute(Qt.WidgetAttribute.WA_Hover, True)
92
+ arrow = QToolButton(group)
93
+ arrow.setObjectName('ocrLanguageMenu')
94
+ arrow.setFixedSize(14, 34)
95
+ arrow.setIconSize(QSize(12, 12))
96
+ arrow.setIcon(toolbar_icon('chevron_down'))
97
+ arrow.setFocusPolicy(Qt.FocusPolicy.NoFocus)
98
+ arrow.setMenu(menu)
99
+ arrow.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
100
+ arrow.setStyleSheet('QToolButton { border: none; padding: 0; } '
101
+ 'QToolButton::menu-indicator { image: none; }')
102
+ layout.addWidget(button)
103
+ layout.addWidget(arrow)
104
+ group_action = self.addWidget(group)
105
+ self._action_groups[group_action] = (action, menu)
106
+ self._group_buttons[action] = button
107
+ return arrow
108
+
76
109
  def _control_row(self, controls):
77
110
  row = QWidget()
78
111
  layout = QHBoxLayout(row)
@@ -116,8 +149,14 @@ class OverflowToolBar(QToolBar):
116
149
  self.overflow_menu.addSeparator()
117
150
  elif action in self._overflow_controls:
118
151
  self.overflow_menu.addAction(self._control_row(self._overflow_controls[action]))
152
+ elif action in self._action_groups:
153
+ primary, menu = self._action_groups[action]
154
+ self.overflow_menu.addAction(primary)
155
+ self.overflow_menu.addMenu(menu)
119
156
  elif not isinstance(action, QWidgetAction):
120
157
  self.overflow_menu.addAction(action)
158
+ if isinstance(widget, QToolButton) and widget.menu() is not None:
159
+ self.overflow_menu.addMenu(widget.menu())
121
160
  actions = self.overflow_menu.actions()
122
161
  if actions and actions[-1].isSeparator():
123
162
  self.overflow_menu.removeAction(actions[-1])
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes