Skip to content

Instantly share code, notes, and snippets.

@Scarygami
Last active December 28, 2015 04:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Scarygami/7440126 to your computer and use it in GitHub Desktop.
Save Scarygami/7440126 to your computer and use it in GitHub Desktop.
Turn your Google+ albums into interactive tours. See [https://googledrive.com/host/0B1pwzJXH7GP8U0M1Ny1mRm5TT0E/] for a live result
#!/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.
"""Turn your Google+ albums into interactive tours.
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. Detailed instructions below.
Getting client_secrets from https://cloud.google.com/console
1. Create project
2. Go to "APIs & Auth" -> "Registered Apps"
3. Register App -> Native -> Register
4. Download JSON
5. Rename file to client_secrets.json and put it in the script folder
Getting client_secrets from https://code.google.com/apis/console:
1. Create project
2. Go to "API Access"
3. Create Client-ID -> Installed Application -> Other -> Create
4. Download JSON
5. Put client_secrets.json in the script folder
To run the script find the ID of the album you want.
If you open the album in Google+ the URL will look like
https://plus.google.com/photos/{your_user_id}/albums/{your_album_id}
You want the {your_album_id} part (long number).
Then run the script like this:
python autoawesome-tour.py {your_album_id}
If you have a location history file from Google Takeout
you can supply this file to the script to automatically
assign locations to the photos based on timestamps:
python autoawesome-tour.py --locations={your_location_file} {your_album_id}
"""
from __future__ import division
import codecs
import httplib2
import json
import os
import sys
from argparse import ArgumentParser
from datetime import datetime, timedelta
from oauth2client import client
from oauth2client import file
from oauth2client import tools
from operator import itemgetter
HTML = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>%s</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<script src="https://maps.google.com/maps/api/js?sensor=true"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="map_canvas"></div>
<div id="title">
<h1>%s by %s</h1>
<img src="%s">
<button id="start">Start</button>
</div>
<div id="info">
<img id="image" src="">
<div id="description"></div>
</div>
<div id="controls">
<button id="prev">Prev</button>
<button id="playpause">Pause</button>
<button id="next">Next</button>
</div>
<script src="tour.js"></script>
</body>
</html>
"""
CSS = """* { box-sizing: border-box; padding: 0; margin: 0; border: 0; }
html { height: 100%; }
body { height: 100%; font-family: sans-serif; }
#map_canvas {
position: absolute;
top: 0; left: 0;
height: 100%;
width: 100%;
}
#title {
position: absolute;
width: 640px;
background-color: rgba(255,255,255,0.8);
text-align: center;
top: 50px;
left: 50%;
margin-left: -320px;
}
#title img {
display: block;
}
button {
border: 2px solid black;
background-color: rgba(255,255,255,0.5);
font-size: 2em;
padding: 2px 5px;
border-radius: 10px;
cursor: pointer;
outline: none;
}
#start {
position: absolute;
bottom: 5px;
right: 5px;
}
#controls {
display: none;
position: absolute;
top: 5px;
right: 5px;
}
#info {
display: none;
position: absolute;
top: 5px;
left: 5px;
max-width: 45%;
}
#image {
display: block;
width: 100%;
}
#description {
bottom: 0;
left: 0;
width: 100%;
position: absolute;
background-color: rgba(255,255,255,0.5);
text-align: center;
padding: 2px;
font-weight: bold;
}
#start:hover {
background-color: rgba(255,255,255, 0.8);
}
"""
JS = """(function (global) {
"use strict";
var
google = global.google,
doc = global.document,
data, map, latlng, myOptions, position, marker,
info = doc.getElementById("info"),
image = doc.getElementById("image"),
description = doc.getElementById("description"),
start = doc.getElementById("start"),
title = doc.getElementById("title"),
controls = doc.getElementById("controls"),
playpause = doc.getElementById("playpause"),
next = doc.getElementById("next"),
prev = doc.getElementById("prev"),
polyLine, autoplay = false, timeout;
data = %s;
google.maps.visualRefresh = true;
latlng = new google.maps.LatLng(data.locations[0].latitude, data.locations[0].longitude);
myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID,
disableDefaultUI: true
};
map = new google.maps.Map(doc.getElementById("map_canvas"), myOptions);
marker = new google.maps.Marker({
position: latlng,
map: map,
title: data.locations[0].title || ""
});
polyLine = new google.maps.Polyline({
strokeColor: "black",
strokeOpacity: 1.0,
strokeWeight: 4,
map: map
});
function show_position() {
var img;
if (position >= data.locations.length) {
marker.setPosition(new google.maps.LatLng(data.locations[0].latitude, data.locations[0].longitude));
marker.setTitle(data.locations[0].title || "");
polyLine.setPath([]);
map.panTo(marker.getPosition());
info.style.display = "none";
controls.style.display = "none";
title.style.display = "block";
return;
}
img = new global.Image();
img.onload = function () {
var path;
image.src = img.src;
if (!!data.locations[position].title) {
description.textContent = data.locations[position].title;
description.style.display = "block";
} else {
description.textContent = "";
description.style.display = "none";
}
marker.setPosition(new google.maps.LatLng(data.locations[position].latitude, data.locations[position].longitude));
marker.setTitle(data.locations[position].title || "");
path = polyLine.getPath();
path.push(marker.getPosition());
map.panTo(marker.getPosition());
info.style.display = "block";
if (autoplay) {
position += 1;
timeout = global.setTimeout(show_position, 1000);
}
};
img.src = data.locations[position].image;
}
start.onclick = function () {
title.style.display = "none";
controls.style.display = "block";
playpause.textContent = "Pause";
next.style.visibility = "hidden";
prev.style.visibility = "hidden";
controls.getEl
position = 0;
polyLine.setPath([]);
autoplay = true;
show_position();
};
playpause.onclick = function () {
autoplay = !autoplay;
playpause.textContent = autoplay ? "Pause" : "Start";
next.style.visibility = autoplay ? "hidden" : "visible";
prev.style.visibility = autoplay ? "hidden" : "visible";
if (autoplay) {
show_position();
} else {
global.clearTimeout(timeout);
}
};
next.onclick = function () {
if (position < data.locations.length - 1) {
position += 1;
show_position();
}
};
prev.onclick = function () {
if (position > 0) {
position -= 1;
show_position();
}
};
}(this));
"""
def main(argv):
arg_parser = ArgumentParser(parents=[tools.argparser])
arg_parser.add_argument("-o", "--output", default="output", help="Output folder")
arg_parser.add_argument("-l", "--locations", help="Locations file from Google Takeout for mapping images")
arg_parser.add_argument("album", metavar="ALBUMID", help="Google+ Album ID")
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 %s" % args.output)
sys.exit(1)
if args.locations is not None:
if not os.path.isfile(args.locations):
arg_parser.error("Couldn't find locations file %s" % args.locations)
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("tour.dat")
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = tools.run_flow(flow, storage, args)
if credentials.access_token_expired:
credentials.refresh(http=httplib2.Http())
http = credentials.authorize(http=httplib2.Http())
album_url = ("https://picasaweb.google.com/data/feed/api" +
"/user/default/albumid/%s?alt=json") % args.album
print "Fetching album..."
response, content = http.request(album_url)
if response.status >= 400:
print "Error fetching album"
sys.exit(1)
data = json.loads(content)["feed"]
if len(data["entry"]) == 0:
print "No photos found in album"
sys.exit(1)
location_data = None
if args.locations is not None:
with open(args.locations) as data_file:
location_data = json.load(data_file)
if location_data is None or "locations" not in location_data or len(location_data["locations"]) == 0:
print "No locations found"
sys.exit(1)
print "Album retrieved, analysing photos..."
tour = {}
if "title" in data:
tour["title"] = data["title"]["$t"]
else:
tour["title"] = "Autowesome Tour"
if "author" in data:
tour["author"] = data["author"][0]["name"]["$t"]
if "icon" in data:
tour["image"] = data["icon"]["$t"].replace("/s160-c/","/s640/")
images = []
for entry in data["entry"]:
image = {}
if "exif$tags" in entry and "exif$time" in entry["exif$tags"]:
timestamp = int(entry["exif$tags"]["exif$time"]["$t"]) / 1000
else:
timestamp = int(entry["gphoto$timestamp"]["$t"]) / 1000
time = datetime.fromtimestamp(timestamp)
image["time"] = time
if "summary" in entry:
image["title"] = entry["summary"]["$t"]
image["image"] = entry["content"]["src"]
if "georss$where" in entry and "gml$Point" in entry["georss$where"]:
latitude, longitude = entry["georss$where"]["gml$Point"]["gml$pos"]["$t"].split(" ", 1)
image["latitude"] = float(latitude)
image["longitude"] = float(longitude)
images.append(image)
images.sort(key=itemgetter("time"))
min_date = images[0]["time"] - timedelta(hours=6)
max_date = images[-1]["time"] + timedelta(hours=6)
locations = []
if location_data is not None:
print "Geotagging photos..."
for location in location_data["locations"]:
time = datetime.fromtimestamp(int(location["timestampMs"]) / 1000)
if time > min_date and time < max_date:
new_location = {}
new_location["time"] = time
new_location["latitude"] = location["latitudeE7"] / 10000000
new_location["longitude"] = location["longitudeE7"] / 10000000
locations.append(new_location)
locations.sort(key=itemgetter("time"))
tour["locations"] = []
for image in images:
if "latitude" in image:
tour["locations"].append(image)
else:
if len(locations) > 0:
location = min(locations, key=lambda x:abs(x["time"] - image["time"]))
if abs(location["time"] - image["time"]) < timedelta(hours=1):
image["latitude"] = location["latitude"]
image["longitude"] = location["longitude"]
tour["locations"].append(image)
if len(tour["locations"]) == 0:
print "No suitable images/locations found"
sys.exit(1)
print "Creating tour..."
dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime) else None
with codecs.open(os.path.join(args.output, "index.html"), "w", "utf-8") as output_file:
output_file.write(HTML % (tour["title"], tour["title"], tour["author"], tour["image"]))
with codecs.open(os.path.join(args.output, "style.css"), "w", "utf-8") as output_file:
output_file.write(CSS)
with codecs.open(os.path.join(args.output, "tour.js"), "w", "utf-8") as output_file:
output_file.write(JS % json.dumps(tour, default=dthandler, indent=2, separators=(",", ": ")))
print "All done!"
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