OSDN Git Service

add wp_imgswap2.py for new OSDN Magazine
[otptools/otptools.git] / wp_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 import math
13
14 import htmltaglib
15 import deterfile
16 import getjpggeom
17
18 usage = """usage: %s <target file> <output_file> <image_dir> [link_prefix] [max_image_width] [max_image_height]""" % (os.path.basename(sys.argv[0]),)
19
20 rex_imgtag = re.compile(r"""<img\s+src=["'](.*?)["'].*?>""")
21 rex_atag = re.compile(r"""<a\s+href=["'](.*?)["'].*?>""")
22 rex_alt = re.compile(r"""alt=["'](.*?)["']""")
23 rex_figuretag = re.compile(r"""<figure\s+style=["'](.*?)["'].*?>""")
24
25 try:
26     in_f = codecs.open(sys.argv[1], "r", "utf_8" )
27     out_f = codecs.open(sys.argv[2], "w", "utf_8" )
28     image_dir = sys.argv[3]
29 except IndexError:
30     sys.exit(usage)
31
32 try:
33     link_prefix = sys.argv[4]
34 except IndexError:
35     link_prefix = ""
36
37 try:
38     max_image_width = float(sys.argv[5])
39 except IndexError:
40     max_image_width = 480.0
41
42 try:
43     max_image_height = float(sys.argv[6])
44 except IndexError:
45     max_image_height = 640.0
46
47 def _get_png_geom(filepath):
48     s = filepath.split('.')
49     ext = s[-1]
50     if (ext == 'JPG') or (ext == 'jpg'):
51         (w, h) = getjpggeom.get_jpeg_geometory(filepath)
52         return (w, h)
53     else:
54         desc = deterfile.file(filepath)
55
56     try:
57         m = re.match(r"([0-9]+)\s*x\s*([0-9]+)", desc[1])
58     except IndexError:
59         err = ", ".join(desc)
60         raise Exception("deterfile error: %s, file: %s . " % (err,filepath))
61     if m:
62         w = m.group(1)
63         h = m.group(2)
64         return (int(w), int(h))
65     else:
66         return None
67
68
69 def replace_img_tag(line, tagstr, path):
70     if not os.path.isfile(path):
71         return line
72
73     attrs = htmltaglib.parse_attributes(tagstr)
74     (root, ext) = os.path.splitext(os.path.basename(path))
75     (w, h) = _get_png_geom(path)
76
77     if (w <= max_image_width) and (h <= max_image_height):
78         # use image as-is.
79         filename = root + ext
80         attrs['height'] = str(h)
81         attrs['width'] = str(w)
82     else:
83         # use resized image
84         new_w = float(w)
85         new_h = float(h)
86         if new_w > max_image_width:
87             new_h = int(math.floor(h * max_image_width / w))
88             new_w = int(max_image_width)
89             print "replace width, %d %d" % (new_w, new_h)
90         if new_h > max_image_height:
91             new_h = int(max_image_height)
92             new_w = int(math.floor(w * max_image_height / h))
93             print "replace height, %d %d" % (new_w, new_h)
94         attrs['height'] = str(new_h)
95         attrs['width'] = str(new_w)
96         filename = '''%s-%sx%s%s''' % (root, attrs['width'], attrs['height'], ext)
97
98     wp_image_url = '''%s%s''' % (image_dir, filename)
99     attrs['src'] = wp_image_url
100         # if tag has 'alt' attribute, use it
101     if rex_alt.search(tagstr):
102         alt_text = rex_alt.search(tagstr).group(1)
103         attrs['alt'] = alt_text
104     
105     new_tag_str = htmltaglib.build_tag('img', attrs)
106     return line.replace(tagstr, new_tag_str)
107
108 def replace_a_tag(line, tagstr, path):
109     if not os.path.isfile(path):
110         return line
111
112     attrs = htmltaglib.parse_attributes(tagstr)
113 #    wp_image_url = image_dir + os.path.basename(path)
114     (root, ext) = os.path.splitext(os.path.basename(path))
115     wp_image_url = link_prefix + "/" + root
116     attrs['href'] = wp_image_url
117     new_tag_str = htmltaglib.build_tag('a', attrs)
118
119     return line.replace(tagstr, new_tag_str)
120
121 def replace_figure_tag(line, tagstr, path):
122     attrs = htmltaglib.parse_attributes(tagstr)
123     width = max_image_width
124     if 'style' in attrs:
125         m = re.search(ur'width:\s*([0-9]+)px', attrs['style'])
126         if m:
127             w = int(m.group(1))
128             if w <= 480:
129                 width = w
130
131     attrs['style'] = "width:" + str(width) + "px;"
132     new_tag_str = htmltaglib.build_tag('figure', attrs)
133
134     return line.replace(tagstr, new_tag_str)
135
136 for line in in_f:
137     # proc for IMG tag
138     match = rex_imgtag.search(line)
139     if match:
140         tagstr = match.group(0)
141         path = match.group(1)
142         line = replace_img_tag(line, tagstr, path)
143
144     #proc for A tag
145     match = rex_atag.search(line)
146     if match:
147         tagstr = match.group(0)
148         path = match.group(1)
149         line = replace_a_tag(line, tagstr, path)
150
151     #proc for FIGURE tag
152     match = rex_figuretag.search(line)
153     if match:
154         tagstr = match.group(0)
155         style= match.group(1)
156         line = replace_figure_tag(line, tagstr, style)
157
158     print >> out_f, line,