2017-07-27 31 views
2

我相信這是我的第一個StackOverflow問題,所以請好。Python Wand在使用OCR轉換PDF時使用Mac上的所有可用磁盤空間

我正在對每個50-200頁的PDF(總共約1GB)進行OCR處理,發現我的Macbook Pro上所有可用的100GB剩餘硬盤空間都已消失。根據以前的帖子,ImageMagick似乎是here所示的罪魁禍首。

我發現這些文件被稱爲'magick- *'並存儲在/ private/var/tmp中。只有23 PDF,它創造了總計181GB的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 

回答

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)) 
0

Image應作爲一個上下文管理器,因爲魔杖確定的時序來配置資源,包括臨時文件,內存緩衝區,等等。 with塊幫助魔杖知道這些Image對象仍然需要時,當他們現在是不必要的邊界。請參閱official docs

+0

Imagemagick不應將任何文件保留在/ tmp中,除非該命令在處理過程中意外失敗,例如/ tmp空間不足或內存不足。如果命令完成,則Imagemagick將自動刪除這些文件,除非它沒有正確的權限。檢查您的資源限制。抱歉,我對Python魔杖本身知之甚少。 – fmw42

+0

@ fmw42當然Wand也可以處理這個問題。如果Python進程由於運行時錯誤而終止,或者正常退出Wand將釋放它所做的所有資源。但是,如果Python進程運行時間很長,則只有在整個程序結束時才能處理這些資源。使用魔杖圖像作爲上下文管理器有助於確定在整個程序結束之前何時可以處理資源。 – minhee

相關問題