#!/usr/bin/env python

"""contacttags: hacky script to get the top tags from contacts on flickr"""

import FlickrClient, sys, math

client = FlickrClient.FlickrClient(open('apikey').read(32))
userurl = sys.argv[1]
numtags = sys.argv[2]

user = client.flickr_urls_lookupUser(url='http://www.flickr.com/photos/' + userurl)
userinfo = client.flickr_people_getInfo(user_id = user('id'));
username = str(userinfo.realname)

contacts = client.flickr_contacts_getPublicList(user_id = user('id'));
alltags = {}
for peep in contacts:
  peepid = peep('nsid')
  sys.stderr.write("processing " + peepid + "\n")
  tags = client.flickr_tags_getListUserPopular(user_id = peepid, count=100)
  for tag in tags.tags:
    if alltags.has_key(str(tag)):
      alltags[str(tag)] += int(tag('count'))
    else :
      alltags[str(tag)] = int(tag('count'))

sys.stderr.write("ordering list\n")
items = alltags.items()
items.sort(lambda x,y: cmp(y[1],x[1]))
topitems = items[1:int(numtags)]
topitems.sort(lambda x,y: cmp(x[0],y[0]))

print "<html>"
print "<head>"
print "<title>Flickr tags from contacts of %s</title>" % username
print '<link rel="stylesheet" href="/2005/03/contacttags/tags.css" type="text/css" title="basic" media="screen, projection" />'
print "<body>"
print '<h1><a href="http://www.flickr.com">Flickr</a> tags from <a href="http://www.flickr.com/people/%s/contacts">contacts</a> of <a href="http://www.flickr.com/photos/%s/">%s</a></h1>' % (userurl,userurl,username)
print "<ul>"
for item in topitems:
  weight = int(math.log(item[1]))
  print "<li>" + ("<em>"*weight) + item[0] + ("</em>"*weight) + "</li>"
print "</body></html>"

