photoalbum: rewote to use the image object
[treecutter.git] / xinclude / photoalbum.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 import os
5 import sys
6 import glob
7 from shutil import rmtree,copytree
8 from lxml import etree
9 from lxml.builder import ElementMaker
10 from treecutter.image import Image
11
12 from treecutter import constants as const
13
14 class PhotoAlbum(object):
15     def __init__(self, uri):
16         self.uri = unicode(uri)
17         self.albumid = abs(hash(self.uri))
18         self.filelist = []
19
20     def files(self):
21         d = self.uri
22         for root, subdir, files in os.walk(d):
23             for f in files:
24                 img = Image(os.path.join(root,f))
25                 if not img.generated():
26                     self.filelist.append(img)
27
28     def db_xml(self):
29         db = ElementMaker(namespace=const.DB_NS, nsmap=const.NSMAP)
30         sl = db.itemizedlist(**{const.XML+"id": "slider"})
31         cnt = 0
32         for img in self.filelist:
33             cnt = cnt + 1
34             caption = db.caption()
35             for p in img.caption().split('\n\n'):
36                 caption.append(db.para(p))
37             link = db.para(db.link(img.infostr(),
38                                    **{const.XLINK+"href": img.filename()}))
39             caption.append(link)
40             sl.append(
41                 db.listitem(db.mediaobject(
42                         db.imageobject(db.imagedata(fileref=img.slider())),caption),
43                             **{const.XML+"id": "p%x%d" % (self.albumid,cnt)}))
44
45         th = db.itemizedlist(**{const.XML+"id": "thumb"})
46         cnt = 0
47         for img in self.filelist:
48             cnt = cnt + 1
49             th.append(db.listitem(db.para(db.link(db.inlinemediaobject(
50                         db.imageobject(db.imagedata(fileref=img.thumbnail()))),**{const.XLINK+"href": "#p%x%d" % (self.albumid, cnt)}))))
51         return db.informalfigure(sl,th,**{const.XML+"id": "box"})
52
53 def recursively_empty(e):
54     if e.text:
55         return False
56     return all((recursively_empty(c) for c in e.iterchildren()))
57
58 def clean_db(xml):
59     context = etree.iterwalk(xml)
60     for action, elem in context:
61         parent = elem.getparent()
62         if recursively_empty(elem):
63             parent.remove(elem)
64
65 if __name__ == "__main__":
66     for arg in sys.argv[1:]:
67         al = arg.split("=",1)
68         if al[0] == "lang":
69             lang = al[1]
70         if al[0] == "xptr":
71             argument = al[1]
72
73     album = PhotoAlbum(argument)
74     album.files()
75     axml = album.db_xml()
76 #    clean_db(axml)
77
78     #print(etree.tostring(cxml, pretty_print=True))
79     #sys.stderr.write(axml.encode('utf-8'))
80     #sys.stderr.write(etree.tostring(axml,encoding='UTF-8',pretty_print=True))
81     sys.stdout.write(etree.tostring(axml,encoding='UTF-8',pretty_print=True))