caption: add a captioning script.
authorW. Trevor King <wking@tremily.us>
Sun, 30 Sep 2012 01:04:37 +0000 (21:04 -0400)
committerW. Trevor King <wking@tremily.us>
Sun, 30 Sep 2012 01:08:44 +0000 (21:08 -0400)
posts/gallery/caption.py [new file with mode: 0755]

diff --git a/posts/gallery/caption.py b/posts/gallery/caption.py
new file mode 100755 (executable)
index 0000000..3187efa
--- /dev/null
@@ -0,0 +1,71 @@
+#!/usr/bin/python
+#
+# Copyright (C) 2012 W. Trevor King <wking@drexel.edu>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+"""Iterate through directories with `*.jpg`s, adding captions.
+"""
+
+import mailcap as _mailcap
+import mimetypes as _mimetypes
+import shlex as _shlex
+import pipes as _pipes
+_shlex.quote = _pipes.quote  # http://bugs.python.org/issue9723
+import subprocess as _subprocess
+import os as _os
+import os.path as _os_path
+
+
+_CAPS = _mailcap.getcaps()  # from mailcap-test.py
+EDITOR = _shlex.split(_os.environ['EDITOR'])
+
+def view(filename, mime=None):
+    if mime is None:
+        mime,encoding = _mimetypes.guess_type(filename)
+        if mime is None:
+            raise NotImplementedError(filename)
+    match = _mailcap.findmatch(_CAPS, mime, filename=_shlex.quote(filename))
+    if match[0] is None:
+        raise NotImplementedError(mime)
+    return _subprocess.Popen(match[0], shell=True, close_fds=True)
+
+def caption(path, recursive=False):
+    if recursive:
+        for dirpath,dirnames,filenames in _os.walk(path):
+            for filename in sorted(filenames):
+                r,extension = _os_path.splitext(filename)
+                if extension in ['.jpg', '.png']:
+                    p = _os_path.join(dirpath, filename)
+                    caption(p)
+    else:
+        caption_file = '{}.txt'.format(path)
+        if _os_path.exists(caption_file):
+            return
+        command = EDITOR + [caption_file]
+        p1 = _subprocess.Popen(command, close_fds=True)
+        p2 = view(path)
+        p1.wait()
+        p2.wait()
+
+
+if __name__ == '__main__':
+    import sys
+
+    if len(sys.argv) < 2:
+        sys.argv.append('.')
+    for root in sys.argv[1:]:
+        root = _os_path.expanduser(root)
+        caption(path=root, recursive=True)