Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
umahmood committed Nov 1, 2015
0 parents commit a56141f
Show file tree
Hide file tree
Showing 4 changed files with 213 additions and 0 deletions.
61 changes: 61 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Created by https://www.gitignore.io/api/python

### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover

# Translations
*.mo
*.pot

# Django stuff:
*.log

# Sphinx documentation
docs/_build/

# PyBuilder
target/
22 changes: 22 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
The MIT License (MIT)

Copyright (c) 2015 Usman Mahmood

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Random Imgur

Random Imgur is a python 3 script, which downloads random images from the popular
image hosting site [Imgur](https://imgur.com/).

It's like a box of chocolates. You never know what you're gonna get.

# Installation

> git clone https://github.com/umahmood/random-imgur.git && cd random-imgur
# Usage

To download 10 random images:

> python3 random-imgur.py --img=10
This will download all files into a directory named 'downloaded_imgurs'. To
specify a custom directory:

> python3 random-imgur.py --img=50 --dir="path/to/folder"
For help run:

> python3 random-imgur.py --h
# License

See the [LICENSE](LICENSE.md) file for license rights and limitations (MIT).

100 changes: 100 additions & 0 deletions random-imgur.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
import os
import sys
import random
import hashlib
import argparse

import requests
import requests.exceptions

def get_imgur_url():
"""
Builds an imgur url in the form http://i.imgur.com/{5 characters}.jpg.
@return: (tuple) - url (string), file name (string)
"""
imgur_url = "http://i.imgur.com/"
ext = ".jpg"
r1 = random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
r2 = random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
r3 = random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
r4 = random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
r5 = random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')

code = r1 + r2 + r3 + r4 + r5
file_name = code
full_url = imgur_url + file_name + ext

return (full_url, file_name)

def is_placeholder_image(img_data):
"""
Checks for the placeholder image. If an imgur url is not valid (such as
http//i.imgur.com/12345.jpg), imgur returns a blank placeholder image.
@param: img_data (bytes) - bytes representing the image.
@return: (boolean) True if placeholder image otherwise False
"""
sha256_placeholder = "9b5936f4006146e4e1e9025b474c02863c0b5614132ad40db4b925a10e8bfbb9"
m = hashlib.sha256()
m.update(img_data)
return m.hexdigest() == sha256_placeholder

def save_image(download_dir, file_name, file_ext, img_data):
"""
Saves an image to the download directory with a given file name and extension.
@param: img_data (bytes) - bytes representing the image.
@param: file_name (string) - name to the save the file as i.e. foo.jpg.
@param: download_dir (string) - path to the download directory.
@return: None
"""
try:
file_path = "{0}{1}{2}.{3}".format(download_dir, os.sep, file_name, file_ext)
with open(file_path, "wb") as f:
f.write(img_data)
except FileNotFoundError as e:
raise e

def download_imgur(url):
"""
Downloads an image from imgur.
@param: url (string) - Imgur url to download i.e. http://i.imgur.com/1a2b3c.jpg.
@return: None if the download fails else images binary data and content type.
"""
try:
r = requests.get(url)
if not r.ok:
return None
sub_type = r.headers["content-type"][6:] # turns image/gif to gif
file_type = "jpg" if sub_type not in ["gif", "webm", "png"] else sub_type
return r.content, file_type
except (exceptions.ConnectionError, exceptions.HTTPError) as e:
pass

def main(max_imgs, download_dir):
count = 0
while count < max_imgs:
imgur_url, file_name = get_imgur_url()
img_data, file_type = download_imgur(imgur_url)
if not img_data or is_placeholder_image(img_data):
continue
save_image(download_dir, file_name, file_type, img_data)
count += 1

if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Process command line arguments for " + __file__)
parser.add_argument('--img', type=int, required=True, nargs='?', help='number of images to download.')
parser.add_argument('--dir', type=str, default="downloaded_imgurs", nargs='?', help="download directory.")

args = parser.parse_args()

if not os.path.exists(args.dir):
os.mkdir(args.dir)

sys.exit(main(args.img, args.dir))

0 comments on commit a56141f

Please sign in to comment.