File size: 5,181 Bytes
8d55ddb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# vim:fileencoding=utf-8:ts=2:sw=2:expandtab
import re
import os
import os.path
import glob
import mimetypes
import subprocess

from ..Base import S3
from . import Job, S3BackedFile


class S3BackedDocument(S3BackedFile):

  def __init__(self, *, OutputKey, **kw):
    super().__init__(**kw)
    self.OutputKey = OutputKey

  def GenerateImagesFromPDF(self, *, PDFPath):
    # Generate images from pages of PDF and save images to S3
    PageNamePrefix = PDFPath.replace('.pdf', '')
    PageNameFormat = PageNamePrefix + '-%d.png'

    # Call ghostscript to produce the images
    try:
      out = subprocess.check_output((self.Binaries.Ghostscript, '-sDEVICE=png256', '-dNOPAUSE', '-r300', '-o', PageNameFormat, PDFPath), stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as exc:
      raise Exception("ERROR: {0}".format(exc.output))

    # search for all files with the relevant prefix and upload them to S3
    images = glob.glob(PageNamePrefix + '-*.png')
    regex = re.compile(PageNamePrefix + '-(\d+)\.png')
    images.sort(key=lambda im: int(regex.sub('\g<1>', im)))
    thumbs = []

    # Loop over the images of pages to create thumbnails from them
    for im in images:

      # Prepare filenames
      regular_thumnail_file = im.replace('.png', '.1200x1200.png')
      small_thumbnail_file = im.replace('.png', '.160x160.png')
      page_num = int(regex.sub('\g<1>', im))

      # Now, upload the 2 thumbnails to S3
      for fname in (regular_thumnail_file, small_thumbnail_file):
        # Get the size specification from the filename.
        # EX: if fname == thumb-1.1200x1200.png, fsize = 1200x1200
        fsize = fname.split('.')[-2]
        # Create regular version
        try:
          cmd = (
            self.Binaries.Convert,
            im,
            '-resize', fsize,
            fname,
            )
          subprocess.call(cmd, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as exc:
          raise Exception("ERROR: {0}".format(exc.output))

        # We'll upload using a stream
        with open(fname, 'rb') as fp:
          o_key = os.path.join(self.OutputKeyPrefix, fname.replace(PageNamePrefix, 'thumb'))
          o_mime = mimetypes.guess_type(fname)[0] or "application/octet-stream"
          S3.PutObject(
            session=self.Config.Session,
            bucket=self.Config.S3_OutputBucket,
            key=o_key,
            content=fp,
            type_=o_mime,
            )

          # Log message saying that images has uploaded
          self.Logger.debug("Finished Upload of {0} to S3".format(o_key))

          # Inspect the path so that we get image props
          props = self.InspectImage(fname)
          props['Key'] = o_key
          props['PageNumber'] = page_num
          thumbs.append(props)

          # Mark for cleanup
          self.MarkFilePathForCleanup(fname)

      # Make sure the main file gets deleted after we exit
      self.MarkFilePathForCleanup(im)

    # Return all the keys that have been uploaded to S3
    return thumbs

  def ConvertToPDF(self):
    # Prepare some variables we need for this job
    FilePath = self.LocalFilePath
    OutputFilePath = self.GetLocalFilePathFromS3Key(Key=self.OutputKey, KeyPrefix=self.OutputKeyPrefix)
    self.Logger.debug("Will convert {0} to {1}".format(self.InputKey, self.OutputKey))

    # Use pyuno to speak to the headless openoffice server
    try:
      out = subprocess.check_output((self.Binaries.Python2, self.Binaries.DocumentConverter, FilePath, OutputFilePath), stderr=subprocess.STDOUT)
      self.Logger.debug("Done with conversion")
    except subprocess.CalledProcessError as exc:
      raise Exception("ERROR: {0}".format(exc.output))

    # After conversion upload the file to S3
    o_key = os.path.join(self.OutputKeyPrefix, self.OutputKey)
    o_mime = mimetypes.guess_type(self.OutputKey)[0] or "application/octet-stream"
    with open(OutputFilePath, 'rb') as fp:
      S3.PutObject(
        session=self.Config.Session,
        bucket=self.Config.S3_OutputBucket,
        key=o_key,
        content=fp,
        type_=o_mime,
        )

    # Save output key
    self.Output['Outputs'].append({'Key': o_key, 'Type': 'PDF'})
    # Log a message
    self.Logger.debug("Finished Upload of {0} to S3".format(self.OutputKey))

    # Generate images from all pages of PDF
    o_thumbs = self.GenerateImagesFromPDF(PDFPath=OutputFilePath)
    self.Output['Outputs'].extend(o_thumbs)
    # Add number of thumbnails to Input
    # NOTE: we create 2 thumbnails per input, hence the division by 2
    self.Output['Input'] = {'NumPages': (len(o_thumbs) / 2)}

    # Mark the new file for deletion
    self.MarkFilePathForCleanup(OutputFilePath)

  def Run(self):
    self.ConvertToPDF()


@Job
def ConvertToPDF(*, InputKey, OutputKeyPrefix, Config, Logger, OutputKey='output.pdf'):
  Logger.debug("ResizeImage job for {0} started".format(InputKey))
  # Prepare context in which we'll run
  ctxt = S3BackedDocument(
    InputKey=InputKey,
    OutputKeyPrefix=OutputKeyPrefix,
    OutputKey=OutputKey,
    Config=Config,
    Logger=Logger,
    )
  # Start the processing
  with ctxt as doc:
    doc.Run()