コード例 #1
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
コード例 #2
0
 def parse(cls, path: str) -> List[QuoteModel]:
     """ Parse CSV file and return list of QuoteModel objects """
     if (cls.can_ingest(path)):
         result = []
         df = pandas.read_csv(path, header=0)
         for index, row in df.iterrows():
             result.append(
                 QuoteModel(row['author'].strip(), row['body'].strip()))
         return result
     else:
         raise Exception("Cannot parse file, incorrect type")
コード例 #3
0
 def parse(cls, path: str) -> List[QuoteModel]:
     """ Parse docx file and return list of QuoteModel objects """
     if (cls.can_ingest(path)):
         result = []
         f = docx.Document(path)
         for line in f.paragraphs:
             if line.text != "":
                 meme = line.text.split("-")
                 result.append(QuoteModel(meme[1].strip(), meme[0].strip()))
         return result
     else:
         raise Exception("Cannot parse file, incorrect type")
コード例 #4
0
    def parse(cls, path: str) -> List[QuoteModel]:
        """Reads a csv file and returns a list of quotes."""
        if not cls.can_ingest(path):
            raise ValueError('Wrong file format')

        try:
            df = pd.read_csv(path)
            results = df.apply(lambda x: QuoteModel(x.body, x.author), axis=1)
            return list(results)
        except AttributeError:
            raise ValueError('Wrong file format')
        except PackageNotFoundError:
            raise FileNotFoundError
コード例 #5
0
    def parse(cls, path: str) -> List[QuoteModel]:
        """Reads a docx file and returns a list of quotes."""
        if not cls.can_ingest(path):
            raise ValueError('Wrong file format')

        try:
            document = Document(path)
            lines = [p.text for p in document.paragraphs]
            results = [
                QuoteModel.from_line(line) for line in lines if line != ''
            ]
            return results
        except PackageNotFoundError:
            raise FileNotFoundError(f'File not found or wrong format: {path}')
コード例 #6
0
    def parse(cls, path: str) -> List[QuoteModel]:
        """Reads a txt file and returns a list of quotes."""
        if not cls.can_ingest(path):
            raise ValueError('Wrong file format')

        result = []
        with open(path, 'r') as f:
            for row in f:
                if row.rstrip() != '':
                    try:
                        body, author = row.rstrip().split('-')
                        result.append(
                            QuoteModel(body.replace('"', ''),
                                       author.replace('"', '')))
                    except ValueError:
                        raise ValueError('Wrong file format')

        return result
コード例 #7
0
ファイル: meme.py プロジェクト: janroijen/meme-generator
def generate_meme(path=None, body=None, author=None):
    """
    Generate a meme

    Arguments:
        path {str} -- the path to the image file
        body {str} -- the quote body to be added to the image
        author {str} -- the author of the quote
    """
    img = None
    quote = None

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

        img = random.choice(imgs)
    else:
        img = path

    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 = MemeGenerator('./tmp')
    path = meme.make_meme(img, quote.body, quote.author)
    return path
コード例 #8
0
def generate_meme(path=None, body=None, author=None) -> str:
    """Generate a meme given an path and a quote.

    Arguments:
        path {str} -- file location for the input image.
        body {str} -- quote body.
        author {str} -- quote author.
    Returns:
        str -- file location for the output image.
    """
    img = ""
    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

    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)

    font_path = './_data/fonts/LilitaOne-Regular.ttf'
    meme = MemeEngine('./tmp', font_path)
    path = meme.make_meme(img, quote.body, quote.author)
    return path
コード例 #9
0
    def parse(cls, path: str) -> List[QuoteModel]:
        """ Parse PDF file and return list of QuoteModel objects """
        if (cls.can_ingest(path)):
            tmp = f'{random.randint(0,1000000)}.txt'
            call = subprocess.call(['pdftotext', path, tmp])
            file_ref = open(tmp, "r", encoding="utf-8-sig")
            result = []
            for line in file_ref.readlines():
                line = line.strip('\n\r').strip()
                if len(line) > 0:
                    parsed = line.split('-')
                    result.append(
                        QuoteModel(parsed[1].strip(), parsed[0].strip()))

            file_ref.close()
            os.remove(tmp)

            return result
        else:
            raise Exception("Cannot parse file, incorrect type")
コード例 #10
0
ファイル: MemeEngine.py プロジェクト: Projit32/MemeGenerator
    def make_meme(self, image, body, author, width=500) -> str:
        """Make the meme from image,body and author."""
        try:
            img = Image.open(image)
            aspect_ratio = img.width / img.height
            (new_width, new_height) = (500, int(500 * aspect_ratio))
            im = img.resize((new_width, new_height))

            quote = QuoteModel(body, author).__repr__()
            pos1 = random.randint(10, 50)
            pos2 = random.randint(10, 100)

            font = ImageFont.truetype("arial.ttf", 20)
            draw = ImageDraw.Draw(im)
            draw.text((pos1, pos2), text=quote, font=font)
            file_path = r'{}/{}.png'.format(self.out_path,
                                            random.randint(0, 1000))
            im.save(file_path)
            return file_path
        except Exception as e:
            raise Exception(e)
コード例 #11
0
def meme_post():
    """Create a user defined meme."""
    # @TODO:
    # 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')
    body = request.form.get('body')
    author = request.form.get('author')

    delete_image_flag = False
    if image_url == '':
        img = random.choice(imgs)
    else:
        extension = image_url.split('.')[-1].lower()
        r = requests.get(image_url, allow_redirects=True)
        tmp = f'./tmp/{random.randint(0, 9999999999999999)}.{extension}'
        open(tmp, 'wb').write(r.content)
        delete_image_flag = True
        img = tmp

    if body == '':
        quote = random.choice(quotes)
    else:
        if author == '':
            if delete_image_flag:
                os.remove(img)
            abort(Response('Author Required if Body is Used'))
        quote = QuoteModel(body, author)

    path = meme.make_meme(img, quote.body, quote.author)
    if delete_image_flag:
        os.remove(img)

    return render_template('meme.html', path=path)