Add 'Currencies' filter to the ring player stats viewer.
[fpdb-dooglus.git] / pyfpdb / PkrToFpdb.py
blob73770dbbda1f6b91e7981dfa02eedd87ee0416bd
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
4 # Copyright 2010-2011, Carl Gherardi
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 ########################################################################
21 import L10n
22 _ = L10n.get_translation()
24 import sys
25 from HandHistoryConverter import *
28 class Pkr(HandHistoryConverter):
30 # Class Variables
32 sitename = "PKR"
33 filetype = "text"
34 codepage = ("utf8", "cp1252")
35 siteId = 12 # Needs to match id entry in Sites database
37 mixes = { 'HORSE': 'horse', '8-Game': '8game', 'HOSE': 'hose'} # Legal mixed games
38 sym = {'USD': "\$"} # ADD Euro, Sterling, etc HERE
39 substitutions = {
40 'LEGAL_ISO' : "USD", # legal ISO currency codes
41 'LS' : "\$|" # legal currency symbols - Euro(cp1252, utf-8)
44 limits = { 'NO LIMIT':'nl', 'POT LIMIT':'pl', 'LIMIT':'fl' }
45 games = { # base, category
46 "HOLD'EM" : ('hold','holdem'),
47 'FIXMEOmaha' : ('hold','omahahi'),
48 'FIXMEOmaha Hi/Lo' : ('hold','omahahilo'),
49 'FIXME5 Card Draw' : ('draw','fivedraw')
51 currencies = { u'€':'EUR', '$':'USD', '':'T$' }
53 # Static regexes
54 re_GameInfo = re.compile(u"""
55 Table\s\#\d+\s\-\s(?P<TABLE>[a-zA-Z\ \d]+)\s
56 Starting\sHand\s\#(?P<HID>[0-9]+)\s
57 Start\stime\sof\shand:\s(?P<DATETIME>.*)\s
58 Last\sHand\s\#[0-9]+\s
59 Game\sType:\s(?P<GAME>HOLD'EM|5\sCard\sDraw)\s
60 Limit\sType:\s(?P<LIMIT>NO\sLIMIT|LIMIT|POT\sLIMIT)\s
61 Table\sType\:\sRING\s
62 Money\sType:\sREAL\sMONEY\s
63 Blinds\sare\snow\s(?P<CURRENCY>%(LS)s|)?
64 (?P<SB>[.0-9]+)/(%(LS)s)?
65 (?P<BB>[.0-9]+)
66 """ % substitutions, re.MULTILINE|re.VERBOSE)
68 re_PlayerInfo = re.compile(u"""
69 ^Seat\s(?P<SEAT>[0-9]+):\s
70 (?P<PNAME>.*)\s-\s
71 (%(LS)s)?(?P<CASH>[.0-9]+)
72 """ % substitutions, re.MULTILINE|re.VERBOSE)
74 re_HandInfo = re.compile("""
75 ^Table\s\'(?P<TABLE>[-\ a-zA-Z\d]+)\'\s
76 ((?P<MAX>\d+)-max\s)?
77 (?P<PLAY>\(Play\sMoney\)\s)?
78 (Seat\s\#(?P<BUTTON>\d+)\sis\sthe\sbutton)?""",
79 re.MULTILINE|re.VERBOSE)
81 re_SplitHands = re.compile('\n\n+')
82 re_TailSplitHands = re.compile('(\n\n\n+)')
83 re_Button = re.compile('Seat #(?P<BUTTON>\d+) is the button', re.MULTILINE)
84 re_Board = re.compile(r"\[(?P<CARDS>.+)\]")
85 # self.re_setHandInfoRegex('.*#(?P<HID>[0-9]+): Table (?P<TABLE>[ a-zA-Z]+) - \$?(?P<SB>[.0-9]+)/\$?(?P<BB>[.0-9]+) - (?P<GAMETYPE>.*) - (?P<HR>[0-9]+):(?P<MIN>[0-9]+) ET - (?P<YEAR>[0-9]+)/(?P<MON>[0-9]+)/(?P<DAY>[0-9]+)Table (?P<TABLE>[ a-zA-Z]+)\nSeat (?P<BUTTON>[0-9]+)')
87 re_DateTime = re.compile("""(?P<Y>[0-9]{4})\/(?P<M>[0-9]{2})\/(?P<D>[0-9]{2})[\- ]+(?P<H>[0-9]+):(?P<MIN>[0-9]+):(?P<S>[0-9]+)""", re.MULTILINE)
89 def compilePlayerRegexs(self, hand):
90 players = set([player[1] for player in hand.players])
91 if not players <= self.compiledPlayers: # x <= y means 'x is subset of y'
92 # we need to recompile the player regexs.
93 self.compiledPlayers = players
94 player_re = "(?P<PNAME>" + "|".join(map(re.escape, players)) + ")"
95 subst = {'PLYR': player_re, 'CUR': self.sym[hand.gametype['currency']]}
96 log.debug("player_re: " + player_re)
97 self.re_PostSB = re.compile(r"^%(PLYR)s posts small blind %(CUR)s(?P<SB>[.0-9]+)" % subst, re.MULTILINE)
98 # FIXME: Sionel posts $0.04 is a second big blind in a different format.
99 self.re_PostBB = re.compile(r"^%(PLYR)s posts big blind %(CUR)s(?P<BB>[.0-9]+)" % subst, re.MULTILINE)
100 self.re_Antes = re.compile(r"^%(PLYR)s: posts the ante %(CUR)s(?P<ANTE>[.0-9]+)" % subst, re.MULTILINE)
101 self.re_BringIn = re.compile(r"^%(PLYR)s: brings[- ]in( low|) for %(CUR)s(?P<BRINGIN>[.0-9]+)" % subst, re.MULTILINE)
102 self.re_PostBoth = re.compile(r"^%(PLYR)s: posts small \& big blinds %(CUR)s(?P<SBBB>[.0-9]+)" % subst, re.MULTILINE)
103 self.re_HeroCards = re.compile(r"^Dealing( \[(?P<OLDCARDS>.+?)\])?( \[(?P<NEWCARDS>.+?)\]) to %(PLYR)s" % subst, re.MULTILINE)
104 self.re_Action = re.compile(r"""
105 ^%(PLYR)s(?P<ATYPE>\sbets|\schecks|\sraises|\scalls|\sfolds)(\sto)?
106 (\s(%(CUR)s)?(?P<BET>[.\d]+))?
107 """ % subst, re.MULTILINE|re.VERBOSE)
108 self.re_ShowdownAction = re.compile(r"^%(PLYR)s shows \[(?P<CARDS>.*)\]" % subst, re.MULTILINE)
109 self.re_CollectPot = re.compile(r"^%(PLYR)s wins %(CUR)s(?P<POT>[.\d]+)" % subst, re.MULTILINE)
110 self.re_sitsOut = re.compile("^%s sits out" % player_re, re.MULTILINE)
111 self.re_ShownCards = re.compile("^Seat (?P<SEAT>[0-9]+): %s (\(.*\) )?(?P<SHOWED>showed|mucked) \[(?P<CARDS>.*)\].*" % player_re, re.MULTILINE)
113 def readSupportedGames(self):
114 return [["ring", "hold", "nl"],
115 ["ring", "hold", "pl"],
116 ["ring", "hold", "fl"],
118 ["tour", "hold", "nl"],
119 ["tour", "hold", "pl"],
120 ["tour", "hold", "fl"],
123 def determineGameType(self, handText):
124 info = {}
125 m = self.re_GameInfo.search(handText)
126 if not m:
127 tmp = handText[0:100]
128 log.error(_("Unable to recognise gametype from: '%s'") % tmp)
129 log.error("determineGameType: " + _("Raising FpdbParseError"))
130 raise FpdbParseError(_("Unable to recognise gametype from: '%s'") % tmp)
132 mg = m.groupdict()
133 #print "DEBUG: %s" % mg
135 info['type'] = 'ring'
137 if 'LIMIT' in mg:
138 info['limitType'] = self.limits[mg['LIMIT']]
139 if 'GAME' in mg:
140 (info['base'], info['category']) = self.games[mg['GAME']]
141 if 'SB' in mg:
142 info['sb'] = mg['SB']
143 if 'BB' in mg:
144 info['bb'] = mg['BB']
145 if 'CURRENCY' in mg:
146 info['currency'] = self.currencies[mg['CURRENCY']]
148 if info['limitType'] == 'fl' and info['bb'] is not None and info['type'] == 'ring' and info['base'] != 'stud':
149 try:
150 info['sb'] = self.Lim_Blinds[mg['BB']][0]
151 info['bb'] = self.Lim_Blinds[mg['BB']][1]
152 except KeyError:
153 log.error(_("Lim_Blinds has no lookup for '%s'") % mg['BB'])
154 log.error("determineGameType: " + _("Raising FpdbParseError"))
155 raise FpdbParseError(_("Lim_Blinds has no lookup for '%s'") % mg['BB'])
157 return info
159 def readHandInfo(self, hand):
160 info = {}
161 m = self.re_HandInfo.search(hand.handText,re.DOTALL)
162 if m:
163 info.update(m.groupdict())
164 # hand.maxseats = int(m2.group(1))
165 else:
166 pass # throw an exception here, eh?
167 m = self.re_GameInfo.search(hand.handText)
168 if m:
169 info.update(m.groupdict())
170 # m = self.re_Button.search(hand.handText)
171 # if m: info.update(m.groupdict())
172 # TODO : I rather like the idea of just having this dict as hand.info
173 log.debug("readHandInfo: %s" % info)
174 for key in info:
175 if key == 'DATETIME':
176 #2008/11/12 10:00:48 CET [2008/11/12 4:00:48 ET]
177 #2008/08/17 - 01:14:43 (ET)
178 #2008/09/07 06:23:14 ET
179 m1 = self.re_DateTime.finditer(info[key])
180 datetimestr = "2000/01/01 00:00:00" # default used if time not found
181 for a in m1:
182 datetimestr = "%s/%s/%s %s:%s:%s" % (a.group('Y'), a.group('M'),a.group('D'),a.group('H'),a.group('MIN'),a.group('S'))
183 hand.startTime = datetime.datetime.strptime(datetimestr, "%Y/%m/%d %H:%M:%S")
184 if key == 'HID':
185 hand.handid = info[key]
186 if key == 'TOURNO':
187 hand.tourNo = info[key]
188 if key == 'BUYIN':
189 if info[key] == 'Freeroll':
190 hand.buyin = '$0+$0'
191 else:
192 #FIXME: The key looks like: '€0.82+€0.18 EUR'
193 # This should be parsed properly and used
194 hand.buyin = info[key]
195 if key == 'LEVEL':
196 hand.level = info[key]
198 if key == 'TABLE':
199 if hand.tourNo != None:
200 hand.tablename = re.split(" ", info[key])[1]
201 else:
202 hand.tablename = info[key]
203 if key == 'BUTTON':
204 hand.buttonpos = info[key]
205 if key == 'MAX':
206 hand.maxseats = int(info[key])
208 if key == 'MIXED':
209 hand.mixed = self.mixes[info[key]] if info[key] is not None else None
210 if key == 'PLAY' and info['PLAY'] is not None:
211 # hand.currency = 'play' # overrides previously set value
212 hand.gametype['currency'] = 'play'
214 def readButton(self, hand):
215 m = self.re_Button.search(hand.handText)
216 if m:
217 hand.buttonpos = int(m.group('BUTTON'))
218 else:
219 log.info('readButton: not found')
221 def readPlayerStacks(self, hand):
222 log.debug("readPlayerStacks")
223 m = self.re_PlayerInfo.finditer(hand.handText)
224 players = {} # Player Stacks are printed in the same format
225 # At the beginning and end of the hand history
226 # The hash is to cache the player names, and ignore
227 # The second round
228 for a in m:
229 if players.has_key(a.group('PNAME')):
230 pass # Ignore
231 else:
232 #print "DEBUG: addPlayer(%s, %s, %s)" % (a.group('SEAT'), a.group('PNAME'), a.group('CASH'))
233 hand.addPlayer(int(a.group('SEAT')), a.group('PNAME'), a.group('CASH'))
234 players[a.group('PNAME')] = True
236 def markStreets(self, hand):
237 # PREFLOP = ** Dealing down cards **
238 # This re fails if, say, river is missing; then we don't get the ** that starts the river.
239 if hand.gametype['base'] in ("hold"):
240 m = re.search(r"Dealing Cards(?P<PREFLOP>.+(?=Dealing Flop)|.+)"
241 r"(Dealing Flop(?P<FLOP> \[\S\S \S\S \S\S\].+(?=Dealing Turn)|.+))?"
242 r"(Dealing Turn (?P<TURN>\[\S\S\].+(?=Dealing River)|.+))?"
243 r"(Dealing River (?P<RIVER>\[\S\S\].+))?", hand.handText,re.DOTALL)
244 elif hand.gametype['base'] in ("stud"):
245 m = re.search(r"(?P<ANTES>.+(?=\*\*\* 3rd STREET \*\*\*)|.+)"
246 r"(\*\*\* 3rd STREET \*\*\*(?P<THIRD>.+(?=\*\*\* 4th STREET \*\*\*)|.+))?"
247 r"(\*\*\* 4th STREET \*\*\*(?P<FOURTH>.+(?=\*\*\* 5th STREET \*\*\*)|.+))?"
248 r"(\*\*\* 5th STREET \*\*\*(?P<FIFTH>.+(?=\*\*\* 6th STREET \*\*\*)|.+))?"
249 r"(\*\*\* 6th STREET \*\*\*(?P<SIXTH>.+(?=\*\*\* RIVER \*\*\*)|.+))?"
250 r"(\*\*\* RIVER \*\*\*(?P<SEVENTH>.+))?", hand.handText,re.DOTALL)
251 elif hand.gametype['base'] in ("draw"):
252 m = re.search(r"(?P<PREDEAL>.+(?=\*\*\* DEALING HANDS \*\*\*)|.+)"
253 r"(\*\*\* DEALING HANDS \*\*\*(?P<DEAL>.+(?=\*\*\* FIRST DRAW \*\*\*)|.+))?"
254 r"(\*\*\* FIRST DRAW \*\*\*(?P<DRAWONE>.+(?=\*\*\* SECOND DRAW \*\*\*)|.+))?"
255 r"(\*\*\* SECOND DRAW \*\*\*(?P<DRAWTWO>.+(?=\*\*\* THIRD DRAW \*\*\*)|.+))?"
256 r"(\*\*\* THIRD DRAW \*\*\*(?P<DRAWTHREE>.+))?", hand.handText,re.DOTALL)
257 hand.addStreets(m)
259 def readCommunityCards(self, hand, street): # street has been matched by markStreets, so exists in this hand
260 if street in ('FLOP','TURN','RIVER'): # a list of streets which get dealt community cards (i.e. all but PREFLOP)
261 #print "DEBUG readCommunityCards:", street, hand.streets.group(street)
262 m = self.re_Board.search(hand.streets[street])
263 hand.setCommunityCards(street, m.group('CARDS').split(' '))
265 def readAntes(self, hand):
266 log.debug("reading antes")
267 m = self.re_Antes.finditer(hand.handText)
268 for player in m:
269 #~ logging.debug("hand.addAnte(%s,%s)" %(player.group('PNAME'), player.group('ANTE')))
270 hand.addAnte(player.group('PNAME'), player.group('ANTE'))
272 def readBringIn(self, hand):
273 m = self.re_BringIn.search(hand.handText,re.DOTALL)
274 if m:
275 #~ logging.debug("readBringIn: %s for %s" %(m.group('PNAME'), m.group('BRINGIN')))
276 hand.addBringIn(m.group('PNAME'), m.group('BRINGIN'))
278 def readBlinds(self, hand):
279 try:
280 m = self.re_PostSB.search(hand.handText)
281 hand.addBlind(m.group('PNAME'), 'small blind', m.group('SB'))
282 except: # no small blind
283 hand.addBlind(None, None, None)
284 for a in self.re_PostBB.finditer(hand.handText):
285 hand.addBlind(a.group('PNAME'), 'big blind', a.group('BB'))
286 for a in self.re_PostBoth.finditer(hand.handText):
287 hand.addBlind(a.group('PNAME'), 'both', a.group('SBBB'))
289 def readHeroCards(self, hand):
290 # streets PREFLOP, PREDRAW, and THIRD are special cases beacause
291 # we need to grab hero's cards
292 for street in ('PREFLOP', 'DEAL'):
293 if street in hand.streets.keys():
294 m = self.re_HeroCards.finditer(hand.streets[street])
295 for found in m:
296 # if m == None:
297 # hand.involved = False
298 # else:
299 hand.hero = found.group('PNAME')
300 newcards = found.group('NEWCARDS').split(' ')
301 hand.addHoleCards(street, hand.hero, closed=newcards, shown=False, mucked=False, dealt=True)
303 for street, text in hand.streets.iteritems():
304 if not text or street in ('PREFLOP', 'DEAL'): continue # already done these
305 m = self.re_HeroCards.finditer(hand.streets[street])
306 for found in m:
307 player = found.group('PNAME')
308 if found.group('NEWCARDS') is None:
309 newcards = []
310 else:
311 newcards = found.group('NEWCARDS').split(' ')
312 if found.group('OLDCARDS') is None:
313 oldcards = []
314 else:
315 oldcards = found.group('OLDCARDS').split(' ')
317 if street == 'THIRD' and len(newcards) == 3: # hero in stud game
318 hand.hero = player
319 hand.dealt.add(player) # need this for stud??
320 hand.addHoleCards(street, player, closed=newcards[0:2], open=[newcards[2]], shown=False, mucked=False, dealt=False)
321 else:
322 hand.addHoleCards(street, player, open=newcards, closed=oldcards, shown=False, mucked=False, dealt=False)
325 def readAction(self, hand, street):
326 m = self.re_Action.finditer(hand.streets[street])
327 for action in m:
328 acts = action.groupdict()
329 #print "DEBUG: readAction: acts: %s" % acts
330 if action.group('ATYPE') == ' raises':
331 hand.addRaiseTo( street, action.group('PNAME'), action.group('BET') )
332 elif action.group('ATYPE') == ' calls':
333 # Amount in hand history is not cumulative
334 # ie. Player3 calls 0.08
335 # Player5 raises to 0.16
336 # Player3 calls 0.16 (Doh! he's only calling 0.08
337 # TODO: Going to have to write an addCallStoopid()
338 #print "DEBUG: addCall( %s, %s, None)" %(street,action.group('PNAME'))
339 hand.addCall( street, action.group('PNAME'), action.group('BET') )
340 elif action.group('ATYPE') == ' bets':
341 hand.addBet( street, action.group('PNAME'), action.group('BET') )
342 elif action.group('ATYPE') == ' folds':
343 hand.addFold( street, action.group('PNAME'))
344 elif action.group('ATYPE') == ' checks':
345 hand.addCheck( street, action.group('PNAME'))
346 elif action.group('ATYPE') == ' discards':
347 hand.addDiscard(street, action.group('PNAME'), action.group('BET'), action.group('DISCARDED'))
348 elif action.group('ATYPE') == ' stands pat':
349 hand.addStandsPat( street, action.group('PNAME'))
350 else:
351 print (_("DEBUG:") + _("Unimplemented %s: '%s' '%s'") % ("readAction", action.group('PNAME'), action.group('ATYPE')))
354 def readShowdownActions(self, hand):
355 # TODO: pick up mucks also??
356 for shows in self.re_ShowdownAction.finditer(hand.handText):
357 cards = shows.group('CARDS').split(' ')
358 #print "DEBUG: addShownCards(%s, %s)" %(cards, shows.group('PNAME'))
359 hand.addShownCards(cards, shows.group('PNAME'))
361 def readCollectPot(self,hand):
362 for m in self.re_CollectPot.finditer(hand.handText):
363 #print "DEBUG: addCollectPot(%s, %s)" %(m.group('PNAME'), m.group('POT'))
364 hand.addCollectPot(player=m.group('PNAME'),pot=m.group('POT'))
366 def readShownCards(self,hand):
367 for m in self.re_ShownCards.finditer(hand.handText):
368 if m.group('CARDS') is not None:
369 cards = m.group('CARDS')
370 cards = cards.split(' ') # needs to be a list, not a set--stud needs the order
372 (shown, mucked) = (False, False)
373 if m.group('SHOWED') == "showed": shown = True
374 elif m.group('SHOWED') == "mucked": mucked = True
376 hand.addShownCards(cards=cards, player=m.group('PNAME'), shown=shown, mucked=mucked)