Пример #1
0
    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
Пример #2
0
	def checkIfTopPhotoLocationSame(self, k=3):
		k = min(k, len(self._event['photos']))
		photos = self._event['photos']
		location_name = Photo(photos[0]).getLocationName()
		if location_name == '':
			return 0
		for i in xrange(1, k):
			if not Photo(photos[i]).getLocationName() == location_name:
				return 0
		return 1
Пример #3
0
def snapshotsinstance(id, secret):
    if id is '1' :
        photo = 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')
    elif id is '2' :
        photo = 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', '2')
    else :
        photo = 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', '3')
    return flask.render_template('snapshotinstance.html', username = photo.username, name = photo.name, num_faves = photo.num_favorites,
                                title = photo.title, tags = photo.tags, id = photo.id, secret = photo.secret, url = photo.imageUrl)
Пример #4
0
	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 pixelate(self, nr_pixels_in_x: int, nr_pixels_in_y: int) -> Photo:
        """
        Pixelate the given photo by chopping it up in rectangles, and replace every square by its average color
        """

        # TODO: Instead of calculating the average color of a box, resize the source image
        #       to the amount of pixels you need, then this resizing takes care of calculating
        #       the average color. The result is not identical, but you can't say with the
        #       human eye which one is better. We now do resize the original photo, but we
        #       didn't remove the calculation yet and just take the one pixel value.
        self.original_size = (nr_pixels_in_x, nr_pixels_in_y)
        self.original_photo = self.original_photo.resize(self.original_size)

        result = Photo.new(mode='RGB', size=self.output_size)
        for original_box, output_box in self._get_boxes(
                nr_pixels_in_x, nr_pixels_in_y):
            print(original_box)
            sub_img = Photo(self.original_photo.crop(original_box))
            output_img_size = (output_box[2] - output_box[0],
                               output_box[3] - output_box[1])
            colored_box = Image.new(mode='RGB',
                                    size=output_img_size,
                                    color=sub_img.avg_color)
            result.paste(colored_box, box=output_box)
        return result
    def photo_pixelate(self, src_dir: str, nr_pixels_in_x: int,
                       nr_pixels_in_y: int) -> Photo:
        """
        Pixelate the given photo by chopping it up in rectangles, and replace every square by its most matching photo
        """

        result = Photo.new(mode='RGB', size=self.output_size)
        analyzer = PhotoAnalyzer(src_dir,
                                 nr_photo_pixels=nr_pixels_in_x *
                                 nr_pixels_in_y)
        for original_box, output_box in self._get_boxes(
                nr_pixels_in_x, nr_pixels_in_y):
            sub_img = Photo(self.original_photo.crop(original_box))
            output_img_size = (output_box[2] - output_box[0],
                               output_box[3] - output_box[1])
            best_photo = analyzer.select_best_photo(
                sub_img.avg_color, desired_size=output_img_size)
            best_photo = best_photo.convert('RGBA')
            colored_box = Image.new(mode='RGB',
                                    size=best_photo.size,
                                    color=sub_img.avg_color)
            mask = Image.new(mode='RGBA',
                             size=best_photo.size,
                             color=(0, 0, 0, cheat_parameter))
            best_photo.paste(colored_box, mask=mask)
            result.paste(best_photo, box=output_box)
        return result
Пример #7
0
    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()
Пример #8
0
def traitement(url_photo, parameters, dest):
    """
    Fonction assurant le traitement pour une photo
    """
    file = Photo(url_photo, dest)
    # traitement photo
    if "size" in parameters:
        file.redimensionner(*parameters["size"])

    if "copyright" in parameters and \
       "text" in parameters["copyright"] and \
       "font" in parameters["copyright"] and \
       "color" in parameters["copyright"] and \
       "coords" in parameters["copyright"]:
        file.ajouter_texte(parameters["copyright"]["text"],
                           parameters["copyright"]["font"],
                           parameters["copyright"]["coords"],
                           parameters["copyright"]["color"])

    if "border" in parameters and "width" in parameters["border"] \
        and "color" in parameters["border"]:
        file.ajouter_bordure(parameters["border"]["width"], parameters["border"]["color"])

    if "watermark" in parameters and \
       "url" in parameters["watermark"] and "coords" in parameters["watermark"]:
        file.ajouter_logo(parameters["watermark"]["url"], parameters["watermark"]["coords"])

    file.sauvegarder()
Пример #9
0
    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()
Пример #10
0
def transfer_photo(photo_path: str,
                   export_path: str,
                   year: bool = False,
                   month: bool = False,
                   name_pattern: str = "_place_reason_people"):
    """Moves a photo to a "date" folder, if a date was extracted.

    :param photo_path: path to photo
    :type photo_path: str
    :param export_path: path to the directory where the photo folder will be created
    :type export_path: str
    :param year: indicates if the photos will be grouped by year
    :type year: boolean
    :param month: indicates if the photos will be grouped by month
    :type month: boolean
    :param name_pattern: A string name pattern after which the photo folders will be named 
    :type name_pattern: str
    |
    """
    photo = Photo(photo_path)
    date = photo.get_date(year=year, month=month)

    if date:
        photo_folder_name = photo_dir_name(date,
                                           year=year,
                                           month=month,
                                           name_pattern=name_pattern)
        if not dir_name_exists(photo_folder_name, export_path):
            # I dont simply use a set because the photo_dir might exist from the past
            create_photo_dir(photo_folder_name, export_path)
        photo.move_to_folder(os.path.join(export_path, photo_folder_name))
    else:
        write_not_transferred_photos(photo_path, export_path)
Пример #11
0
def main():
    """Does the job"""
    keep = True
    photos = request_photos()
    page = 1
    t = False

    while keep is True:
        p = next(photos, False)

        if p is False:
            photos = request_photos(page + 1)
            continue

        trial = Photo.objects(flickr=p["id"]).first()
        print("Trying to find %s in collection" % (p["id"]))

        if trial is not None:
            print("Photo already published, looping again")
            print("Found ID: %s\n" % (p["id"]))
            continue

        print("Found a valid photo, posting")
        keep = False
        url = make_photo_url(p["farm"], p["server"], p["id"], p["secret"])
        t = tweet(url)
        Photo(flickr=p["id"], tweet=t["id_str"]).save()

    return t
Пример #12
0
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
Пример #13
0
 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')
Пример #14
0
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
Пример #15
0
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))
Пример #16
0
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_add(name, photo):
    ph = Photo(title='title',
               location='location',
               author=name,
               comment='comment',
               tags=['tags'],
               photo=photo).save()
    return ph
Пример #18
0
 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
Пример #19
0
def create_new_photo():
    user = request.json['username']
    description = request.json['description']
    url = request.json['url']

    photo = Photo(user, url, description)
    photo = photo.save_to_mongo()
    return jsonify(photo)
Пример #20
0
def getPhotoList(letter):
    """
	:param letter: char
	:rtype: list of Photos'
	"""
    dataList = readInput(getFile(letter))
    photoList = [Photo(dataItem) for dataItem in dataList]
    return photoList
Пример #21
0
 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)
Пример #22
0
    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]),]
Пример #23
0
 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)
Пример #24
0
    def format(self):
        # dirs = os.listdir(self.path)
        dirs = self.path.iterdir()
        has_child_album = False
        parts = self.path.parts
        album_levels = parts[-self.root:len(parts)] if self.root > 0 else []
        photo_list = []
        album_list = []
        result = {
            'name': self.name,
            'type': 'album',
            'root': self.root,
            'parents': album_levels
        }

        print(f'Processing the album {self.name}')

        for i, path in enumerate(dirs):
            if path.is_dir():
                album_list.append(path)
            elif str(path.suffix).endswith(
                ('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')):
                photo_list.append(path)

        photo_list = self.sort_dirs(photo_list, 'photo')
        album_list = self.sort_dirs(album_list, 'album')

        for path in photo_list:
            photo = Photo(path)
            photo_conf = photo.format()
            if photo_conf:
                self.items_order.append(path.name)
                self.items_dict[path.name] = photo_conf

        for path in album_list:
            sub_album = Album(path, path.name, self.root + 1)
            self.items_order.append(path.name)
            self.items_dict[path.name] = sub_album.format()
            has_child_album = True

        child_items = {'order': self.items_order, 'dict': self.items_dict}

        if has_child_album:
            return {**result, 'items': child_items}
        else:
            # write list to album config file
            album_path = conf.ALBUMS_PATH.joinpath('-'.join(album_levels) +
                                                   '.json')
            print('Write the album config to', album_path)
            conf.write_json(album_path, child_items)

            return {
                **result, 'path':
                './' + str(album_path.relative_to(conf.DIR_PATH)),
                'no_sub_album': True
            }
Пример #25
0
 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
Пример #26
0
	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.toJSON()
			
		for photo in event['photos']:
			p = Photo(photo)
			text2 += ' '
			text2 += p.getCaption()
		return kldiv(tokenize(text1), tokenize(text2))
Пример #27
0
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'))
Пример #28
0
 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
Пример #29
0
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)
Пример #30
0
 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