init
Browse files- .gitattributes +6 -0
- .gitignore +8 -0
- ocr/.vscode/launch.json +12 -0
- ocr/auto.py +125 -0
- ocr/draw_box.py +48 -0
- ocr/gendatav2.py +145 -0
- ocr/getdata.py +861 -0
- ocr/readme.txt +247 -0
- ocr/requirements.txt +4 -0
.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,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
ocr/.venv/
|
| 3 |
+
*.pdf
|
| 4 |
+
!戚蓼生序本石头记.pdf
|
| 5 |
+
!新刻金瓶梅词话.第001回至057回.总一百回.明.兰陵笑笑生撰.明万历四十五年刊本.台北故宫博物院藏.pdf
|
| 6 |
+
!新刻金瓶梅词话.第058回至100回.总一百回.明.兰陵笑笑生撰.明万历四十五年刊本.台北故宫博物院藏.pdf
|
| 7 |
+
|
| 8 |
+
|
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/auto.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import subprocess
|
| 2 |
+
import sys
|
| 3 |
+
import os
|
| 4 |
+
import shutil
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
# 获取当前目录
|
| 9 |
+
current_dir = os.path.dirname(os.path.abspath(__file__))
|
| 10 |
+
getdata_script = os.path.join(current_dir, "getdata.py")
|
| 11 |
+
gendata_script = os.path.join(current_dir, "gendatav2.py")
|
| 12 |
+
|
| 13 |
+
# 章节列表
|
| 14 |
+
chapters = [
|
| 15 |
+
"新刻金瓶梅詞話卷之十_第九十一回",
|
| 16 |
+
"新刻金瓶梅詞話卷之十_第九十二回",
|
| 17 |
+
"新刻金瓶梅詞話卷之十_第九十三回",
|
| 18 |
+
"新刻金瓶梅詞話卷之十_第九十四回",
|
| 19 |
+
"新刻金瓶梅詞話卷之十_第九十五回",
|
| 20 |
+
"新刻金瓶梅詞話卷之十_第九十六回",
|
| 21 |
+
"新刻金瓶梅詞話卷之十_第九十七回",
|
| 22 |
+
"新刻金瓶梅詞話卷之十_第九十八回",
|
| 23 |
+
"新刻金瓶梅詞話卷之十_第九十九回",
|
| 24 |
+
"新刻金瓶梅詞話卷之十_第一百回"
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
for i, chapter_name in enumerate(chapters):
|
| 28 |
+
print(f"\n=====================================")
|
| 29 |
+
print(f"开始处理章节: {chapter_name}")
|
| 30 |
+
print(f"=====================================")
|
| 31 |
+
|
| 32 |
+
if os.path.exists(chapter_name):
|
| 33 |
+
shutil.rmtree(chapter_name)
|
| 34 |
+
# 构建命令
|
| 35 |
+
command = [
|
| 36 |
+
sys.executable,
|
| 37 |
+
getdata_script,
|
| 38 |
+
"--chapter",
|
| 39 |
+
chapter_name
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
print(f"正在执行命令: {' '.join(command)}")
|
| 43 |
+
|
| 44 |
+
# 调用 getdata.py
|
| 45 |
+
try:
|
| 46 |
+
subprocess.run(command, check=True)
|
| 47 |
+
print(f"{chapter_name} 的 getdata.py 执行成功")
|
| 48 |
+
|
| 49 |
+
# 删除 out/raw 下以 0000_ 或 0001_ 开头的文件
|
| 50 |
+
raw_dir = os.path.join(current_dir, "out", "raw")
|
| 51 |
+
if os.path.exists(raw_dir):
|
| 52 |
+
for filename in os.listdir(raw_dir):
|
| 53 |
+
if filename.startswith("0000_paragraphs") or filename.startswith("0001_paragraphs") or filename.startswith("0002_paragraphs") or filename.startswith("0000_pages") or filename.startswith("0001_pages") or filename.startswith("0002_pages"):
|
| 54 |
+
file_to_delete = os.path.join(raw_dir, filename)
|
| 55 |
+
try:
|
| 56 |
+
os.remove(file_to_delete) # 有些好像又不需要删除
|
| 57 |
+
print(f"已删除: {file_to_delete}")
|
| 58 |
+
except Exception as e:
|
| 59 |
+
print(f"删除 {file_to_delete} 失败: {e}")
|
| 60 |
+
|
| 61 |
+
# 运行 gendatav2.py
|
| 62 |
+
print(f"正在运行 {chapter_name} 的 gendatav2.py")
|
| 63 |
+
gendata_command = [sys.executable, gendata_script]
|
| 64 |
+
subprocess.run(gendata_command, check=True)
|
| 65 |
+
print(f"{chapter_name} 的 gendatav2.py 执行成功")
|
| 66 |
+
|
| 67 |
+
# 创建目标文件夹
|
| 68 |
+
target_dir = os.path.join(current_dir, chapter_name)
|
| 69 |
+
os.makedirs(target_dir, exist_ok=True)
|
| 70 |
+
print(f"确保目标文件夹存在: {target_dir}")
|
| 71 |
+
|
| 72 |
+
# 移动 out 和 out2
|
| 73 |
+
for folder_name in ["out", "out2"]:
|
| 74 |
+
src_dir = os.path.join(current_dir, folder_name)
|
| 75 |
+
dest_dir = os.path.join(target_dir, folder_name)
|
| 76 |
+
|
| 77 |
+
if os.path.exists(src_dir):
|
| 78 |
+
# 如果目标路径已存在同名文件夹,先删除,防止移动时发生嵌套或报错
|
| 79 |
+
if os.path.exists(dest_dir):
|
| 80 |
+
shutil.rmtree(dest_dir)
|
| 81 |
+
shutil.move(src_dir, dest_dir)
|
| 82 |
+
print(f"已将 {folder_name} 移动到 {chapter_name} 内")
|
| 83 |
+
else:
|
| 84 |
+
print(f"未找到 {folder_name} 文件夹,跳过")
|
| 85 |
+
|
| 86 |
+
except subprocess.CalledProcessError as e:
|
| 87 |
+
print(f"{chapter_name} 的 getdata.py 执行失败,返回码: {e.returncode}")
|
| 88 |
+
except Exception as e:
|
| 89 |
+
print(f"发生错误: {e}")
|
| 90 |
+
|
| 91 |
+
# 如果不是最后一个章节,则延迟 3 分钟
|
| 92 |
+
if i < len(chapters) - 1:
|
| 93 |
+
print(f"\n{chapter_name} 处理完成。")
|
| 94 |
+
print("等待 3 分钟 (180秒) 后继续处理下一个章节...")
|
| 95 |
+
for remaining in range(180, 0, -10):
|
| 96 |
+
print(f"还剩 {remaining} 秒...")
|
| 97 |
+
time.sleep(min(10, remaining))
|
| 98 |
+
print("延迟结束,准备继续。\n")
|
| 99 |
+
|
| 100 |
+
print("\n=====================================")
|
| 101 |
+
print("所有章节处理完成,准备将生成的章节文件夹移动到上一层目录...")
|
| 102 |
+
print("=====================================")
|
| 103 |
+
|
| 104 |
+
parent_dir = os.path.dirname(current_dir)
|
| 105 |
+
for chapter_name in chapters:
|
| 106 |
+
src_dir = os.path.join(current_dir, chapter_name)
|
| 107 |
+
dest_dir = os.path.join(parent_dir, chapter_name)
|
| 108 |
+
|
| 109 |
+
if os.path.exists(src_dir):
|
| 110 |
+
try:
|
| 111 |
+
# 如果目标路径已存在,为了避免 shutil.move 嵌套,可以选择删除或者直接���盖,这里选择覆盖(先删后移)
|
| 112 |
+
if os.path.exists(dest_dir):
|
| 113 |
+
print(f"上一层目录已存在 {chapter_name},正在删除旧文件夹...")
|
| 114 |
+
shutil.rmtree(dest_dir)
|
| 115 |
+
shutil.move(src_dir, dest_dir)
|
| 116 |
+
print(f"成功将 {chapter_name} 移动到: {parent_dir}")
|
| 117 |
+
except Exception as e:
|
| 118 |
+
print(f"移动 {chapter_name} 时发生错误: {e}")
|
| 119 |
+
else:
|
| 120 |
+
print(f"当前目录未找到 {chapter_name} 文件夹,跳过。")
|
| 121 |
+
|
| 122 |
+
print("\n所有任务执行完毕!")
|
| 123 |
+
|
| 124 |
+
if __name__ == "__main__":
|
| 125 |
+
main()
|
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/gendatav2.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
if pth_img.stem in {
|
| 105 |
+
'TPM0001_00006_00089b', 'TPM0001_00009_00002a', 'TPM0001_00009_00002b',
|
| 106 |
+
'TPM0001_00009_00003a', 'TPM0001_00009_00003b', 'TPM0001_00009_00004a',
|
| 107 |
+
'TPM0001_00009_00004b', 'TPM0001_00011_00011b', 'TPM0001_00011_00092b'
|
| 108 |
+
}:
|
| 109 |
+
continue
|
| 110 |
+
raise Exception(f"image {imageName} not found")
|
| 111 |
+
if pageId not in box_jsons:
|
| 112 |
+
raise Exception(f"pageId {pageId} no box_json")
|
| 113 |
+
|
| 114 |
+
pageIds_pageNames[pageId] = baseName
|
| 115 |
+
boxs = box_jsons[pageId]['wordBoxList']
|
| 116 |
+
pth_boxs = str( dir_out2 / Path( imageName.replace(".webp", ".boxs") ) )
|
| 117 |
+
|
| 118 |
+
shutil.copy(pth_img, str( dir_out2 / Path(imageName) ) )
|
| 119 |
+
with open(pth_boxs, 'w', encoding='utf-8') as fp:
|
| 120 |
+
json.dump(boxs, fp, indent=4, ensure_ascii=False)
|
| 121 |
+
fp.close()
|
| 122 |
+
|
| 123 |
+
pth_text_pages = str(Path(dir_out2) / "page_texts.json")
|
| 124 |
+
with open(pth_text_pages, 'w', encoding='utf-8') as fp:
|
| 125 |
+
json.dump(text_pages, fp, indent=4, ensure_ascii=False)
|
| 126 |
+
fp.close()
|
| 127 |
+
|
| 128 |
+
pth_pageIds_pageNames = str(Path(dir_out2) / "pageIds_pageNames.json")
|
| 129 |
+
with open(pth_pageIds_pageNames, 'w', encoding='utf-8') as fp:
|
| 130 |
+
json.dump(pageIds_pageNames, fp, indent=4, ensure_ascii=False)
|
| 131 |
+
fp.close()
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
pth_paragraphs = str(Path(dir_out2) / "paragraphs.json")
|
| 135 |
+
with open(pth_paragraphs, 'w', encoding='utf-8') as fp:
|
| 136 |
+
json.dump(paragraphs, fp, indent=4, ensure_ascii=False)
|
| 137 |
+
fp.close()
|
| 138 |
+
|
| 139 |
+
do_drawbox()
|
| 140 |
+
|
| 141 |
+
def do_gendata():
|
| 142 |
+
main()
|
| 143 |
+
|
| 144 |
+
if __name__ == "__main__":
|
| 145 |
+
do_gendata()
|
ocr/getdata.py
ADDED
|
@@ -0,0 +1,861 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 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 |
+
"volume": re.compile(r"/api/ancientlib/read/get/volume/(?:\?|$)"),
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
IMAGE_URL_RE = re.compile(r"https?://[^ ]+(?:\.webp|\.image|\.png|\.jpe?g|\.bmp)(?:\?.*)?$", re.IGNORECASE)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _safe_name(s: str) -> str:
|
| 30 |
+
s = re.sub(r"[^a-zA-Z0-9._-]+", "_", s)
|
| 31 |
+
return s[:180] if len(s) > 180 else s
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _json_loads_maybe(data: str) -> Optional[Any]:
|
| 35 |
+
try:
|
| 36 |
+
return json.loads(data)
|
| 37 |
+
except Exception:
|
| 38 |
+
return None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _iter_strings(obj: Any) -> Iterable[str]:
|
| 42 |
+
if isinstance(obj, str):
|
| 43 |
+
yield obj
|
| 44 |
+
return
|
| 45 |
+
if isinstance(obj, list):
|
| 46 |
+
for it in obj:
|
| 47 |
+
yield from _iter_strings(it)
|
| 48 |
+
return
|
| 49 |
+
if isinstance(obj, dict):
|
| 50 |
+
for v in obj.values():
|
| 51 |
+
yield from _iter_strings(v)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _extract_text_from_json(payload: Any) -> str:
|
| 55 |
+
if not isinstance(payload, (dict, list)):
|
| 56 |
+
return ""
|
| 57 |
+
chunks: List[str] = []
|
| 58 |
+
|
| 59 |
+
def walk(o: Any) -> None:
|
| 60 |
+
if isinstance(o, dict):
|
| 61 |
+
for k, v in o.items():
|
| 62 |
+
lk = str(k).lower()
|
| 63 |
+
if lk in {"text", "content", "paragraph", "para", "value", "word"} and isinstance(v, str):
|
| 64 |
+
chunks.append(v)
|
| 65 |
+
else:
|
| 66 |
+
walk(v)
|
| 67 |
+
elif isinstance(o, list):
|
| 68 |
+
for it in o:
|
| 69 |
+
walk(it)
|
| 70 |
+
|
| 71 |
+
walk(payload)
|
| 72 |
+
out = "\n".join(x.strip() for x in chunks if x and x.strip())
|
| 73 |
+
out = re.sub(r"\n{3,}", "\n\n", out)
|
| 74 |
+
return out.strip()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _find_image_urls(payload: Any) -> List[str]:
|
| 78 |
+
urls: List[str] = []
|
| 79 |
+
for s in _iter_strings(payload):
|
| 80 |
+
if s.startswith("http") and (".webp" in s or ".image" in s or "/page/" in s):
|
| 81 |
+
urls.append(s)
|
| 82 |
+
dedup: List[str] = []
|
| 83 |
+
seen = set()
|
| 84 |
+
for u in urls:
|
| 85 |
+
if u not in seen:
|
| 86 |
+
seen.add(u)
|
| 87 |
+
dedup.append(u)
|
| 88 |
+
return dedup
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _maybe_decode_url(s: str) -> List[str]:
|
| 92 |
+
if not isinstance(s, str) or len(s) < 16:
|
| 93 |
+
return []
|
| 94 |
+
out: List[str] = []
|
| 95 |
+
try:
|
| 96 |
+
raw = base64.b64decode(s, validate=False)
|
| 97 |
+
txt = raw.decode("utf-8", errors="ignore")
|
| 98 |
+
except Exception:
|
| 99 |
+
return []
|
| 100 |
+
for m in re.finditer(r"https?://[^\\s\"']+", txt):
|
| 101 |
+
u = m.group(0)
|
| 102 |
+
if IMAGE_URL_RE.match(u) and ("byteimg.com" in u or "bytednsdoc.com" in u):
|
| 103 |
+
out.append(u)
|
| 104 |
+
return out
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _extract_image_urls_from_pages(payload: Any) -> List[str]:
|
| 108 |
+
urls: List[str] = []
|
| 109 |
+
if not isinstance(payload, dict):
|
| 110 |
+
return urls
|
| 111 |
+
data = payload.get("data")
|
| 112 |
+
if not isinstance(data, dict):
|
| 113 |
+
return urls
|
| 114 |
+
pages = data.get("pages")
|
| 115 |
+
if not isinstance(pages, list):
|
| 116 |
+
return urls
|
| 117 |
+
for p in pages:
|
| 118 |
+
if not isinstance(p, dict):
|
| 119 |
+
continue
|
| 120 |
+
for key in ("picUrl", "thumbUrl"):
|
| 121 |
+
v = p.get(key)
|
| 122 |
+
if isinstance(v, str):
|
| 123 |
+
urls.extend(_maybe_decode_url(v))
|
| 124 |
+
for v in p.values():
|
| 125 |
+
if isinstance(v, str) and IMAGE_URL_RE.match(v) and ("byteimg.com" in v or "bytednsdoc.com" in v):
|
| 126 |
+
urls.append(v)
|
| 127 |
+
return list(dict.fromkeys(urls))
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _guess_page_keys(payload: Any) -> List[Tuple[str, Any]]:
|
| 131 |
+
hits: List[Tuple[str, Any]] = []
|
| 132 |
+
if isinstance(payload, dict):
|
| 133 |
+
for k, v in payload.items():
|
| 134 |
+
lk = str(k).lower()
|
| 135 |
+
if lk in {"pageid", "page_id", "page"} and isinstance(v, (str, int)):
|
| 136 |
+
hits.append((str(k), v))
|
| 137 |
+
hits.extend(_guess_page_keys(v))
|
| 138 |
+
elif isinstance(payload, list):
|
| 139 |
+
for it in payload:
|
| 140 |
+
hits.extend(_guess_page_keys(it))
|
| 141 |
+
return hits
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@dataclass
|
| 145 |
+
class CapturedResponse:
|
| 146 |
+
kind: str
|
| 147 |
+
url: str
|
| 148 |
+
request_id: str
|
| 149 |
+
status: int
|
| 150 |
+
mime_type: str
|
| 151 |
+
body_text: str
|
| 152 |
+
|
| 153 |
+
def json(self) -> Optional[Any]:
|
| 154 |
+
return _json_loads_maybe(self.body_text)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _make_driver(headless: bool) -> webdriver.Chrome:
|
| 158 |
+
options = webdriver.ChromeOptions()
|
| 159 |
+
if headless:
|
| 160 |
+
options.add_argument("--headless=new")
|
| 161 |
+
options.add_argument("--no-sandbox")
|
| 162 |
+
options.add_argument("--disable-dev-shm-usage")
|
| 163 |
+
options.add_argument("--disable-blink-features=AutomationControlled")
|
| 164 |
+
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")
|
| 165 |
+
options.add_experimental_option("excludeSwitches", ["enable-automation"])
|
| 166 |
+
options.add_experimental_option("useAutomationExtension", False)
|
| 167 |
+
options.set_capability("goog:loggingPrefs", {"performance": "ALL"})
|
| 168 |
+
driver = webdriver.Chrome(options=options)
|
| 169 |
+
driver.execute_cdp_cmd("Network.enable", {})
|
| 170 |
+
return driver
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _drain_network(
|
| 174 |
+
driver: webdriver.Chrome,
|
| 175 |
+
tracked: Dict[str, Tuple[str, str, int, str]],
|
| 176 |
+
ready: List[CapturedResponse],
|
| 177 |
+
image_urls: List[str],
|
| 178 |
+
img_dir: Path,
|
| 179 |
+
max_images: int,
|
| 180 |
+
img_saved: List[Dict[str, Any]],
|
| 181 |
+
) -> None:
|
| 182 |
+
try:
|
| 183 |
+
logs = driver.get_log("performance")
|
| 184 |
+
except Exception:
|
| 185 |
+
return
|
| 186 |
+
for entry in logs:
|
| 187 |
+
try:
|
| 188 |
+
msg = json.loads(entry["message"])["message"]
|
| 189 |
+
except Exception:
|
| 190 |
+
continue
|
| 191 |
+
method = msg.get("method")
|
| 192 |
+
params = msg.get("params", {})
|
| 193 |
+
if method == "Network.requestWillBeSent":
|
| 194 |
+
request = params.get("request", {})
|
| 195 |
+
url = request.get("url", "")
|
| 196 |
+
if "00015" in url:
|
| 197 |
+
print(f"[DEBUG] Network.requestWillBeSent for 00015: url={url}")
|
| 198 |
+
if IMAGE_URL_RE.match(url) and ("byteimg.com" in url or "bytednsdoc.com" in url):
|
| 199 |
+
image_urls.append(url)
|
| 200 |
+
elif method == "Network.responseReceived":
|
| 201 |
+
response = params.get("response", {})
|
| 202 |
+
url = response.get("url", "")
|
| 203 |
+
mime_type = str(response.get("mimeType", "") or "")
|
| 204 |
+
if IMAGE_URL_RE.match(url) and ("byteimg.com" in url or "bytednsdoc.com" in url):
|
| 205 |
+
image_urls.append(url)
|
| 206 |
+
request_id = params.get("requestId")
|
| 207 |
+
if request_id and mime_type.startswith("image/") and IMAGE_URL_RE.match(url) and ("byteimg.com" in url or "bytednsdoc.com" in url):
|
| 208 |
+
status = int(response.get("status", 0) or 0)
|
| 209 |
+
tracked[request_id] = ("image", url, status, mime_type)
|
| 210 |
+
print(f"[DEBUG] Tracked image response: request_id={request_id}, url={url}, status={status}")
|
| 211 |
+
continue
|
| 212 |
+
elif request_id and "00015" in url:
|
| 213 |
+
print(f"[DEBUG] Found 00015 in url but didn't track as image. mime_type={mime_type}, url={url}, request_id={request_id}")
|
| 214 |
+
kind = None
|
| 215 |
+
for k, pat in TARGET_PATTERNS.items():
|
| 216 |
+
if pat.search(url):
|
| 217 |
+
kind = k
|
| 218 |
+
break
|
| 219 |
+
if not kind:
|
| 220 |
+
continue
|
| 221 |
+
request_id = params.get("requestId")
|
| 222 |
+
if not request_id:
|
| 223 |
+
continue
|
| 224 |
+
status = int(response.get("status", 0) or 0)
|
| 225 |
+
tracked[request_id] = (kind, url, status, mime_type)
|
| 226 |
+
elif method == "Network.loadingFinished":
|
| 227 |
+
request_id = params.get("requestId")
|
| 228 |
+
if not request_id or request_id not in tracked:
|
| 229 |
+
continue
|
| 230 |
+
kind, url, status, mime_type = tracked.pop(request_id)
|
| 231 |
+
try:
|
| 232 |
+
body = driver.execute_cdp_cmd("Network.getResponseBody", {"requestId": request_id})
|
| 233 |
+
except Exception as e:
|
| 234 |
+
if kind == "image":
|
| 235 |
+
print(f"[DEBUG] Failed to get response body for image {url}: {e}")
|
| 236 |
+
continue
|
| 237 |
+
if kind == "image":
|
| 238 |
+
if max_images > 0 and len(img_saved) >= max_images:
|
| 239 |
+
print(f"[DEBUG] Max images reached, skipping {url}")
|
| 240 |
+
continue
|
| 241 |
+
raw = body.get("body", "")
|
| 242 |
+
if not raw:
|
| 243 |
+
print(f"[DEBUG] Empty body for image {url}")
|
| 244 |
+
continue
|
| 245 |
+
if body.get("base64Encoded"):
|
| 246 |
+
try:
|
| 247 |
+
data = base64.b64decode(raw)
|
| 248 |
+
except Exception as e:
|
| 249 |
+
print(f"[DEBUG] Failed to decode base64 for image {url}: {e}")
|
| 250 |
+
continue
|
| 251 |
+
else:
|
| 252 |
+
data = raw.encode("utf-8", errors="ignore")
|
| 253 |
+
ext = ".bin"
|
| 254 |
+
if "webp" in (mime_type or "").lower():
|
| 255 |
+
ext = ".webp"
|
| 256 |
+
elif "png" in (mime_type or "").lower():
|
| 257 |
+
ext = ".png"
|
| 258 |
+
elif "jpeg" in (mime_type or "").lower() or "jpg" in (mime_type or "").lower():
|
| 259 |
+
ext = ".jpg"
|
| 260 |
+
|
| 261 |
+
page_id = ""
|
| 262 |
+
m = re.search(r"/page/([^/]+)/", url)
|
| 263 |
+
if m:
|
| 264 |
+
page_id = f"_{m.group(1)}"
|
| 265 |
+
else:
|
| 266 |
+
m2 = re.search(r"1k[a-z0-9]{11}", url)
|
| 267 |
+
if m2:
|
| 268 |
+
page_id = f"_{m2.group(0)}"
|
| 269 |
+
|
| 270 |
+
# Default file name format
|
| 271 |
+
file_name = f"{len(img_saved):04d}{page_id}{ext}"
|
| 272 |
+
|
| 273 |
+
# Try to extract actual filename from URL, e.g. SWX0005_00001_00001.webp
|
| 274 |
+
m_name = re.search(r"-([a-zA-Z0-9_]+\.(?:webp|png|jpe?g|jpg|bmp))", url, re.IGNORECASE)
|
| 275 |
+
if m_name:
|
| 276 |
+
file_name = m_name.group(1)
|
| 277 |
+
else:
|
| 278 |
+
m_name2 = re.search(r"/([^/]+?\.(?:webp|png|jpe?g|jpg|bmp))(?:[?~]|$)", url, re.IGNORECASE)
|
| 279 |
+
if m_name2:
|
| 280 |
+
name_part = m_name2.group(1)
|
| 281 |
+
if "-" in name_part:
|
| 282 |
+
file_name = name_part.split("-", 1)[-1]
|
| 283 |
+
else:
|
| 284 |
+
file_name = name_part
|
| 285 |
+
|
| 286 |
+
out_path = img_dir / file_name
|
| 287 |
+
try:
|
| 288 |
+
out_path.write_bytes(data)
|
| 289 |
+
print(f"[DEBUG] Saved image: {file_name} from {url}")
|
| 290 |
+
except Exception as e:
|
| 291 |
+
print(f"[DEBUG] Failed to save image {file_name} from {url}: {e}")
|
| 292 |
+
continue
|
| 293 |
+
img_saved.append({"url": url, "mimeType": mime_type, "path": str(out_path)})
|
| 294 |
+
continue
|
| 295 |
+
|
| 296 |
+
body_text = body.get("body", "")
|
| 297 |
+
if body.get("base64Encoded"):
|
| 298 |
+
try:
|
| 299 |
+
body_text = base64.b64decode(body_text).decode("utf-8", errors="replace")
|
| 300 |
+
except Exception:
|
| 301 |
+
body_text = ""
|
| 302 |
+
|
| 303 |
+
if kind == "loader":
|
| 304 |
+
try:
|
| 305 |
+
data = json.loads(body_text)
|
| 306 |
+
if "paragraphList" in data:
|
| 307 |
+
para_payload = {
|
| 308 |
+
"errorCode": 0,
|
| 309 |
+
"errorMsg": "",
|
| 310 |
+
"data": {
|
| 311 |
+
"paragraphs": data["paragraphList"]
|
| 312 |
+
}
|
| 313 |
+
}
|
| 314 |
+
body_text = json.dumps(para_payload, ensure_ascii=False)
|
| 315 |
+
kind = "paragraphs"
|
| 316 |
+
url = "https://www.shidianguji.com/api/ancientlib/read/book/paragraphs/v2?mock=from_loader"
|
| 317 |
+
print(f"[DEBUG] Transformed loader response to paragraphs format")
|
| 318 |
+
except Exception as e:
|
| 319 |
+
print(f"[DEBUG] Failed to parse loader JSON: {e}")
|
| 320 |
+
|
| 321 |
+
ready.append(
|
| 322 |
+
CapturedResponse(
|
| 323 |
+
kind=kind,
|
| 324 |
+
url=url,
|
| 325 |
+
request_id=request_id,
|
| 326 |
+
status=status,
|
| 327 |
+
mime_type=mime_type,
|
| 328 |
+
body_text=body_text,
|
| 329 |
+
)
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def _collect_dom_image_urls(driver: webdriver.Chrome) -> List[str]:
|
| 334 |
+
try:
|
| 335 |
+
urls = driver.execute_script(
|
| 336 |
+
"return Array.from(document.images||[]).map(i=>i.currentSrc||i.src).filter(Boolean);"
|
| 337 |
+
)
|
| 338 |
+
except Exception:
|
| 339 |
+
return []
|
| 340 |
+
if not isinstance(urls, list):
|
| 341 |
+
return []
|
| 342 |
+
out: List[str] = []
|
| 343 |
+
for u in urls:
|
| 344 |
+
if isinstance(u, str) and IMAGE_URL_RE.match(u) and ("byteimg.com" in u or "bytednsdoc.com" in u):
|
| 345 |
+
out.append(u)
|
| 346 |
+
return list(dict.fromkeys(out))
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def _try_click_by_text(driver: webdriver.Chrome, text: str, timeout_s: float = 2.5) -> bool:
|
| 350 |
+
xp = (
|
| 351 |
+
f"//*[self::button or self::a or @role='button' or self::div]"
|
| 352 |
+
f"[contains(normalize-space(.), {json.dumps(text, ensure_ascii=False)})]"
|
| 353 |
+
)
|
| 354 |
+
try:
|
| 355 |
+
els = driver.find_elements(By.XPATH, xp)
|
| 356 |
+
except Exception:
|
| 357 |
+
return False
|
| 358 |
+
for el in els[:5]:
|
| 359 |
+
try:
|
| 360 |
+
if not el.is_displayed() or not el.is_enabled():
|
| 361 |
+
continue
|
| 362 |
+
el.click()
|
| 363 |
+
return True
|
| 364 |
+
except Exception:
|
| 365 |
+
continue
|
| 366 |
+
return False
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def _enter_image_mode(driver: webdriver.Chrome) -> None:
|
| 370 |
+
for t in ("原图", "影印", "图片", "图像", "掃圖", "扫描", "切换"):
|
| 371 |
+
if _try_click_by_text(driver, t, timeout_s=0):
|
| 372 |
+
time.sleep(0.8)
|
| 373 |
+
break
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def main() -> int:
|
| 377 |
+
ap = argparse.ArgumentParser()
|
| 378 |
+
ap.add_argument("--book-id", default="HY1540")
|
| 379 |
+
ap.add_argument("--chapter", default="評論出像水滸傳卷之一_楔子") # 因为目录有两个之四, 不写或者写 [0] 表示点击第一个(默认行为) 写 [1] 表示点击第二个
|
| 380 |
+
ap.add_argument("--out", default="out")
|
| 381 |
+
ap.add_argument("--headless", action="store_true")
|
| 382 |
+
ap.add_argument("--timeout", type=int, default=20000)
|
| 383 |
+
ap.add_argument("--max-images", type=int, default=1000)
|
| 384 |
+
args = ap.parse_args()
|
| 385 |
+
|
| 386 |
+
out_dir = Path(args.out).resolve()
|
| 387 |
+
raw_dir = out_dir / "raw"
|
| 388 |
+
img_dir = out_dir / "images"
|
| 389 |
+
coord_dir = out_dir / "coords"
|
| 390 |
+
text_dir = out_dir / "text"
|
| 391 |
+
for d in (raw_dir, img_dir, coord_dir, text_dir):
|
| 392 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 393 |
+
|
| 394 |
+
driver = _make_driver(headless=args.headless)
|
| 395 |
+
driver.set_window_size(1400, 900)
|
| 396 |
+
captured: List[CapturedResponse] = []
|
| 397 |
+
tracked: Dict[str, Tuple[str, str, int, str]] = {}
|
| 398 |
+
image_urls: List[str] = []
|
| 399 |
+
img_saved: List[Dict[str, Any]] = []
|
| 400 |
+
try:
|
| 401 |
+
url = f"https://www.shidianguji.com/zh/book/{args.book_id}"
|
| 402 |
+
driver.get(url)
|
| 403 |
+
|
| 404 |
+
# Drain network to capture the initial chapter data
|
| 405 |
+
for _ in range(5):
|
| 406 |
+
time.sleep(1)
|
| 407 |
+
before = len(captured)
|
| 408 |
+
_drain_network(driver, tracked, captured, image_urls, img_dir, int(args.max_images), img_saved)
|
| 409 |
+
if len(captured) == before and any(c.kind in ("paragraphs", "pages") for c in captured):
|
| 410 |
+
break
|
| 411 |
+
|
| 412 |
+
initial_captured = list(captured)
|
| 413 |
+
initial_img_saved = list(img_saved)
|
| 414 |
+
initial_image_urls = list(image_urls)
|
| 415 |
+
|
| 416 |
+
captured.clear()
|
| 417 |
+
img_saved.clear()
|
| 418 |
+
image_urls.clear()
|
| 419 |
+
tracked.clear()
|
| 420 |
+
|
| 421 |
+
chapter_parts = args.chapter.split("_")
|
| 422 |
+
current_part_idx = 0
|
| 423 |
+
|
| 424 |
+
clicked = False
|
| 425 |
+
no_scroll_count = 0
|
| 426 |
+
for scroll_attempts in range(400):
|
| 427 |
+
raw_target_part = chapter_parts[current_part_idx]
|
| 428 |
+
|
| 429 |
+
# 解析可选的索引,例如 "新刻金瓶梅詞話卷之四[1]" 表示点击第2个匹配的元素(索引从0开始)
|
| 430 |
+
target_part = raw_target_part
|
| 431 |
+
target_index = 0
|
| 432 |
+
m_idx = re.search(r'\[(\d+)\]$', raw_target_part)
|
| 433 |
+
if m_idx:
|
| 434 |
+
target_index = int(m_idx.group(1))
|
| 435 |
+
target_part = raw_target_part[:m_idx.start()]
|
| 436 |
+
|
| 437 |
+
part_clicked_in_this_attempt = False
|
| 438 |
+
|
| 439 |
+
# 处理常见的异体字,如 "囘" 和 "回"
|
| 440 |
+
search_parts = [target_part]
|
| 441 |
+
if '囘' in target_part:
|
| 442 |
+
search_parts.append(target_part.replace('囘', '回'))
|
| 443 |
+
if '回' in target_part:
|
| 444 |
+
search_parts.append(target_part.replace('回', '囘'))
|
| 445 |
+
|
| 446 |
+
els = []
|
| 447 |
+
actual_part = target_part
|
| 448 |
+
for sp in search_parts:
|
| 449 |
+
try:
|
| 450 |
+
# 寻找目标元素
|
| 451 |
+
els = driver.find_elements(By.XPATH, f"//*[contains(normalize-space(.), {json.dumps(sp, ensure_ascii=False)}) and not(.//*[contains(normalize-space(.), {json.dumps(sp, ensure_ascii=False)})])]")
|
| 452 |
+
if not els:
|
| 453 |
+
els = driver.find_elements(By.LINK_TEXT, sp)
|
| 454 |
+
if not els:
|
| 455 |
+
els = driver.find_elements(By.PARTIAL_LINK_TEXT, sp)
|
| 456 |
+
if els:
|
| 457 |
+
actual_part = sp
|
| 458 |
+
break
|
| 459 |
+
except Exception as e:
|
| 460 |
+
print(f"[DEBUG] Exception finding '{sp}': {e}")
|
| 461 |
+
pass
|
| 462 |
+
|
| 463 |
+
target_part = actual_part
|
| 464 |
+
|
| 465 |
+
try:
|
| 466 |
+
# 为了调试,打印找到的元素数量
|
| 467 |
+
if els:
|
| 468 |
+
print(f"[DEBUG] Found {len(els)} elements for '{target_part}'")
|
| 469 |
+
for idx_debug, el_debug in enumerate(els):
|
| 470 |
+
try:
|
| 471 |
+
rect = driver.execute_script("return arguments[0].getBoundingClientRect();", el_debug)
|
| 472 |
+
tag_name = el_debug.tag_name
|
| 473 |
+
text_content = el_debug.text.strip()
|
| 474 |
+
print(f"[DEBUG] Element {idx_debug}: tag={tag_name}, text='{text_content}', rect={rect}")
|
| 475 |
+
except Exception as e:
|
| 476 |
+
print(f"[DEBUG] Element {idx_debug}: Error getting info: {e}")
|
| 477 |
+
|
| 478 |
+
seen_y_coords = []
|
| 479 |
+
for el in els:
|
| 480 |
+
try:
|
| 481 |
+
# 确保元素可见,但有时候框架中节点在视口外会被认为是 is_displayed() == False,
|
| 482 |
+
# 可以先尝试滚动到视图内再判断。
|
| 483 |
+
driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", el)
|
| 484 |
+
time.sleep(0.3)
|
| 485 |
+
|
| 486 |
+
# 某些特殊的折叠列表可能元素高度/宽度为0,我们通过 JS 获取位置和尺寸
|
| 487 |
+
rect = driver.execute_script("return arguments[0].getBoundingClientRect();", el)
|
| 488 |
+
if rect['width'] <= 0 or rect['height'] <= 0:
|
| 489 |
+
continue
|
| 490 |
+
|
| 491 |
+
# 根据 Y 坐标去重,同一个位置的多个元素只算作一个匹配项
|
| 492 |
+
el_y = rect['top']
|
| 493 |
+
is_new_item = True
|
| 494 |
+
for seen_y in seen_y_coords:
|
| 495 |
+
if abs(seen_y - el_y) < 5:
|
| 496 |
+
is_new_item = False
|
| 497 |
+
break
|
| 498 |
+
|
| 499 |
+
if is_new_item:
|
| 500 |
+
seen_y_coords.append(el_y)
|
| 501 |
+
|
| 502 |
+
# seen_y_coords 的长度就是当前发现了几个独立的视觉项
|
| 503 |
+
# 如果当前项的索引(长度-1)小于目标索引,则跳过
|
| 504 |
+
if len(seen_y_coords) - 1 < target_index:
|
| 505 |
+
continue
|
| 506 |
+
|
| 507 |
+
click_success = False
|
| 508 |
+
try:
|
| 509 |
+
# 如果元素有特殊的父级可点击区域,有时候点击自身会失败,尝试点击父级
|
| 510 |
+
# 在识典古籍中,目录经常是特定的 div 或者 span
|
| 511 |
+
el.click()
|
| 512 |
+
click_success = True
|
| 513 |
+
except Exception:
|
| 514 |
+
# Try JS click as fallback if standard click fails
|
| 515 |
+
try:
|
| 516 |
+
driver.execute_script("arguments[0].click();", el)
|
| 517 |
+
click_success = True
|
| 518 |
+
except Exception:
|
| 519 |
+
pass
|
| 520 |
+
|
| 521 |
+
# 如果点击成功了,我们需要检查它是不是实际上展开了。
|
| 522 |
+
# 因为在有些 UI 中,点击一个已经被选中的层级会把它折叠起来。
|
| 523 |
+
if click_success:
|
| 524 |
+
print(f"[DEBUG] Clicked '{target_part}' successfully.")
|
| 525 |
+
# 等待展开动画
|
| 526 |
+
time.sleep(1.5)
|
| 527 |
+
|
| 528 |
+
# 判断是否成功展开:如果是父节点,我们需要能看到它的子节点
|
| 529 |
+
if current_part_idx < len(chapter_parts) - 1:
|
| 530 |
+
raw_next_part = chapter_parts[current_part_idx + 1]
|
| 531 |
+
next_part = raw_next_part
|
| 532 |
+
m_next_idx = re.search(r'\[(\d+)\]$', raw_next_part)
|
| 533 |
+
if m_next_idx:
|
| 534 |
+
next_part = raw_next_part[:m_next_idx.start()]
|
| 535 |
+
|
| 536 |
+
next_search_parts = [next_part]
|
| 537 |
+
if '囘' in next_part:
|
| 538 |
+
next_search_parts.append(next_part.replace('囘', '回'))
|
| 539 |
+
if '回' in next_part:
|
| 540 |
+
next_search_parts.append(next_part.replace('回', '囘'))
|
| 541 |
+
|
| 542 |
+
next_els = []
|
| 543 |
+
actual_next_part = next_part
|
| 544 |
+
for nsp in next_search_parts:
|
| 545 |
+
next_els = driver.find_elements(By.XPATH, f"//*[contains(normalize-space(.), {json.dumps(nsp, ensure_ascii=False)}) and not(.//*[contains(normalize-space(.), {json.dumps(nsp, ensure_ascii=False)})])]")
|
| 546 |
+
if not next_els:
|
| 547 |
+
next_els = driver.find_elements(By.LINK_TEXT, nsp)
|
| 548 |
+
if not next_els:
|
| 549 |
+
next_els = driver.find_elements(By.PARTIAL_LINK_TEXT, nsp)
|
| 550 |
+
if next_els:
|
| 551 |
+
actual_next_part = nsp
|
| 552 |
+
break
|
| 553 |
+
|
| 554 |
+
is_next_visible = False
|
| 555 |
+
for next_el in next_els:
|
| 556 |
+
try:
|
| 557 |
+
if driver.execute_script("var rect = arguments[0].getBoundingClientRect(); return rect.width > 0 && rect.height > 0;", next_el):
|
| 558 |
+
is_next_visible = True
|
| 559 |
+
break
|
| 560 |
+
except:
|
| 561 |
+
pass
|
| 562 |
+
|
| 563 |
+
if not is_next_visible:
|
| 564 |
+
print(f"[DEBUG] '{target_part}' was clicked but '{actual_next_part}' is still not visible. It might have been collapsed. Clicking again.")
|
| 565 |
+
# 再点一次将其展开
|
| 566 |
+
try:
|
| 567 |
+
el.click()
|
| 568 |
+
except:
|
| 569 |
+
driver.execute_script("arguments[0].click();", el)
|
| 570 |
+
time.sleep(1.5)
|
| 571 |
+
|
| 572 |
+
part_clicked_in_this_attempt = True
|
| 573 |
+
if current_part_idx == len(chapter_parts) - 1:
|
| 574 |
+
clicked = True
|
| 575 |
+
else:
|
| 576 |
+
current_part_idx += 1
|
| 577 |
+
no_scroll_count = 0
|
| 578 |
+
break
|
| 579 |
+
except Exception as e:
|
| 580 |
+
print(f"[DEBUG] Exception while interacting with '{target_part}': {e}")
|
| 581 |
+
continue
|
| 582 |
+
except Exception as e:
|
| 583 |
+
print(f"[DEBUG] Exception finding '{target_part}': {e}")
|
| 584 |
+
pass
|
| 585 |
+
|
| 586 |
+
if clicked:
|
| 587 |
+
break
|
| 588 |
+
|
| 589 |
+
if part_clicked_in_this_attempt:
|
| 590 |
+
continue
|
| 591 |
+
|
| 592 |
+
# 如果没找到或没点击成功,滚动所有可滚动的 div,尝试让章节列表显示出来
|
| 593 |
+
try:
|
| 594 |
+
scrolled = driver.execute_script('''
|
| 595 |
+
var els = document.querySelectorAll("div, ul, main, nav, section, aside");
|
| 596 |
+
var scrolledAny = false;
|
| 597 |
+
for (var i = 0; i < els.length; i++) {
|
| 598 |
+
var d = els[i];
|
| 599 |
+
if (d.scrollHeight > d.clientHeight && window.getComputedStyle(d).overflowY !== "hidden") {
|
| 600 |
+
var before = d.scrollTop;
|
| 601 |
+
d.scrollBy(0, 250);
|
| 602 |
+
if (d.scrollTop > before) {
|
| 603 |
+
scrolledAny = true;
|
| 604 |
+
}
|
| 605 |
+
}
|
| 606 |
+
}
|
| 607 |
+
return scrolledAny;
|
| 608 |
+
''')
|
| 609 |
+
if not scrolled:
|
| 610 |
+
no_scroll_count += 1
|
| 611 |
+
if no_scroll_count >= 20:
|
| 612 |
+
print(f"[DEBUG] Reached the bottom of the list (tried 20 times). {target_part} not found.")
|
| 613 |
+
break
|
| 614 |
+
else:
|
| 615 |
+
no_scroll_count = 0
|
| 616 |
+
except Exception:
|
| 617 |
+
pass
|
| 618 |
+
time.sleep(0.5)
|
| 619 |
+
|
| 620 |
+
if clicked:
|
| 621 |
+
print(f"[DEBUG] Clicked {args.chapter}, waiting for new network data...")
|
| 622 |
+
# Wait until we see new 'paragraphs' or 'pages' in captured
|
| 623 |
+
for _ in range(15):
|
| 624 |
+
time.sleep(1)
|
| 625 |
+
_drain_network(driver, tracked, captured, image_urls, img_dir, int(args.max_images), img_saved)
|
| 626 |
+
if any(c.kind in ("paragraphs", "pages") for c in captured):
|
| 627 |
+
print(f"[DEBUG] New data captured for {args.chapter}")
|
| 628 |
+
break
|
| 629 |
+
else:
|
| 630 |
+
print(f"[DEBUG] {args.chapter} not clicked (not found).")
|
| 631 |
+
|
| 632 |
+
has_new_data = any(c.kind in ("paragraphs", "pages") for c in captured)
|
| 633 |
+
|
| 634 |
+
if not has_new_data:
|
| 635 |
+
if clicked:
|
| 636 |
+
print(f"[DEBUG] No new data loaded after clicking {args.chapter}. Using initial chapter data.")
|
| 637 |
+
else:
|
| 638 |
+
print(f"[DEBUG] Using initial chapter data because {args.chapter} was not found.")
|
| 639 |
+
captured.extend(initial_captured)
|
| 640 |
+
img_saved.extend(initial_img_saved)
|
| 641 |
+
image_urls.extend(initial_image_urls)
|
| 642 |
+
else:
|
| 643 |
+
print(f"[DEBUG] Successfully loaded new chapter {args.chapter}. Merging missing data types from initial chapter data.")
|
| 644 |
+
for kind in ("pages", "word_box", "volume", "paragraphs"):
|
| 645 |
+
if not any(c.kind == kind for c in captured):
|
| 646 |
+
print(f"[DEBUG] Inheriting {kind} from initial capture.")
|
| 647 |
+
captured.extend([c for c in initial_captured if c.kind == kind])
|
| 648 |
+
|
| 649 |
+
# Keep initial images as they might be part of the same volume
|
| 650 |
+
img_saved.extend(initial_img_saved)
|
| 651 |
+
image_urls.extend(initial_image_urls)
|
| 652 |
+
|
| 653 |
+
time.sleep(0.8)
|
| 654 |
+
_enter_image_mode(driver)
|
| 655 |
+
|
| 656 |
+
deadline = time.time() + max(10, int(args.timeout))
|
| 657 |
+
last_activity = time.time()
|
| 658 |
+
no_activity_count = 0
|
| 659 |
+
print(f"Starting loop, deadline in {deadline - time.time()} seconds")
|
| 660 |
+
|
| 661 |
+
# Try to find a scrollable container
|
| 662 |
+
from selenium.webdriver.common.keys import Keys
|
| 663 |
+
|
| 664 |
+
while time.time() < deadline:
|
| 665 |
+
before_cap = len(captured)
|
| 666 |
+
before_img = len(img_saved)
|
| 667 |
+
_drain_network(driver, tracked, captured, image_urls, img_dir, int(args.max_images), img_saved)
|
| 668 |
+
if len(captured) != before_cap or len(img_saved) != before_img:
|
| 669 |
+
print(f"Activity! captured: {len(captured)} (+{len(captured)-before_cap}), img_saved: {len(img_saved)} (+{len(img_saved)-before_img})")
|
| 670 |
+
last_activity = time.time()
|
| 671 |
+
no_activity_count = 0
|
| 672 |
+
|
| 673 |
+
# Send PAGE_DOWN to body
|
| 674 |
+
try:
|
| 675 |
+
driver.find_element(By.TAG_NAME, "body").send_keys(Keys.PAGE_DOWN)
|
| 676 |
+
except Exception:
|
| 677 |
+
pass
|
| 678 |
+
|
| 679 |
+
# Click next page if possible
|
| 680 |
+
try:
|
| 681 |
+
# The user indicated: <div class="vik-toolbox-btn click act" type="page-next">
|
| 682 |
+
next_btn = driver.find_element(By.XPATH, "//div[@type='page-next' or contains(@class, 'page-next') or contains(text(), '下一张')]")
|
| 683 |
+
# Add a small delay to prevent clicking too fast which might skip pages
|
| 684 |
+
# Check if we're not loading something
|
| 685 |
+
if next_btn.is_displayed():
|
| 686 |
+
# Check if button is disabled (has disable class)
|
| 687 |
+
cls = next_btn.get_attribute("class") or ""
|
| 688 |
+
if "disable" not in cls:
|
| 689 |
+
# Find current page text to ensure we only click once page changes
|
| 690 |
+
page_text_el = driver.find_elements(By.XPATH, "//div[contains(text(), '/')]")
|
| 691 |
+
curr_text = ""
|
| 692 |
+
for p in page_text_el:
|
| 693 |
+
if "/" in p.text:
|
| 694 |
+
curr_text = p.text
|
| 695 |
+
break
|
| 696 |
+
driver.execute_script("arguments[0].click();", next_btn)
|
| 697 |
+
# Wait for page to change
|
| 698 |
+
for _ in range(10):
|
| 699 |
+
time.sleep(0.2)
|
| 700 |
+
new_text = ""
|
| 701 |
+
for p in driver.find_elements(By.XPATH, "//div[contains(text(), '/')]"):
|
| 702 |
+
if "/" in p.text:
|
| 703 |
+
new_text = p.text
|
| 704 |
+
break
|
| 705 |
+
if new_text != curr_text:
|
| 706 |
+
break
|
| 707 |
+
except Exception:
|
| 708 |
+
pass
|
| 709 |
+
|
| 710 |
+
# Also try to scroll window and any potential scrollable divs
|
| 711 |
+
driver.execute_script('''
|
| 712 |
+
window.scrollBy(0, 900);
|
| 713 |
+
var divs = document.querySelectorAll("div");
|
| 714 |
+
for (var i = 0; i < divs.length; i++) {
|
| 715 |
+
if (divs[i].scrollHeight > divs[i].clientHeight && window.getComputedStyle(divs[i]).overflowY !== "hidden") {
|
| 716 |
+
divs[i].scrollBy(0, 900);
|
| 717 |
+
}
|
| 718 |
+
}
|
| 719 |
+
''')
|
| 720 |
+
|
| 721 |
+
time.sleep(0.6)
|
| 722 |
+
image_urls.extend(_collect_dom_image_urls(driver))
|
| 723 |
+
if time.time() - last_activity > 15:
|
| 724 |
+
no_activity_count += 1
|
| 725 |
+
print(f"No activity for 15 seconds (count: {no_activity_count}).")
|
| 726 |
+
if no_activity_count >= 3:
|
| 727 |
+
print("Too many consecutive periods of no activity, breaking loop.")
|
| 728 |
+
break
|
| 729 |
+
|
| 730 |
+
# Check if next button is actually disabled
|
| 731 |
+
try:
|
| 732 |
+
next_btn = driver.find_element(By.XPATH, "//div[@type='page-next' or contains(@class, 'page-next') or contains(text(), '下一张')]")
|
| 733 |
+
cls = next_btn.get_attribute("class") or ""
|
| 734 |
+
if "disable" in cls:
|
| 735 |
+
print("Reached end of chapter (next button disabled).")
|
| 736 |
+
break
|
| 737 |
+
else:
|
| 738 |
+
print("Next button not disabled, but no network activity. Try clicking again.")
|
| 739 |
+
driver.execute_script("arguments[0].click();", next_btn)
|
| 740 |
+
last_activity = time.time() - 10 # give it 5 more seconds before checking again
|
| 741 |
+
continue
|
| 742 |
+
except Exception:
|
| 743 |
+
print("Could not find next button, breaking loop.")
|
| 744 |
+
break
|
| 745 |
+
break
|
| 746 |
+
print(f"Loop finished. time.time() < deadline: {time.time() < deadline}")
|
| 747 |
+
|
| 748 |
+
for i, c in enumerate(captured):
|
| 749 |
+
ext = "json" if "json" in (c.mime_type or "") or c.body_text.strip().startswith("{") else "txt"
|
| 750 |
+
name = _safe_name(f"{i:04d}_{c.kind}_{c.status}_{c.url}")
|
| 751 |
+
(raw_dir / f"{name}.{ext}").write_text(c.body_text, encoding="utf-8", errors="replace")
|
| 752 |
+
|
| 753 |
+
img_urls = list(dict.fromkeys([u for u in image_urls if u.startswith("http")]))
|
| 754 |
+
pages_payloads = [c.json() for c in captured if c.kind == "pages" and c.status == 200]
|
| 755 |
+
|
| 756 |
+
page_id_to_hash = {}
|
| 757 |
+
for p in pages_payloads:
|
| 758 |
+
if p is not None:
|
| 759 |
+
img_urls.extend(_extract_image_urls_from_pages(p))
|
| 760 |
+
# Build pageId -> hash mapping
|
| 761 |
+
if isinstance(p, dict) and isinstance(p.get("data"), dict):
|
| 762 |
+
pages_list = p["data"].get("pages", [])
|
| 763 |
+
if isinstance(pages_list, list):
|
| 764 |
+
for page in pages_list:
|
| 765 |
+
if isinstance(page, dict):
|
| 766 |
+
pid = str(page.get("pageId", ""))
|
| 767 |
+
uri = str(page.get("uri", ""))
|
| 768 |
+
if pid and uri:
|
| 769 |
+
m = re.search(r"/page/([^/]+)/", uri)
|
| 770 |
+
if m:
|
| 771 |
+
page_id_to_hash[pid] = m.group(1)
|
| 772 |
+
else:
|
| 773 |
+
m2 = re.search(r"1k[a-z0-9]{11}", uri)
|
| 774 |
+
if m2:
|
| 775 |
+
page_id_to_hash[pid] = m2.group(0)
|
| 776 |
+
|
| 777 |
+
img_urls = list(dict.fromkeys(img_urls))
|
| 778 |
+
|
| 779 |
+
coords: Dict[str, Any] = {}
|
| 780 |
+
for c in captured:
|
| 781 |
+
if c.kind != "word_box" or c.status != 200:
|
| 782 |
+
continue
|
| 783 |
+
payload = c.json()
|
| 784 |
+
if payload is None:
|
| 785 |
+
continue
|
| 786 |
+
|
| 787 |
+
page_id = None
|
| 788 |
+
# Extract pageId directly from pageId2WordBoxContent if available
|
| 789 |
+
if isinstance(payload, dict) and isinstance(payload.get("data"), dict):
|
| 790 |
+
content = payload["data"].get("pageId2WordBoxContent")
|
| 791 |
+
if isinstance(content, dict) and content:
|
| 792 |
+
page_id = str(next(iter(content.keys())))
|
| 793 |
+
|
| 794 |
+
if not page_id:
|
| 795 |
+
page_keys = _guess_page_keys(payload)
|
| 796 |
+
for _, v in page_keys:
|
| 797 |
+
if isinstance(v, (str, int)):
|
| 798 |
+
page_id = str(v)
|
| 799 |
+
break
|
| 800 |
+
|
| 801 |
+
hash_suffix = ""
|
| 802 |
+
if page_id and page_id in page_id_to_hash:
|
| 803 |
+
hash_suffix = f"_{page_id_to_hash[page_id]}"
|
| 804 |
+
|
| 805 |
+
key = f"wordbox_{len(coords):04d}{hash_suffix}"
|
| 806 |
+
coords[key] = payload
|
| 807 |
+
(coord_dir / f"{_safe_name(key)}.json").write_text(
|
| 808 |
+
json.dumps(payload, ensure_ascii=False),
|
| 809 |
+
encoding="utf-8",
|
| 810 |
+
errors="replace",
|
| 811 |
+
)
|
| 812 |
+
|
| 813 |
+
paragraph_texts: List[str] = []
|
| 814 |
+
for c in captured:
|
| 815 |
+
if c.kind != "paragraphs" or c.status != 200:
|
| 816 |
+
continue
|
| 817 |
+
payload = c.json()
|
| 818 |
+
if payload is None:
|
| 819 |
+
continue
|
| 820 |
+
t = _extract_text_from_json(payload)
|
| 821 |
+
if t:
|
| 822 |
+
paragraph_texts.append(t)
|
| 823 |
+
full_text = "\n\n".join(paragraph_texts).strip()
|
| 824 |
+
if not full_text and coords:
|
| 825 |
+
fallback_chunks: List[str] = []
|
| 826 |
+
for v in coords.values():
|
| 827 |
+
t = _extract_text_from_json(v)
|
| 828 |
+
if t:
|
| 829 |
+
fallback_chunks.append(t)
|
| 830 |
+
full_text = "\n\n".join(fallback_chunks).strip()
|
| 831 |
+
|
| 832 |
+
if full_text:
|
| 833 |
+
(text_dir / "text.txt").write_text(full_text, encoding="utf-8", errors="replace")
|
| 834 |
+
|
| 835 |
+
summary = {
|
| 836 |
+
"bookId": args.book_id,
|
| 837 |
+
"chapter": args.chapter,
|
| 838 |
+
"captured": [
|
| 839 |
+
{"kind": c.kind, "status": c.status, "mimeType": c.mime_type, "url": c.url}
|
| 840 |
+
for c in captured
|
| 841 |
+
],
|
| 842 |
+
"imageUrls": img_urls[: max(0, int(args.max_images))],
|
| 843 |
+
"imagesSaved": img_saved,
|
| 844 |
+
"coords_keys": list(coords.keys()),
|
| 845 |
+
"out": str(out_dir),
|
| 846 |
+
}
|
| 847 |
+
(out_dir / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 848 |
+
return 0
|
| 849 |
+
finally:
|
| 850 |
+
try:
|
| 851 |
+
driver.quit()
|
| 852 |
+
from gendatav2 import do_gendata
|
| 853 |
+
do_gendata()
|
| 854 |
+
except Exception:
|
| 855 |
+
pass
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
if __name__ == "__main__":
|
| 860 |
+
raise SystemExit(main())
|
| 861 |
+
|
ocr/readme.txt
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
see huggingface_echodict\typst_jpm
|
| 3 |
+
|
| 4 |
+
https://www.shidianguji.com/zh/book/HY1540
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
uv venv --python 3.10 --seed --clear
|
| 8 |
+
|
| 9 |
+
.venv/Scripts/pip.exe install -r requirements.txt --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org
|
| 10 |
+
|
| 11 |
+
.venv/Scripts/python.exe
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
python getdata.py
|
| 15 |
+
先修改第几章,运行下载文本和坐标画框转换格式
|
| 16 |
+
|
| 17 |
+
duckdb + ducklake + readest + typst
|
| 18 |
+
|
| 19 |
+
针对竖排/繁体/异体字与旧书噪声,选型
|
| 20 |
+
|
| 21 |
+
**推荐选型(你的场景:竖排 + 繁体/异体字 + 旧书噪声)**
|
| 22 |
+
|
| 23 |
+
- 首选检测:`CRAFT` 或 `DBNet++`
|
| 24 |
+
- 首选识别:`SVTR-LCNet` / `PARSeq`(中文词表可扩)
|
| 25 |
+
- 实战最稳组合:`CRAFT(检测) + SVTR(识别)` 或 `DBNet++(检测) + PARSeq(识别)`
|
| 26 |
+
|
| 27 |
+
**为什么这样选**
|
| 28 |
+
|
| 29 |
+
- `CRAFT` 优势:
|
| 30 |
+
- 对字符级与复杂排版(竖排、密集、非规则间距)通常更稳。
|
| 31 |
+
- 对旧书里断笔、脏污、背景纹理干扰有较好容错。
|
| 32 |
+
- 缺点是后处理和部署复杂度较高,速度一般。
|
| 33 |
+
|
| 34 |
+
- `DBNet++` 优势:
|
| 35 |
+
- 工业成熟、训练和部署相对标准化。
|
| 36 |
+
- 对低对比、模糊页表现好。
|
| 37 |
+
- 缺点是天然偏“文本区域”,若你要严格“单字框”,需更细后处理或字符级训练策略。
|
| 38 |
+
|
| 39 |
+
- `YOLO` 在你这个特定场景的定位:
|
| 40 |
+
- 可作为强基线(快、易训),但在旧书噪声+极小字+竖排密集时,通常上限不如 `CRAFT/DBNet++` 体系稳定。
|
| 41 |
+
|
| 42 |
+
**针对“繁体/异体字”最关键点(比模型更重要)**
|
| 43 |
+
|
| 44 |
+
- 字典必须扩展到繁体与常见异体字(否则识别上限被词表卡死)。
|
| 45 |
+
- 训练数据要覆盖旧字形、破损字、弱印刷样式。
|
| 46 |
+
- 识别模型建议用可扩词表的 Transformer 系(`PARSeq`、`SVTR`)而不是仅固定简体词集模型。
|
| 47 |
+
|
| 48 |
+
**给你一个直接可执行的决策**
|
| 49 |
+
|
| 50 |
+
- 要“最高鲁棒性”(不太在乎部署复杂):`CRAFT + PARSeq/SVTR`
|
| 51 |
+
- 要“精度和工程平衡”:`DBNet++ + SVTR`
|
| 52 |
+
- 要“快速上线先跑通”:`YOLOv8字符检测 + SVTR`,后续再切 `CRAFT/DBNet++`
|
| 53 |
+
|
| 54 |
+
**一句话结论**
|
| 55 |
+
- 你的场景优先从 `DBNet++` 和 `CRAFT` 二选一做检测,识别端用 `SVTR/PARSeq` 并扩繁体异体词表;这比单纯换更大检测器更能提升最终效果。
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
https://github.com/wkentaro/labelme
|
| 59 |
+
文本标注
|
| 60 |
+
|
| 61 |
+
https://borninfreedom.github.io/posts/2024/07/blog-post-1/
|
| 62 |
+
论文解析——Character Region Awareness for Text Detection,字符级文本检测CRAFT算法
|
| 63 |
+
|
| 64 |
+
https://arxiv.org/abs/1912.04561 A Feasible Framework for Arbitrary-Shaped Scene Text Recognition
|
| 65 |
+
https://github.com/zhang0jhon/AttentionOCR 代码
|
| 66 |
+
ICDAR2019 Robust Reading Challenge on Arbitrary-Shaped Text Competition的冠军
|
| 67 |
+
它具有以下几个优点:中英文通用、准确性高、代码开源和有预训练模型。简而言之,亲测好用!
|
| 68 |
+
https://zhuanlan.zhihu.com/p/138589087
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
https://www.shuge.org/meet/topic/78721/
|
| 72 |
+
https://www.ancientbooks.cn/
|
| 73 |
+
书格
|
| 74 |
+
|
| 75 |
+
https://wenyuan.aliyun.com/
|
| 76 |
+
汉典重光
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
https://www.shidianguji.com/zh/book/SWX0005 这网页的顶部有一个按钮 “原本影像”,点一下能出图片。最右边是正文,最左边是章节目录。正文里每一个字符都有一组坐标值能与对应的图片中的字符框对应。看看它在前端是怎样建立对应关系的,相应 api 是什么,怎么下载相关数据,包括文字,坐标,原图
|
| 80 |
+
https://solo.trae.ai/
|
| 81 |
+
|
| 82 |
+
<div class="vik-toolbox-btn click act" type="page-next"> 这里有一个"下一张" 按钮,点击会切换到下一张图片,看看它是怎来得到下一张图片的,把后面的图片都下载下来
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
A)最快:Network 里 “Copy as fetch” → 粘贴到 Console 执行
|
| 86 |
+
对每个接口都能用(paragraphs / word-box):
|
| 87 |
+
|
| 88 |
+
打开书页(比如 https://www.shidianguji.com/zh/book/SWX0005 进入阅读)
|
| 89 |
+
F12 → Network
|
| 90 |
+
过滤 paragraphs/v2 或 word-box-page-content/m-get
|
| 91 |
+
点开一条真实请求(确保 Preview/Response 有数据,不是 0 bytes)
|
| 92 |
+
右键该请求 → Copy → Copy as fetch
|
| 93 |
+
粘贴到 Console 回车执行
|
| 94 |
+
返回的就是 JSON(then(r=>r.json())...)
|
| 95 |
+
如果你遇到 bdturing-verify(滑块验证),先在网页上完成验证后再复制那条“成功返回数据”的请求。
|
| 96 |
+
|
| 97 |
+
(() => {
|
| 98 |
+
window.__cap = { fetch: [], xhr: [] };
|
| 99 |
+
|
| 100 |
+
// hook fetch
|
| 101 |
+
const _fetch = window.fetch;
|
| 102 |
+
window.fetch = async function(input, init = {}) {
|
| 103 |
+
try {
|
| 104 |
+
const url = typeof input === "string" ? input : input.url;
|
| 105 |
+
const method = (init.method || "GET").toUpperCase();
|
| 106 |
+
const body = init.body;
|
| 107 |
+
if (url.includes("/api/ancientlib/read/")) {
|
| 108 |
+
window.__cap.fetch.push({ t: Date.now(), url, method, init: { ...init, body } });
|
| 109 |
+
console.log("[CAP fetch]", method, url, body ? "(has body)" : "");
|
| 110 |
+
}
|
| 111 |
+
} catch (e) {}
|
| 112 |
+
return _fetch.apply(this, arguments);
|
| 113 |
+
};
|
| 114 |
+
|
| 115 |
+
// hook XHR
|
| 116 |
+
const _open = XMLHttpRequest.prototype.open;
|
| 117 |
+
const _send = XMLHttpRequest.prototype.send;
|
| 118 |
+
XMLHttpRequest.prototype.open = function(method, url) {
|
| 119 |
+
this.__cap_info = { t: Date.now(), method, url, body: null };
|
| 120 |
+
return _open.apply(this, arguments);
|
| 121 |
+
};
|
| 122 |
+
XMLHttpRequest.prototype.send = function(body) {
|
| 123 |
+
try {
|
| 124 |
+
if (this.__cap_info && String(this.__cap_info.url).includes("/api/ancientlib/read/")) {
|
| 125 |
+
this.__cap_info.body = body;
|
| 126 |
+
window.__cap.xhr.push(this.__cap_info);
|
| 127 |
+
console.log("[CAP xhr]", this.__cap_info.method, this.__cap_info.url, body ? "(has body)" : "");
|
| 128 |
+
}
|
| 129 |
+
} catch (e) {}
|
| 130 |
+
return _send.apply(this, arguments);
|
| 131 |
+
};
|
| 132 |
+
|
| 133 |
+
console.log("抓包器已安装:现在请在页面里翻页/滚动/点击“原本影像”等触发接口请求。");
|
| 134 |
+
})();
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
function lastReq(match) {
|
| 138 |
+
const all = [...window.__cap.fetch, ...window.__cap.xhr]
|
| 139 |
+
.filter(x => x.url && x.url.includes(match))
|
| 140 |
+
.sort((a,b) => b.t - a.t);
|
| 141 |
+
return all[0];
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
async function replay(req) {
|
| 145 |
+
if (!req) throw new Error("没抓到请求,请先触发一次页面请求。");
|
| 146 |
+
const url = req.url;
|
| 147 |
+
const method = (req.method || "GET").toUpperCase();
|
| 148 |
+
const body = req.init?.body ?? req.body ?? null;
|
| 149 |
+
|
| 150 |
+
const res = await fetch(url, {
|
| 151 |
+
method,
|
| 152 |
+
// 不要乱加 Origin/Referer(浏览器会自己带);关键是带登录态:
|
| 153 |
+
credentials: "include",
|
| 154 |
+
headers: { "content-type": "application/json" },
|
| 155 |
+
body
|
| 156 |
+
});
|
| 157 |
+
|
| 158 |
+
const text = await res.text();
|
| 159 |
+
if (!text) {
|
| 160 |
+
console.warn("响应为空,可能触发滑块验证(bdturing)。请先在网页上完成验证后再抓一次。");
|
| 161 |
+
return null;
|
| 162 |
+
}
|
| 163 |
+
try { return JSON.parse(text); } catch (e) {
|
| 164 |
+
console.log("非 JSON 文本前200:", text.slice(0, 200));
|
| 165 |
+
throw e;
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
// 1) 拿 paragraphs
|
| 170 |
+
(async () => {
|
| 171 |
+
const req = lastReq("/book/paragraphs/v2");
|
| 172 |
+
console.log("使用请求:", req?.method, req?.url);
|
| 173 |
+
const data = await replay(req);
|
| 174 |
+
console.log("paragraphs:", data);
|
| 175 |
+
window.__paragraphs = data; // 缓存
|
| 176 |
+
})();
|
| 177 |
+
|
| 178 |
+
// 2) 拿 word-box
|
| 179 |
+
(async () => {
|
| 180 |
+
const req = lastReq("/word-box-page-content/m-get/");
|
| 181 |
+
console.log("使用请求:", req?.method, req?.url);
|
| 182 |
+
const data = await replay(req);
|
| 183 |
+
console.log("wordbox:", data);
|
| 184 |
+
window.__wordbox = data; // 缓存
|
| 185 |
+
})();
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
https://ocr.kandianguji.com/ocr_api
|
| 190 |
+
|
| 191 |
+
token:8be3d75a-8a66-4b5d-9047-d4895e4c8000
|
| 192 |
+
|
| 193 |
+
email:13788325535
|
| 194 |
+
|
| 195 |
+
请求参数:
|
| 196 |
+
|
| 197 |
+
token:您所申请的API Token,点此申请 必传
|
| 198 |
+
|
| 199 |
+
email:申请API Token的账号,看典古籍网站的注册账号(参数名为email,手机号注册的传手机号) 必传
|
| 200 |
+
|
| 201 |
+
image:需要识别的古籍图像,base64编码后的字符串类型,您可以在此处转换您的图像为base64编码 必传
|
| 202 |
+
|
| 203 |
+
char_ocr:是否进行单字符检测识别,不检测文本行,只检测图像上的字符,文本行顺序可能会出错;布尔类型;默认值:False
|
| 204 |
+
|
| 205 |
+
det_mode:文字内容排版样式,目前有三种可选:auto(自动识别)、sp(竖向排版)、hp(横向排版);字符串类型,默认值:auto
|
| 206 |
+
|
| 207 |
+
image_size:识别前图像尺寸调整,图像越小识别速度越快,0为不调整,设置指定值将按照设置对图像最长边进行等比例调整;整数类型,默认值:0
|
| 208 |
+
|
| 209 |
+
return_position:是否返回文本行坐标信息和字符坐标信息;布尔类型,默认值:False
|
| 210 |
+
|
| 211 |
+
return_choices:是否返回每个字符的其它候选字;布尔类型,默认值:False
|
| 212 |
+
|
| 213 |
+
version:指定识别算法版本;字符串类型,可选:default(v1标准版本)、beta(古籍语序优化版本)、v2(最新版本),默认值:default
|
| 214 |
+
|
| 215 |
+
det_layout(v2):是否开启版面识别(对图像上的内容进行判断是否是正文、页眉页脚/版心等),对分栏式、多栏式文档识别效果较好;布尔类型(开启True、关闭False),默认值:False
|
| 216 |
+
|
| 217 |
+
only_plain_text(v2):是否只识别返回正文内容,仅当版面识别开启时生效,不识别页眉/页脚/版心等;布尔类型(开启True、关闭False),默认值:False
|
| 218 |
+
|
| 219 |
+
return_layout(v2):是否返回版面信息,仅当版面识别开启时生效;布尔类型(开启True、关闭False),默认值:False
|
| 220 |
+
|
| 221 |
+
auto_insert_space(v2):按照字符间距自动插入空格;布尔类型(开启True、关闭False),默认值:False
|
| 222 |
+
|
| 223 |
+
hp_line_words_angel(v2):指定横排句子文字排序方向;字符串类型(从左到右left2right、从右到左right2left),默认值:left2right
|
| 224 |
+
|
| 225 |
+
sp_line_words_angel(v2):指定竖排句子文字排序方向;字符串类型(从上到下top2bottom、从下到上bottom2top),默认值:top2bottom
|
| 226 |
+
|
| 227 |
+
请求方式:
|
| 228 |
+
|
| 229 |
+
POST请求,请求体可以为Form Data或JSON两种方式均可接受
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
duckdb + ducklake + readest + typst see huggingface_echodict\typst_hlm\ocr\readme.txt
|
| 235 |
+
|
| 236 |
+
https://aistudio.baidu.com/projectdetail/4438534?channelType=0&channel=0 真实 ocr 项目经验
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
https://huggingface.co/datasets/ByteDance/AncientDoc 字节的数据集
|
| 240 |
+
|
| 241 |
+

|
| 242 |
+
|
| 243 |
+
https://aistudio.baidu.com/datasetdetail/165369 真可以下载的 **古籍数据集**
|
| 244 |
+
|
| 245 |
+
https://huggingface.co/datasets/Teklia/CASIA-HWDB2-line
|
| 246 |
+
|
| 247 |
+
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
|