Example #1
0
    def generate_meme(cls,
                      output_path,
                      image_path=None,
                      body=None,
                      author=None):
        """ Generate a meme given an path and a quote """
        img = None
        quote = None

        if image_path is None:
            imgs = cls.__get_images()
            img = random.choice(imgs)
        else:
            img = image_path

        if body is None:
            quotes = cls.__get_quotes()
            quote = random.choice(quotes)
        else:
            if author is None:
                raise Exception('Author Required if Body is Used')
            quote = QuoteModel(author, body)

        meme = MemeEngine(output_path)
        path = meme.make_meme(img, quote.body, quote.author)

        return path
Example #2
0
def generate_meme(path=None, body=None, author=None):
    """ Generate a meme given an path and a quote """
    img = None
    quote = None

    if path is None:
        images = './_data/photos/dog/'
        imgs = []
        for root, dirs, files in os.walk(images):
            imgs = [os.path.join(root, name) for name in files]

        img = random.choice(imgs)
    else:
        img = path[0]

    if body is None:
        quote_files = [
            './_data/DogQuotes/DogQuotesTXT.txt',
            './_data/DogQuotes/DogQuotesDOCX.docx',
            './_data/DogQuotes/DogQuotesPDF.pdf',
            './_data/DogQuotes/DogQuotesCSV.csv'
        ]
        quotes = []
        for f in quote_files:
            quotes.extend(Ingestor.parse(f))

        quote = random.choice(quotes)
    else:
        if author is None:
            raise Exception('Author Required if Body is Used')
        quote = QuoteModel(body, author)

    meme = MemeEngine('./tmp')
    path = meme.make_meme(img, quote.body, quote.author)
    return path
Example #3
0
 def parse(cls, path:str) -> List[QuoteModel]:
     if not cls.can_ingest(path):
       raise Exception('cannot ingest extension')
     document = Document(path)
     quotes = []
     for para in document.paragraphs:
         if para.text != "":
             parse = para.text.split(' - ')
             quote = QuoteModel(parse[0],parse[1])
             quotes.append(quote)
     return quotes
Example #4
0
    def parse(cls, path: str) -> List[QuoteModel]:
        if not cls.can_ingest(path):
            raise Exception('cannot ingest exception')

        items = []
        df = pandas.read_csv(path, header=0)

        for _, row in df.iterrows():
            items.append(QuoteModel(*row))

        return items
Example #5
0
    def parse(cls, path: str) -> List[QuoteModel]:
        if not cls.can_ingest(path):
            raise Exception('cannot ingest extension')
        quotes = []
        df = pandas.read_csv(path, header=0)

        for index, row in df.iterrows():
            print(row)
            new_quote = QuoteModel(row['body'], row['author'])
            quotes.append(new_quote)

        return quotes
Example #6
0
    def parse(cls, path: str) -> List[QuoteModel]:
        if not cls.can_ingest(path):
            raise Exception('cannot ingest exception')

        with open(path, 'r') as f:
            items = []

            for line in f.readlines():
                try:
                    items.append(QuoteModel(*parse_text_line(line)))
                except IndexError as e:
                    pass

        return items
Example #7
0
    def parse(cls, path: str) -> List[QuoteModel]:
        if not cls.can_ingest(path):
            raise Exception('cannot ingest extension')
        file = open(path, "r", encoding="utf-8-sig")
        lines = file.readlines()
        file.close()
        quotes = []
        for quote in lines:
            parsed = quote.rstrip("\n").split(" - ")
            if len(parsed) > 1:
                body = parsed[0]
                author = parsed[1]
                new_quote = QuoteModel(body, author)
                quotes.append(new_quote)

        return quotes
Example #8
0
def meme_post():
    """Create a user defined meme."""
    image_url = request.form['image_url']
    text_body = QuoteModel(request.form['body'], request.form['author'])
    response = requests.get(image_url)
    path_temp = './temp/image_temp.png'

    # write a temp image to a disk
    with open(path_temp, 'wb') as write_temp_image:
        write_temp_image.write(response.content)

    # memo generation
    path = meme.make_meme(path_temp, text_body.body_text, text_body.author)

    # remove a temp image
    os.remove(path_temp)

    return render_template('meme.html', path=path)
Example #9
0
def meme_post():
    """Create a user defined meme."""
    # Get the user input
    img_url = request.form['image_url']
    quote = QuoteModel(request.form['body'], request.form['author'])
    # Save the image temporarily for generating a meme out of it.
    r = requests.get(img_url)
    path_tmp = './tmp/posted-image.png'
    with open(path_tmp, 'wb') as f:
        f.write(r.content)

    # Generate a meme based on user input.
    path = meme.make_meme(path_tmp, quote.body, quote.author)
    # path = url_for('static', filename="out/" + path)

    # Remove the temporary saved image:
    os.remove(path_tmp)

    return render_template('meme.html', path=path)
Example #10
0
def meme_post():
    """ Create a user defined meme """
    try:
        image_url = request.form['image_url']
        body = request.form['body']
        author = request.form['author']
    except:
        raise Exception('Bad request')

    quote = QuoteModel(body, author)

    r = requests.get(image_url, allow_redirects=True)
    img = f'./tmp/{random.randint(0, 100000000)}.jpg'
    open(img, 'wb').write(r.content)

    path = meme.make_meme(img, quote.body, quote.author)

    os.remove(img)

    return render_template('meme.html', path=path)
def meme_post():
    """Create a user defined meme."""
    image_url = request.form['image_url']
    file_type = image_url.split('.')[-1]
    accepted_file_types = ['jpg', 'png']
    if file_type not in accepted_file_types:
        raise Exception(f'Image file type must be {accepted_file_types}')

    r = requests.get(image_url)
    i = Image.open(BytesIO(r.content))
    tmp_file = f'./tmp_image_{random.randint(0, 100000000)}.{file_type}'
    i.save(tmp_file)

    body = request.form['body']
    author = request.form['author']
    quote = QuoteModel(body, author)
    path = meme.make_meme(tmp_file, quote.body, quote.author)

    os.remove(tmp_file)
    return render_template('meme.html', path=path)
Example #12
0
def generate_meme(path=None, body=None, author=None):
    """Inputs:
        path: str = path to image file
        body: str = body of a quote about art
        author: str = author of an art quote

        Returns path to .jpg meme of image combined with art quote"""

    img = None
    quote = None

    if path is None:
        path = "./data/ArtImages"
        imgs = []
        for root, _, files in os.walk(path):
            imgs = [os.path.join(root, name) for name in files]
        img = random.choice(imgs)
    else:
        img = path

    if body is None:
        quote_files = [
            "./data/ArtQuotes/ArtQuotesCSV.csv",
            "./data/ArtQuotes/ArtQuotesDOC.docx",
            "./data/ArtQuotes/ArtQuotesPDF.pdf",
            "./data/ArtQuotes/ArtQuotesTXT.txt",
        ]

        quotes = []
        for file in quote_files:
            quotes.extend(Importer.parse(file))

        quote = random.choice(quotes)
    else:
        if author is None:
            raise Exception("All quotes must have an author")
        quote = QuoteModel(body, author)

    meme = Meme("./static")
    meme_path = meme.make_meme(img, quote.body, quote.author)
    return meme_path
Example #13
0
def meme_post():
    """Create a user defined meme."""
    img_url = request.form['image_url']
    body = request.form['body']
    author = request.form['author']

    # Create quote
    quote = QuoteModel(body, author)

    # Save image in temp file
    image_content = requests.get(img_url, stream=True).content
    temp_path = './tmp/temp_img.jpg'
    open(temp_path, 'wb').write(image_content)

    # Create meme
    path = meme.make_meme(temp_path, quote.body, quote.author)

    # Remove the temporary saved image
    os.remove(temp_path)

    return render_template('meme.html', path=path)
Example #14
0
def meme_post():
    """ Create a user defined meme """
    image_url = request.form['image_url']
    body = request.form['body']
    author = request.form['author']

    if not validators.url(image_url):
        raise Exception("URL not valid")

    image = requests.get(image_url, allow_redirects=True)
    destination = f'./tmp/{random.randint(0, 100000000)}.jpg'

    if not os.path.exists('./tmp'):
        os.makedirs('./tmp')

    open(destination, 'wb').write(image.content)

    quote = QuoteModel.QuoteModel(body, author)
    path = meme.make_meme(destination, quote.body, quote.author)

    return render_template('meme.html', path=path)
def meme_post():
    """ Create a user defined meme """

    # 1. Use requests to save the image from the image_url
    #    form param to a temp local file.
    # 2. Use the meme object to generate a meme using this temp
    #    file and the body and author form paramaters.
    # 3. Remove the temporary saved image.

    image_url = request.form.get('image_url')
    r = requests.get(image_url)
    tmp = dir_path + '/' + str(random.randint(0, 100000000)) + '.png'
    with open(tmp, 'wb') as f:
        f.write(r.content)

    if request.form.get('body') != "" and request.form.get('author') != "":
        quote = QuoteModel(request.form.get('body'),
                           request.form.get('author'))
    else:
        quote = random.choice(quotes)
    path = meme.make_meme(tmp, quote.body, quote.author)
    # os.remove(tmp)
    print(path)
    return render_template('meme.html', path=path)
def meme_post():
    """ Create a user defined meme """

    # Read the form parameters
    img = request.form.get('image_url')
    body = request.form.get('body')
    author = request.form.get('author')

    temp_file = Path(f'./tmp/{random.randint(0, 100000000)}.png')
    temp_file.parent.mkdir(exist_ok=True)

    try:
        response = requests.get(img, allow_redirects=True)
        open(temp_file, 'wb').write(response.content)
    except RequestException:
        print("Can't accees the given image URL")

    # create the meme using the temporary downloaded image
    quote = QuoteModel(body, author)
    path = meme.make_meme(temp_file, quote.body, quote.author)

    temp_file.unlink(missing_ok=True)

    return render_template('meme.html', path=path)
Example #17
0
    def make_meme(self, img_path: str, text: str, author: str,
                  width=500) -> str:
        """Return a meme which is resized and contains a caption.

        Keyword Arguments:
            img_path (str) -- The file path to the image
            text (str) -- The quote body.
            author (str) -- The author of the quote.
            width (int) -- The width of the new image which is less than 500px.
        """
        try:
            f = open(img_path, 'r')
        except IOError:
            raise Exception('Invalid file path. Please enter a valid path.')
        else:
            f.close()

        im = Image.open(img_path)
        height = im.size[1]

        # Resize image
        assert width <= 500, f'Width must be less than 500px'
        ratio = width / float(im.size[0])
        height = int(ratio * float(height))
        meme_img = im.resize((width, height), Image.NEAREST)

        # Create font
        total_pixels = height*width
        font_size = int(total_pixels*0.0001)
        if font_size <= 10:
            font_size = 10
        fnt = ImageFont.truetype("./Fonts/arial.ttf", font_size)

        # Add quote and author to image
        draw = ImageDraw.Draw(meme_img)
        quote = QuoteModel(text, author)

        # Randomly choosing coordinates to place the text that is dynamic
        rand_width = randint(0, width)
        rand_height = randint(0, height)

        width_anchor = 'l'
        height_anchor = 't'

        if rand_width >= width*.75:
            width_anchor = 'r'
        elif rand_width >= width*.25:
            width_anchor = 'm'
        if rand_height >= height*.75:
            height_anchor = 'b'
        elif rand_height >= height*.25:
            height_anchor = 'm'

        anchor = width_anchor + height_anchor

        draw.text((rand_width, rand_height), str(quote), anchor=anchor,
                  font=fnt)

        # Output meme image
        output_filename = 'meme_' + img_path.split('/')[-1]
        output_path = self.output_dir + '/' + output_filename
        meme_img.save(output_path)
        return output_path