OSDN Git Service

add wp_imgswap2.py for new OSDN Magazine
[otptools/otptools.git] / otp_imgswap.py
1 #!/usr/bin/env python
2 # -*- encoding: utf-8 -*-
3 #
4 # otp_imgswap.py : otp image tag swapper
5 #
6
7 import sys
8 import codecs
9 import re
10 import os.path
11 import hashlib
12
13 usage = """usage: %s <target file> <output_file>""" % (os.path.basename(sys.argv[0]),)
14
15
16 def get_md5(fpath):
17     f = open( fpath, "rb")
18     buf = f.read()
19     f.close()
20     m = hashlib.md5()
21     m.update(buf)
22     return m.hexdigest()
23
24
25 rex_imgtag = re.compile(r"""<img\s+src=["'](.*?)["'].*?>""")
26 rex_atag = re.compile(r"""<a\s+href=["'](.*?)["'].*?>""")
27 rex_alt = re.compile(r"""alt=["'](.*?)["']""")
28 try:
29     in_f = codecs.open(sys.argv[1], "r", "utf_8" )
30     out_f = codecs.open(sys.argv[2], "w", "utf_8" )
31 except IndexError:
32     sys.exit(usage)
33
34 for line in in_f:
35
36     # proc for IMG tag
37     match = rex_imgtag.search(line)
38     if match:
39         tagstr = match.group(0)
40         path = match.group(1)
41         if os.path.isfile(path):
42             md5 = get_md5(path)
43             # tag has alt ?
44             if rex_alt.search(tagstr):
45                 alt = rex_alt.search(tagstr).group(1)
46                 slashtag = """<SLASH-IMAGE ID="%s" TITLE="%s">""" % (md5,alt)
47             else:
48                 slashtag = """<SLASH-IMAGE ID="%s">""" % (md5,)
49             line = line.replace(tagstr, slashtag)
50
51     #proc for A tag
52     match = rex_atag.search(line)
53     if match:
54         tagstr = match.group(0)
55         path = match.group(1)
56         try:
57             if os.path.isfile(path):
58                 md5 = get_md5(path)
59             # tag has alt ?
60                 slashtag = """<A HREF="/blob.pl?id=%s">""" % (md5,)
61                 line = line.replace(tagstr, slashtag)
62         except UnicodeEncodeError:
63             print >> sys.stderr, "invalid path: %s (%s)" % (path.encode("utf-8"), line.strip().encode("utf-8"))
64     print >> out_f, line,