dlxj commited on
Commit
d4ff54a
·
1 Parent(s): 3bea82f
.gitattributes CHANGED
@@ -1,4 +1,8 @@
 
1
  *.7z filter=lfs diff=lfs merge=lfs -text
 
 
 
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.avro filter=lfs diff=lfs merge=lfs -text
4
  *.bin filter=lfs diff=lfs merge=lfs -text
@@ -58,3 +62,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
1
+ data/**/* filter=lfs diff=lfs merge=lfs -text
2
  *.7z filter=lfs diff=lfs merge=lfs -text
3
+ *.mdx filter=lfs diff=lfs merge=lfs -text
4
+ *.pdf filter=lfs diff=lfs merge=lfs -text
5
+ *.ttf filter=lfs diff=lfs merge=lfs -text
6
  *.arrow filter=lfs diff=lfs merge=lfs -text
7
  *.avro filter=lfs diff=lfs merge=lfs -text
8
  *.bin filter=lfs diff=lfs merge=lfs -text
 
62
  # Video files - compressed
63
  *.mp4 filter=lfs diff=lfs merge=lfs -text
64
  *.webm filter=lfs diff=lfs merge=lfs -text
65
+ ocr/out/** filter=lfs diff=lfs merge=lfs -text
66
+ ocr/out2/** filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pdf
3
+ !戚蓼生序本石头记.pdf
4
+
5
+
ocr/.vscode/launch.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "0.2.0",
3
+ "configurations": [
4
+ {
5
+ "name": "Python Debugger: Current File",
6
+ "type": "debugpy",
7
+ "request": "launch",
8
+ "program": "${file}",
9
+ "console": "integratedTerminal"
10
+ }
11
+ ]
12
+ }
ocr/draw_box.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import json
3
+ import glob
4
+ from pathlib import Path
5
+ import cv2
6
+ import numpy as np
7
+
8
+ def draw_box(pth_webp, pth_boxs):
9
+
10
+ with open(pth_boxs, encoding='utf-8') as fp:
11
+ boxs = json.load(fp)
12
+ fp.close()
13
+
14
+ imgData = np.fromfile(pth_webp, dtype=np.uint8)
15
+ img = cv2.imdecode(imgData, cv2.IMREAD_UNCHANGED)
16
+
17
+ if len(img.shape) != 3: # 转彩图
18
+ img_color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
19
+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) # DBNet 原版只能处理彩图,这里转一下
20
+ else:
21
+ img_color = img.copy()
22
+
23
+
24
+ for box in boxs:
25
+ charPoly = box["charPoly"]
26
+ lu = [charPoly["x0"], charPoly["y0"]]
27
+ ru = [charPoly["x1"], charPoly["y1"]]
28
+ rd = [charPoly["x2"], charPoly["y2"]]
29
+ ld = [charPoly["x3"], charPoly["y3"]]
30
+ points = np.array([lu, ru, rd, ld])
31
+
32
+ cv2.polylines(img_color, [points], isClosed=True, color=( # 多边形,框得比较全
33
+ 100, 0, 255), thickness=2) # 只画线,不填充
34
+
35
+ # cv2.imshow("box", img_color)
36
+ # cv2.waitKey(0)
37
+
38
+ path_jpg = pth_webp.replace(".webp", ".jpg")
39
+ cv2.imwrite(path_jpg, img_color)
40
+
41
+ def do_drawbox():
42
+ webps = glob.glob('./out2/*.webp', recursive=False)
43
+ for pth_webp in webps:
44
+ pth_box = pth_webp.replace(".webp", ".boxs")
45
+ draw_box(pth_webp, pth_box)
46
+
47
+ if __name__ == "__main__":
48
+ do_drawbox()
ocr/find_paragraph.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Find paragraphs in loader response
3
+ """
4
+ import time
5
+ from selenium import webdriver
6
+ from selenium.webdriver.common.by import By
7
+ from selenium.webdriver.support import expected_conditions as EC
8
+ from selenium.webdriver.support.ui import WebDriverWait
9
+ import json
10
+
11
+ options = webdriver.ChromeOptions()
12
+ options.add_argument("--headless=new")
13
+ options.add_argument("--no-sandbox")
14
+ options.add_argument("--disable-dev-shm-usage")
15
+ options.add_argument("--disable-blink-features=AutomationControlled")
16
+ options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
17
+ options.add_experimental_option("excludeSwitches", ["enable-automation"])
18
+ options.add_experimental_option("useAutomationExtension", False)
19
+ options.set_capability("goog:loggingPrefs", {"performance": "ALL"})
20
+ driver = webdriver.Chrome(options=options)
21
+ driver.set_window_size(1400, 900)
22
+ driver.execute_cdp_cmd("Network.enable", {})
23
+
24
+ driver.get("https://www.shidianguji.com/zh/book/SWX0005")
25
+ time.sleep(5)
26
+ wait = WebDriverWait(driver, 10)
27
+ try:
28
+ els = driver.find_elements(By.XPATH, "//*[contains(text(), '第二回')]")
29
+ if els:
30
+ print("Clicking 第二回")
31
+ driver.execute_script("arguments[0].click();", els[0])
32
+ except Exception as e:
33
+ pass
34
+
35
+ time.sleep(5)
36
+ logs = driver.get_log("performance")
37
+ for entry in logs:
38
+ msg = json.loads(entry["message"])["message"]
39
+ method = msg.get("method")
40
+ if method == "Network.responseReceived":
41
+ req_id = msg.get("params", {}).get("requestId")
42
+ url = msg.get("params", {}).get("response", {}).get("url", "")
43
+ if "__loader=__session" in url:
44
+ try:
45
+ body = driver.execute_cdp_cmd("Network.getResponseBody", {"requestId": req_id})
46
+ data = json.loads(body.get("body", ""))
47
+ print("Loader Response JSON keys:", list(data.keys()))
48
+ if "paragraphList" in data:
49
+ print("Found paragraphList in Loader!")
50
+ print("Type:", type(data["paragraphList"]))
51
+ if isinstance(data["paragraphList"], list) and len(data["paragraphList"]) > 0:
52
+ print("First item keys:", list(data["paragraphList"][0].keys()))
53
+ print("First item content snippet:", str(data["paragraphList"][0])[:150])
54
+ except:
55
+ pass
56
+ driver.quit()
ocr/gendatav2.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 转换一章数据
3
+ """
4
+
5
+ import os
6
+ import shutil
7
+ import json
8
+ import glob
9
+ from pathlib import Path
10
+ import cv2
11
+ import numpy as np
12
+
13
+ from draw_box import do_drawbox
14
+
15
+
16
+ def main():
17
+ dir_out2 = "out2"
18
+ if Path(dir_out2).exists():
19
+ shutil.rmtree(dir_out2)
20
+
21
+ if not Path(dir_out2).exists():
22
+ os.makedirs(dir_out2)
23
+
24
+ pageIds_pageNames = {}
25
+
26
+ raw_jsons = glob.glob('./out/raw/**/*.json', recursive=True)
27
+ box_jsons = {}
28
+ paragraphs = []
29
+ texts = ""
30
+ text_pages = {}
31
+ pages = []
32
+ for raw_json in raw_jsons:
33
+ if 'pages_200' in raw_json:
34
+ with open(raw_json, encoding='utf-8') as fp:
35
+ pages_json = json.load(fp)
36
+ page = pages_json["data"]["pages"]
37
+ pages += page
38
+ fp.close()
39
+ if 'paragraphs_200' in raw_json:
40
+ with open(raw_json, encoding='utf-8') as fp:
41
+ paragraphs_json = json.load(fp)
42
+ paragraphs += paragraphs_json["data"]["paragraphs"]
43
+ fp.close()
44
+
45
+ if 'word_box_200' in raw_json:
46
+ with open(raw_json, encoding='utf-8') as fp:
47
+ word_box_json = json.load(fp)
48
+ box_jsons = {**box_jsons, **word_box_json["data"]["pageId2WordBoxContent"]}
49
+ fp.close()
50
+
51
+ currPageId = -1
52
+ lastPageId = -1
53
+ currPageText = ""
54
+
55
+ for i, js in enumerate(paragraphs):
56
+ startPageId = js["startPageId"]
57
+ endPageId = js["endPageId"]
58
+ content = js["content"]
59
+ content = json.loads(content, strict=False )
60
+ lines = content["lines"]
61
+ lastLineNum = -1
62
+ for line in lines:
63
+ lineNum = line["lineNum"]
64
+ lineType = line["lineType"]
65
+ content_line = line["content"].replace('\ufeff', '').replace("\u3000", " ") #.replace(" ", "")
66
+ if 'pagePass' in line:
67
+ pagePass = line["pagePass"]
68
+ PageId = pagePass["PageId"]
69
+
70
+ if currPageId == -1:
71
+ currPageId = PageId
72
+
73
+ if currPageText: # 页切换,保存上一页文本
74
+ text_pages[currPageId] = currPageText
75
+ currPageText = ""
76
+ currPageId = PageId
77
+
78
+
79
+ currPageText += content_line
80
+
81
+ texts += content_line
82
+
83
+ if i == len(paragraphs) - 1:
84
+ if currPageText: # 最后一个段落,保存上一页文本
85
+ if currPageId not in text_pages:
86
+ text_pages[currPageId] = currPageText
87
+ currPageText = ""
88
+ currPageId = PageId
89
+ else:
90
+ currPageText += " "
91
+ texts += " "
92
+
93
+
94
+ # pages = pages_json["data"]["pages"]
95
+
96
+ for page in pages:
97
+ pageId = page["pageId"]
98
+ pageNum = page["pageNum"]
99
+ uri = page["uri"]
100
+ imageName = uri.split("-")[-1]
101
+ baseName = Path(imageName).stem
102
+ pth_img = Path("out/images") / imageName
103
+ if not pth_img.exists():
104
+ raise Exception(f"image {imageName} not found")
105
+ if pageId not in box_jsons:
106
+ raise Exception(f"pageId {pageId} no box_json")
107
+
108
+ pageIds_pageNames[pageId] = baseName
109
+ boxs = box_jsons[pageId]['wordBoxList']
110
+ pth_boxs = str( dir_out2 / Path( imageName.replace(".webp", ".boxs") ) )
111
+
112
+ shutil.copy(pth_img, str( dir_out2 / Path(imageName) ) )
113
+ with open(pth_boxs, 'w', encoding='utf-8') as fp:
114
+ json.dump(boxs, fp, indent=4, ensure_ascii=False)
115
+ fp.close()
116
+
117
+ pth_text_pages = str(Path(dir_out2) / "page_texts.json")
118
+ with open(pth_text_pages, 'w', encoding='utf-8') as fp:
119
+ json.dump(text_pages, fp, indent=4, ensure_ascii=False)
120
+ fp.close()
121
+
122
+ pth_pageIds_pageNames = str(Path(dir_out2) / "pageIds_pageNames.json")
123
+ with open(pth_pageIds_pageNames, 'w', encoding='utf-8') as fp:
124
+ json.dump(pageIds_pageNames, fp, indent=4, ensure_ascii=False)
125
+ fp.close()
126
+
127
+
128
+ pth_paragraphs = str(Path(dir_out2) / "paragraphs.json")
129
+ with open(pth_paragraphs, 'w', encoding='utf-8') as fp:
130
+ json.dump(paragraphs, fp, indent=4, ensure_ascii=False)
131
+ fp.close()
132
+
133
+ do_drawbox()
134
+
135
+ def do_gendata():
136
+ main()
137
+
138
+ if __name__ == "__main__":
139
+ do_gendata()
ocr/getdata.py ADDED
@@ -0,0 +1,718 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 取一章数据
3
+ """
4
+ import argparse
5
+ import base64
6
+ import json
7
+ import re
8
+ import time
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
12
+
13
+ from selenium import webdriver
14
+ from selenium.webdriver.common.by import By
15
+ from selenium.webdriver.support import expected_conditions as EC
16
+ from selenium.webdriver.support.ui import WebDriverWait
17
+
18
+ TARGET_PATTERNS = {
19
+ "paragraphs": re.compile(r"/api/ancientlib/read/book/paragraphs/v2(?:\?|$)"),
20
+ "pages": re.compile(r"/api/ancientlib/read/book/pages/v3/(?:\?|$)"),
21
+ "word_box": re.compile(r"/api/ancientlib/read/word-box-page-content/m-get/(?:\?|$)"),
22
+ "loader": re.compile(r"__loader=__session"),
23
+ }
24
+
25
+ IMAGE_URL_RE = re.compile(r"https?://[^ ]+(?:\.webp|\.image|\.png|\.jpe?g|\.bmp)(?:\?.*)?$", re.IGNORECASE)
26
+
27
+
28
+ def _safe_name(s: str) -> str:
29
+ s = re.sub(r"[^a-zA-Z0-9._-]+", "_", s)
30
+ return s[:180] if len(s) > 180 else s
31
+
32
+
33
+ def _json_loads_maybe(data: str) -> Optional[Any]:
34
+ try:
35
+ return json.loads(data)
36
+ except Exception:
37
+ return None
38
+
39
+
40
+ def _iter_strings(obj: Any) -> Iterable[str]:
41
+ if isinstance(obj, str):
42
+ yield obj
43
+ return
44
+ if isinstance(obj, list):
45
+ for it in obj:
46
+ yield from _iter_strings(it)
47
+ return
48
+ if isinstance(obj, dict):
49
+ for v in obj.values():
50
+ yield from _iter_strings(v)
51
+
52
+
53
+ def _extract_text_from_json(payload: Any) -> str:
54
+ if not isinstance(payload, (dict, list)):
55
+ return ""
56
+ chunks: List[str] = []
57
+
58
+ def walk(o: Any) -> None:
59
+ if isinstance(o, dict):
60
+ for k, v in o.items():
61
+ lk = str(k).lower()
62
+ if lk in {"text", "content", "paragraph", "para", "value", "word"} and isinstance(v, str):
63
+ chunks.append(v)
64
+ else:
65
+ walk(v)
66
+ elif isinstance(o, list):
67
+ for it in o:
68
+ walk(it)
69
+
70
+ walk(payload)
71
+ out = "\n".join(x.strip() for x in chunks if x and x.strip())
72
+ out = re.sub(r"\n{3,}", "\n\n", out)
73
+ return out.strip()
74
+
75
+
76
+ def _find_image_urls(payload: Any) -> List[str]:
77
+ urls: List[str] = []
78
+ for s in _iter_strings(payload):
79
+ if s.startswith("http") and (".webp" in s or ".image" in s or "/page/" in s):
80
+ urls.append(s)
81
+ dedup: List[str] = []
82
+ seen = set()
83
+ for u in urls:
84
+ if u not in seen:
85
+ seen.add(u)
86
+ dedup.append(u)
87
+ return dedup
88
+
89
+
90
+ def _maybe_decode_url(s: str) -> List[str]:
91
+ if not isinstance(s, str) or len(s) < 16:
92
+ return []
93
+ out: List[str] = []
94
+ try:
95
+ raw = base64.b64decode(s, validate=False)
96
+ txt = raw.decode("utf-8", errors="ignore")
97
+ except Exception:
98
+ return []
99
+ for m in re.finditer(r"https?://[^\\s\"']+", txt):
100
+ u = m.group(0)
101
+ if IMAGE_URL_RE.match(u) and ("byteimg.com" in u or "bytednsdoc.com" in u):
102
+ out.append(u)
103
+ return out
104
+
105
+
106
+ def _extract_image_urls_from_pages(payload: Any) -> List[str]:
107
+ urls: List[str] = []
108
+ if not isinstance(payload, dict):
109
+ return urls
110
+ data = payload.get("data")
111
+ if not isinstance(data, dict):
112
+ return urls
113
+ pages = data.get("pages")
114
+ if not isinstance(pages, list):
115
+ return urls
116
+ for p in pages:
117
+ if not isinstance(p, dict):
118
+ continue
119
+ for key in ("picUrl", "thumbUrl"):
120
+ v = p.get(key)
121
+ if isinstance(v, str):
122
+ urls.extend(_maybe_decode_url(v))
123
+ for v in p.values():
124
+ if isinstance(v, str) and IMAGE_URL_RE.match(v) and ("byteimg.com" in v or "bytednsdoc.com" in v):
125
+ urls.append(v)
126
+ return list(dict.fromkeys(urls))
127
+
128
+
129
+ def _guess_page_keys(payload: Any) -> List[Tuple[str, Any]]:
130
+ hits: List[Tuple[str, Any]] = []
131
+ if isinstance(payload, dict):
132
+ for k, v in payload.items():
133
+ lk = str(k).lower()
134
+ if lk in {"pageid", "page_id", "page"} and isinstance(v, (str, int)):
135
+ hits.append((str(k), v))
136
+ hits.extend(_guess_page_keys(v))
137
+ elif isinstance(payload, list):
138
+ for it in payload:
139
+ hits.extend(_guess_page_keys(it))
140
+ return hits
141
+
142
+
143
+ @dataclass
144
+ class CapturedResponse:
145
+ kind: str
146
+ url: str
147
+ request_id: str
148
+ status: int
149
+ mime_type: str
150
+ body_text: str
151
+
152
+ def json(self) -> Optional[Any]:
153
+ return _json_loads_maybe(self.body_text)
154
+
155
+
156
+ def _make_driver(headless: bool) -> webdriver.Chrome:
157
+ options = webdriver.ChromeOptions()
158
+ if headless:
159
+ options.add_argument("--headless=new")
160
+ options.add_argument("--no-sandbox")
161
+ options.add_argument("--disable-dev-shm-usage")
162
+ options.add_argument("--disable-blink-features=AutomationControlled")
163
+ options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
164
+ options.add_experimental_option("excludeSwitches", ["enable-automation"])
165
+ options.add_experimental_option("useAutomationExtension", False)
166
+ options.set_capability("goog:loggingPrefs", {"performance": "ALL"})
167
+ driver = webdriver.Chrome(options=options)
168
+ driver.execute_cdp_cmd("Network.enable", {})
169
+ return driver
170
+
171
+
172
+ def _drain_network(
173
+ driver: webdriver.Chrome,
174
+ tracked: Dict[str, Tuple[str, str, int, str]],
175
+ ready: List[CapturedResponse],
176
+ image_urls: List[str],
177
+ img_dir: Path,
178
+ max_images: int,
179
+ img_saved: List[Dict[str, Any]],
180
+ ) -> None:
181
+ try:
182
+ logs = driver.get_log("performance")
183
+ except Exception:
184
+ return
185
+ for entry in logs:
186
+ try:
187
+ msg = json.loads(entry["message"])["message"]
188
+ except Exception:
189
+ continue
190
+ method = msg.get("method")
191
+ params = msg.get("params", {})
192
+ if method == "Network.requestWillBeSent":
193
+ request = params.get("request", {})
194
+ url = request.get("url", "")
195
+ if "00015" in url:
196
+ print(f"[DEBUG] Network.requestWillBeSent for 00015: url={url}")
197
+ if IMAGE_URL_RE.match(url) and ("byteimg.com" in url or "bytednsdoc.com" in url):
198
+ image_urls.append(url)
199
+ elif method == "Network.responseReceived":
200
+ response = params.get("response", {})
201
+ url = response.get("url", "")
202
+ mime_type = str(response.get("mimeType", "") or "")
203
+ if IMAGE_URL_RE.match(url) and ("byteimg.com" in url or "bytednsdoc.com" in url):
204
+ image_urls.append(url)
205
+ request_id = params.get("requestId")
206
+ if request_id and mime_type.startswith("image/") and IMAGE_URL_RE.match(url) and ("byteimg.com" in url or "bytednsdoc.com" in url):
207
+ status = int(response.get("status", 0) or 0)
208
+ tracked[request_id] = ("image", url, status, mime_type)
209
+ print(f"[DEBUG] Tracked image response: request_id={request_id}, url={url}, status={status}")
210
+ continue
211
+ elif request_id and "00015" in url:
212
+ print(f"[DEBUG] Found 00015 in url but didn't track as image. mime_type={mime_type}, url={url}, request_id={request_id}")
213
+ kind = None
214
+ for k, pat in TARGET_PATTERNS.items():
215
+ if pat.search(url):
216
+ kind = k
217
+ break
218
+ if not kind:
219
+ continue
220
+ request_id = params.get("requestId")
221
+ if not request_id:
222
+ continue
223
+ status = int(response.get("status", 0) or 0)
224
+ tracked[request_id] = (kind, url, status, mime_type)
225
+ elif method == "Network.loadingFinished":
226
+ request_id = params.get("requestId")
227
+ if not request_id or request_id not in tracked:
228
+ continue
229
+ kind, url, status, mime_type = tracked.pop(request_id)
230
+ try:
231
+ body = driver.execute_cdp_cmd("Network.getResponseBody", {"requestId": request_id})
232
+ except Exception as e:
233
+ if kind == "image":
234
+ print(f"[DEBUG] Failed to get response body for image {url}: {e}")
235
+ continue
236
+ if kind == "image":
237
+ if max_images > 0 and len(img_saved) >= max_images:
238
+ print(f"[DEBUG] Max images reached, skipping {url}")
239
+ continue
240
+ raw = body.get("body", "")
241
+ if not raw:
242
+ print(f"[DEBUG] Empty body for image {url}")
243
+ continue
244
+ if body.get("base64Encoded"):
245
+ try:
246
+ data = base64.b64decode(raw)
247
+ except Exception as e:
248
+ print(f"[DEBUG] Failed to decode base64 for image {url}: {e}")
249
+ continue
250
+ else:
251
+ data = raw.encode("utf-8", errors="ignore")
252
+ ext = ".bin"
253
+ if "webp" in (mime_type or "").lower():
254
+ ext = ".webp"
255
+ elif "png" in (mime_type or "").lower():
256
+ ext = ".png"
257
+ elif "jpeg" in (mime_type or "").lower() or "jpg" in (mime_type or "").lower():
258
+ ext = ".jpg"
259
+
260
+ page_id = ""
261
+ m = re.search(r"/page/([^/]+)/", url)
262
+ if m:
263
+ page_id = f"_{m.group(1)}"
264
+ else:
265
+ m2 = re.search(r"1k[a-z0-9]{11}", url)
266
+ if m2:
267
+ page_id = f"_{m2.group(0)}"
268
+
269
+ # Default file name format
270
+ file_name = f"{len(img_saved):04d}{page_id}{ext}"
271
+
272
+ # Try to extract actual filename from URL, e.g. SWX0005_00001_00001.webp
273
+ m_name = re.search(r"-([a-zA-Z0-9_]+\.(?:webp|png|jpe?g|jpg|bmp))", url, re.IGNORECASE)
274
+ if m_name:
275
+ file_name = m_name.group(1)
276
+ else:
277
+ m_name2 = re.search(r"/([^/]+?\.(?:webp|png|jpe?g|jpg|bmp))(?:[?~]|$)", url, re.IGNORECASE)
278
+ if m_name2:
279
+ name_part = m_name2.group(1)
280
+ if "-" in name_part:
281
+ file_name = name_part.split("-", 1)[-1]
282
+ else:
283
+ file_name = name_part
284
+
285
+ out_path = img_dir / file_name
286
+ try:
287
+ out_path.write_bytes(data)
288
+ print(f"[DEBUG] Saved image: {file_name} from {url}")
289
+ except Exception as e:
290
+ print(f"[DEBUG] Failed to save image {file_name} from {url}: {e}")
291
+ continue
292
+ img_saved.append({"url": url, "mimeType": mime_type, "path": str(out_path)})
293
+ continue
294
+
295
+ body_text = body.get("body", "")
296
+ if body.get("base64Encoded"):
297
+ try:
298
+ body_text = base64.b64decode(body_text).decode("utf-8", errors="replace")
299
+ except Exception:
300
+ body_text = ""
301
+
302
+ if kind == "loader":
303
+ try:
304
+ data = json.loads(body_text)
305
+ if "paragraphList" in data:
306
+ para_payload = {
307
+ "errorCode": 0,
308
+ "errorMsg": "",
309
+ "data": {
310
+ "paragraphs": data["paragraphList"]
311
+ }
312
+ }
313
+ body_text = json.dumps(para_payload, ensure_ascii=False)
314
+ kind = "paragraphs"
315
+ url = "https://www.shidianguji.com/api/ancientlib/read/book/paragraphs/v2?mock=from_loader"
316
+ print(f"[DEBUG] Transformed loader response to paragraphs format")
317
+ except Exception as e:
318
+ print(f"[DEBUG] Failed to parse loader JSON: {e}")
319
+
320
+ ready.append(
321
+ CapturedResponse(
322
+ kind=kind,
323
+ url=url,
324
+ request_id=request_id,
325
+ status=status,
326
+ mime_type=mime_type,
327
+ body_text=body_text,
328
+ )
329
+ )
330
+
331
+
332
+ def _collect_dom_image_urls(driver: webdriver.Chrome) -> List[str]:
333
+ try:
334
+ urls = driver.execute_script(
335
+ "return Array.from(document.images||[]).map(i=>i.currentSrc||i.src).filter(Boolean);"
336
+ )
337
+ except Exception:
338
+ return []
339
+ if not isinstance(urls, list):
340
+ return []
341
+ out: List[str] = []
342
+ for u in urls:
343
+ if isinstance(u, str) and IMAGE_URL_RE.match(u) and ("byteimg.com" in u or "bytednsdoc.com" in u):
344
+ out.append(u)
345
+ return list(dict.fromkeys(out))
346
+
347
+
348
+ def _try_click_by_text(driver: webdriver.Chrome, text: str, timeout_s: float = 2.5) -> bool:
349
+ xp = (
350
+ f"//*[self::button or self::a or @role='button' or self::div]"
351
+ f"[contains(normalize-space(.), {json.dumps(text, ensure_ascii=False)})]"
352
+ )
353
+ try:
354
+ els = driver.find_elements(By.XPATH, xp)
355
+ except Exception:
356
+ return False
357
+ for el in els[:5]:
358
+ try:
359
+ if not el.is_displayed() or not el.is_enabled():
360
+ continue
361
+ el.click()
362
+ return True
363
+ except Exception:
364
+ continue
365
+ return False
366
+
367
+
368
+ def _enter_image_mode(driver: webdriver.Chrome) -> None:
369
+ for t in ("原图", "影印", "图片", "图像", "掃圖", "扫描", "切换"):
370
+ if _try_click_by_text(driver, t, timeout_s=0):
371
+ time.sleep(0.8)
372
+ break
373
+
374
+
375
+ def main() -> int:
376
+ ap = argparse.ArgumentParser()
377
+ ap.add_argument("--book-id", default="SWX0005")
378
+ ap.add_argument("--chapter", default="第八十回")
379
+ ap.add_argument("--out", default="out")
380
+ ap.add_argument("--headless", action="store_true")
381
+ ap.add_argument("--timeout", type=int, default=20000)
382
+ ap.add_argument("--max-images", type=int, default=1000)
383
+ args = ap.parse_args()
384
+
385
+ out_dir = Path(args.out).resolve()
386
+ raw_dir = out_dir / "raw"
387
+ img_dir = out_dir / "images"
388
+ coord_dir = out_dir / "coords"
389
+ text_dir = out_dir / "text"
390
+ for d in (raw_dir, img_dir, coord_dir, text_dir):
391
+ d.mkdir(parents=True, exist_ok=True)
392
+
393
+ driver = _make_driver(headless=args.headless)
394
+ driver.set_window_size(1400, 900)
395
+ captured: List[CapturedResponse] = []
396
+ tracked: Dict[str, Tuple[str, str, int, str]] = {}
397
+ image_urls: List[str] = []
398
+ img_saved: List[Dict[str, Any]] = []
399
+ try:
400
+ url = f"https://www.shidianguji.com/zh/book/{args.book_id}"
401
+ driver.get(url)
402
+
403
+ # Drain network to capture the initial chapter data
404
+ for _ in range(5):
405
+ time.sleep(1)
406
+ before = len(captured)
407
+ _drain_network(driver, tracked, captured, image_urls, img_dir, int(args.max_images), img_saved)
408
+ if len(captured) == before and any(c.kind in ("paragraphs", "pages") for c in captured):
409
+ break
410
+
411
+ initial_captured = list(captured)
412
+ initial_img_saved = list(img_saved)
413
+ initial_image_urls = list(image_urls)
414
+
415
+ captured.clear()
416
+ img_saved.clear()
417
+ image_urls.clear()
418
+ tracked.clear()
419
+
420
+ clicked = False
421
+ no_scroll_count = 0
422
+ for scroll_attempts in range(400):
423
+ try:
424
+ els = driver.find_elements(By.LINK_TEXT, args.chapter)
425
+ if not els:
426
+ els = driver.find_elements(By.PARTIAL_LINK_TEXT, args.chapter)
427
+ if not els:
428
+ xp = f"//*[contains(normalize-space(.), {json.dumps(args.chapter, ensure_ascii=False)}) and not(.//*[contains(normalize-space(.), {json.dumps(args.chapter, ensure_ascii=False)})])]"
429
+ els = driver.find_elements(By.XPATH, xp)
430
+
431
+ for el in els:
432
+ try:
433
+ driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", el)
434
+ time.sleep(0.2)
435
+ try:
436
+ el.click()
437
+ clicked = True
438
+ break
439
+ except Exception:
440
+ # Try JS click as fallback if standard click fails
441
+ driver.execute_script("arguments[0].click();", el)
442
+ clicked = True
443
+ break
444
+ except Exception:
445
+ continue
446
+ except Exception:
447
+ pass
448
+
449
+ if clicked:
450
+ break
451
+
452
+ # 如果没找到或没点击成功,滚动所有可滚动的 div,尝试让章节列表显示出来
453
+ try:
454
+ scrolled = driver.execute_script('''
455
+ var els = document.querySelectorAll("div, ul, main, nav, section, aside");
456
+ var scrolledAny = false;
457
+ for (var i = 0; i < els.length; i++) {
458
+ var d = els[i];
459
+ if (d.scrollHeight > d.clientHeight && window.getComputedStyle(d).overflowY !== "hidden") {
460
+ var before = d.scrollTop;
461
+ d.scrollBy(0, 250);
462
+ if (d.scrollTop > before) {
463
+ scrolledAny = true;
464
+ }
465
+ }
466
+ }
467
+ return scrolledAny;
468
+ ''')
469
+ if not scrolled:
470
+ no_scroll_count += 1
471
+ if no_scroll_count >= 20:
472
+ print(f"[DEBUG] Reached the bottom of the list (tried 20 times). {args.chapter} not found.")
473
+ break
474
+ else:
475
+ no_scroll_count = 0
476
+ except Exception:
477
+ pass
478
+ time.sleep(0.5)
479
+
480
+ if clicked:
481
+ print(f"[DEBUG] Clicked {args.chapter}, waiting for new network data...")
482
+ # Wait until we see new 'paragraphs' or 'pages' in captured
483
+ for _ in range(15):
484
+ time.sleep(1)
485
+ _drain_network(driver, tracked, captured, image_urls, img_dir, int(args.max_images), img_saved)
486
+ if any(c.kind in ("paragraphs", "pages") for c in captured):
487
+ print(f"[DEBUG] New data captured for {args.chapter}")
488
+ break
489
+ else:
490
+ print(f"[DEBUG] {args.chapter} not clicked (not found).")
491
+
492
+ has_new_data = any(c.kind in ("paragraphs", "pages") for c in captured)
493
+
494
+ if not has_new_data:
495
+ if clicked:
496
+ print(f"[DEBUG] No new data loaded after clicking {args.chapter}. Using initial chapter data.")
497
+ else:
498
+ print(f"[DEBUG] Using initial chapter data because {args.chapter} was not found.")
499
+ captured.extend(initial_captured)
500
+ img_saved.extend(initial_img_saved)
501
+ image_urls.extend(initial_image_urls)
502
+ else:
503
+ print(f"[DEBUG] Successfully loaded new chapter {args.chapter}. Discarding initial chapter data.")
504
+ for img in initial_img_saved:
505
+ try:
506
+ Path(img["path"]).unlink(missing_ok=True)
507
+ except Exception as e:
508
+ print(f"[DEBUG] Failed to delete initial image {img['path']}: {e}")
509
+
510
+ time.sleep(0.8)
511
+ _enter_image_mode(driver)
512
+
513
+ deadline = time.time() + max(10, int(args.timeout))
514
+ last_activity = time.time()
515
+ no_activity_count = 0
516
+ print(f"Starting loop, deadline in {deadline - time.time()} seconds")
517
+
518
+ # Try to find a scrollable container
519
+ from selenium.webdriver.common.keys import Keys
520
+
521
+ while time.time() < deadline:
522
+ before_cap = len(captured)
523
+ before_img = len(img_saved)
524
+ _drain_network(driver, tracked, captured, image_urls, img_dir, int(args.max_images), img_saved)
525
+ if len(captured) != before_cap or len(img_saved) != before_img:
526
+ print(f"Activity! captured: {len(captured)} (+{len(captured)-before_cap}), img_saved: {len(img_saved)} (+{len(img_saved)-before_img})")
527
+ last_activity = time.time()
528
+ no_activity_count = 0
529
+
530
+ # Send PAGE_DOWN to body
531
+ try:
532
+ driver.find_element(By.TAG_NAME, "body").send_keys(Keys.PAGE_DOWN)
533
+ except Exception:
534
+ pass
535
+
536
+ # Click next page if possible
537
+ try:
538
+ # The user indicated: <div class="vik-toolbox-btn click act" type="page-next">
539
+ next_btn = driver.find_element(By.XPATH, "//div[@type='page-next' or contains(@class, 'page-next') or contains(text(), '下一张')]")
540
+ # Add a small delay to prevent clicking too fast which might skip pages
541
+ # Check if we're not loading something
542
+ if next_btn.is_displayed():
543
+ # Check if button is disabled (has disable class)
544
+ cls = next_btn.get_attribute("class") or ""
545
+ if "disable" not in cls:
546
+ # Find current page text to ensure we only click once page changes
547
+ page_text_el = driver.find_elements(By.XPATH, "//div[contains(text(), '/')]")
548
+ curr_text = ""
549
+ for p in page_text_el:
550
+ if "/" in p.text:
551
+ curr_text = p.text
552
+ break
553
+ driver.execute_script("arguments[0].click();", next_btn)
554
+ # Wait for page to change
555
+ for _ in range(10):
556
+ time.sleep(0.2)
557
+ new_text = ""
558
+ for p in driver.find_elements(By.XPATH, "//div[contains(text(), '/')]"):
559
+ if "/" in p.text:
560
+ new_text = p.text
561
+ break
562
+ if new_text != curr_text:
563
+ break
564
+ except Exception:
565
+ pass
566
+
567
+ # Also try to scroll window and any potential scrollable divs
568
+ driver.execute_script('''
569
+ window.scrollBy(0, 900);
570
+ var divs = document.querySelectorAll("div");
571
+ for (var i = 0; i < divs.length; i++) {
572
+ if (divs[i].scrollHeight > divs[i].clientHeight && window.getComputedStyle(divs[i]).overflowY !== "hidden") {
573
+ divs[i].scrollBy(0, 900);
574
+ }
575
+ }
576
+ ''')
577
+
578
+ time.sleep(0.6)
579
+ image_urls.extend(_collect_dom_image_urls(driver))
580
+ if time.time() - last_activity > 15:
581
+ no_activity_count += 1
582
+ print(f"No activity for 15 seconds (count: {no_activity_count}).")
583
+ if no_activity_count >= 3:
584
+ print("Too many consecutive periods of no activity, breaking loop.")
585
+ break
586
+
587
+ # Check if next button is actually disabled
588
+ try:
589
+ next_btn = driver.find_element(By.XPATH, "//div[@type='page-next' or contains(@class, 'page-next') or contains(text(), '下一张')]")
590
+ cls = next_btn.get_attribute("class") or ""
591
+ if "disable" in cls:
592
+ print("Reached end of chapter (next button disabled).")
593
+ break
594
+ else:
595
+ print("Next button not disabled, but no network activity. Try clicking again.")
596
+ driver.execute_script("arguments[0].click();", next_btn)
597
+ last_activity = time.time() - 10 # give it 5 more seconds before checking again
598
+ continue
599
+ except Exception:
600
+ print("Could not find next button, breaking loop.")
601
+ break
602
+ break
603
+ print(f"Loop finished. time.time() < deadline: {time.time() < deadline}")
604
+
605
+ for i, c in enumerate(captured):
606
+ ext = "json" if "json" in (c.mime_type or "") or c.body_text.strip().startswith("{") else "txt"
607
+ name = _safe_name(f"{i:04d}_{c.kind}_{c.status}_{c.url}")
608
+ (raw_dir / f"{name}.{ext}").write_text(c.body_text, encoding="utf-8", errors="replace")
609
+
610
+ img_urls = list(dict.fromkeys([u for u in image_urls if u.startswith("http")]))
611
+ pages_payloads = [c.json() for c in captured if c.kind == "pages" and c.status == 200]
612
+
613
+ page_id_to_hash = {}
614
+ for p in pages_payloads:
615
+ if p is not None:
616
+ img_urls.extend(_extract_image_urls_from_pages(p))
617
+ # Build pageId -> hash mapping
618
+ if isinstance(p, dict) and isinstance(p.get("data"), dict):
619
+ pages_list = p["data"].get("pages", [])
620
+ if isinstance(pages_list, list):
621
+ for page in pages_list:
622
+ if isinstance(page, dict):
623
+ pid = str(page.get("pageId", ""))
624
+ uri = str(page.get("uri", ""))
625
+ if pid and uri:
626
+ m = re.search(r"/page/([^/]+)/", uri)
627
+ if m:
628
+ page_id_to_hash[pid] = m.group(1)
629
+ else:
630
+ m2 = re.search(r"1k[a-z0-9]{11}", uri)
631
+ if m2:
632
+ page_id_to_hash[pid] = m2.group(0)
633
+
634
+ img_urls = list(dict.fromkeys(img_urls))
635
+
636
+ coords: Dict[str, Any] = {}
637
+ for c in captured:
638
+ if c.kind != "word_box" or c.status != 200:
639
+ continue
640
+ payload = c.json()
641
+ if payload is None:
642
+ continue
643
+
644
+ page_id = None
645
+ # Extract pageId directly from pageId2WordBoxContent if available
646
+ if isinstance(payload, dict) and isinstance(payload.get("data"), dict):
647
+ content = payload["data"].get("pageId2WordBoxContent")
648
+ if isinstance(content, dict) and content:
649
+ page_id = str(next(iter(content.keys())))
650
+
651
+ if not page_id:
652
+ page_keys = _guess_page_keys(payload)
653
+ for _, v in page_keys:
654
+ if isinstance(v, (str, int)):
655
+ page_id = str(v)
656
+ break
657
+
658
+ hash_suffix = ""
659
+ if page_id and page_id in page_id_to_hash:
660
+ hash_suffix = f"_{page_id_to_hash[page_id]}"
661
+
662
+ key = f"wordbox_{len(coords):04d}{hash_suffix}"
663
+ coords[key] = payload
664
+ (coord_dir / f"{_safe_name(key)}.json").write_text(
665
+ json.dumps(payload, ensure_ascii=False),
666
+ encoding="utf-8",
667
+ errors="replace",
668
+ )
669
+
670
+ paragraph_texts: List[str] = []
671
+ for c in captured:
672
+ if c.kind != "paragraphs" or c.status != 200:
673
+ continue
674
+ payload = c.json()
675
+ if payload is None:
676
+ continue
677
+ t = _extract_text_from_json(payload)
678
+ if t:
679
+ paragraph_texts.append(t)
680
+ full_text = "\n\n".join(paragraph_texts).strip()
681
+ if not full_text and coords:
682
+ fallback_chunks: List[str] = []
683
+ for v in coords.values():
684
+ t = _extract_text_from_json(v)
685
+ if t:
686
+ fallback_chunks.append(t)
687
+ full_text = "\n\n".join(fallback_chunks).strip()
688
+
689
+ if full_text:
690
+ (text_dir / "text.txt").write_text(full_text, encoding="utf-8", errors="replace")
691
+
692
+ summary = {
693
+ "bookId": args.book_id,
694
+ "chapter": args.chapter,
695
+ "captured": [
696
+ {"kind": c.kind, "status": c.status, "mimeType": c.mime_type, "url": c.url}
697
+ for c in captured
698
+ ],
699
+ "imageUrls": img_urls[: max(0, int(args.max_images))],
700
+ "imagesSaved": img_saved,
701
+ "coords_keys": list(coords.keys()),
702
+ "out": str(out_dir),
703
+ }
704
+ (out_dir / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
705
+ return 0
706
+ finally:
707
+ try:
708
+ driver.quit()
709
+ from gendatav2 import do_gendata
710
+ do_gendata()
711
+ except Exception:
712
+ pass
713
+
714
+
715
+
716
+ if __name__ == "__main__":
717
+ raise SystemExit(main())
718
+
ocr/kandianguji_ocr.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import base64
3
+ import json
4
+ import requests
5
+
6
+ API_URL = "https://ocr.kandianguji.com/ocr_api"
7
+ TOKEN = "8be3d75a-8a66-4b5d-9047-d4895e4c8000"
8
+ EMAIL = "13788325535"
9
+
10
+ def get_kandianguji_ocr_result(image_path: str, **kwargs):
11
+ """
12
+ 调用看典古籍OCR API识别图像。
13
+
14
+ 参数:
15
+ image_path (str): 需要识别的图像文件路径。
16
+ **kwargs: 其他可选API参数 (如 version='v2', det_layout=True 等)。
17
+ 详细参数请参考 readme.txt 文档。
18
+
19
+ 返回:
20
+ dict: API响应的JSON数据。
21
+ """
22
+ if not os.path.exists(image_path):
23
+ raise FileNotFoundError(f"指定的图像文件不存在: {image_path}")
24
+
25
+ # 1. 将图像转换为base64编码
26
+ with open(image_path, "rb") as img_file:
27
+ image_base64 = base64.b64encode(img_file.read()).decode('utf-8')
28
+
29
+ # 2. 构建基础请求数据
30
+ payload = {
31
+ "token": TOKEN,
32
+ "email": EMAIL,
33
+ "image": image_base64
34
+ }
35
+
36
+ # 3. 合并可选参数
37
+ # 根据 readme.txt 提取的默认可选参数
38
+ default_options = {
39
+ "char_ocr": True,
40
+ "det_mode": "sp",
41
+ "det_layout": True,
42
+ "image_size": 0,
43
+ "return_position": True,
44
+ "return_choices": True,
45
+ "version": "v2",
46
+ "only_plain_text": False,
47
+ "return_layout": True,
48
+ "auto_insert_space": False,
49
+ "hp_line_words_angel": "left2right",
50
+ "sp_line_words_angel": "top2bottom"
51
+ }
52
+
53
+ # 更新默认参数(如果 kwargs 中提供了新的值)
54
+ for key, value in default_options.items():
55
+ payload[key] = kwargs.get(key, value)
56
+
57
+ # 4. 发送POST请求
58
+ headers = {
59
+ "Content-Type": "application/json"
60
+ }
61
+
62
+ try:
63
+ response = requests.post(API_URL, json=payload, headers=headers)
64
+ # 检查响应状态码
65
+ response.raise_for_status()
66
+ return response.json()
67
+ except requests.exceptions.RequestException as e:
68
+ print(f"API请求失败: {e}")
69
+ # 如果有响应体,打印出来以便调试
70
+ if 'response' in locals() and response is not None:
71
+ print(f"响应内容: {response.text}")
72
+ return None
73
+
74
+ if __name__ == "__main__":
75
+ # 测试用例 (请替换为真实的古籍图片路径)
76
+ sample_image = "0375.jpg"
77
+
78
+ print("看典古籍OCR API 接口测试")
79
+ print("-" * 30)
80
+
81
+ if os.path.exists(sample_image):
82
+ print(f"正在识别图片: {sample_image}")
83
+ # 调用示例,可按需传入 v2 版本的特有参数
84
+ result = get_kandianguji_ocr_result(
85
+ sample_image,
86
+ version="v2",
87
+ det_layout=True
88
+ )
89
+
90
+ if result:
91
+ print("\n识别结果:")
92
+ s = json.dumps(result, indent=2, ensure_ascii=False)
93
+ with open("out.json", 'w', encoding='utf-8') as f:
94
+ f.write(s)
95
+ print(s)
96
+ else:
97
+ print(f"提示: 请在当前目录下放置一张名为 '{sample_image}' 的图片用于测试。")
98
+ print("或者修改 sample_image 变量的值指向有效的图片路径。")
ocr/ppcor_aliocr_convert.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ # pip install numpy==1.23.5 opencv-python==4.10.0.84 -i https://mirrors.aliyun.com/pypi/simple/
3
+
4
+ PPOCRLabel --lang ch # 启动标注工具
5
+
6
+ cp autodl-tmp/train_data.zip . && \
7
+ unzip train_data.zip -d PaddleOCR
8
+
9
+ # https://github.com/PaddlePaddle/PaddleOCR/blob/static/doc/doc_ch/FAQ.md
10
+
11
+ # 7za a -t7z -m0=lzma -mx=9 -mfb=64 -md=32m -ms=on data.7z data/
12
+
13
+ 新建文件夹 train_data, 要标注的图片全部放在里面
14
+
15
+ 新建 train_data/Label.txt 内容如下
16
+ 行中用 \t 分隔 , points 的标记顺序是 左上 右上 右下 左下
17
+ train_data/0093.bmp [{"transcription":"参考答案及解析","points":[[525,179],[1295,167],[1295,268],[521,292]],"difficult":false}]
18
+ train_data/0094.bmp [{"transcription":"其他内容","points":[[525,179],[1295,167],[1295,268],[521,292]],"difficult":false}]
19
+
20
+
21
+ 给 PaddleOCR 用,前面是坐标和图片都变换;这里图像不变,坐标不变
22
+
23
+
24
+ 将阿里OCR 的识别结果(图片和标注)转换成 icdar2015 格式 (注意:它的文本是含 utf8 bom 的)
25
+
26
+ 给 mmocr 训练用。格式是 icdar2015 的格式,文件夹的组织方式是按照 mmocr 的要求创建的
27
+
28
+ """
29
+
30
+
31
+ """
32
+
33
+ ! unzip ./GD500.zip -d DB/datasets
34
+
35
+ icdar2015 文本检测数据集
36
+ 标注格式: x1,y1,x2,y2,x3,y3,x4,y4,text
37
+
38
+ 其中, x1,y1为左上角坐标,x2,y2为右上角坐标,x3,y3为右下角坐标,x4,y4为左下角坐标。
39
+
40
+ # 表示text难以辨认。
41
+ """
42
+
43
+ import random
44
+ from pathlib import Path
45
+ import os
46
+ import shutil
47
+ import glob
48
+ import base64
49
+ from importlib.resources import path
50
+ import math
51
+ import numpy as np
52
+ import cv2
53
+ import json
54
+ import decimal
55
+ import datetime
56
+ from pickletools import uint8
57
+ class DecimalEncoder(json.JSONEncoder):
58
+ def default(self, o):
59
+ if isinstance(o, decimal.Decimal):
60
+ return float(o)
61
+ elif isinstance(o, datetime.datetime):
62
+ return str(o)
63
+ super(DecimalEncoder, self).default(o)
64
+
65
+
66
+ def save_json(filename, dics):
67
+ with open(filename, 'w', encoding='utf-8') as fp:
68
+ json.dump(dics, fp, indent=4, cls=DecimalEncoder, ensure_ascii=False)
69
+ fp.close()
70
+
71
+
72
+ def load_json(filename):
73
+ with open(filename, encoding='utf-8') as fp:
74
+ js = json.load(fp)
75
+ fp.close()
76
+ return js
77
+
78
+ # convert string to json
79
+
80
+
81
+ def parse(s):
82
+ return json.loads(s, strict=False)
83
+
84
+ # convert dict to string
85
+
86
+
87
+ def string(d):
88
+ return json.dumps(d, cls=DecimalEncoder, ensure_ascii=False)
89
+
90
+
91
+ def transform(points, M):
92
+ # points 算出四个点变换后移动到哪里了
93
+ # points = np.array([[word_x, word_y], # 左上
94
+ # [word_x + word_width, word_y], # 右上
95
+ # [word_x + word_width, word_y + word_height], # 右下
96
+ # [word_x, word_y + word_height], # 左下
97
+ # ])
98
+ # add ones
99
+ ones = np.ones(shape=(len(points), 1))
100
+
101
+ points_ones = np.hstack([points, ones])
102
+
103
+ # transform points
104
+ transformed_points = M.dot(points_ones.T).T
105
+
106
+ transformed_points_int = np.round(
107
+ transformed_points, decimals=0).astype(np.int32) # 批量四舍五入
108
+
109
+ return transformed_points_int
110
+
111
+
112
+ def cutPoly(img, pts):
113
+ # img = cv2.imdecode(np.fromfile('./t.png', dtype=np.uint8), -1)
114
+ # pts = np.array([[10,150],[150,100],[300,150],[350,100],[310,20],[35,10]])
115
+
116
+ # (1) Crop the bounding rect
117
+ rect = cv2.boundingRect(pts)
118
+ x, y, w, h = rect
119
+ croped = img[y:y+h, x:x+w].copy()
120
+
121
+ # (2) make mask
122
+ pts = pts - pts.min(axis=0)
123
+
124
+ mask = np.zeros(croped.shape[:2], np.uint8)
125
+ cv2.drawContours(mask, [pts], -1, (255, 255, 255), -1, cv2.LINE_AA)
126
+
127
+ # (3) do bit-op
128
+ dst = cv2.bitwise_and(croped, croped, mask=mask)
129
+
130
+ # (4) add the white background
131
+ bg = np.ones_like(croped, np.uint8)*255
132
+ cv2.bitwise_not(bg, bg, mask=mask)
133
+ dst2 = bg + dst
134
+
135
+ # cv2.imwrite("croped.png", croped)
136
+ # cv2.imwrite("mask.png", mask)
137
+ # cv2.imwrite("dst.png", dst)
138
+ # cv2.imwrite("dst2.png", dst2)
139
+
140
+ return dst2
141
+
142
+
143
+ def md5(fname):
144
+ import hashlib
145
+ hash_md5 = hashlib.md5()
146
+ with open(fname, "rb") as f:
147
+ for chunk in iter(lambda: f.read(4096), b""):
148
+ hash_md5.update(chunk)
149
+ return hash_md5.hexdigest()
150
+
151
+ def get_all_md5():
152
+ m5s = []
153
+ import glob
154
+ jpgs = glob.glob('./bookimage/**/*.jpg', recursive=True)
155
+ for jpg in jpgs:
156
+ m5 = md5(jpg)
157
+ m5s.append( m5 )
158
+ return m5s
159
+
160
+ def get_json_paths():
161
+ json_paths = []
162
+ m5s = get_all_md5()
163
+ for m5 in m5s:
164
+ j_pth = f"/yingedu/project/ocr_server_test/data/json/{m5.lower()}.json"
165
+ if os.path.exists(j_pth):
166
+ json_paths.append(j_pth)
167
+ return json_paths
168
+
169
+ def do_convert_aliocr():
170
+
171
+ # 24HLZYZG64/0001.jpg c04d111ef69b9892d39f9430b6906047 md5是这个
172
+ # ls /yingedu/project/ocr_server_test/data/json/0bf0383ece9a533683e615bf57525812.json aliocr 原始识别结果
173
+ # ls /yingedu/project/ocr_server_test/data/img/0bf0383ece9a533683e615bf57525812.txt aliocr 原始识别图像(二值化降燥后压缩成2M)
174
+
175
+
176
+
177
+ root = 'train_data'
178
+ tmp = 'tmp'
179
+ label_path = os.path.join(root, 'Label.txt')
180
+
181
+ key_path = os.path.join(root, 'keys.txt')
182
+
183
+ fileState_path = os.path.join(root, 'fileState.txt')
184
+
185
+ if os.path.exists(root):
186
+ shutil.rmtree(root)
187
+ # os.rmdir(root)
188
+ if os.path.exists(tmp):
189
+ shutil.rmtree(tmp)
190
+
191
+ if not os.path.exists(root):
192
+ os.makedirs(root)
193
+
194
+ if not os.path.exists(tmp):
195
+ os.makedirs(tmp)
196
+
197
+ label = ''
198
+ keys = ''
199
+ states = ''
200
+
201
+
202
+ dic_words = {} # 所有词
203
+
204
+ # 开始转换
205
+
206
+ # https://help.aliyun.com/document_detail/294540.html 阿里云ocr结果字段定义
207
+ # prism-wordsInfo 里的 angle 文字块的角度,这个角度只影响width和height,当角度为-90、90、-270、270,width和height的值需要自行互换
208
+
209
+ dir_json = './测试图片/json' # '/yingedu/project/ocr_server_test/data/json' # './data/json'
210
+ dir_img = './测试图片/img' # '/yingedu/project/ocr_server_test/data/img' # './data/img'
211
+
212
+ g_count = 1
213
+ g_count2 = 1
214
+
215
+
216
+ json_paths = glob.glob('{}/*.json'.format(dir_json), recursive=False)
217
+
218
+
219
+ #json_paths = get_json_paths()
220
+
221
+ for json_path in json_paths:
222
+
223
+ arr = []
224
+
225
+ base = Path(json_path).stem
226
+
227
+ # if base == '0bf0383ece9a533683e615bf57525812':
228
+ # continue
229
+
230
+ img_path = os.path.join(dir_img, '{}.txt'.format(base))
231
+
232
+ if not os.path.exists(img_path): # 没有相应的图片,可能被删除了
233
+ print(f'Warnnig: no image {img_path}')
234
+ continue
235
+
236
+ jsn = load_json(json_path)
237
+
238
+ if not ('prism_wordsInfo' in jsn):
239
+ print(f'Warning: no charater in {img_path}')
240
+ continue
241
+
242
+ with open(img_path, "r", encoding="utf-8") as fp:
243
+ imgdata = fp.read()
244
+ imgdata = base64.b64decode(imgdata)
245
+ imgdata = np.frombuffer(imgdata, np.uint8)
246
+ img = cv2.imdecode(imgdata, cv2.IMREAD_UNCHANGED)
247
+
248
+ # cv2.imshow('img', img)
249
+ # cv2.waitKey(0)
250
+
251
+ if len(img.shape) != 3: # 转彩图
252
+ img_color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
253
+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) # DBNet 原版只能处理彩图,这里转一下
254
+
255
+ else:
256
+ img_color = img.copy()
257
+
258
+ img_color_origin = img_color.copy()
259
+ img_color_origin2 = img_color.copy()
260
+
261
+ name = f'{g_count}.jpg'
262
+ dst_img_path = f'{root}/{name}'
263
+ states += f'G:\\train_data\\{name}\t1\n'
264
+ g_count += 1
265
+
266
+ cv2.imwrite(dst_img_path, img)
267
+
268
+ wordsInfo = jsn['prism_wordsInfo']
269
+ for j in range(len(wordsInfo)):
270
+ jo = wordsInfo[j]
271
+ word = jo["word"]
272
+
273
+ for w in list(word):
274
+ if not (w in dic_words):
275
+ dic_words[w] = True
276
+
277
+ # prism-wordsInfo 里的 angle 文字块的角度,这个角度只影响width和height,当角度为-90、90、-270、270,width和height的值需要自行互换
278
+ angle = jo['angle']
279
+
280
+ img_color = img_color_origin.copy()
281
+
282
+ word_x = jo['x']
283
+ word_y = jo['y']
284
+ word_width = jo['width']
285
+ word_height = jo['height']
286
+
287
+ if abs(angle) == 90 or abs(angle) == 270:
288
+ word_width = jo['height']
289
+ word_height = jo['width']
290
+ elif angle != 0:
291
+
292
+ # 变换前画出绿框,方便追踪点的前后变化
293
+ # img_color = cv2.rectangle(img_color, (word_x, word_y), (
294
+ # word_x + word_width, word_y + word_height), (0, 255, 0), 2) # 矩形的左上角, 矩形的右下角
295
+
296
+ # cv2.imshow("green", img_color)
297
+ # cv2.waitKey(0)
298
+
299
+ # 变换前的多边形蓝框
300
+ points = np.array([
301
+ [word_x, word_y], # 左上
302
+ [word_x + word_width, word_y], # 右上
303
+ [word_x + word_width, word_y + word_height], # 右下
304
+ [word_x, word_y + word_height], # 左下
305
+ ])
306
+
307
+ # # cv2.fillPoly(img_color, pts=[points], color=(255, 0, 0)) # 填充
308
+ # cv2.polylines(img_color, [points], isClosed=True, color=(
309
+ # 255, 0, 0), thickness=1) # 只画线,不填充
310
+
311
+ # cv2.imshow("polys", img_color)
312
+ # cv2.waitKey(0)
313
+
314
+ # 获取图像的维度,并计算中心
315
+ (h, w) = img_color.shape[:2]
316
+ (cX, cY) = (w // 2, h // 2)
317
+
318
+ # - (cX,cY): 旋转的中心点坐标
319
+ # - 180: 旋转的度数,正度数表示逆时针旋转,而负度数表示顺时针旋转。
320
+ # - 1.0:旋转后图像的大小,1.0原图,2.0变成原来的2倍,0.5变成原来的0.5倍
321
+ # 1° = π/180弧度 1 弧度 = 180 / 3.1415926 // 0.0190033 是Mathematica 算出来的弧度,先转换成角度 // -0.0190033 * (180 / 3.1415926)
322
+ M = cv2.getRotationMatrix2D((cX, cY), angle, 1.0)
323
+ img_color = cv2.warpAffine(img_color, M, (w, h))
324
+ img_color_transform = img_color.copy()
325
+
326
+ # cv2.imshow("after trans", img_color)
327
+ # cv2.waitKey(0)
328
+
329
+ # https://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/warp_affine/warp_affine.html # 原理
330
+ # https://stackoverflow.com/questions/30327659/how-can-i-remap-a-point-after-an-image-rotation # How can I remap a point after an image rotation?
331
+ # 如何得到移动后的坐标点
332
+
333
+ # points 算出四个点变换后移动到哪里了
334
+ points = np.array([[word_x, word_y], # 左上
335
+ # 右上
336
+ [word_x + word_width, word_y],
337
+ [word_x + word_width, word_y + \
338
+ word_height], # 右下
339
+ [word_x, word_y + word_height], # 左下
340
+ ])
341
+ # add ones
342
+ ones = np.ones(shape=(len(points), 1))
343
+
344
+ points_ones = np.hstack([points, ones])
345
+
346
+ # transform points
347
+ transformed_points = M.dot(points_ones.T).T
348
+
349
+ transformed_points_int = np.round(
350
+ transformed_points, decimals=0).astype(np.int32) # 批量四舍五入
351
+
352
+ # cv2.polylines(img_color, [transformed_points_int], isClosed=True, color=(
353
+ # 0, 0, 255), thickness=2) # 画转换后的点
354
+
355
+ # cv2.polylines(img_color_origin, [points], isClosed=True, color=(
356
+ # random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), thickness=2) # 画转换前的点
357
+
358
+ # cv2.imshow("orgin", img_color_origin)
359
+ # cv2.waitKey(0)
360
+
361
+ # 四个角的位置 # 左上、右上、右下、左下,当NeedRotate为true时,如果最外层的angle不为0,需要按照angle矫正图片后,坐标才准确(错,经验证不需要)
362
+ pos = jo["pos"]
363
+ x = int(pos[0]["x"]) # 左上
364
+ y = int(pos[0]["y"])
365
+
366
+ x2 = int(pos[2]["x"]) # 右下
367
+ y2 = int(pos[2]["y"])
368
+
369
+ lu = [pos[0]['x'], pos[0]['y']] # left up 四个角顺时针方向数
370
+ ru = [pos[1]['x'], pos[1]['y']]
371
+ rd = [pos[2]['x'], pos[2]['y']]
372
+ ld = [pos[3]['x'], pos[3]['y']]
373
+
374
+ # 生成 icdar2015 格式的人工标记训练数据(用于训练 mmocr)
375
+ # gt_txt_list.append( "{},{},{},{},{},{},{},{},{}".format(lu[0], lu[1], ru[0], ru[1], rd[0], rd[1], ld[0], ld[1], word) )
376
+
377
+ # 绘制矩形
378
+ start_point = (x, y) # 矩形的左上角
379
+
380
+ end_point = (x2, y2) # 矩形的右下角
381
+
382
+ color = (0, 0, 255) # BGR
383
+
384
+ thickness = 2
385
+
386
+ # 逐行画框
387
+ # img_color_origin2 = cv2.rectangle(img_color_origin2, start_point, end_point, color, thickness)
388
+ # cv2.imshow("box", img_color_origin2)
389
+
390
+ # cv2.waitKey(0)
391
+
392
+ points = [lu, ru, rd, ld]
393
+
394
+ points0 = np.array([[word_x, word_y], # 左上
395
+ # 右上
396
+ [word_x + word_width, word_y],
397
+ [word_x + word_width, word_y + \
398
+ word_height], # 右下
399
+ [word_x, word_y + word_height], # 左下
400
+ ])
401
+ points1 = np.array([lu, ru, rd, ld])
402
+
403
+ if not (abs(angle) == 90 or abs(angle) == 270) and angle != 0:
404
+ points = transform(points, M)
405
+ else:
406
+ points = np.array(points)
407
+
408
+ ps3 = np.array(
409
+ [
410
+ [min(points[0][0], points1[0][0]), min(
411
+ points[0][1], points1[0][1])], # 左上(取最两者中最小的)
412
+
413
+ [max(points[1][0], points1[1][0]), min(
414
+ points[1][1], points1[1][1])], # 右上
415
+
416
+ [max(points[2][0], points1[2][0]), max(
417
+ points[2][1], points1[2][1])], # 右下
418
+
419
+ [min(points[3][0], points1[3][0]), max(
420
+ points[3][1], points1[3][1])] # 左下
421
+ ]
422
+ )
423
+
424
+ # img_cuted = cutPoly(img, points1)
425
+ # cv2.imwrite(f'./tmp/{g_count2}.jpg', img_cuted)
426
+ # with open(f'./tmp/{g_count2}.txt', 'w', encoding='utf-8') as f:
427
+ # f.write(word)
428
+ # g_count2 += 1
429
+
430
+ # cv2.polylines(img_color_origin, [points], isClosed=True, color=( # 多边形,框得比较全
431
+ # 100, 0, 255), thickness=2) # 只画线,不填充
432
+
433
+
434
+ arr.append( {"transcription":f"{word}","points":[lu, ru, rd, ld],"difficult":False} )
435
+
436
+
437
+ cv2.polylines(img_color_origin, [points1], isClosed=True, color=(
438
+ random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), thickness=2) # 画转换前的点
439
+
440
+ # cv2.polylines(img_color_origin, [ps3], isClosed=True, color=(255, 0, 0), thickness=2)
441
+
442
+ # cv2.imshow("orgin", img_color_origin)
443
+ # cv2.waitKey(0)
444
+
445
+ # break
446
+
447
+
448
+ arr_str = string(arr)
449
+ line = f'{dst_img_path}\t{arr_str}\n'
450
+ label += line
451
+
452
+ print( f'{g_count - 1} / {len(json_paths)} task done.' )
453
+
454
+ ks = list( dic_words.keys() )
455
+
456
+ keys = '\n'.join(ks)
457
+
458
+ with open(label_path, "w", encoding='utf-8') as fp:
459
+ fp.write(label)
460
+
461
+ with open(key_path, "w", encoding='utf-8') as fp:
462
+ fp.write(keys)
463
+
464
+ with open(fileState_path, "w", encoding='utf-8') as fp:
465
+ fp.write(states)
466
+
467
+ print('all task done.')
468
+
469
+ def show_box_shidianguji(pth_img):
470
+ imgData = np.fromfile(pth_img, dtype=np.uint8)
471
+ img = cv2.imdecode(imgData, cv2.IMREAD_UNCHANGED)
472
+
473
+ if len(img.shape) != 3: # 转彩图
474
+ img_color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
475
+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) # DBNet 原版只能处理彩图,这里转一下
476
+ else:
477
+ img_color = img.copy()
478
+
479
+
480
+ charPoly = {
481
+ "x0": 537, "y0": 67, "x1": 578, "y1": 66, "x2": 578, "y2": 122, "x3": 537,"y3": 123
482
+ }
483
+
484
+ lu = [charPoly["x0"], charPoly["y0"]]
485
+ ru = [charPoly["x1"], charPoly["y1"]]
486
+ rd = [charPoly["x2"], charPoly["y2"]]
487
+ ld = [charPoly["x3"], charPoly["y3"]]
488
+ points = np.array([lu, ru, rd, ld])
489
+
490
+ cv2.polylines(img_color, [points], isClosed=True, color=( # 多边形,框得比较全
491
+ 100, 0, 255), thickness=2) # 只画线,不填充
492
+
493
+ cv2.imshow("box", img_color)
494
+ cv2.waitKey(0)
495
+
496
+ pass
497
+
498
+ if __name__ == "__main__":
499
+ # do_convert_aliocr()
500
+ show_box_shidianguji("out/images/0000_1kzz90e16h5ic.webp")
501
+ pass
ocr/qwen_ocr.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 如果没有安装OpenAI Python SDK,可使用命令安装:pip install OpenAI
2
+
3
+ import base64
4
+ from openai import OpenAI
5
+
6
+ # 读取图片并转为 base64
7
+ image_path = "0375.jpg"
8
+ with open(image_path, "rb") as f:
9
+ image_data = base64.b64encode(f.read()).decode("utf-8")
10
+
11
+ # 初始化客户端
12
+ client = OpenAI(
13
+ base_url="https://www.autodl.art/api/v1",
14
+ api_key="7bPZpONEQgxsP7kniD1AzmP3Tr0e84nmfExGroS1v11CBUKi",
15
+ )
16
+
17
+ # 调用接口(这里使用了stream=True进行流式响应)
18
+ stream = client.chat.completions.create(
19
+ model="qwen3.6-plus",
20
+ messages=[
21
+ {
22
+ "role": "user",
23
+ "content": [
24
+ {
25
+ "type": "text",
26
+ "text": "提取图片中的文字,按阅读顺序输出"
27
+ },
28
+ {
29
+ "type": "image_url",
30
+ "image_url": {
31
+ "url": f"data:image/jpeg;base64,{image_data}"
32
+ }
33
+ }
34
+ ]
35
+ }
36
+ ],
37
+ stream=True,
38
+ )
39
+
40
+ # 流式打印输出
41
+ for chunk in stream:
42
+ if chunk.choices and chunk.choices[0].delta.content:
43
+ print(chunk.choices[0].delta.content, end="")
ocr/readme.txt ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ see huggingface_echodict\typst_hlm
3
+
4
+ https://www.shidianguji.com/zh/book/TPM0001
5
+
6
+
7
+ Python 3.13.12
8
+
9
+
10
+ python getdata.py
11
+ 先修改第几章,运行下载文本和坐标画框转换格式
12
+
13
+ duckdb + ducklake + readest + typst
14
+
15
+ 针对竖排/繁体/异体字与旧书噪声,选型
16
+
17
+ **推荐选型(你的场景:竖排 + 繁体/异体字 + 旧书噪声)**
18
+
19
+ - 首选检测:`CRAFT` 或 `DBNet++`
20
+ - 首选识别:`SVTR-LCNet` / `PARSeq`(中文词表可扩)
21
+ - 实战最稳组合:`CRAFT(检测) + SVTR(识别)` 或 `DBNet++(检测) + PARSeq(识别)`
22
+
23
+ **为什么这样选**
24
+
25
+ - `CRAFT` 优势:
26
+ - 对字符级与复杂排版(竖排、密集、非规则间距)通常更稳。
27
+ - 对旧书里断笔、脏污、背景纹理干扰有较好容错。
28
+ - 缺点是后处理和部署复杂度较高,速度一般。
29
+
30
+ - `DBNet++` 优势:
31
+ - 工业成熟、训练和部署相对标准化。
32
+ - 对低对比、模糊页表现好。
33
+ - 缺点是天然偏“文本区域”,若你要严格“单字框”,需更细后处理或字符级训练策略。
34
+
35
+ - `YOLO` 在你这个特定场景的定位:
36
+ - 可作为强基线(快、易训),但在旧书噪声+极小字+竖排密集时,通常上限不如 `CRAFT/DBNet++` 体系稳定。
37
+
38
+ **针对“繁体/异体字”最关键点(比模型更重要)**
39
+
40
+ - 字典必须扩展到繁体与常见异体字(否则识别上限被词表卡死)。
41
+ - 训练数据要覆盖旧字形、破损字、弱印刷样式。
42
+ - 识别模型建议用可扩词表的 Transformer 系(`PARSeq`、`SVTR`)而不是仅固定简体词集模型。
43
+
44
+ **给你一个直接可执行的决策**
45
+
46
+ - 要“最高鲁棒性”(不太在乎部署复杂):`CRAFT + PARSeq/SVTR`
47
+ - 要“精度和工程平衡”:`DBNet++ + SVTR`
48
+ - 要“快速上线先跑通”:`YOLOv8字符检测 + SVTR`,后续再切 `CRAFT/DBNet++`
49
+
50
+ **一句话结论**
51
+ - 你的场景优先从 `DBNet++` 和 `CRAFT` 二选一做检测,识别端用 `SVTR/PARSeq` 并扩繁体异体词表;这比单纯换更大检测器更能提升最终效果。
52
+
53
+
54
+ https://github.com/wkentaro/labelme
55
+ 文本标注
56
+
57
+ https://borninfreedom.github.io/posts/2024/07/blog-post-1/
58
+ 论文解析——Character Region Awareness for Text Detection,字符级文本检测CRAFT算法
59
+
60
+ https://arxiv.org/abs/1912.04561 A Feasible Framework for Arbitrary-Shaped Scene Text Recognition
61
+ https://github.com/zhang0jhon/AttentionOCR 代码
62
+ ICDAR2019 Robust Reading Challenge on Arbitrary-Shaped Text Competition的冠军
63
+ 它具有以下几个优点:中英文通用、准确性高、代码开源和有预训练模型。简而言之,亲测好用!
64
+ https://zhuanlan.zhihu.com/p/138589087
65
+
66
+
67
+ https://www.shuge.org/meet/topic/78721/
68
+ https://www.ancientbooks.cn/
69
+ 书格
70
+
71
+ https://wenyuan.aliyun.com/
72
+ 汉典重光
73
+
74
+
75
+ https://www.shidianguji.com/zh/book/SWX0005 这网页的顶部有一个按钮 “原本影像”,点一下能出图片。最右边是正文,最左边是章节目录。正文里每一个字符都有一组坐标值能与对应的图片中的字符框对应。看看它在前端是怎样建立对应关系的,相应 api 是什么,怎么下载相关数据,包括文字,坐标,原图
76
+ https://solo.trae.ai/
77
+
78
+ <div class="vik-toolbox-btn click act" type="page-next"> 这里有一个"下一张" 按钮,点击会切换到下一张图片,看看它是怎来得到下一张图片的,把后面的图片都下载下来
79
+
80
+
81
+ A)最快:Network 里 “Copy as fetch” → 粘贴到 Console 执行
82
+ 对每个接口都能用(paragraphs / word-box):
83
+
84
+ 打开书页(比如 https://www.shidianguji.com/zh/book/SWX0005 进入阅读)
85
+ F12 → Network
86
+ 过滤 paragraphs/v2 或 word-box-page-content/m-get
87
+ 点开一条真实请求(确保 Preview/Response 有数据,不是 0 bytes)
88
+ 右键该请求 → Copy → Copy as fetch
89
+ 粘贴到 Console 回车执行
90
+ 返回的就是 JSON(then(r=>r.json())...)
91
+ 如果你遇到 bdturing-verify(滑块验证),先在网页上完成验证后再复制那条“成功返回数据”的请求。
92
+
93
+ (() => {
94
+ window.__cap = { fetch: [], xhr: [] };
95
+
96
+ // hook fetch
97
+ const _fetch = window.fetch;
98
+ window.fetch = async function(input, init = {}) {
99
+ try {
100
+ const url = typeof input === "string" ? input : input.url;
101
+ const method = (init.method || "GET").toUpperCase();
102
+ const body = init.body;
103
+ if (url.includes("/api/ancientlib/read/")) {
104
+ window.__cap.fetch.push({ t: Date.now(), url, method, init: { ...init, body } });
105
+ console.log("[CAP fetch]", method, url, body ? "(has body)" : "");
106
+ }
107
+ } catch (e) {}
108
+ return _fetch.apply(this, arguments);
109
+ };
110
+
111
+ // hook XHR
112
+ const _open = XMLHttpRequest.prototype.open;
113
+ const _send = XMLHttpRequest.prototype.send;
114
+ XMLHttpRequest.prototype.open = function(method, url) {
115
+ this.__cap_info = { t: Date.now(), method, url, body: null };
116
+ return _open.apply(this, arguments);
117
+ };
118
+ XMLHttpRequest.prototype.send = function(body) {
119
+ try {
120
+ if (this.__cap_info && String(this.__cap_info.url).includes("/api/ancientlib/read/")) {
121
+ this.__cap_info.body = body;
122
+ window.__cap.xhr.push(this.__cap_info);
123
+ console.log("[CAP xhr]", this.__cap_info.method, this.__cap_info.url, body ? "(has body)" : "");
124
+ }
125
+ } catch (e) {}
126
+ return _send.apply(this, arguments);
127
+ };
128
+
129
+ console.log("抓包器已安装:现在请在页面里翻页/滚动/点击“原本影像”等触发接口请求。");
130
+ })();
131
+
132
+
133
+ function lastReq(match) {
134
+ const all = [...window.__cap.fetch, ...window.__cap.xhr]
135
+ .filter(x => x.url && x.url.includes(match))
136
+ .sort((a,b) => b.t - a.t);
137
+ return all[0];
138
+ }
139
+
140
+ async function replay(req) {
141
+ if (!req) throw new Error("没抓到请求,请先触发一次页面请求。");
142
+ const url = req.url;
143
+ const method = (req.method || "GET").toUpperCase();
144
+ const body = req.init?.body ?? req.body ?? null;
145
+
146
+ const res = await fetch(url, {
147
+ method,
148
+ // 不要乱加 Origin/Referer(浏览器会自己带);关键是带登录态:
149
+ credentials: "include",
150
+ headers: { "content-type": "application/json" },
151
+ body
152
+ });
153
+
154
+ const text = await res.text();
155
+ if (!text) {
156
+ console.warn("响应为空,可能触发滑块验证(bdturing)。请先在网页上完成验证后再抓一次。");
157
+ return null;
158
+ }
159
+ try { return JSON.parse(text); } catch (e) {
160
+ console.log("非 JSON 文本前200:", text.slice(0, 200));
161
+ throw e;
162
+ }
163
+ }
164
+
165
+ // 1) 拿 paragraphs
166
+ (async () => {
167
+ const req = lastReq("/book/paragraphs/v2");
168
+ console.log("使用请求:", req?.method, req?.url);
169
+ const data = await replay(req);
170
+ console.log("paragraphs:", data);
171
+ window.__paragraphs = data; // 缓存
172
+ })();
173
+
174
+ // 2) 拿 word-box
175
+ (async () => {
176
+ const req = lastReq("/word-box-page-content/m-get/");
177
+ console.log("使用请求:", req?.method, req?.url);
178
+ const data = await replay(req);
179
+ console.log("wordbox:", data);
180
+ window.__wordbox = data; // 缓存
181
+ })();
182
+
183
+
184
+
185
+ https://ocr.kandianguji.com/ocr_api
186
+
187
+ token:8be3d75a-8a66-4b5d-9047-d4895e4c8000
188
+
189
+ email:13788325535
190
+
191
+ 请求参数:
192
+
193
+ token:您所申请的API Token,点此申请 必传
194
+
195
+ email:申请API Token的账号,看典古籍网站的注册账号(参数名为email,手机号注册的传手机号) 必传
196
+
197
+ image:需要识别的古籍图像,base64编码后的字符串类型,您可以在此处转换您的图像为base64编码 必传
198
+
199
+ char_ocr:是否进行单字符检测识别,不检测文本行,只检测图像上的字符,文本行顺序可能会出错;布尔类型;默认值:False
200
+
201
+ det_mode:文字内容排版样式,目前有三种可选:auto(自动识别)、sp(竖向排版)、hp(横向排版);字符串类型,默认值:auto
202
+
203
+ image_size:识别前图像尺寸调整,图像越小识别速度越快,0为不调整,设置指定值将按照设置对图像最长边进行等比例调整;整数类型,默认值:0
204
+
205
+ return_position:是否返回文本行坐标信息和字符坐标信息;布尔类型,默认值:False
206
+
207
+ return_choices:是否返回每个字符的其它候选字;布尔类型,默认值:False
208
+
209
+ version:指定识别算法版本;字符串类型,可选:default(v1标准版本)、beta(古籍语序优化版本)、v2(最新版本),默认值:default
210
+
211
+ det_layout(v2):是否开启版面识别(对图像上的内容进行判断是否是正文、页眉页脚/版心等),对分栏式、多栏式文档识别效果较好;布尔类型(开启True、关闭False),默认值:False
212
+
213
+ only_plain_text(v2):是否只识别返回正文内容,仅当版面识别开启时生效,不识别页眉/页脚/版心等;布尔类型(开启True、关闭False),默认值:False
214
+
215
+ return_layout(v2):是否返回版面信息,仅当版面识别开启时生效;布尔类型(开启True、关闭False),默认值:False
216
+
217
+ auto_insert_space(v2):按照字符间距自动插入空格;布尔类型(开启True、关闭False),默认值:False
218
+
219
+ hp_line_words_angel(v2):指定横排句子文字排序方向;字符串类型(从左到右left2right、从右到左right2left),默认值:left2right
220
+
221
+ sp_line_words_angel(v2):指定竖排句子文字排序方向;字符串类型(从上到下top2bottom、从下到上bottom2top),默认值:top2bottom
222
+
223
+ 请求方式:
224
+
225
+ POST请求,请求体可以为Form Data或JSON两种方式均可接受
226
+
227
+
228
+
229
+
230
+ duckdb + ducklake + readest + typst see huggingface_echodict\typst_hlm\ocr\readme.txt
231
+
232
+ https://aistudio.baidu.com/projectdetail/4438534?channelType=0&channel=0 真实 ocr 项目经验
233
+
234
+
235
+ https://huggingface.co/datasets/ByteDance/AncientDoc 字节的数据集
236
+
237
+ ![img](深入理解神经网络:从逻辑回归到CNN.assets/b5ec48e89a6402434386c3479c641e7b.png)
238
+
239
+ https://aistudio.baidu.com/datasetdetail/165369 真可以下载的 **古籍数据集**
240
+
241
+ https://huggingface.co/datasets/Teklia/CASIA-HWDB2-line
242
+
243
+ https://github.com/esun-ai/traditional-chinese-text-recogn-dataset
ocr/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ requests
2
+ selenium==4.40.0
3
+ numpy<2.0.0
4
+ opencv-python==4.10.0.84