def getRandomPhoto(photos): print('Selecting a random photo') photo = choice(photos) p = Photo(photo['imgUrl']) p.retrieve() photo['imageData'] = p.getData() return photo
def scaleImage(filename, filigrane=None): """Common processing for one image : - create a subfolder "scaled" and "thumb" - populate it @param filename: path to the file @param filigrane: None or a Signature instance (see imagizer.photo.Signature) """ rootdir = os.path.dirname(filename) scaledir = os.path.join(rootdir, config.ScaledImages["Suffix"]) thumbdir = os.path.join(rootdir, config.Thumbnails["Suffix"]) fileutils.mkdir(scaledir) fileutils.mkdir(thumbdir) photo = Photo(filename, dontCache=True) param = config.ScaledImages.copy() param.pop("Suffix") param["strThumbFile"] = os.path.join(scaledir, os.path.basename(filename))[:-4] + "--%s.jpg" % config.ScaledImages["Suffix"] photo.saveThumb(**param) param = config.Thumbnails.copy() param.pop("Suffix") param["strThumbFile"] = os.path.join(thumbdir, os.path.basename(filename))[:-4] + "--%s.jpg" % config.Thumbnails["Suffix"] photo.saveThumb(**param) if filigrane is not None: filigrane.substract(photo.pil).save(filename, quality=config.FiligraneQuality, optimize=config.FiligraneOptimize, progressive=config.FiligraneOptimize) try: os.chmod(filename, config.DefaultFileMode) except OSError: logger.warning("in scaleImage: Unable to chmod %s" % filename)
def direction_without_camera(self): photo = Photo(1024, 768, "0", 30) images = photo.use_photos_test_images() for image in images: cmd = "cp photos_test/%s photos/direction.jpg" % image system(cmd) self.move_robot(photo)
def _auto_rotate_thanks_to_exif(self, thumb=True): tgetDir = "thumbs" if not thumb: tgetDir = "preview" tmpFile = join(self.tempdir, "toto.jpg") copy(self.exim1, tmpFile) oldpwd = getcwd() chdir(self.tempdir) photo = Photo(tmpFile) tmpDir = join(self.tempdir, tgetDir) os.mkdir(tmpDir) if not thumb: photo.makeThumbnail(tgetDir) else: photo.makePreview(tgetDir) # for d in walk(self.tempdir): # print d # uncomment to get this picture and check it (I use the handy xv) # copy(photo.thumbPath, '/tmp/thumb.jpg') chdir(oldpwd)
def load_all_photos_by_likes(self, db, cursor, limit=10): sql = ( "SELECT photos.id, photos.fb_id, photos.filename, photos.caption, \ photos.owner_id, photos.state, photos.created_at, photos.approved_at, \ likes_count.count \ FROM photos \ LEFT JOIN (SELECT photo_id, count(*) AS count FROM likes GROUP BY photo_id) AS likes_count \ ON photos.id = likes_count.photo_id \ ORDER BY likes_count.count DESC, \ photos.approved_at DESC LIMIT %d" % limit ) try: cursor.execute(sql) data = cursor.fetchall() for row in data: photo = Photo() photo.load_from_tuple(row) self.photos_list.append(photo) return self.photos_list except Exception, e: raise e
def getWordList(self, event): # word_list is a list of (word, freq) cp = CaptionParser(True) for photo in event['photos']: photo = Photo(photo) cp.insertCaption(photo.getCaption()) return cp.getTopWords(-1, False)
def save_avatar(self, filepath): photo = Photo() photo.filepath = filepath photo.us_id = self.id DBSession.add(photo) DBSession.flush() return photo
def mergeWith(self, event): if type(event) is types.DictType: event = Event(event) event = event.toJSON() photo_list1 = self._event['photos'] photo_list2 = event['photos'] new_photo_list = [] l1 = 0 l2 = 0 merged = 0 while l1 < len(photo_list1) and l2 < len(photo_list2): p1 = Photo(photo_list1[l1]) p2 = Photo(photo_list2[l2]) compare = p1.compare(p2) if compare == 1: new_photo_list.append(photo_list1[l1]) l1 += 1 continue if compare == -1: new_photo_list.append(photo_list2[l2]) l2 += 1 merged += 1 continue # compare == 0 new_photo_list.append(photo_list1[l1]) l1 += 1 l2 += 1 while l1 < len(photo_list1): new_photo_list.append(photo_list1[l1]) l1 += 1 while l2 < len(photo_list2): new_photo_list.append(photo_list2[l2]) l2 += 1 merged += 1 self._event['photos'] = new_photo_list # update actual value self.setActualValue(self._getActualValueByCounting()) # do not change the order of the following code actual_value_1 = self._event['actual_value'] actual_value_2 = event['actual_value'] zscore1 = float(self._event['zscore']) zscore2 = float(event['zscore']) std1 = float(self._event['predicted_std']) std2 = float(event['predicted_std']) new_std = (std1 * actual_value_1 + std2 * actual_value_2) / (actual_value_1 + actual_value_2) new_zscore = (zscore1 * actual_value_1 + zscore2 * actual_value_2) / (actual_value_1 + actual_value_2) self.setZscore(new_zscore) new_mu = actual_value_1 - new_zscore * new_std self.setPredictedValues(new_mu, new_std) return merged
def _getTopWords(self, k, stopword_removal=False): caption_parser = CaptionParser(stopword_removal=stopword_removal) for photo in self._event["photos"]: p = Photo(photo) caption = p.getCaption() if not caption is None: caption_parser.insertCaption(caption) return caption_parser.getTopWords(k)
def direction(self): photo = Photo(260, 260, "180", 30) i = 0 start = True while i < 100: photo.take_photo_with_picamera() self.move_robot(photo) i += 1
def save_photo(self, filepath, main=False): photo = Photo() photo.filepath = filepath photo.product_id = self.id photo.is_main = main DBSession.add(photo) DBSession.flush() return photo
def getCaptionPercentage(self): cap_number = 0 photos = self._event["photos"] for photo in photos: photo = Photo(photo) cap_len = len(photo.getCaption()) if cap_len > 0: cap_number += 1 return cap_number * 1.0 / len(photos)
def _getTopWords(self, k, stopword_removal=False): # get top words by counting the frequecy text_parser = TextParser(stopword_removal=stopword_removal) for photo in self._event['photos']: p = Photo(photo) caption = p.getCaption() if not caption is None: text_parser.insertCaption(caption) return text_parser.getTopWords(k)
def update_img(self, user_list=None, force=False, token_list=token_list): if user_list is None: user_list = self._get_all_user() album = Album() photo = Photo() for user in user_list: album.update(token_list, user, force) photo.update(token_list, user, force) photo.update_data(user) return True
def getElementsByKeyword(self, word): # return a list of elements containg the word res_element = [] for element in self._event[self._element_type]: if self._element_type == 'photos': text = Photo(element).getText() else: text = Tweet(element).getText() if word.lower() in text.lower(): res_element.append(element) return res_element
def getPhotosbyKeyword(self, word): # return a list of photos containg the word res_photo = [] for photo in self._event['photos']: cap = Photo(photo).getCaption() if cap is None: continue cap = cap.lower() if word in cap: res_photo.append(photo) return res_photo
def removeDuplicateElements(self): new_elements = {} for element in self._event[self._element_type]: if self._element_type == 'photos': d = Photo(element) else: d = Tweet(element) key = d.getText() + '|' + d.getUserId() new_elements[key] = d self._event[self._element_type] = [] for key, d in new_elements.items(): self._event[self._element_type].append(d) # need to sort the elements elements or tweets self.sortElements()
def getTopPhotosLocationSimilarity(self, k=10): freq = {} most_freq = 0 k = min(k, len(self._event['photos'])) for photo in self._event['photos']: p = Photo(photo) location_name = p.getLocationName() if location_name == '': continue cur_freq = freq.get(location_name, 0) + 1 freq[location_name] = cur_freq if cur_freq > most_freq: most_freq = cur_freq return most_freq * 1.0 / k
def getAvgCaptionLen(self): cap_number = 0 cap_lens = 0 photos = self._event["photos"] for photo in photos: photo = Photo(photo) cap_len = len(photo.getCaption()) if cap_len > 0: cap_lens += cap_len cap_number += 1 if cap_number == 0: return -1 else: return 1.0 * cap_lens / cap_number
def getAvgCaptionLen(self): # not a good feature cap_number = 0 cap_lens = 0 photos = self._event['photos'] for photo in photos: photo = Photo(photo) cap_len = len(photo.getCaption()) if cap_len > 0: cap_lens += cap_len cap_number += 1 if cap_number == 0: return -1 else: return 1.0 * cap_lens / cap_number
def __init__(self, color): self.drone = Drone('/' + color) self.color = color drone = self.drone self.modes = { "idle": Mode(drone), "follow": FollowGesture(drone), "land": TakeoffLand(drone), "takeoff": TakeoffLand(drone, takeoff=True), "north": Move(drone, 0), "east": Move(drone, 3 * math.pi / 2), "south": Move(drone, math.pi), "west": Move(drone, math.pi / 2), "stop": Move(drone, 0), "forward": Move(drone, 0, relative=True), "duck": Move(drone, 0, -1), "jump": Move(drone, 0, 1), "analyze": Photo(drone) } self.look_modes = { "look": Turn(drone), "right": Turn(drone, -1), "left": Turn(drone, 1) } self.look_direction = 0 self.current_mode_pub = rospy.Publisher("/" + color + "_current_mode", String, queue_size=10) self.look_mode_pub = rospy.Publisher("/" + color + "_look_mode", String, queue_size=10) self.current_mode = self.modes["idle"] self.look_mode = self.modes["idle"] print('Drone ' + color + ' initialized')
def get_photos(): # 1. select an image photos = flickr.walk(text=KEYWORD, privacy_filter=1, tags=KEYWORD, extras='url_c', safe_search=1, content_type=1, has_geo=1, per_page=100) photo_info = [] for i, photo in enumerate(photos): uid = photo.get('owner') pid = photo.get('id') url = photo.get('url_c') title = photo.get('title') # info = flickr.photos.getInfo(photo_id=pid) # soup = BeautifulSoup(info.text, "lxml") # xml.etree.ElementTree.dump(flickr.photos.getInfo(photo_id=pid)) # region = str(soup.find({'location'}).region.string) # print(soup.find("location")) # print(pid, title, region) p = Photo(uid, pid, url, title) photo_info.append(p) if i > 1: break return photo_info
def create_widgets(self): self.columns = tk.PanedWindow(self.root, orient=tk.HORIZONTAL) self.columns.configure(sashrelief = tk.RAISED, sashwidth=5, sashpad=2) self.columns.pack(fill=tk.BOTH, expand=True) self.leftPane = ttk.Frame(self.columns) self.centerRows = tk.PanedWindow(self.columns, orient=tk.VERTICAL) self.leftTree = ttk.Treeview(self.leftPane) self.leftPane.bind("<Configure>", self.resizeTree) self.leftTree.bind('<<TreeviewSelect>>', self.treeItemSelected) self.leftTree.pack(fill=tk.BOTH, expand=True) self.thumbs = [ Photo(path) for path in self.pathes ] self.populateLeftTree() self.imageFrame = ttk.Frame(self.centerRows) self.imageFrame.bind("<Configure>", self.resizeImages) self.imageFrame.pack(expand=True, fill=tk.BOTH) self.buttonsFrame = ttk.Frame(self.columns) self.quit = ttk.Button(self.buttonsFrame, text="QUIT", command=self.root.destroy) self.quit.pack(side=tk.BOTTOM) self.buttonsFrame.pack() self.columns.add(self.leftPane) self.columns.add(self.centerRows) self.centerRows.add(self.imageFrame, stretch="always") self.centerRows.add(self.buttonsFrame, stretch="never") self.root.geometry("700x700") self.renderImages()
class TestPhoto: """ Classe de test de la classe Photo """ photo_jpg = Photo("test.jpg", "test") photo_bmp = None def test_attr(self): """ Teste les attributs de l'objet """ assert self.photo_jpg.name == "test.jpg" assert self.photo_jpg.taille[0] == 3072 assert self.photo_jpg.taille[1] == 2304 def test_str(self): """ Tester la méthode magique __str__ """ assert str(self.photo_jpg) == "test.jpg" def test_false_format(self): """ Tester si une erreur est renvoyée lorsqu'on essaye de lire une image qui n'est ni au format JPEG, ni au format PNG, ni au format GIF. """ erreur = False try: self.photo_bmp = Photo("test.bmp", "test") except TypeError: erreur = True finally: assert erreur
def __init__(self): self.photo = Photo() self.photo_live = True self.global_count = 0 self.MainWindow = uic.loadUi('main.ui') self.webcam = cv.CreateCameraCapture(-1) self.timer = QtCore.QTimer(self.MainWindow) self.MainWindow.connect( self.timer, QtCore.SIGNAL('timeout()'), self.show_frame ) self.MainWindow.connect( self.MainWindow.pushButton, QtCore.SIGNAL("clicked()"), self.take_photo ) if AUTO_PRINT: self.MainWindow.pushButton_2.hide() else: self.MainWindow.connect( self.MainWindow.pushButton_2, QtCore.SIGNAL("clicked()"), self.print_photo_button ) if PATCH_BACKGROUND_IMG is not None: palette = QtGui.QPalette() palette.setBrush( QtGui.QPalette.Background, QtGui.QBrush( QtGui.QPixmap(PATCH_BACKGROUND_IMG) ) ) self.MainWindow.setPalette(palette) if PATCH_LOGO_IMG is not None: self.MainWindow.lbllogo.setPixmap( QtGui.QPixmap(PATCH_LOGO_IMG) ) self.timer.start(1)
def __init__(self, path: str) -> None: self.photos = {} # print(f'Read input {path}') file = open(path, 'r') photo_id = 0 first_line = True for line in file: line = line.strip() # print(line) if first_line: first_line = False else: line_splited = list(line.split(' ')) orientation_line = line_splited.pop(0) orientation = 0 if orientation_line == 'V': orientation = 1 number_tags = line_splited.pop(0) tags = set(line_splited) self.photos[photo_id] = Photo(photo_id, orientation, tags) photo_id += 1 # self.orientation_counter[orientation] += 1 # for tag in tags: # self.tags_counter[tag] += 1 file.close()
def snapshotsmain(): photo1 = Photo('3', 'J Dimas', ' josecdimas', '0', '0', 'WINTER SUNNY DAY IN AUSTIN', 'https://farm5.staticflickr.com/4657/40162172101_a30055288c.jpg', '#Austin #Austin, TX #ATX #Zilker Park #winter #dried grass', '1', '1') photo2 = Photo('5', 'Don Mason', '-Dons', '0', '0', 'A great start to the day', 'https://farm5.staticflickr.com/4605/25036430577_0f11597674.jpg', '#Austin #Camera #Houndstooth - Frost #Texas #United States \ #coffee #coffee houses #latte art #TX #USA #Nikon #Nikon F3T #cappuccino', '2', '1') photo3 = Photo('0', 'unknown', 'ClevrCat', '0', '0', 'YESSS. POST-WORKOUT AND HAIRCUT COFFEE. HOUNDSTOOTH HAS THE CUTEST CUPS TOO. \ #ATX #CAFFEINE #COFFEE #HOUNDSTOOTH #AUSTIN @HOUNDSTOOTHCOFFEE' , 'https://farm9.staticflickr.com/8515/29772433785_43acb1720a.jpg', '#IFTTT #Instagram #Yesss. #Post-workout #haircut #coffee. #Houndstooth #has #cutest #cups #too. #Atx #caffeine #austin #@houndstoothcoffee', '3', '1') return flask.render_template('snapshotsmain.html', name1 = photo1.name, name2 = photo2.name, name3 = photo3.name, title1 = photo1.title, title2 = photo2.title, title3 = photo3.title, num_favs1 = photo1.num_favorites, num_favs2 = photo2.num_favorites, num_favs3 = photo3.num_favorites, username1 = photo1.username, username2 = photo2.username, username3 = photo3.username, url1 = photo1.imageUrl, url2 = photo2.imageUrl, url3 = photo3.imageUrl, id1 = photo1.id, id2 = photo2.id, id3 = photo3.id, secret1 = photo1.secret, secret2 = photo2.secret, secret3 = photo3.secret)
def main(input_file): horizontal_photos = [] vertical_photos = [] with open(input_file) as file: numberOfPhotos = int(file.readline().strip('\n')) index = 0 while index < numberOfPhotos: currentPhoto = file.readline().strip('\n').split(" ") orientation = currentPhoto[0] numberOfTags = int(currentPhoto[1]) tags = [] for i in range(numberOfTags): tags.append(currentPhoto[i + 2]) if orientation == "H": horizontal_photos.append(Photo(index, orientation, tags)) else: vertical_photos.append(Photo(index, orientation, tags)) index += 1 vertical_graph = nx.Graph() for vertical_photo in vertical_photos: # print(vertical_photo.id) vertical_graph.add_node(vertical_photo.id) i = 0 for index in range (len(vertical_photos)): best_weight = 0 best_index = 0 print(i) i = i +1 for index2 in range (index+1, len(vertical_photos)): weight = resolve_score(vertical_photos[index].tags, vertical_photos[index2].tags) if weight > best_weight: best_weight = weight best_index = index2 vertical_graph.add_weighted_edges_from([(vertical_photos[index].id, vertical_photos[best_index].id, best_weight)]) print(vertical_graph.edges(data=True))
def fetch_photo(): logger.debug('Fetching photos.') json_response = {} data = json.loads(request.data) for camera_data in data['cameras']: name = camera_data['name'] ip = camera_data['ip_address'] camera = Camera(name, ip) url = 'http://%s:8080/fetch_imgs' % (camera.ip_address) logger.debug('Making a call to: %s' % url) try: output_filename = 'imgs_' + camera.ip_address + '.tar.gz' f = urllib2.urlopen(url) with open(os.path.basename(output_filename), "wb") as local_file: local_file.write(f.read()) camera_path = imgs_path + '/' + camera.ip_address camera_short_path = 'imgs/' + camera.ip_address tarball_path = camera_path + '/' + output_filename if not os.path.exists(camera_path): os.mkdir(camera_path) elif os.path.exists(tarball_path): os.remove(tarball_path) shutil.move('./' + output_filename, camera_path) tar = tarfile.open(tarball_path) tar.extractall(camera_path) tar.close() os.remove(tarball_path) files = os.listdir(camera_path) imgs = [] for filename in files: if filename != '.gitignore': path = camera_path + '/' + filename url = url_for('static', filename=camera_short_path + '/' + filename) photo = Photo('photo', path, url) camera.imgs.append(photo) json_response[camera.ip_address] = { 'success': True, 'camera': camera } except URLError as e: logger.error('Error fetching image from %s(%s): %s' % (camera.name, camera.ip_address, str(e))) json_response[camera.ip_address] = { 'success': False, 'camera': camera } return json.dumps(json_response, default=ComplexHandler)
def mongo_set_attributes_by_id(name, photo_id, body): attributes = body ph = Photo.objects(id=ObjectId(photo_id), author=name).update(title=attributes.title, location=attributes.location, comment=attributes.comment, tags=attributes.tags) return ph
def mongo_add(name, photo): ph = Photo(title='title', location='location', author=name, comment='comment', tags=['tags'], photo=photo).save() return ph
def mongo_get_photos(name, offset, limit): list_ph = Photo.objects( author=name).order_by('id').skip(offset).limit(limit) if list_ph.count(with_limit_and_skip=False) > (offset + limit): has_more = True else: has_more = False return (has_more, list_ph)
def mongo_get_photo_by_name_and_id(display_name, photo_id): try: ph = Photo.objects(photo_id=photo_id, display_name=display_name).get() return ph except (pymongo.errors.AutoReconnect, pymongo.errors.ServerSelectionTimeoutError, pymongo.errors.NetworkTimeout) as e: raise
def mongo_set_attributes_by_id(name, photo_id, body): attributes = body ph = Photo.objects(id=ObjectId(photo_id), author=name).update(title=attributes['title'], location=attributes['location'], comment=attributes['comment'], tags=attributes['tags']) return ph
def progress(self): if self._started != True: self._started = True taskPhoto = Photo(PIN_LIGHT_FLASH, PIN_LIGHT_RED) print(taskPhoto.getFileName) #image = Convert(PIN_LIGHT_YELLOW, image_name) #draw = Draw(PIN_LIGHT_GREEN, image_name) self._started = False
def getPhotoList(letter): """ :param letter: char :rtype: list of Photos' """ dataList = readInput(getFile(letter)) photoList = [Photo(dataItem) for dataItem in dataList] return photoList
def save_product_photo(self, photo, main=False): if type(photo) is type(''): return False file_content = photo.file.read() if len(file_content) == 0: return False filename, ext = os.path.splitext(photo.filename) filename = unicodedata.normalize('NFD', filename).encode('ascii', 'ignore') md5_ = md5(str(file_content)).hexdigest() new_filename = md5_ + '_' + filename.lower() + ext.lower() if not os.path.exists(Photo.BASE_STORAGE_PATH + new_filename[0]): os.makedirs(Photo.BASE_STORAGE_PATH + new_filename[0]) new_filename_with_path = Photo.BASE_STORAGE_PATH + new_filename[0] + '/' + new_filename Photo.save_original(new_filename_with_path, file_content) img = Image.open(new_filename_with_path) #if img.mode != "RBG": # img = img.convert("RGB") maps_image = Photo.resize(img, Photo.MAPS_THUMBNAIL, new_filename, 'maps_') tiny_image = Photo.resize(img, Photo.TINY_THUMBNAIL, new_filename, 'tiny_') small_image = Photo.resize(img, Photo.SMALL_THUMBNAIL, new_filename, 'small_') big_image = Photo.resize(img, Photo.BIG_THUMBNAIL, new_filename, 'big_') maxi_image = Photo.resize(img, Photo.MAXI_THUMBNAIL, new_filename, 'maxi_') photo = self.save_photo(new_filename_with_path, main=main) return photo
def configData(self): self.d = tk.StringVar() path = "/Users/dmitrygalyuk/Dropbox/Projects/py/TestApp/photos" self.pathes = [] for file in os.listdir(path): self.pathes.append(os.path.join(path, file)) self.photos = [Photo(self.pathes[0]),]
def test_that_pixelate_returns_pixelated_photo(self): pixelated_wolf = self.creator.pixelate(nr_pixels_in_x=50, nr_pixels_in_y=35) output_file = Path.to_testphoto('wolf_pixelated_50_35.bmp') if self.RESET_EXPECTED_OUTPUT: pixelated_wolf.save(output_file) # Expected image is a bitmap, to prevent jpeg artefacts in comparison expected_pixelated_wolf = Photo.open(output_file) self.assertEqual(expected_pixelated_wolf, pixelated_wolf)
def showAll(): photoInfos = [] for photo in Photo.all(): photoInfo = {} photoInfo['imageUrl'] = url_for('img', key=photo.key()) photoInfo['exif'] = photo.getExif() photoInfos.append(photoInfo) return render_template('showAll.html', photoInfos=photoInfos)
def equal_rgb_image(self) -> Photo: photo = Photo.new(size=(120, 40), mode='RGB') red_box = Image.new(size=(40, 40), color=(255, 0, 0), mode='RGB') green_box = Image.new(size=(40, 40), color=(0, 255, 0), mode='RGB') blue_box = Image.new(size=(40, 40), color=(0, 0, 255), mode='RGB') photo.paste(red_box, (0, 0)) photo.paste(green_box, (40, 0)) photo.paste(blue_box, (80, 0)) return photo
def mongo_get_photos_by_name(display_name, offset, limit): try: photos_by_display_name = Photo.objects( display_name=display_name).order_by('photo_id').skip(offset).limit( limit) return photos_by_display_name except (pymongo.errors.AutoReconnect, pymongo.errors.ServerSelectionTimeoutError, pymongo.errors.NetworkTimeout) as e: raise
def countHashtagsFromPhotosContainingTopKeywords(self, k=3): # count the number of hashtags of photos that associated with topwords # k is the number of top keywords # rank top keywords by counting their frequency word_photo_list = self.getTopKeywordsAndPhotos(k, 10000) cnt = [0] * k cnt2 = [0] * k for i in xrange(0, len(word_photo_list)): j = 0 for photo in word_photo_list[i][2]: p = Photo(photo) cap = p.getCaption() j += 1 cnt[i] += cap.count('#') # return the number of hashtags cnt[i] = cnt[i] * 1.0 / j # reteurn the number of photos cnt2[i] = len(word_photo_list[i][2]) return [cnt, cnt2]
def computeWordKLDivergenceWithByEddie(self, event): # this method calls the kl divergence computation by eddie's methods text1 = '' text2 = '' for photo in self._event['photos']: p = Photo(photo) text1 += ' ' text1 += p.getCaption() if type(event) is types.DictType: pass else: event = event.toDict() for photo in event['photos']: p = Photo(photo) text2 += ' ' text2 += p.getCaption() return kldiv(tokenize(text1), tokenize(text2))
def index(): # Rendering if site is installed. if Path("photolog.cfg").is_file(): content = oauth.request() j = json.loads(content) photos = [Photo(e) for e in j['photos']['photo']] return render_template('index.html', photos=photos) else: # Redirect to getting access token page. return redirect(url_for('install'))
def test_that_resize_images_resizes_all_images(self): self.setup_photo_dir_structure() collector = PhotoCollector(self.dirname) collector._split_by_size_ratio() collector._select_images(desired_size_ratio=100) # Crop the first image, such that the original is not square anymore mosaic_dir = os.path.join(self.photos_dir, 'mosaic') first_cat = os.path.join(mosaic_dir, '00000001.jpg') img = Photo.open(first_cat) img = img.crop((0, 0, 400, 200)) img.save(first_cat) collector._resize_images(desired_size_ratio=100, desired_width=100) for file in os.scandir(mosaic_dir): img = Photo.open(file.path) desired_size = (100, 100) self.assertTupleEqual(desired_size, img.size)
def countHashtagsFromPhotosContainingTopKeywords(self, k=3): # count the number of hashtags of photos that associated with topwords # k is the number of top keywords # rank top keywords by counting their frequency word_photo_list = self.getTopKeywordsAndPhotos(k, 10000) cnt = [0]*k cnt2 = [0]*k for i in xrange(0, len(word_photo_list)): j = 0 for photo in word_photo_list[i][2]: p = Photo(photo) cap = p.getCaption() j += 1 cnt[i] += cap.count('#') # return the number of hashtags cnt[i] = cnt[i] * 1.0 / j # reteurn the number of photos cnt2[i] = len(word_photo_list[i][2]) return [cnt, cnt2]
def mongo_delete_photo_by_id(name, photo_id): try: ph = Photo.objects(id=ObjectId(photo_id), author=name).get() except (Photo.DoesNotExist, Photo.MultipleObjectsReturned): return False except (pymongo.errors.AutoReconnect, pymongo.errors.ServerSelectionTimeoutError, pymongo.errors.NetworkTimeout) as e: raise ph.delete() return True
def _getEventText(self, event): """For a given event, return the text as a list. Note for photo without text, use a None to hold the place""" assert self._element_type in Event(event).toDict().keys() event_text = [] for element in event[self._element_type]: if self._element_type == "photos": element = Photo(element) else: element = Tweet(element) try: if self._is_ascii(element.getText()): event_text.append(element.getText().lower()) else: event_text.append("") except: event_text.append("") return event_text
def mongo_get_attributes_by_id(name, photo_id): ph = Photo.objects(id=ObjectId(photo_id), author=name).get() attributes = json.loads( json.dumps({ 'title': ph.title, 'location': ph.location, 'author': ph.author, 'comment': ph.comment, 'tags': ph.tags })) return attributes
def load_after(self, timestamp, limit, state, cursor): sql = "SELECT id, fb_id, filename, caption, owner_id, state, \ created_at, approved_at \ FROM photos \ WHERE state = %s AND approved_at > %s \ ORDER BY approved_at ASC LIMIT %s" try: cursor.execute(sql, (state, timestamp, limit)) data = cursor.fetchall() for row in data: photo = Photo() photo.load_from_tuple(row) self.photos_list.append(photo) return self.photos_list except Exception, e: raise e
def mongo_delete_photo_by_name_and_id(display_name, photo_id): try: ph = Photo.objects(photo_id=photo_id, display_name=display_name).get() except (pymongo.errors.AutoReconnect, pymongo.errors.ServerSelectionTimeoutError, pymongo.errors.NetworkTimeout) as e: raise except (Photo.DoesNotExist) as e: return False ph.delete() return True
def random_photo() -> int: arguments: argparse.Namespace = handle_command_line_arguments() used_photos: Set[str] = read_used_photos_file(arguments.used_photos) photos: List[Photo] = [ Photo(arguments.photos_dir, photo_path) for photo_path in os.listdir(arguments.photos_dir) if photo_valid(photo_path, used_photos) ] selected_photo: Photo = random.choice(photos) print(selected_photo)
def photos(self) -> Dict[str, Photo]: if not self._photos: self._photos = { filename: Photo.open(os.path.join(self.src_dir, filename)) for filename in sorted(os.listdir(self.src_dir)) if self._is_image(filename) } if not self._photos: msg = f'No photos found in directory {self.src_dir}' raise FileNotFoundError(msg) return self._photos
def test_false_format(self): """ Tester si une erreur est renvoyée lorsqu'on essaye de lire une image qui n'est ni au format JPEG, ni au format PNG, ni au format GIF. """ erreur = False try: self.photo_bmp = Photo("test.bmp", "test") except TypeError: erreur = True finally: assert erreur
def load(self, offset, limit, state, cursor): sql = ( "SELECT id, fb_id, filename, caption, owner_id, state, created_at \ FROM photos \ WHERE state = '%s' LIMIT %d OFFSET %d" % (state, limit, offset) ) try: cursor.execute(sql) data = cursor.fetchall() for row in data: photo = Photo() photo.load_from_tuple(row) self.photos_list.append(photo) return self.photos_list except Exception, e: raise e
def _get_resized_photo(self, filename: str, size: Size) -> Photo: """ Look up the resized photo with the given filename and size If it has not been resized yet, resize it on the spot and cache it in the dictionary _resized_photos """ key = (filename, *size) if key not in self._resized_photos: photo = self.photos[filename] self._resized_photos[key] = Photo(img=photo.resize(size)) return self._resized_photos[key]
def mergeWith(self, event): if type(event) is types.DictType: event = Event(event) event = event.toJSON() photo_list1 = self._event['photos'] photo_list2 = event['photos'] new_photo_list = [] l1 = 0 l2 = 0 merged = 0 while l1 < len(photo_list1) and l2 < len(photo_list2): p1 = Photo(photo_list1[l1]) p2 = Photo(photo_list2[l2]) compare = p1.compare(p2) if compare == 1: new_photo_list.append(photo_list1[l1]) l1 += 1 continue if compare == -1: new_photo_list.append(photo_list2[l2]) l2 += 1 merged += 1 continue # compare == 0 new_photo_list.append(photo_list1[l1]) l1 += 1 l2 += 1 while l1 < len(photo_list1): new_photo_list.append(photo_list1[l1]) l1 += 1 while l2 < len(photo_list2): new_photo_list.append(photo_list2[l2]) l2 += 1 merged += 1 return merged
def removeDuplicatePhotos(self): # this method is not good, just for tempory use # by judging if the caption is duplicate new_photos = [] num_duplicate = 0 for photo in self._event['photos']: p = Photo(photo) is_duplicate = False cap1 = p.getCaption() user1 = p.getUserName() for new_photo in new_photos: p2 = Photo(new_photo) cap2 = p2.getCaption() user2 = p2.getUserName() if user1 == user2 and (len(cap1)>0 and cap1 == cap2): is_duplicate = True num_duplicate += 1 break if not is_duplicate: new_photos.append(photo) if num_duplicate > 0: self._event['photos'] = new_photos return num_duplicate
def PhotoDistanceByCaption(photo1, photo2): p1 = Photo(photo1) p2 = Photo(photo2) cap1 = p1.getCaption() cap2 = p2.getCaption() cp1 = TextParser(True) cp1.insertCaption(cap1) cp2 = TextParser(True) cp2.insertCaption(cap2) word_list1 = cp1.getTopWords(-1) word_list2 = cp2.getTopWords(-1) if len(word_list1) == 0 or len(word_list2) == 0: # unable to compare return None word_dict1 = {} for word, freq in word_list1: word_dict1[word] = freq word_dict2 = {} for word, freq in word_list2: word_dict2[word] = freq return kldiv(word_dict1, word_dict2)