-
Notifications
You must be signed in to change notification settings - Fork 0
/
imgprocessor.py
executable file
·159 lines (132 loc) · 6.88 KB
/
imgprocessor.py
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
150
151
152
153
154
155
156
157
158
159
import os
import time
import sys
import logging.handlers
import logging
from PIL import Image
from configparser import ConfigParser
from configparser import ExtendedInterpolation
from pkg_resources import resource_stream, Requirement
class imgprocessor(object):
'''the class is used for processing of the image dynamically and accepts the name of the original image
the screensize and the bandwidth. This provides path to the file of image which can be loaded by consuming app
Based on these values, the program will do simple logic of sending the most optimal size image and uses
the optimal PIL-SIMD based Image generation which is faster than most other tools including Imagemagica by approx 10-15times
'''
'''All configured bandwidth, screens will be initialized with a weightage'''
bandwidth = dict()
screens = dict()
scales = dict()
'''Default screensize, band will be set once initialized'''
defaultscreen = {}
defaultband = {}
'''The root path for all images'''
imagepath = {}
sumup=0
'''loginfo level from config'''
loginfo = ""
'''Initialize the logger to log information'''
mylogger = logging.getLogger('Imagehandler')
handler = logging.handlers.RotatingFileHandler('imghandler.log','a',maxBytes=10000000,backupCount=5)
mylogger.addHandler(handler)
mylogger.setLevel("ERROR")
def __init__(self):
self.mylogger.info(msg="Starttime is {}".format(time.time()))
config = ConfigParser()
config._interpolation = ExtendedInterpolation()
'''Resource based loading option.'''
#resource = resource_stream(Requirement.parse('imgprocessor==0.01'),'config.cfg').read()
#resource = resource.decode('UTF-8','replace')
#print(resource)
#config.read_string(resource)
'''get executionpath'''
dirname = os.path.dirname(os.path.realpath(__file__))
config.read(os.path.join (dirname ,"config.cfg"))
loglevel = config.get(section="config", option="loglevel")
self.mylogger.setLevel(level=loglevel)
self.mylogger.info(msg="Dirname is {}".format(dirname))
#print(config.keys())
#print(config.sections())
self.mylogger.info(msg="Dirname is in {}".format(os.path.join (dirname ,"config.cfg")))
'''Initialize all the configurations like screensizes, bandconfig etc'''
screenconfig = config.get(section="config",option="screensize")
bandconfig = config.get(section="config",option="band")
scaleconfig = config.get(section="config", option="scale")
self.defaultscreen = config.get(section="config",option="defaultscreen")
self.defaultband = config.get(section="config",option="defaultbandwidth")
self.imagepath = config.get(section="config",option="path")
#self.mylogger.setLevel(config.get(section="config",option="loglevel"))
self.screens = dict(screenmix.split(",") for screenmix in screenconfig.split(";"))
self.bandwidth = dict(band.split(",") for band in bandconfig.split(";"))
self.scales = dict(scale.split(",") for scale in scaleconfig.split(";"))
self.mylogger.info(msg="Done initialization")
def generate(self,filename,size="1080",bandwidth="*",returnFullpath=False):
try:
self.mylogger.info('Generating file {}'.format(filename))
'''Expected name of the file to be generated'''
scale = self._getoptimizesizebasedonsizebandwidth(size, bandwidth)
savefilename = filename.split(".")[0] + "_" + str(self.sumup) + "." + filename.split(".")[1]
savefilename = os.path.join(self.imagepath, savefilename )
'''if filealready exist return file name'''
if os.path.isfile(savefilename):
return savefilename
'''Open the file if it isnt there and resize, send back the path'''
'''Check if input fullpath leads to file, if not throw exception'''
fullpath = os.path.join(self.imagepath, filename)
if not os.path.isfile(fullpath):
raise NameError('File not found')
#print(savefilename)
#print(fullpath)
'''if fullpath is file, then open the same'''
img = Image.open(fullpath, 'r')
self.mylogger.info("Size of image is {}".format(img.size))
img.thumbnail((int(img.size[0]*float(scale)) , int(img.size[0]*float(scale))),Image.BICUBIC)
img.save(savefilename)
self.mylogger.info("Saved file {} for {}".format(filename,savefilename))
if returnFullpath:
return savefilename
else:
return os.path.join(self.imagepath,savefilename)
self.mylogger.info(msg="returned for file {}".format(filename))
except NameError as filenotfound:
raise NameError('File {} doesnt exist'.format(filename))
self.mylogger.exception("Exception occurred in image generation for {}".format(filename))
except Exception as genEx:
self.mylogger.exception("Exception occurred in image generation for {}".format(filename))
finally:
self.mylogger.info("Completed")
'''We will set the optimized value for image generation based on size & bandwidth'''
def _getoptimizesizebasedonsizebandwidth(self,size,band):
'''If the sizeinfo is not configured, send the highest sizeinfo available'''
self.mylogger.info(msg='Size & bandwidth is {} & {}'.format(size,band))
try:
size = self.screens[str(size)]
#print(size)
except Exception:
size = max({val:key for key, val in self.screens.items()})
#self.mylogger.info('Size was not found and defaulting to size {}'.format(size))
'''if input value isnt configured, send the highest bandwidth configured'''
try:
band = self.bandwidth[band.lower()]
#print(band)
except Exception:
band = max({val:key for key, val in self.bandwidth.items()})
#self.mylogger.info('Bandwidth was not found and defaulting to size {}'.format(bandwidth))
self.sumup = float(size) + float(band)
self.mylogger.info('Sumup value is {}'.format(self.sumup))
#print(self.sumup)
if float(self.sumup) <= 4:
self.sumup = 4
return self.scales.get("4")
elif float(self.sumup) <= 7:
'''I am sure screen is of medium size and bandwidth is around 2g'''
self.sumup = 7
return self.scales.get("7")
elif float(self.sumup) <= 10:
'''I know this is of medium resolution and high bandwidth or high res with low bandwidth'''
self.sumup = 10
return self.scales.get("10")
else:
'''I am sure if the value is > 4, its either 3g, 4g etc with higher screensize'''
self.sumup = 11
return self.scales.get("*")