これは私の最初のStackOverflowに関する質問です。Python Wand OCRを使用してPDFを変換する際に、Mac上で使用可能なすべてのディスクスペースを使用
私は50~200ページの範囲のPDFリポジトリ(合計1GBまで)をOCRしていて、Macbook Proの残りの100GBのハードドライブスペースが突然なくなったことがわかりました。以前の投稿に基づいて、ImageMagickはhereのような原因であるようだ。
これらのファイルは「magick- *」と呼ばれ、/ private/var/tmpに格納されています。たったの23のPDFのために、それは1876ギガバイト合計3576のファイルを作成しました。
これらのファイルは、コード内で直ちに削除するにはどうすればできますか?この問題を解決するための提案をありがとうございます。
import io, os
import json
import unicodedata
from PIL import Image as PI
import pyocr
import pyocr.builders
from wand.image import Image
from tqdm import tqdm
# Where you want to save the PDFs
destination_folder = 'contract_data/Contracts_Backlog/'
pdfs = [unicodedata.normalize('NFKC',f.decode('utf8')) for f in os.listdir(destination_folder) if f.lower().endswith('.pdf')]
txt_files = [unicodedata.normalize('NFKC',f.decode('utf8')) for f in os.listdir(destination_folder) if f.lower().endswith('.txt')]
### Perform OCR on PDFs
def ocr_pdf_to_text(filename):
tool = pyocr.get_available_tools()[0]
lang = 'spa'
req_image = []
final_text = []
image_pdf = Image(filename=filename, resolution=300)
image_jpeg = image_pdf.convert('jpeg')
for img in image_jpeg.sequence:
img_page = Image(image=img)
req_image.append(img_page.make_blob('jpeg'))
for img in req_image:
txt = tool.image_to_string(
PI.open(io.BytesIO(img)),
lang=lang,
builder=pyocr.builders.TextBuilder()
)
final_text.append(txt)
return final_text
for filename in tqdm(pdfs):
txt_file = filename[:-3] +'txt'
txt_filename = destination_folder + txt_file
if not txt_file in txt_files:
print 'Converting ' + filename
try:
ocr_txt = ocr_pdf_to_text(destination_folder + filename)
with open(txt_filename,'w') as f:
for i in range(len(ocr_txt)):
f.write(json.dumps({i:ocr_txt[i].encode('utf8')}))
f.write('\n')
f.close()
except:
print "Could not OCR " + filename
Imagemagickは、/ tmp内の領域が不足しているか、または十分なメモリが足りないなど、処理が途中で予期せず失敗した場合を除き、/ tmpにファイルを残すべきではありません。コマンドが終了すると、Imagemagickは適切な特権を持っていない限り、これらのファイルを自動的に削除します。リソースの制限を確認してください。申し訳ありませんが、Python Wand自体についてはほとんど分かりません。 – fmw42
@ fmw42もちろん、ワンドもそれを処理します。 Pythonプロセスが実行時エラーにより終了するか、通常は終了します。Wandは、作成したすべてのリソースを破棄します。しかし、Pythonプロセスが長く実行されると、プログラム全体が終了するまでこれらのリソースを処分することはできません。コンテキスト・マネージャーとしてワンド・イメージを使用すると、プログラム全体が終了する前にリソースがいつ廃棄されるかを判断するのに役立ちます。 – minhee