【问题标题】:Python Wand Eating all available Disk Space on Mac when converting PDFs using OCR使用 OCR 转换 PDF 时,Python Wand 吃掉 Mac 上的所有可用磁盘空间
【发布时间】:2017-07-27 03:57:48
【问题描述】:

我相信这是我的第一个 StackOverflow 问题,所以请善待。

我正在对每个 50-200 页不等的 PDF 存储库(总共约 1GB)进行 OCR,发现突然间我的 Macbook Pro 上所有可用的 100GB 剩余硬盘空间都消失了。根据之前的帖子,ImageMagick 似乎是罪魁祸首,如here 所示。

我发现这些文件被称为“magick-*”并存储在/private/var/tmp 中。它仅针对 23 个 PDF 创建了 3576 个文件,总计 181GB。

在不再需要这些文件后,如何在代码中立即删除它们?预先感谢您提出解决此问题的任何建议。

代码如下:

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

【问题讨论】:

    标签: python pdf imagemagick ocr wand


    【解决方案1】:

    解决这个问题的一种巧妙方法是在主循环中添加一个 os.remove() 语句以在创建后删除 tmp 文件。

    tempdir = '/private/var/tmp/'
    files = os.listdir(tempdir)
        for file in files:
            if "magick" in file:
                os.remove(os.path.join(tempdir,file))
    

    【讨论】:

      【解决方案2】:

      Image 应该用作上下文管理器,因为 Wand 确定释放资源的时间,包括临时文件、内存缓冲区等。 with block help Wand 知道何时仍需要这些 Image 对象以及何时不需要它们的边界。

      另请参阅official docs

      【讨论】:

      • Imagemagick 不应将其任何文件留在 /tmp 中,除非命令在处理过程中意外失败,例如 /tmp 中空间不足或内存不足。如果命令完成,那么 Imagemagick 将/应该自动删除这些文件,除非它没有正确的权限。检查您的资源限制。抱歉,我对 Python Wand 本身知之甚少。
      • @fmw42 当然,Wand 也可以处理。如果 Python 进程由于运行时错误而终止或正常退出,Wand 会处理它所做的所有资源。但是,如果 Python 进程运行时间较长,则这些资源要等到整个程序结束后才能被释放。使用 Wand 图像作为上下文管理器有助于确定何时可以在整个程序结束之前处理资源。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-31
      • 2020-09-05
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 2014-08-04
      • 2012-11-15
      相关资源
      最近更新 更多