def formatContent(self, line, album, currDir, pic): albumDescription = album.getDescription().strip() # TODO: this can be done better if pic.getOriginal() != '': line = line.replace('@album-description@', '') line = line.replace('@web-pic@', self.formatWebPic(pic)) line = line.replace('@comment@', pic.getComment()) elif albumDescription != '': line = line.replace('@album-description@', albumDescription) line = line.replace('@web-pic@', '') line = line.replace('@comment@', '') else: if album.getNumPics() > 0: firstPic = album.getPics()[0].getFileName() pic = Pic(self.start_response,'%s%s%s' % (currDir, os.sep, firstPic)) else: pic = Pic(self.start_response,'') line = line.replace('@album-description@', '') line = line.replace('@web-pic@', self.formatWebPic(pic)) line = line.replace('@comment@', pic.getComment()) return line
def test_pickle_Pic_object(self): # make sure pickling and unpickling is working. from Pic import Pic # Pic object needs a "start_response" object. We'll fake it. import wsgiref.simple_server this_handler = wsgiref.simple_server.ServerHandler(sys.stdin,sys.stdout,sys.stderr, os.environ) pic_path = os.path.join(os.pardir,'test_album','boys','1370366193_1ace76e049_b_d.jpg') # Try to pickle this_Pic = Pic(this_handler.start_response, pic_path) self.assertTrue('1370366193_1ace76e049_b_d.jpg' in this_Pic.getFileName()) # Now unpickle new_Pic = Pic.loadPickledVersion(this_handler.start_response,pic_path) self.assertTrue('1370366193_1ace76e049_b_d.jpg' in new_Pic.getFileName()) # clean up our pickly mess os.remove(this_Pic.getPicklePath(pic_path))
def test_filenotfound_error(self): # this file was causing pix2 to throw a FileNotFoundError from Pic import Pic # Pic object needs a "start_response" object. We'll fake it. import wsgiref.simple_server this_handler = wsgiref.simple_server.ServerHandler(sys.stdin, sys.stdout, sys.stderr, os.environ) pic_path = os.path.join(os.pardir, "test_album", "other", "ice_is_food.psd") # Try to convert picture and make sure it's a JPEG (JFIF in the header) this_Pic = Pic(this_handler.start_response, pic_path) pic_iterator = this_Pic.spitOutResizedImage("thumb") first_part_of_file = str(list(pic_iterator)[0]) pic_iterator.close() self.assertTrue("JFIF" in first_part_of_file)
def test_div_zero_error(self): # this file was causing PIL to throw ZeroDivisionError from Pic import Pic # Pic object needs a "start_response" object. We'll fake it. import wsgiref.simple_server this_handler = wsgiref.simple_server.ServerHandler(sys.stdin, sys.stdout, sys.stderr, os.environ) pic_path = os.path.join(os.pardir, "test_album", "girls", "IMG_20130512_103812.jpg") # Try to convert picture and make sure it's a JPEG (JFIF in the header) this_Pic = Pic(this_handler.start_response, pic_path) pic_iterator = this_Pic.spitOutResizedImage("thumb") first_part_of_file = str(list(pic_iterator)[0]) pic_iterator.close() self.assertTrue("JFIF" in first_part_of_file)
def test_Pic_object_info(self): # there was a problem using PIL to read ray_img882.tif from Pic import Pic # Pic object needs a "start_response" object. We'll fake it. import wsgiref.simple_server this_handler = wsgiref.simple_server.ServerHandler(sys.stdin, sys.stdout, sys.stderr, os.environ) pic_path = os.path.join(os.pardir, "test_album", "boys", "ray_img882.tif") # Try to convert picture and make sure it's a JPEG (JFIF in the header) this_Pic = Pic(this_handler.start_response, pic_path) pic_iterator = this_Pic.spitOutResizedImage("thumb") first_part_of_file = str(list(pic_iterator)[0]) pic_iterator.close() self.assertTrue("JFIF" in first_part_of_file)
def test_mac_aliases(self): # Mac aliases cause problems. Designed behavior is to detect the problem # and ignore the alias, not attempt to recognize aliases. from Pic import Pic # Pic object needs a "start_response" object. We'll fake it. import wsgiref.simple_server this_handler = wsgiref.simple_server.ServerHandler(sys.stdin, sys.stdout, sys.stderr, os.environ) pic_path = os.path.join(os.pardir, "test_album", "girls", "DSC01202.JPG") # Try to convert picture and make sure it's a JPEG (JFIF in the header) this_Pic = Pic(this_handler.start_response, pic_path) pic_iterator = this_Pic.spitOutResizedImage("thumb") first_part_of_file = str(list(pic_iterator)[0]) pic_iterator.close()
def __init__(self, im, shape, faces): self.pic = Pic(im, faces) scene.background = [1, 1, 1] self.scene = Scene(scene, self.pic) scene.bind('keydown', self.keyInput) Object(self.pic, self.scene, shape) self.scene.background.visible = false
def __init__(self, albumDir, start_response, recurse = 1): self.albumDir = albumDir self.albums = [] self.pics = [] if recurse < 1: return recurse -= 1 for entry in sorted(os.listdir(albumDir),reverse=True): if entry[0] in ['.',"`","'"] or entry in ['info.txt','captions.txt']: # skip files that start with a dot or "grave accent" or single quote, # which was used to ignore photos in yappa. Also skip the yappa-style # info.txt or captions.txt files. continue #pathAndEntry = '%s%s%s' % (albumDir, os.sep, entry) pathAndEntry = os.path.join(albumDir,entry) if os.path.isdir(pathAndEntry): self.albums.append(Album(pathAndEntry, start_response, recurse=recurse)) elif os.path.isfile(pathAndEntry): # for performance, try to load pickled version try: self.pics.append(Pic.loadPickledVersion(start_response,pathAndEntry)) except (IOError, EOFError, FileNotFoundError, ValueError): # load from scratch try: #remove faulty pickled version self.pics.append(Pic(start_response,pathAndEntry)) except: print('file in picture folder is not a picture: %s\n reason: %s' % (pathAndEntry,sys.exc_info()[0]), file=sys.stderr)
def test_os_error(self): # this file was causing pix2 to throw a OSError from Pic import Pic # Pic object needs a "start_response" object. We'll fake it. import wsgiref.simple_server this_handler = wsgiref.simple_server.ServerHandler(sys.stdin, sys.stdout, sys.stderr, os.environ) pic_path = os.path.join( os.pardir, "test_album", "other", "Stella, on back - Q.A.C. Speech Day - June 14, 1975 L. to R. Two male teachers, Mrs. Elhhetih, Mrs. Lacey, Mde De Nehludoff, Y.T., Mrs. Bisade, Mrs. Abdullehi - principal - and Mrs. Abbe Kyari - wife of the then Governor of Keduna State.tif", ) # Try to convert picture and make sure it's a JPEG (JFIF in the header) this_Pic = Pic(this_handler.start_response, pic_path) pic_iterator = this_Pic.spitOutResizedImage("thumb") first_part_of_file = str(list(pic_iterator)[0]) pic_iterator.close() self.assertTrue("JFIF" in first_part_of_file)
def test_pickle_path(self): # some pickle paths were too long for the filesystem from Pic import Pic import Setup long_file_name = os.path.abspath( os.path.join( os.pardir, "test_album", "other", "Stella, on back - Q.A.C. Speech Day - June 14, 1975 L. to R. Two male teachers, Mrs. Elhhetih, Mrs. Lacey, Mde De Nehludoff, Y.T., Mrs. Bisade, Mrs. Abdullehi - principal - and Mrs. Abbe Kyari - wife of the then Governor of Keduna State.tif", ) ) short_file_name = Pic.getPicklePath(long_file_name) self.assertTrue(len(short_file_name) < Setup.f_namemax)
def getBreadCrumb(self): linkPath = self.getLinkPathRaw() breadCrumb = [] runningCrumb = '' while linkPath != '' and linkPath != '.': [head,tail] = os.path.split(linkPath) runningCrumb = head breadCrumb.append( '<a href="?album=%s">%s</a>' % ( \ Pic.makePathUrlFriendly(linkPath), \ escape(tail,True).encode('ascii','xmlcharrefreplace').decode('ascii') \ )) linkPath = head return breadCrumb
def load_pics(): current_dir = os.getcwd() pics = current_dir + "/pics" pic_list = [] for filename in os.listdir(pics): img = cv2.imread(pics + "/" + filename, cv2.IMREAD_GRAYSCALE) pic_list.append(Pic(filename, img)) PICTURE_SCORES.append(KeyValuePair(filename, 0)) global NUM_OF_PICS NUM_OF_PICS = len(pic_list) return pic_list
def __call__(self, environ, start_response): # this is the function called by the wsgi server # for x in environ: # if 'css' in str(environ[x]): # print('{}: {}'.format(x,environ[x])) try: iForm = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ.copy()) album = self._getArg(iForm, 'album') pic = self._getArg(iForm, 'pic') control = self._getArg(iForm, 'control') adminAction = self._getArg(iForm, 'admin') random_pic = self._getArg(iForm, 'random') pict_creator = self._getArg(iForm, 'pict_creator') download = self._getArg(iForm, 'download') # assume that the application is invoked with either a blank path "/" # or something that starts with "index." (html, cgi, etc...) if not environ['PATH_INFO'][:7] == '/index.' and not environ['PATH_INFO'] == '/': if not Setup.serveStaticFiles: # throw a 404 page start_response('404 NOT FOUND', [('Content-Type', 'text/plain')]) return [b'Not Configured to Serve Static Pages'] # Assume this is a static file. This should really be handled by # the web server, but we'll handle it here gracefully for poorly # configured servers or for testing with wsgiref print('Warning! Static file was served: {}'.format(os.path.normpath(environ['PATH_INFO'])),file=sys.stderr) # get path to file requested = os.path.join( os.path.normpath(Setup.pathToStatic), os.path.normpath(os.path.relpath(environ['PATH_INFO'],Setup.webPathToStatic)) ) print('File served: {}'.format(requested),file=sys.stderr) if not os.path.isfile(requested): # throw a 404 page start_response('404 NOT FOUND', [('Content-Type', 'text/plain')]) return [b'Not Found'] # get file extension _,ext = posixpath.splitext(environ['PATH_INFO']) if ext in self.extensions_map: mime_txt = self.extensions_map[ext] elif ext.lower() in self.extensions_map: mime_txt = self.extensions_map[ext] else: mime_txt = self.extensions_map[''] writer = start_response('200 OK', [('Content-Type',mime_txt)]) f = open(requested,'rb') return wsgiref.util.FileWrapper(f, blksize=131072) if pict_creator != '': # make a picture pict_path = self._getArg(iForm, 'pict_path') pic_obj = Pic(start_response, os.path.join(Setup.albumLoc, pict_path)) return pic_obj.spitOutResizedImage(pict_creator) elif download == 'jpeg': # download the picture, converted to jpeg if necessary pict_path = self._getArg(iForm, 'pict_path') pic_obj = Pic(start_response,os.path.join(Setup.albumLoc, pict_path)) return pic_obj.downloadImage(download) elif random_pic != '': # send a single randomized photo # Using a recursion limit of 10 just for safety. Increase if necessary. if album == '': currDir = Setup.albumLoc else: currDir = os.path.join(Setup.albumLoc,album) album_obj = Album(currDir,start_response,recurse=10) # each album is recursively filled, and each contains pictures def get_albums(album): album_list = [album] for x in album.albums: album_list.extend(get_albums(x)) return album_list all_albums = get_albums(album_obj) all_pics = [] for x in all_albums: all_pics.extend(x.pics) if len(all_pics) < 1: # empty album start_response('404 NOT FOUND', [('Content-Type', 'text/plain')]) return [b'Empty Album'] for x in range(1000000): # limit to a million tries so there is no infinite loop random_pic = random.choice(all_pics) if random_pic.isPic: break [ pic_fname_safe, pic_relpic_safe, pic_name_safe, pic_relweb_safe, pic_width, pic_height ] = random_pic.getResizedLink('web') start_response('200 OK', [('Content-Type','text/html')]) output = '<img alt="{}" title="{}" src="{}" width="{}" height="{}" />'.format( pic_fname_safe, pic_name_safe, pic_relweb_safe,pic_width, pic_height ) return [output.encode('utf-8')] else: # make the web page #print('Content-type: text/html; charset=utf-8\n') #print '<!-- path : %s -->' % os.path.abspath(os.curdir) #print '<!-- argv[0] : %s -->' % os.path.dirname(sys.argv[0]) presenter = Presenter(album, pic, control, start_response) return [presenter.content] except: print(''' <pre><h1>pix broke, you get to keep both pieces</h1> Traceback has been logged.</pre> ''',file=sys.stderr) traceback.print_exc(file=sys.stderr) return []
def getLinkPath(self): path = self.getLinkPathRaw() # make it safe for url path = Pic.makePathUrlFriendly(path,use_quote_plus=True) return path