chiark / gitweb /
Merge ../ypp-sc-tools.pctb-dict-test
[ypp-sc-tools.db-test.git] / yarrg / yppedia-ocean-scraper
1 #!/usr/bin/python
2
3 # helper program for getting information from yppedia
4
5 # This is part of ypp-sc-tools, a set of third-party tools for assisting
6 # players of Yohoho Puzzle Pirates.
7 #
8 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
9 #
10 # This program is free software: you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation, either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 #
23 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
24 # are used without permission.  This program is not endorsed or
25 # sponsored by Three Rings.
26
27 copyright_info = '''
28 yppedia-ocean-scraper is part of ypp-sc-tools Copyright (C) 2009 Ian Jackson
29 This program comes with ABSOLUTELY NO WARRANTY; this is free software,
30 and you are welcome to redistribute it under certain conditions.  For
31 details, read the top of the yppedia-ocean-scraper file.
32 '''
33
34 import signal
35 signal.signal(signal.SIGINT, signal.SIG_DFL)
36
37 import sys
38 import os
39 import urllib
40 import urllib2
41 import re as regexp
42 from optparse import OptionParser
43 from BeautifulSoup import BeautifulSoup
44
45
46 # For fuck's sake!
47 import codecs
48 import locale
49 def fix_stdout():
50     sys.stdout = codecs.EncodedFile(sys.stdout, locale.getpreferredencoding())
51     def null_decode(input, errors='strict'):
52         return input, len(input)
53     sys.stdout.decode = null_decode
54 # From
55 #  http://ewx.livejournal.com/457086.html?thread=3016574
56 #  http://ewx.livejournal.com/457086.html?thread=3016574
57 # lightly modified.
58 # See also Debian #415968.
59 fix_stdout()
60
61
62 ocean = None
63 soup = None
64 opts = None
65 arches = {}
66
67 def debug(k,v):
68         if opts.debug:
69                 print >>sys.stderr, k,`v`
70
71 def fetch():
72         global soup
73         if opts.chart:
74                 url_base = 'index.php?title=Template:Map:%s_Ocean&action=edit'
75         else:
76                 url_base = '%s_Ocean'
77         url = ('http://yppedia.puzzlepirates.com/' +
78                         (url_base % urllib.quote(ocean,'')))
79         debug('fetching',url)
80         dataf = urllib2.urlopen(url)
81         debug('fetched',dataf)
82         soup = BeautifulSoup(dataf)
83
84
85 title_arch_re = regexp.compile('(\\S.*\\S) Archipelago \\((\\S+)\\)$')
86 title_any_re = regexp.compile('(\\S.*\\S) \((\\S+)\\)$')
87 href_img_re = regexp.compile('\\.png$')
88
89 def title_arch_info(t):
90         # returns (arch,ocean)
91         debug('checking',t)
92         if t is None: return (None,None)
93         m = title_arch_re.match(t)
94         if not m: return (None,None)
95         return m.groups()
96
97 def title_arch_ok(t):
98         (a,o) = title_arch_info(t)
99         if o is None: return False
100         return o == ocean
101
102 def parse_chart():
103         ta = soup.find('textarea')
104         debug('ta',ta)
105         s = ta.string
106         debug('s',s)
107         s = regexp.sub(r'\&lt\;', '<', s)
108         s = regexp.sub(r'\&gt\;', '>', s)
109         s = regexp.sub(r'\&quot\;', '"', s)
110         s = regexp.sub(r'\&amp\;', '&', s)
111         debug('s',s)
112         return s
113
114 def parse_ocean():
115         content = soup.find('div', attrs = {'id': 'content'})
116
117         def findall_title_arch_ok(t):
118                 return t.findAll('a', attrs = {'title': title_arch_ok})
119
120         def is_archestable(u):
121                 if u.name != 'table': return False
122                 return len(findall_title_arch_ok(u)) > 1
123
124         archestable = content.findChild('table', attrs={'border':'1'})
125         debug('at',archestable)
126
127         archsoups = []
128         for row in archestable.findAll('tr',recursive=False):
129                 archsoups += row.findAll('td',recursive=False)
130         debug('ac',archsoups)
131
132         def is_island(v):
133                 return len(v.findAll(text = regexp.compile('.*Large'))) > 0
134         def arch_up_map(u):
135                 return u.findParent(is_island)
136
137         for arch in archsoups:
138                 links = arch.findAll('a', href=True)
139                 debug('links',links)
140                 if not links: continue
141                 (a,o) = title_arch_info(links[0]['title'])
142                 debug('arch-ocean', (a,o))
143                 assert(o == ocean)
144                 assert(a not in arches)
145                 isles = []
146                 for link in links[1:]:
147                         debug('link',link)
148                         if href_img_re.search(link['href']): continue
149                         m = title_any_re.match(link['title'])
150                         assert(m.group(2) == ocean)
151                         island = m.group(1)
152                         debug('island', island)
153                         isles.append(island)
154                 isles.sort()
155                 arches[a] = isles
156
157 def output():
158         print 'ocean',ocean
159         al = arches.keys()
160         al.sort()
161         for a in al:
162                 print '',a
163                 for island in arches[a]:
164                         print ' ',island
165
166 def main():
167         global ocean
168         global opts
169
170         pa = OptionParser(
171 '''usage: .../yppedia-ocean-scraper [--debug] [--chart] OCEAN''')
172         ao = pa.add_option
173
174         ao('--chart', action='store_true', dest='chart',
175                 help='print chart source rather than arch/island info')
176         ao('--debug', action='count', dest='debug', default=0,
177                 help='enable debugging output')
178
179         (opts,args) = pa.parse_args()
180         if len(args) != 1:
181                 print >>sys.stderr, copyright_info
182                 pa.error('need an ocean argument')
183         ocean = args[0]
184
185         fetch()
186         if opts.chart:
187                 print parse_chart()
188         else:
189                 parse_ocean()
190                 output()
191
192 main()