OSDN Git Service

add wp_imgswap2.py for new OSDN Magazine
[otptools/otptools.git] / sakura_imgswap.py
1 #!/usr/bin/env python
2 # -*- encoding: utf-8 -*-
3 #
4 # wp_imgswap.py : WordPress image tag swapper
5 #
6
7 import sys
8 import codecs
9 import re
10 import os.path
11 import hashlib
12
13 import htmltaglib
14 import deterfile
15 import getjpggeom
16
17 usage = """usage: %s <target file> <output_file> <image_dir> [link_prefix] [image_width]""" % (os.path.basename(sys.argv[0]),)
18
19 rex_imgtag = re.compile(r"""<img\s+src=["'](.*?)["'].*?>""")
20 rex_atag = re.compile(r"""<a\s+href=["'](.*?)["'].*?>""")
21 rex_alt = re.compile(r"""alt=["'](.*?)["']""")
22 rex_figuretag = re.compile(r"""<figure\s+style=["'](.*?)["'].*?>""")
23
24 try:
25     in_f = codecs.open(sys.argv[1], "r", "utf_8" )
26     out_f = codecs.open(sys.argv[2], "w", "utf_8" )
27     image_dir = sys.argv[3]
28 except IndexError:
29     sys.exit(usage)
30
31 try:
32     image_width = int(sys.argv[4])
33 except IndexError:
34     image_width = 440
35
36
37 def _get_png_geom(filepath):
38     s = filepath.split('.')
39     ext = s[-1]
40     if (ext == 'JPG') or (ext == 'jpg'):
41         (w, h) = getjpggeom.get_jpeg_geometory(filepath)
42         return (w, h)
43     else:
44         desc = deterfile.file(filepath)
45
46     try:
47         m = re.match(r"([0-9]+)\s*x\s*([0-9]+)", desc[1])
48     except IndexError:
49         err = ", ".join(desc)
50         raise Exception("deterfile error: %s, file: %s . " % (err,filepath))
51     if m:
52         w = m.group(1)
53         h = m.group(2)
54         return (int(w), int(h))
55     else:
56         return None
57
58
59 def replace_img_tag(line, tagstr, path):
60     if not os.path.isfile(path):
61         return line
62
63     attrs = htmltaglib.parse_attributes(tagstr)
64     (root, ext) = os.path.splitext(os.path.basename(path))
65
66     filename = ""
67     if 'width' in attrs:
68         (w, h) = _get_png_geom(path)
69         if int(w) > image_width:
70             attrs['height'] = str(int(round(float(h) * float(image_width) / float(w))))
71             attrs['width'] = str(image_width)
72             filename = '''%s-%sx%s%s''' % (root, attrs['width'], attrs['height'], ext)
73         else:
74             attrs['height'] = str(h)
75             attrs['width'] = str(w)
76             filename = '''%s%s''' % (root, ext)
77
78     wp_image_url = '''%s%s''' % (image_dir, filename)
79     attrs['src'] = wp_image_url
80         # if tag has 'alt' attribute, use it
81     if rex_alt.search(tagstr):
82         alt_text = rex_alt.search(tagstr).group(1)
83         attrs['alt'] = alt_text
84     
85     new_tag_str = htmltaglib.build_tag('img', attrs)
86     return line.replace(tagstr, new_tag_str)
87
88 def replace_a_tag(line, tagstr, path):
89     if not os.path.isfile(path):
90         return line
91
92     attrs = htmltaglib.parse_attributes(tagstr)
93     wp_image_url = image_dir + os.path.basename(path)
94 #    (root, ext) = os.path.splitext(os.path.basename(path))
95 #    wp_image_url = link_prefix + "/" + root
96     attrs['href'] = wp_image_url
97     new_tag_str = htmltaglib.build_tag('a', attrs)
98
99     return line.replace(tagstr, new_tag_str)
100
101 for line in in_f:
102     # proc for IMG tag
103     match = rex_imgtag.search(line)
104     if match:
105         tagstr = match.group(0)
106         path = match.group(1)
107         line = replace_img_tag(line, tagstr, path)
108
109     #proc for A tag
110     match = rex_atag.search(line)
111     if match:
112         tagstr = match.group(0)
113         path = match.group(1)
114         line = replace_a_tag(line, tagstr, path)
115
116     print >> out_f, line,