1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

YomiToku(日本語OCR)でsearchable_pdf(透明テキスト)を使う

1
Posted at

前回の記事では プリザンターでYomiToku を使いました。
今回はさらに、YomiTokuのsearchable_pdfを使い、画像から選択可能なテキスト付きPDFを生成する方法を試してみます!
スキャンPDFのように見えるのに、文字が正確に選択できて検索もできる便利なPDFが作れます。

結果

  • OCR の位置情報が正確なので、コピーしてもズレないPDFが作れます

  • この範囲の文字列は使用者は、一年六箇月以上継続勤務した労働者に対しては、という風になっています
    image.png

  • 検索もできるようになる
    image.png

環境

Windows11
GPU NVIDIA GeForce RTX 3060 VRAM 12GB
(推奨GPU >VRAM8G)
YomiToku ver0.10.1
Python ver3.12.10
(3.10~3.12が推奨のよう)

yomitokuをfastapiで立てる

前回と同様にFastAPIを使います。
以下のコードで写真を透過テキスト付のpdfにできます。

# 起動して
uvicorn searchable:app --reload
# 試す
http://127.0.0.1:8000/docs#/default/download_zip_searchable__post
searchable.py
import io
import uuid
import zipfile
from fastapi import FastAPI, HTTPException, UploadFile, File
from fastapi.responses import StreamingResponse
from starlette.concurrency import run_in_threadpool
import shutil
import os
from yomitoku import DocumentAnalyzer
from yomitoku.data.functions import load_pdf, load_image
from fastapi.middleware.cors import CORSMiddleware
# これを入れる
from PIL import Image
from yomitoku.utils.searchable_pdf import create_searchable_pdf

app = FastAPI()
# cors設定
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost"],
    allow_credentials=True,
    allow_methods=["*"], 
    allow_headers=["*"],
)

# gpuかcpuかでdeviceを変更する
analyzer = DocumentAnalyzer(visualize=True, device="cuda")

UPLOAD_DIR = "./uploads"
OUTPUT_DIR = "./outputs"
os.makedirs(UPLOAD_DIR, exist_ok=True)
os.makedirs(OUTPUT_DIR, exist_ok=True)

    
async def run_analyze(file: UploadFile):
    output_files = []
    file_id = str(uuid.uuid4())
    ext = os.path.splitext(file.filename)[1].lower()
    safe_input_name = f"{file_id}{ext}"
    file_path = os.path.join(UPLOAD_DIR, safe_input_name)

    with open(file_path, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)
        output_files.extend([{"path": file_path, 
                             "zip_name": file.filename }])

    # ファイル拡張子で分岐
    if ext == ".pdf":
        imgs = load_pdf(file_path)
    elif ext in [".jpg", ".jpeg", ".png"]:
        imgs = load_image(file_path)
    else:
        raise HTTPException(status_code=400, detail={
            "error": "対応していないファイル形式です",
            "files": output_files
        })

    # 一ページ分づつ処理
    for i, img in enumerate(imgs):
        # 非同期環境で同期関数を安全に実行
        results, ocr_vis, layout_vis = await run_in_threadpool(analyzer, img)

        # searchable_pdfの処理
        img_pil = Image.fromarray(img)
        base = f"{file_id}_{i}"
        pdf_path = os.path.join(OUTPUT_DIR, f"{base}.pdf")
        create_searchable_pdf([img_pil], [results], pdf_path)

        # ファイルをまとめる
        output_files.extend([
            { "path": pdf_path, "zip_name": f"{file.filename}_{i}.pdf" },
        ])

    return {
        "markdown": "",
        "files": output_files
    }

async def zip_download(files: list):
    # メモリ上にzipをつくる
    zip_buffer = io.BytesIO()

    with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
        for file in files:
            # zipへ追加
            zip_file.write(file["path"], arcname=file["zip_name"])
            
    # 読み取り位置を先頭に戻す
    zip_buffer.seek(0)

    # StreamingResponseで返す
    return StreamingResponse(
        zip_buffer,
        media_type="application/zip",
        headers={
            "Content-Disposition": "attachment; filename=files.zip"
        }
    )

@app.post("/searchable/")
async def download_zip(file: UploadFile = File(...)):
    result = None
    try:
        result = await run_analyze(file)
        return await zip_download(result["files"])
    
    except HTTPException as e:
        # FastAPI の HTTPException はそのまま raise
        result = e.detail
        raise e
    
    except Exception as e:
        # その他の例外は500エラーに変換
        raise HTTPException(status_code=500, detail=str(e))
    
    finally:
        # ファイルの削除
        for file in result["files"]:
            try:
                path = file["path"]
                if os.path.exists(path):
                    os.remove(path)
            except Exception as e:
                print(f"削除失敗: {path} ({e})")

searchable_pdf

  • from yomitoku.utils.searchable_pdf import create_searchable_pdfこれを入れて使えるようにします
  • create_searchable_pdf この部分を参照しています

透過テキスト

スキャナーとかでPDFにしてもこういった透過テキスト入りというのはできますけど、文字の位置とテキストの入り方が合っていて使いやすいです。
検索したり、文章をコピーする時も見た目とズレないので良い感じです!

参照

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?