Skip to content

Instantly share code, notes, and snippets.

@techscientist
Forked from Scarygami/autoenhance.py
Created November 2, 2015 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techscientist/b561add64a46ae8bb25a to your computer and use it in GitHub Desktop.
Save techscientist/b561add64a46ae8bb25a to your computer and use it in GitHub Desktop.
Simple command-line tool to autoenhance photos via Google+.
#!/usr/bin/python
#
# Copyright 2013 Gerwin Sturm, FoldedSoft e.U.
# www.foldedsoft.at / google.com/+GerwinSturm
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# Some parts adapted from sample code of the
# Google APIs Client Library for Python
# Copyright (C) 2013 Google Inc.
# Licensed under the Apache License, Version 2.0
"""Simple command-line tool to autoenhance photos via Google+.
To run this sample you will need the Google APIs Client Library for Python
Installation instructions here:
https://developers.google.com/api-client-library/python/start/installation
You will also need to set up a project in the APIs Console (or Cloud console)
https://code.google.com/apis/console or https://cloud.google.com/console
and create credentials for an "Installed applications".
You can then download a client_secrets.json and place it in the same folder
as this script.
"""
import httplib2
import json
import os
import sys
from argparse import ArgumentParser
from oauth2client import client
from oauth2client import file
from oauth2client import tools
UPLOAD_URL = ("https://picasaweb.google.com/data/feed/api" +
"/user/default/albumid/default?alt=json")
def main(argv):
# tools.argparser from the Google APIs Client Library for Python
# includes additional parameters to handle the authentication flow
arg_parser = ArgumentParser(parents=[tools.argparser])
arg_parser.add_argument("-o", "--output", default="output",
help="Output folder to place autoenhanced photos")
arg_parser.add_argument("input", metavar="DIR",
help="Folder with JPG images to autoenhance")
args = arg_parser.parse_args()
if not os.path.exists(args.output):
try:
os.makedirs(args.output)
except:
arg_parser.error("Couldn't create/find output directory.")
sys.exit(1)
# Name of a file containing the OAuth 2.0 information for this
# application, including client_id and client_secret, which are found
# on the API Access tab on the Google APIs Console.
client_secrets = os.path.join(os.path.dirname(__file__),
"client_secrets.json")
# Set up a Flow object to be used if we need to authenticate.
flow = client.flow_from_clientsecrets(client_secrets,
scope="https://picasaweb.google.com/data/",
message=tools.message_if_missing(client_secrets))
# Prepare credentials, and authorize HTTP object with them.
# If the credentials don't exist or are invalid run through the native client
# flow. The Storage object will ensure that if successful the good
# credentials will get written back to a file.
storage = file.Storage("autoenhance.dat")
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = tools.run_flow(flow, storage, args)
http = credentials.authorize(http=httplib2.Http())
files = os.listdir(args.input)
for filename in files:
# We only handle JPG files
if filename.upper().endswith(".JPG") or filename.upper().endswith(".JPEG"):
# Try to image data from file
image_data = None
try:
with open(os.path.join(args.input, filename), mode='rb') as image:
image_data = image.read()
except:
print("%s skipped, couldn't open file" % filename)
if image_data is not None:
# Upload photo to Picasa/Google+ in the private Dropbox/Default album
headers = {}
headers["Content-Type"] = "image/jpeg"
headers["Slug"] = filename
response, content = http.request(UPLOAD_URL, method="POST",
body=image_data, headers=headers)
result_data = json.loads(content)
if "entry" in result_data:
# Upload successful, download the photo again
thumbnail = result_data["entry"]["media$group"]["media$thumbnail"][0]
url = thumbnail["url"].replace("/s72/", "/s5000/")
response, content = http.request(url)
# save the photo data to the output folder
# (might want to check response for errors first)
with open(os.path.join(args.output, filename), 'wb') as output_file:
output_file.write(content)
print("%s autoenhanced successfully." % filename)
# Delete photo from Picasa again
headers = {}
headers["If-Match"] = "*"
http.request(result_data["entry"]["id"]["$t"],
method="DELETE", headers=headers)
sys.exit(0);
if __name__ == '__main__':
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment