#!/clair/bklimt/bin/python2.4
import re
import pg
import os

photos = []
label_map = {}

class Photo:
	def __repr__(self):
		return 'Photo(id=%d, url=%s, keywords=%s, tmstamp=%s)' % (
			`self.id`,
			`self.url`,
			`self.keywords`,
			`self.tmstamp`
		)

query = """
	select
		blog_photo.id as id,
		blog_photo.keywords as keywords,
		blog_photo.url as url,
		blog_photo_page.tmstamp
	from
		blog_photo,
		blog_photo_page
	where
		blog_photo.deleted is null
		and blog_photo.page_id = blog_photo_page.id
	order by
		blog_photo_page.tmstamp,
		blog_photo.id
"""

conn = pg.connect('blog')
rs = conn.query(query)
results = rs.dictresult()
for record in results:
	photo = Photo()
	photo.id = record['id']
	photo.tmstamp = record['tmstamp']
	photo.url = record['url']
	photo.filename = 'photos/%s.jpg' % photo.id
	photo.keywords = record['keywords'].split()
	for keyword in photo.keywords:
		if keyword not in label_map:
			label_map[keyword] = []
		label_map[keyword] = label_map[keyword] + [len(photos)]
	photos = photos + [photo]
conn.close()

f = file('labeled_faces/matches.html')
for line in f.readlines():
	match = re.compile('<!-- MAP: ([0-9]*) -> ([0-9]*) -->').search(line)
	if match is not None:
		oldid = int(match.group(1))
		newid = int(match.group(2))
		for photo in photos:
			if photo.id == oldid:
				photo.face_id = newid
				photo.faces = []
				photo.face_ids = []
				faces_cmd = 'ls scaled_faces/bw/%s_* >/tmp/faces_tmp.txt 2>/dev/null' % newid
				os.system(faces_cmd)
				f2 = file('/tmp/faces_tmp.txt')
				for line2 in f2.readlines():
					photo.faces = photo.faces + [line2.strip()]
					photo.face_ids = photo.face_ids + [line2.strip().split('/')[-1].split('.')[0]]
f.close()

