Example #1
0
    def get_writing(self, string_to_write):
        payload = {
            'text':string_to_write,
            'bias':0.15,
            'samples':1
        }

        try:
            response = requests.get('http://www.cs.toronto.edu/~graves/handwriting.cgi', params=payload)
            if response.status_code != 200:
                return "there was an error creating the image. code: %s" % response.status_code

            html = response.text
            soup = BeautifulSoup(html, 'html.parser')

            image = soup.find_all("img")[-1]
            image_src = image['src']
            b64 = image_src[(image_src.index(',') + 1):]

            file = tempfile.NamedTemporaryFile(suffix=".png")
            file.write(b64.decode("base64"))
            file.flush()
                       
            img = Imgur()
            url = img.save_from_file(file.name)
            file.close()
            return url

        except Exception as e:
            print "there was an error", e.message
            return "foo"
        except:
            logging.debug("there was an error!")
            logging.debug(sys.exc_info()[0])
            return "there was an error writing!"
Example #2
0
    def get_writing(self, string_to_write):
        payload = {'text': string_to_write, 'bias': 0.15, 'samples': 1}

        try:
            response = requests.get(
                'http://www.cs.toronto.edu/~graves/handwriting.cgi',
                params=payload)
            if response.status_code != 200:
                return "there was an error creating the image. code: %s" % response.status_code

            html = response.text
            soup = BeautifulSoup(html, 'html.parser')

            image = soup.find_all("img")[-1]
            image_src = image['src']
            b64 = image_src[(image_src.index(',') + 1):]

            file = tempfile.NamedTemporaryFile(suffix=".png")
            file.write(b64.decode("base64"))
            file.flush()

            img = Imgur()
            url = img.save_from_file(file.name)
            file.close()
            return url

        except Exception as e:
            print "there was an error", e.message
            return "foo"
        except:
            logging.debug("there was an error!")
            logging.debug(sys.exc_info()[0])
            return "there was an error writing!"
Example #3
0
    def __init__(self, imgur_id):
        """Initializes Mongo.

        Args:
            imgur_id: id to authorize the imgur API.
        """
        self._imgur_client_id = imgur_id
        self._imgur = Imgur(self._imgur_client_id)
        self._client = MongoClient('mongodb://127.0.0.1:27017/')
        self._db = self._client.hotornot
def main():

    path = sys.argv[1]
    language = sys.argv[2]

    # Google Sheet Key we want to use to update Data Studio
    sheet_key = 'your-sheet-key'
    g_sheet = gSheet(sheet_key)

    with open('imgur_credentials.json', 'r') as f:
        imgur_credentials = json.load(f)
    imgur_conn = Imgur(imgur_credentials)
    print("Cleaning preexisting images...")
    res = imgur_conn.clean_user_images()
    if not res:
        "Error on cleaning user images!"

    df_posts, caption_text, img_link = assemble_info(path, imgur_conn,
                                                     language)
    df_hash = generate_top_hashes(df_posts)
    df_day = generate_df_per_day(df_posts, language)
    df_data = df_posts[['media_code', 'media_type', 'likes', 'comments']]

    metrics = assemble_metrics(df_posts)

    #------------#-------------#--------#---------------
    mean_likes = metrics['mean_likes']
    mean_comments = metrics['mean_comments']
    likes_image = metrics['likes_image']
    likes_video = metrics['likes_video']
    likes_carousel = metrics['likes_carousel']

    g_sheet.update_data_sheet(df_data)
    g_sheet.update_wordcloud(caption_text, path, imgur_conn, language)
    g_sheet.update_mainmetrics(mean_likes, mean_comments)
    g_sheet.update_top_hashes(df_hash)
    g_sheet.update_media_metrics(likes_image, likes_video, likes_carousel)
    g_sheet.update_day_metrics(df_day)
    g_sheet.update_profile_info(img_link, path)
Example #5
0
 def __init__(self):
     print _('TV-Maxe Channel Editor is starting...')
     self.gui = gtk.Builder()
     self.gui.add_from_file('ceditor.glade')
     self.gui.connect_signals({
         "quit": self.quit,
         "deschide": self.deschide,  #open
         "openFile": self.openFile,
         "openURL": self.openURL,
         "hideOpenURL": self.hideOpenURL,
         "goURL": self.goURL,
         "saveList": self.saveList,
         "showAddWindow": self.showAddWindow,
         "hideAddWindow": self.hideAddWindow,
         "addChannel": self.addChannel,
         "editChannel": self.editChannel,
         "hideChannelEditor": self.hideChannelEditor,
         "saveChannel": self.saveChannel,
         "deleteChannel": self.deleteChannel,
         "uploadImage": self.uploadImage,
         "salveaza": self.salveaza,
         "addChannelURL": self.addChannelURL,
         "addChannelEdit": self.addChannelEdit,
         "removeChannelURL": self.removeChannelURL,
         "addAudio": self.addAudio,
         "addAudioEdit": self.addAudioEdit,
         "removeAudio": self.removeAudio,
         "saveNew": self.saveNew,
         "saveInfo": self.saveNew2,
         "hideInfo": self.hideInfo,
         "on_entry2_changed": self.on_entry2_changed,
         "hideLogoWin": self.hideLogoWin,
         "selectIcon": self.selectIcon
     })
     self.imgur = Imgur()
     self.imageFinder = imageFinder(self)
     self.db = DBManager(':memory:')
     self.db.build()
     self.gui.get_object('cellrenderertext12').set_property(
         'editable', True)
     self.gui.get_object('cellrenderertext10').set_property(
         'editable', True)
     self.gui.get_object('cellrenderertext8').set_property('editable', True)
     self.gui.get_object('cellrenderertext9').set_property('editable', True)
     self.icons = {}
Example #6
0
def send_image(chat_id):
    coins = my_binance.get_coins()
    prices = my_binance.get_prices()
    balance = my_binance.get_balance()

    if coins:
        image = my_image.generate_report(coins, prices, balance)
        image = my_image.get_image()
        image, err = Imgur.upload_image(image=image)

        if err:
            telegram.send_message(
                message="There was a problem with the image, please try again",
                chat_id=chat_id)
        else:
            telegram.send_message(chat_id=chat_id, image=image)
    else:
        telegram.send_message(
            message=
            "Use first /text command to collect the data and generate the image",
            chat_id=chat_id)
Example #7
0
def handle_command(command, details, channel, respond = True):
    """
        Receives commands directed at the bot and determines if they
        are valid commands. If so, then acts on the commands. If not,
        returns back what it needs for clarification.
    """
    response = False
    if command == "learn":
        learner = Learner()
        response = learner.learn(details[0], " ".join(details[1:]))
    elif command == "unlearn":
        learner = Learner()
        content = None
        if len(details) > 1:
            content = " ".join(details[1:])    
        response = learner.unlearn(details[0], content)
    elif command == "commands":
        learner = Learner()
        response = learner.list_commands()
    elif command == "list":
        learner = Learner()
        response = learner.list(details[0])
    elif command == "cowsay":
        out = subprocess.check_output(['cowsay', " ".join(details)])
        response = "```" + out + "```"
    elif command == "meme":
        memer = Memer()
        if not details or len(details) == 0:
            response = memer.list_templates()
        else:
            template = details.pop(0).strip()
            parts = [x.strip() for x in " ".join(details).split(",")]
            top = parts[0] if len(parts) > 0 else None
            bottom = parts[1] if len(parts) > 1 else None

            response = memer.get_meme(template, top, bottom)
            
    elif command == "hostname":
        response = "slurms coming to you live from: `%s (%s)`" % (subprocess.check_output("hostname -A",  shell=True).strip(), subprocess.check_output("hostname -i",  shell=True).strip())
    elif command == "write":
        writer = Writer()
        response = writer.get_writing(" ".join(details))
    elif command == "imglearn":
        learner = Learner()
        imgur = Imgur()
        image_url = imgur.save_from_url(" ".join(details[1:]))
        response = learner.learn(details[0], image_url)

    elif command == "++" or command == "endorse":
        plusser = Plusser()
        reason = ""
        if len(details) > 1:
            reason = " ".join(details[1:])

        response = plusser.plus(details[0], reason)
    elif command == "plusses":
        plusser = Plusser()
        response = plusser.get(details[0])
        
    elif command == "leaders" or command == "leader_board":
        plusser = Plusser()
        response = plusser.leader_board()

    elif command == "monthly_leaders" or command == "monthly_leader_board":
        plusser = Plusser()
        months_ago = 0
        if details and len(details) > 0:
            months_ago = details[0]
        response = plusser.monthly_leader_board(months_ago)

    elif command == "youtube":
        query = " ".join(details)
        videos = youtube.youtube_search(query)
        if len(videos) > 0:
            response = videos[-1]
        else:
            response = "sorry, couldnt find any videos for %s" % query
    elif command == "echo":
        response = " ".join(details)
    elif command == "pipe":
        pipe(command, details, channel)
    elif command == "doom":
        doom = Doom()
        response = doom.doom(details)
    else:
        """
          see if a randomly entered command is something that was previously learned
        """
        learner = Learner()
        response = learner.get(command)
    
    if response and respond:
        slack_client.api_call("chat.postMessage", channel=channel,
                              text=response, as_user=True)
    elif not respond:
        return response
import logging
from exchanges import Exchanges
from imgur import Imgur
from slack import Slack
from firestore import FireStore
from dotenv import load_dotenv

load_dotenv()
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO, datefmt='%m/%d/%Y %I:%M:%S %p')
logger = logging.getLogger(__name__)

if __name__ == '__main__':
    logger.info('Starting crypto-balance-check worker')

    exchanges = Exchanges()
    slack = Slack()
    firestore = FireStore()
    imgur = Imgur()

    positions_by_exchange = exchanges.get_all_positions_by_exchange()
    slack.publish_all_positions_by_exchange(positions_by_exchange)
    firestore.update_historic_balances(positions_by_exchange)
    balances = firestore.get_historic_balances()
    url = imgur.send_graph([b[0] for b in balances], [b[1] for b in balances])
    slack.publish_url(url)

    logger.info('Exiting crypto-balance-check worker')
Example #9
0
class Mongo(object):
    def __init__(self, imgur_id):
        """Initializes Mongo.

        Args:
            imgur_id: id to authorize the imgur API.
        """
        self._imgur_client_id = imgur_id
        self._imgur = Imgur(self._imgur_client_id)
        self._client = MongoClient('mongodb://127.0.0.1:27017/')
        self._db = self._client.hotornot

    def random_girl(self):
        """Fetches a random girl from girls collection.

        Fetches a random girl from the girls collection by limited the result to one
        and skipping over a random number of integers that is equal to or less than 
        the number of elements in the collection.

        Returns:
            A dict object representing the random girl fetched 
            from the collection.
        """
        return [result for result in self._db.girls.find().limit(1) \
            .skip(random.randrange(self._db.girls.count()))][0]

    def random_boy(self):
        """Fetches a random boy from boys collection.

        Fetches a random boy from the boys collection by limited the result to one
        and skipping over a random number of integers that is equal to or less than 
        the number of elements in the collection.

        Returns:
            A dict object representing the random boy fetched 
            from the collection.
        """
        return [result for result in self._db.boys.find().limit(1) \
            .skip(random.randrange(self._db.boys.count()))][0]

    def upload_album(self, hash, girl=True):
        """Uploads image data to a MongoDB collection.

        Fetches an album based on a hash value from the Imgur API and
        formats the hash and link into a dictionary with a default rating
        and vote count for each image in the album. The images are placed into
        a MongoDB collection corresponding to the supplied gender.

        Args:
            hash: A hash associated with an Imgur album.
            girl: gender of the album photos.
        """
        images = self._imgur.album_images(hash)['data']
        for image in images:
            doc = {
                '_id': image['id'],
                'rating': 0.0,
                'count': 0,
                'link': image['link']
            }

            try:
                if girl:
                    self._db.girls.insert_one(doc)
                else:
                    self._db.boys.insert_one(doc)
            except pymongo.errors.DuplicateKeyError:
                continue

    def upload_image(self, hash, girl=True):
        pass

    def update_girl(self, hash, new_rate):
        """Updates a girl with a new average rating.

        Given the associated girl image hash, the new rating is applied to the 
        count and old rating to get a total average. The new average is then 
        updated into the corresponding MongoDB document.

        Args:
            hash: A hash belong to a girl's image.
            new_rate: A new rating supplied by a user.
        """
        image = self._db.girls.find_one({'_id': hash})
        total_average = self.average(image['rating'], new_rate, image['count'])

        self._db.girls.find_one_and_update(
            {'_id': hash}, {
                '$inc': {
                    'count': 1
                },
                '$set': {
                    'rating': total_average
                }
            },
            return_document=pymongo.ReturnDocument.AFTER)

    def update_boy(self, hash, new_rate):
        """Updates a girl with a new average rating.

        Given the associated girl image hash, the new rating is applied to the 
        count and old rating to get a total average. The new average is then 
        updated into the corresponding MongoDB document.

        Args:
            hash: A hash belong to a girl's image.
            new_rate: A new rating supplied by a user.
        """
        image = self._db.boys.find_one({'_id': hash})
        total_average = self.average(image['rating'], new_rate, image['count'])

        self._db.boys.find_one_and_update(
            {'_id': hash}, {
                '$inc': {
                    'count': 1
                },
                '$set': {
                    'rating': total_average
                }
            },
            return_document=pymongo.ReturnDocument.AFTER)

    def top_girls(self):
        """Returns top 5 girls based on rating."""
        return [
            girl for girl in self._db.girls.find().sort(
                'rating', pymongo.DESCENDING).limit(5)
        ]

    def top_boys(self):
        """Returns top 5 guys based on rating."""
        return [
            boy for boy in self._db.boys.find().sort(
                'rating', pymongo.DESCENDING).limit(5)
        ]

    @staticmethod
    def average(old_rating, new_rating, count):
        """Returns a new incremental average."""
        return float(
            round(Decimal((old_rating * count + new_rating) / (count + 1)), 1))
    def __init__(self):

        cream.Module.__init__(self, 'org.sbillaudelle.ImgurUploader')
        
        def start_attempt_cb(*args):
            print args
        
        self.connect('start-attempt', start_attempt_cb)

        parser = optparse.OptionParser()
        (options, args) = parser.parse_args()

        self.imgur = Imgur(API_KEY)

        self.interface = gtk.Builder()
        self.interface.add_from_file(os.path.join(self.context.get_path(), 'data/interface.ui'))

        self.window = self.interface.get_object('window')
        self.treeview = self.interface.get_object('treeview')
        self.filechooser = self.interface.get_object('filechooser')
        self.upload_button = self.interface.get_object('upload_button')
        self.close_button = self.interface.get_object('close_button')
        self.add_image_button = self.interface.get_object('add_image_button')
        self.remove_image_button = self.interface.get_object('remove_image_button')
        self.context_menu = self.interface.get_object('context_menu')
        self.copy_item = self.interface.get_object('copy_item')

        icon_path = os.path.join(self.context.get_path(), 'data/imgur.png')
        self.window.set_icon_from_file(icon_path)
        self.window.set_title(self.context.manifest['name'])

        self.filefilter = gtk.FileFilter()
        self.filefilter.set_name("Alle Bilddateien")
        self.filefilter.add_mime_type('image/bmp')
        self.filefilter.add_mime_type('image/gif')
        self.filefilter.add_mime_type('image/jpeg')
        self.filefilter.add_mime_type('image/jpg')
        self.filefilter.add_mime_type('image/pjpeg')
        self.filefilter.add_mime_type('image/png')
        self.filefilter.add_mime_type('image/tiff')
        self.filefilter.add_mime_type('image/x-bmp')

        self.filechooser.add_filter(self.filefilter)
        self.filechooser.set_current_folder(os.path.expanduser('~'))

        self.window.connect('destroy', lambda *args: self.quit())
        self.add_image_button.connect('clicked', self.add_image_cb)
        self.remove_image_button.connect('clicked', self.remove_image_cb)
        self.upload_button.connect('clicked', lambda *args: self.upload())
        self.close_button.connect('clicked', lambda *args: self.quit())
        self.treeview.connect('button-press-event', self.context_menu_cb)
        self.copy_item.connect('activate', self.copy_url_cb)

        # Initialize drag and drop...
        self.treeview.drag_dest_set(0, [], 0)
        self.treeview.connect('drag_motion', self.drag_motion_cb)
        self.treeview.connect('drag_drop', self.drag_drop_cb)
        self.treeview.connect('drag_data_received', self.drag_data_cb)

        theme = gtk.IconTheme.get_default()
        icon_info = theme.lookup_icon('ok', 16, 0)
        self.icon_done = gdkpixbuf.Pixbuf.new_from_file(icon_info.get_filename())

        self.liststore = gtk.ListStore(gdkpixbuf.Pixbuf, str, gdkpixbuf.Pixbuf, bool, bool, int, str, str, bool)
        
        self.treeview.set_model(self.liststore)
        self.treeview_selection = self.treeview.get_selection()
        self.treeview_selection.set_mode(gtk.SelectionMode.MULTIPLE)

        self.column_info = gtk.TreeViewColumn("Image")
        self.column_info.set_property('expand', True)
        self.column_url = gtk.TreeViewColumn("URL")
        self.column_status = gtk.TreeViewColumn("Status")
        self.treeview.append_column(self.column_info)
        self.treeview.append_column(self.column_url)
        self.treeview.append_column(self.column_status)

        cellrenderer_preview = gtk.CellRendererPixbuf()
        cellrenderer_title = gtk.CellRendererText()
        self.column_info.pack_start(cellrenderer_preview, False)
        self.column_info.pack_start(cellrenderer_title, True)
        self.column_info.add_attribute(cellrenderer_preview, 'pixbuf', 0)
        self.column_info.add_attribute(cellrenderer_title, 'text', 1)

        cellrenderer_url = gtk.CellRendererText()
        self.column_url.pack_start(cellrenderer_url, True)
        self.column_url.add_attribute(cellrenderer_url, 'markup', 7)

        cellrenderer_spinner = gtk.CellRendererSpinner()
        self.column_status.pack_end(cellrenderer_spinner, False)
        self.column_status.add_attribute(cellrenderer_spinner, 'visible', 3)
        self.column_status.add_attribute(cellrenderer_spinner, 'active', 3)
        self.column_status.add_attribute(cellrenderer_spinner, 'pulse', 5)

        cellrenderer_status = gtk.CellRendererPixbuf()
        self.column_status.pack_end(cellrenderer_status, False)
        self.column_status.add_attribute(cellrenderer_status, 'pixbuf', 2)
        self.column_status.add_attribute(cellrenderer_status, 'visible', 4)

        self.window.show_all()

        self.count = 0
        gobject.timeout_add(100, self.pulse, self.liststore, self.column_status, cellrenderer_spinner)

        for arg in args:
            self.add_image(arg)
class ImgurUploader(cream.Module):

    def __init__(self):

        cream.Module.__init__(self, 'org.sbillaudelle.ImgurUploader')
        
        def start_attempt_cb(*args):
            print args
        
        self.connect('start-attempt', start_attempt_cb)

        parser = optparse.OptionParser()
        (options, args) = parser.parse_args()

        self.imgur = Imgur(API_KEY)

        self.interface = gtk.Builder()
        self.interface.add_from_file(os.path.join(self.context.get_path(), 'data/interface.ui'))

        self.window = self.interface.get_object('window')
        self.treeview = self.interface.get_object('treeview')
        self.filechooser = self.interface.get_object('filechooser')
        self.upload_button = self.interface.get_object('upload_button')
        self.close_button = self.interface.get_object('close_button')
        self.add_image_button = self.interface.get_object('add_image_button')
        self.remove_image_button = self.interface.get_object('remove_image_button')
        self.context_menu = self.interface.get_object('context_menu')
        self.copy_item = self.interface.get_object('copy_item')

        icon_path = os.path.join(self.context.get_path(), 'data/imgur.png')
        self.window.set_icon_from_file(icon_path)
        self.window.set_title(self.context.manifest['name'])

        self.filefilter = gtk.FileFilter()
        self.filefilter.set_name("Alle Bilddateien")
        self.filefilter.add_mime_type('image/bmp')
        self.filefilter.add_mime_type('image/gif')
        self.filefilter.add_mime_type('image/jpeg')
        self.filefilter.add_mime_type('image/jpg')
        self.filefilter.add_mime_type('image/pjpeg')
        self.filefilter.add_mime_type('image/png')
        self.filefilter.add_mime_type('image/tiff')
        self.filefilter.add_mime_type('image/x-bmp')

        self.filechooser.add_filter(self.filefilter)
        self.filechooser.set_current_folder(os.path.expanduser('~'))

        self.window.connect('destroy', lambda *args: self.quit())
        self.add_image_button.connect('clicked', self.add_image_cb)
        self.remove_image_button.connect('clicked', self.remove_image_cb)
        self.upload_button.connect('clicked', lambda *args: self.upload())
        self.close_button.connect('clicked', lambda *args: self.quit())
        self.treeview.connect('button-press-event', self.context_menu_cb)
        self.copy_item.connect('activate', self.copy_url_cb)

        # Initialize drag and drop...
        self.treeview.drag_dest_set(0, [], 0)
        self.treeview.connect('drag_motion', self.drag_motion_cb)
        self.treeview.connect('drag_drop', self.drag_drop_cb)
        self.treeview.connect('drag_data_received', self.drag_data_cb)

        theme = gtk.IconTheme.get_default()
        icon_info = theme.lookup_icon('ok', 16, 0)
        self.icon_done = gdkpixbuf.Pixbuf.new_from_file(icon_info.get_filename())

        self.liststore = gtk.ListStore(gdkpixbuf.Pixbuf, str, gdkpixbuf.Pixbuf, bool, bool, int, str, str, bool)
        
        self.treeview.set_model(self.liststore)
        self.treeview_selection = self.treeview.get_selection()
        self.treeview_selection.set_mode(gtk.SelectionMode.MULTIPLE)

        self.column_info = gtk.TreeViewColumn("Image")
        self.column_info.set_property('expand', True)
        self.column_url = gtk.TreeViewColumn("URL")
        self.column_status = gtk.TreeViewColumn("Status")
        self.treeview.append_column(self.column_info)
        self.treeview.append_column(self.column_url)
        self.treeview.append_column(self.column_status)

        cellrenderer_preview = gtk.CellRendererPixbuf()
        cellrenderer_title = gtk.CellRendererText()
        self.column_info.pack_start(cellrenderer_preview, False)
        self.column_info.pack_start(cellrenderer_title, True)
        self.column_info.add_attribute(cellrenderer_preview, 'pixbuf', 0)
        self.column_info.add_attribute(cellrenderer_title, 'text', 1)

        cellrenderer_url = gtk.CellRendererText()
        self.column_url.pack_start(cellrenderer_url, True)
        self.column_url.add_attribute(cellrenderer_url, 'markup', 7)

        cellrenderer_spinner = gtk.CellRendererSpinner()
        self.column_status.pack_end(cellrenderer_spinner, False)
        self.column_status.add_attribute(cellrenderer_spinner, 'visible', 3)
        self.column_status.add_attribute(cellrenderer_spinner, 'active', 3)
        self.column_status.add_attribute(cellrenderer_spinner, 'pulse', 5)

        cellrenderer_status = gtk.CellRendererPixbuf()
        self.column_status.pack_end(cellrenderer_status, False)
        self.column_status.add_attribute(cellrenderer_status, 'pixbuf', 2)
        self.column_status.add_attribute(cellrenderer_status, 'visible', 4)

        self.window.show_all()

        self.count = 0
        gobject.timeout_add(100, self.pulse, self.liststore, self.column_status, cellrenderer_spinner)

        for arg in args:
            self.add_image(arg)
            
    @property
    def selected_images(self):
        return self.treeview.get_selection().get_selected_rows()[1]


    def copy_url_cb(self, source):
        data = ''

        for row in self.selected_images:
            data += '\n' + self.liststore[row][7].replace('<tt>', '').replace('</tt>', '')

        clipboard = gtk.Clipboard.get(gdk.atom_intern('CLIPBOARD', True))
        clipboard.set_text(data.strip(), -1)


    def context_menu_cb(self, source, event):

        if event.button == 3:
            x = int(event.x)
            y = int(event.y)
            path_info = self.treeview.get_path_at_pos(x, y)
            if path_info is not None:
                path, col, cellx, celly = path_info
                if not path in self.selected_images:
                    self.treeview.set_cursor(path, col, 0)
                if self.liststore[path][4]:
                    self.copy_item.set_property('sensitive', True)
                else:
                    self.copy_item.set_property('sensitive', False)
                self.context_menu.popup(None, None, None, None, event.button, event.time)
            return True

        elif event.button == 1 and event.type == gdk.EventType._2BUTTON_PRESS:
            x = int(event.x)
            y = int(event.y)
            path_info = self.treeview.get_path_at_pos(x, y)
            if path_info is not None:
                path, col, cellx, celly = path_info

                if self.liststore[path][4]:
                    url = self.liststore[self.selected_images[0]][7]
                    url = url.replace('<tt>', '').replace('</tt>', '')
                    webbrowser.open(url)


    def drag_motion_cb(self, source, context, x, y, time):
        context.drag_status(gdk.DragAction.MOVE, time)
        return True

    def drag_drop_cb(self, source, context, x, y, time):
        if 'text/uri-list' in context.targets:
            source.drag_get_data(context, 'text/uri-list', time)
        return True

    def drag_data_cb(self, source, context, x, y, data, info, time):
        for uri in data.get_uris():
            path = unquote(uri).replace('file://', '')
            filename = os.path.split(path)[0]
            mimetype = mimetypes.guess_type(path)[0]

            if self.filefilter.filter((path, uri, filename, mimetype)):
                self.add_image(path)

        context.finish(True, False, time)



    def upload(self):
        thread.start_new_thread(self._upload, ())


    def _upload(self):

        for image in self.liststore:
            if image[4]:
                continue

            #gtk.gdk.threads_enter()
            image[3] = True
            #gtk.gdk.threads_leave()

            data = self.imgur.upload(image[6])

            #gtk.gdk.threads_enter()
            image[7] = "<tt>{0}</tt>".format(data['rsp']['image']['imgur_page'])
            image[3] = False
            image[4] = True
            #gtk.gdk.threads_leave()


    def pulse(self, liststore, column, spinner):

        self.count+=1
        
        for item in liststore:
            item[5] = self.count

        return True


    def add_image_cb(self, source):

        res = self.filechooser.run()
        self.filechooser.hide()

        if res == 1:
            filenames = self.filechooser.get_filenames()
            for filename in filenames:
                self.add_image(filename)


    def remove_image_cb(self, source):

        selection = self.treeview_selection.get_selected_rows()[1]

        for row in selection:
            if self.liststore[row][3]:
                self.treeview_selection.unselect_path(row)

        selection = self.treeview_selection.get_selected_rows()[1]

        if not selection:
            return

        while selection:
            row = selection[0]
            self.liststore.remove(self.liststore.get_iter(row))
            selection = self.treeview_selection.get_selected_rows()[1]


    def add_image(self, image_path):
        thread.start_new_thread(self._add_image, (image_path,))


    def _add_image(self, image_path):

        icon = gdkpixbuf.Pixbuf.new_from_file(image_path)
        width = icon.get_width()
        height = icon.get_height()
        factor = float(width) / float(height)

        icon = icon.scale_simple(int(20 * factor), 20, gdkpixbuf.InterpType.BILINEAR)

        #gtk.gdk.threads_enter()
        self.liststore.append((icon, os.path.basename(image_path), self.icon_done, False, False, 0, image_path, '', True))
Example #12
0
 def create_imgur_album(self, image_urls):
     album_link = Imgur().upload_images_to_album(image_urls)
     return album_link
Example #13
0
import pyimgur, tweepy, sys, pymysql
from datetime import date
from imgur import Imgur
from database import Database
from twitter import Twitter
from fractal import Fractal

# Generate the Fractal of the Day
fract = Fractal()
fract.generate(fotd=True)

# Upload
im = Imgur()
image = im.api.upload_image("fotd.png",
                            title="Fractal of the day (1080p) - " +
                            str(date.today()))
print(image.title)
print(image.link)
print(image.size)
print(image.type)
print "deletion link: imgur.com/delete/" + str(image._delete_or_id_hash)

if image.link == "":
    print("no link")
    sys.exit(0)

# Log the Fractal of the Day
db = Database()
db.log_fotd(image.link, image._delete_or_id_hash, image.size)

# Tweet
Example #14
0
def posts():
    form = QuickPost()
    url = form.link.data
    random = form.random.data
    user = current_user.get_id()
    collection = app.config['POSTS_COLLECTION']
    print url
    regex_http = re.compile(r'^(?:http|ftp)s?://')
    if request.method == 'POST' and request.files['file']:
        print 'upload to imgur'
        file = request.files['file']
        if file and allowed_file(file.filename):
            collection = app.config['POSTS_COLLECTION']
            filename = secure_filename(file.filename)
            g = os.path.join(app.config['DIR_PATH'],
                             app.config['UPLOAD_FOLDER'])
            sav = file.save(os.path.join(g, filename))
            user = current_user.get_id()
            _id = app.config['IMGUR_ID']
            _secret = app.config['IMGUR_SECRET']
            tags = ['External', 'Imgur']
            try:
                img = Imgur(_id, _secret)
                f = img.Image_Upload(os.path.join(g, filename))
                entry_make = "<img src=%s><br><a href='%s' target='_blank'>%s</a>" % (
                    f['link'], f['link'], f['link'])
                try:
                    collection.insert({
                        "title": f['id'],
                        "entry": entry_make,
                        "user": user,
                        "created_on": datetime.datetime.now(),
                        "tags": tags
                    })
                    os.remove(os.path.join(g, filename))
                    print 'file deleted'
                    return redirect(url_for('posts'))
                except:
                    flash("Something went bad....", category='error')
            except:
                flash("Something went bad...on imgur", category='error')

    if request.method == 'POST' and regex_http.findall(url):
        print 'checking if user is OK'
        if current_user.is_authenticated() and url != None:
            print 'User is OK'
            handle_posts(url)

    if request.method == 'POST' and random:
        entry_make = random
        tags = ['Random', 'Quick']
        try:
            collection.insert({
                "title": 'Random',
                "entry": entry_make,
                "user": user,
                "created_on": datetime.datetime.now(),
                "tags": tags
            })
            return redirect(url_for('posts'))
        except:
            flash("Something went bad....", category='error')

    page, per_page, offset = get_page_items()
    count = app.config['POSTS_COLLECTION'].find().sort(u'_id', -1).count()
    p = app.config['POSTS_COLLECTION'].find().sort(
        u'_id', -1).limit(per_page).skip(offset)

    pagination = get_pagination(page=page,
                                per_page=per_page,
                                total=count,
                                record_name='posts')
    return render_template('posts.html',
                           posts=p,
                           pagination=pagination,
                           form=form)