Commits

Sergey Astanin  committed 6a46911

Refactor.

  • Participants
  • Parent commits da531ee

Comments (0)

Files changed (1)

-#!/usr/bin/env python2
+#!/usr/bin/env python
 from __future__ import with_statement
 
 from cgi import escape
 from string import Template
 from sys import argv, version_info, exit
 from xml.etree import ElementTree as ET
-import pickle
+# import pickle
 import warnings
 
-# warnings.filterwarnings("ignore",".*DeprecationWarning:.*")
+# for md5 in flickrapi
+warnings.filterwarnings("ignore", category=DeprecationWarning)
 from flickrapi import FlickrAPI
 
-# create file ~/.flickrapi_keys with two variables or define them here
-KEYS = dict([[w.strip(' "').rstrip(' "') for w in l.strip().split("=",1)]
-             for l in file(expanduser("~/.flickrapi_keys")).readlines()])
-KEY = KEYS["KEY"]
-SECRET = KEYS["SECRET"]
-USERNAME = argv[1]
+USAGE = """embedall.py username
 
-flck = FlickrAPI(KEY, SECRET)
-(token, frob) = flck.get_token_part_one(perms='read')
-if not token: raw_input("Press ENTER after you authorized this program")
-flck.get_token_part_two((token, frob))
+Create an HTML index in the local directory for each photoset of the
+user username.  Flickr API keys should be available in ~/.flickrapi_keys file.
+"""
 
-resp = flck.people_findByUsername(username=USERNAME)
-nsid = resp.find("user").get("nsid")
-
-resp = flck.photosets_getList(user_id=nsid)
-psets = [ (ps.get("id"), ps.findtext(".//title"), ps.findtext(".//description"))
-          for ps in resp.findall(".//photoset") ]
-pickle.dump(psets, file("resp.pkl", "w"))
+# Create file ~/.flickrapi_keys with keys
+# ----
+# KEY = 12345678901234567890123456789012
+# SECRET = 1234567890123456
+# ----
+# or define them inline.
+# To get a key, see http://www.flickr.com/services/api/misc.api_keys.html 
+KEY = ""
+SECRET = ""
 
 INDEX_HTML=Template(u"""<!DOCTYPE html>
 <html><head><title>Photosets of $user</title></head>
     </figcaption>
 </figure>""")
 
-def is_large(elm, label="Large"):
-    return elm.get("label") == label
-def is_orig(elm):
-    return is_large(elm, label="Original")
+def authorize():
+    "Connect to Flickr and authorize."
+    global KEY, SECRET
+    if not KEY or not SECRET:
+        ls = file(expanduser("~/.flickrapi_keys")).readlines()
+        d  = dict([[w.strip(' "') for w in l.strip().split("=",1)]
+                  for l in ls ])
+        KEY = d["KEY"]
+        SECRET = d["SECRET"]
+    flck = FlickrAPI(KEY, SECRET)
+    (token, frob) = flck.get_token_part_one(perms='read')
+    if not token: raw_input("Press ENTER after you authorized this program")
+    flck.get_token_part_two((token, frob))
+    return flck
 
-links = [ LINK_HTML.substitute(url=id + ".html", title=ttl)
-          for id,ttl,desc in psets ]
-index_html = INDEX_HTML.substitute(user=USERNAME,links="\n".join(links))
-print >>file("index.html", "w"), index_html.encode("utf8")
+def get_photosets(flickr, username):
+    "Fetch a list of username's photosets: [(photoset_id, title, description)]"
+    if "@N" in username:  # likely an nsid
+        nsid = username
+    elif "@" in username:  # likely an e-mail
+        resp = flickr.people_findByEmail(username=username)
+        nsid = resp.find("user").get("nsid")
+    else:  # likely a username
+        resp = flickr.people_findByUsername(username=username)
+        nsid = resp.find("user").get("nsid")
+    resp = flickr.photosets_getList(user_id=nsid)
+    psets = [ (ps.get("id"), ps.findtext(".//title"), ps.findtext(".//description"))
+              for ps in resp.findall(".//photoset") ]
+    return psets
 
-for ps_id, ps_title, ps_desc in psets:
-    print "photoset:", ps_id
+def get_largest(resp, szs=["Large","Medium 640","Medium","Small","Thumbnail"]):
+    "Process getSizes' response. Find the largest available size of the image."
+    def is_size(elm, size="Large"):
+        return elm.get("label") == size
+    elms = resp.findall(".//size")
+    for sz in szs:
+        found = [ s for s in elms if is_size(s, sz) ]
+        if found:
+           return found[0]
+    return None
+
+def write_index(psets, username):
+    "Write index.html where all photosets are listed."
+    global LINK_HTML, INDEX_HTML
+    links = [ LINK_HTML.substitute(url=id + ".html", title=ttl)
+              for id,ttl,desc in psets ]
+    index_html = INDEX_HTML.substitute(user=username,links="\n".join(links))
+    with file("index.html", "w") as out:
+        print >>out, index_html.encode("utf8")
+
+def write_photoset_index(flickr, pset):
+    "Write photoset_id.html where all set photos are embedded."
+    global PHOTO_HTML, HTML
+    ps_id, ps_title, ps_desc = pset
     ps_desc = ps_desc.replace("\n", "<br>")
-    resp = flck.photosets_getPhotos(photoset_id=ps_id)
+    resp = flickr.photosets_getPhotos(photoset_id=ps_id)
     photos = [ (p.get("id"), p.get("title")) for p in resp.findall(".//photo") ]
     def gen_photo_html((p_id, p_title)):
-        resp = flck.photos_getSizes(photo_id=p_id)
-        large = filter(is_large,resp.findall(".//size"))[0]
-        orig = filter(is_orig,resp.findall(".//size"))[0]
-        resp = flck.photos_getInfo(photo_id=p_id)
-        desc = resp.findtext(".//description")
+        resp = flickr.photos_getSizes(photo_id=p_id)
+        large = get_largest(resp)
+        orig = get_largest(resp, ["Original","Large","Medium 640","Medium"])
+        resp = flickr.photos_getInfo(photo_id=p_id)
+        desc = resp.findtext(".//description").replace("\n", "<br>")
         p_html = PHOTO_HTML.substitute(src=large.get("source"),
-                                       alt=p_title, title=p_title,
-                                       width=large.get("width"),
-                                       height=large.get("height"),
-                                       caption=p_title, desc=desc,
-                                       orig_src=orig.get("source"))
+                   alt=p_title, title=p_title, width=large.get("width"),
+                   height=large.get("height"), caption=p_title, desc=desc,
+                   orig_src=orig.get("source"))
         return p_html
     photos_html = u"\n\n".join(map(gen_photo_html, photos))
     with file(str(ps_id) + ".html", "w") as out:
         html = HTML.substitute(title=ps_title,desc=ps_desc,photos=photos_html)
         print >>out, html.encode("utf8")
 
+def main():
+    global USAGE
+    if len(argv) != 2 or "-h" in argv or "--help" in argv:
+        print USAGE
+        exit(0)
 
+    flck = authorize()
+    username = argv[1]
+    psets = get_photosets(flck, username)
+    write_index(psets, username)
+    for pset in psets:
+        print "photoset:", pset[0], pset[1]
+        write_photoset_index(flck, pset)
+
+if __name__ == "__main__":
+    main()