HHC's: Reorder readActions so more common actions are listed first
[fpbd-bostik.git] / pyfpdb / PkrToFpdb.py
blobdb64d5453ca498cd26870dc2b20004899f5577d3
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)\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 ((?P<MAX>\d+)-max\s)?
76 (?P<PLAY>\(Play\sMoney\)\s)?
77 Moving\sButton\sto\sseat\s(?P<BUTTON>\d+)\s""",
78 re.MULTILINE|re.VERBOSE)
80 re_SplitHands = re.compile('\n\n+')
81 re_TailSplitHands = re.compile('(\n\n\n+)')
82 re_Button = re.compile('Seat #(?P<BUTTON>\d+) is the button', re.MULTILINE)
83 re_Board = re.compile(r"\[(?P<CARDS>.+)\]")
84 # 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]+)')
86 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)
88 def compilePlayerRegexs(self, hand):
89 players = set([player[1] for player in hand.players])
90 if not players <= self.compiledPlayers: # x <= y means 'x is subset of y'
91 # we need to recompile the player regexs.
92 self.compiledPlayers = players
93 player_re = "(?P<PNAME>" + "|".join(map(re.escape, players)) + ")"
94 subst = {'PLYR': player_re, 'CUR': self.sym[hand.gametype['currency']]}
95 log.debug("player_re: " + player_re)
96 self.re_PostSB = re.compile(r"^%(PLYR)s posts small blind %(CUR)s(?P<SB>[.0-9]+)" % subst, re.MULTILINE)
97 # FIXME: Sionel posts $0.04 is a second big blind in a different format.
98 self.re_PostBB = re.compile(r"^%(PLYR)s posts big blind %(CUR)s(?P<BB>[.0-9]+)" % subst, re.MULTILINE)
99 self.re_Antes = re.compile(r"^%(PLYR)s: posts the ante %(CUR)s(?P<ANTE>[.0-9]+)" % subst, re.MULTILINE)
100 self.re_BringIn = re.compile(r"^%(PLYR)s: brings[- ]in( low|) for %(CUR)s(?P<BRINGIN>[.0-9]+)" % subst, re.MULTILINE)
101 self.re_PostBoth = re.compile(r"^%(PLYR)s: posts small \& big blinds %(CUR)s(?P<SBBB>[.0-9]+)" % subst, re.MULTILINE)
102 self.re_HeroCards = re.compile(r"^Dealing( \[(?P<OLDCARDS>.+?)\])?( \[(?P<NEWCARDS>.+?)\]) to %(PLYR)s" % subst, re.MULTILINE)
103 self.re_Action = re.compile(r"""
104 ^%(PLYR)s(?P<ATYPE>\sbets|\schecks|\sraises|\scalls|\sfolds)(\sto)?
105 (\s(%(CUR)s)?(?P<BET>[.\d]+))?
106 """ % subst, re.MULTILINE|re.VERBOSE)
107 self.re_ShowdownAction = re.compile(r"^%(PLYR)s shows \[(?P<CARDS>.*)\]" % subst, re.MULTILINE)
108 self.re_CollectPot = re.compile(r"^%(PLYR)s wins %(CUR)s(?P<POT>[.\d]+)" % subst, re.MULTILINE)
109 self.re_sitsOut = re.compile("^%s sits out" % player_re, re.MULTILINE)
110 self.re_ShownCards = re.compile("^Seat (?P<SEAT>[0-9]+): %s (\(.*\) )?(?P<SHOWED>showed|mucked) \[(?P<CARDS>.*)\].*" % player_re, re.MULTILINE)
112 def readSupportedGames(self):
113 return [["ring", "hold", "nl"],
114 ["ring", "hold", "pl"],
115 ["ring", "hold", "fl"],
117 ["tour", "hold", "nl"],
118 ["tour", "hold", "pl"],
119 ["tour", "hold", "fl"],
122 def determineGameType(self, handText):
123 info = {}
124 m = self.re_GameInfo.search(handText)
125 if not m:
126 tmp = handText[0:200]
127 log.error(_("PkrToFpdb.determineGameType: '%s'") % tmp)
128 raise FpdbParseError
130 mg = m.groupdict()
131 #print "DEBUG: %s" % mg
133 info['type'] = 'ring'
135 if 'LIMIT' in mg:
136 info['limitType'] = self.limits[mg['LIMIT']]
137 if 'GAME' in mg:
138 (info['base'], info['category']) = self.games[mg['GAME']]
139 if 'SB' in mg:
140 info['sb'] = mg['SB']
141 if 'BB' in mg:
142 info['bb'] = mg['BB']
143 if 'CURRENCY' in mg:
144 info['currency'] = self.currencies[mg['CURRENCY']]
146 if info['limitType'] == 'fl' and info['bb'] is not None and info['type'] == 'ring' and info['base'] != 'stud':
147 try:
148 info['sb'] = self.Lim_Blinds[mg['BB']][0]
149 info['bb'] = self.Lim_Blinds[mg['BB']][1]
150 except KeyError:
151 tmp = handText[0:200]
152 log.error(_("PkrToFpdb.determineGameType: Lim_Blinds has no lookup for '%s' - '%s'") % (mg['BB'], tmp))
153 raise FpdbParseError
155 return info
157 def readHandInfo(self, hand):
158 info = {}
159 m1 = self.re_HandInfo.search(hand.handText,re.DOTALL)
160 m2 = self.re_GameInfo.search(hand.handText)
161 if m1 is None or m2 is None:
162 tmp = hand.handText[0:200]
163 log.error(_("PkrToFpdb.readHandInfo: '%s'") % tmp)
164 raise FpdbParseError
166 info.update(m1.groupdict())
167 info.update(m2.groupdict())
168 # m = self.re_Button.search(hand.handText)
169 # if m: info.update(m.groupdict())
170 # TODO : I rather like the idea of just having this dict as hand.info
171 log.debug("readHandInfo: %s" % info)
172 for key in info:
173 if key == 'DATETIME':
174 #2008/11/12 10:00:48 CET [2008/11/12 4:00:48 ET]
175 #2008/08/17 - 01:14:43 (ET)
176 #2008/09/07 06:23:14 ET
177 m3 = self.re_DateTime.finditer(info[key])
178 datetimestr = "2000/01/01 00:00:00" # default used if time not found
179 for a in m3:
180 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'))
181 hand.startTime = datetime.datetime.strptime(datetimestr, "%Y/%m/%d %H:%M:%S")
182 if key == 'HID':
183 hand.handid = info[key]
184 if key == 'TOURNO':
185 hand.tourNo = info[key]
186 if key == 'BUYIN':
187 if info[key] == 'Freeroll':
188 hand.buyin = 0
189 hand.fee = 0
190 hand.buyinCurrency = 'FREE'
191 else:
192 #FIXME: The key looks like: '€0.82+€0.18 EUR'
193 # This should be parsed properly and used
194 hand.buyin = int(100*Decimal(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' and info[key] is not None:
206 hand.maxseats = int(info[key])
207 if key == 'MIXED':
208 hand.mixed = self.mixes[info[key]] if info[key] is not None else None
209 if key == 'PLAY' and info['PLAY'] is not None:
210 # hand.currency = 'play' # overrides previously set value
211 hand.gametype['currency'] = 'play'
213 def readButton(self, hand):
214 m = self.re_Button.search(hand.handText)
215 if m:
216 hand.buttonpos = int(m.group('BUTTON'))
217 else:
218 log.info('readButton: not found')
220 def readPlayerStacks(self, hand):
221 log.debug("readPlayerStacks")
222 m = self.re_PlayerInfo.finditer(hand.handText)
223 players = {} # Player Stacks are printed in the same format
224 # At the beginning and end of the hand history
225 # The hash is to cache the player names, and ignore
226 # The second round
227 for a in m:
228 if players.has_key(a.group('PNAME')):
229 pass # Ignore
230 else:
231 #print "DEBUG: addPlayer(%s, %s, %s)" % (a.group('SEAT'), a.group('PNAME'), a.group('CASH'))
232 hand.addPlayer(int(a.group('SEAT')), a.group('PNAME'), a.group('CASH'))
233 players[a.group('PNAME')] = True
235 def markStreets(self, hand):
236 # PREFLOP = ** Dealing down cards **
237 # This re fails if, say, river is missing; then we don't get the ** that starts the river.
238 if hand.gametype['base'] in ("hold"):
239 m = re.search(r"Dealing Cards(?P<PREFLOP>.+(?=Dealing Flop)|.+)"
240 r"(Dealing Flop(?P<FLOP> \[\S\S \S\S \S\S\].+(?=Dealing Turn)|.+))?"
241 r"(Dealing Turn (?P<TURN>\[\S\S\].+(?=Dealing River)|.+))?"
242 r"(Dealing River (?P<RIVER>\[\S\S\].+))?", hand.handText,re.DOTALL)
243 elif hand.gametype['base'] in ("stud"):
244 m = re.search(r"(?P<ANTES>.+(?=\*\*\* 3rd STREET \*\*\*)|.+)"
245 r"(\*\*\* 3rd STREET \*\*\*(?P<THIRD>.+(?=\*\*\* 4th STREET \*\*\*)|.+))?"
246 r"(\*\*\* 4th STREET \*\*\*(?P<FOURTH>.+(?=\*\*\* 5th STREET \*\*\*)|.+))?"
247 r"(\*\*\* 5th STREET \*\*\*(?P<FIFTH>.+(?=\*\*\* 6th STREET \*\*\*)|.+))?"
248 r"(\*\*\* 6th STREET \*\*\*(?P<SIXTH>.+(?=\*\*\* RIVER \*\*\*)|.+))?"
249 r"(\*\*\* RIVER \*\*\*(?P<SEVENTH>.+))?", hand.handText,re.DOTALL)
250 elif hand.gametype['base'] in ("draw"):
251 m = re.search(r"(?P<PREDEAL>.+(?=\*\*\* DEALING HANDS \*\*\*)|.+)"
252 r"(\*\*\* DEALING HANDS \*\*\*(?P<DEAL>.+(?=\*\*\* FIRST DRAW \*\*\*)|.+))?"
253 r"(\*\*\* FIRST DRAW \*\*\*(?P<DRAWONE>.+(?=\*\*\* SECOND DRAW \*\*\*)|.+))?"
254 r"(\*\*\* SECOND DRAW \*\*\*(?P<DRAWTWO>.+(?=\*\*\* THIRD DRAW \*\*\*)|.+))?"
255 r"(\*\*\* THIRD DRAW \*\*\*(?P<DRAWTHREE>.+))?", hand.handText,re.DOTALL)
256 hand.addStreets(m)
258 def readCommunityCards(self, hand, street): # street has been matched by markStreets, so exists in this hand
259 if street in ('FLOP','TURN','RIVER'): # a list of streets which get dealt community cards (i.e. all but PREFLOP)
260 #print "DEBUG readCommunityCards:", street, hand.streets.group(street)
261 m = self.re_Board.search(hand.streets[street])
262 hand.setCommunityCards(street, m.group('CARDS').split(' '))
264 def readAntes(self, hand):
265 log.debug("reading antes")
266 m = self.re_Antes.finditer(hand.handText)
267 for player in m:
268 #~ logging.debug("hand.addAnte(%s,%s)" %(player.group('PNAME'), player.group('ANTE')))
269 hand.addAnte(player.group('PNAME'), player.group('ANTE'))
271 def readBringIn(self, hand):
272 m = self.re_BringIn.search(hand.handText,re.DOTALL)
273 if m:
274 #~ logging.debug("readBringIn: %s for %s" %(m.group('PNAME'), m.group('BRINGIN')))
275 hand.addBringIn(m.group('PNAME'), m.group('BRINGIN'))
277 def readBlinds(self, hand):
278 try:
279 m = self.re_PostSB.search(hand.handText)
280 hand.addBlind(m.group('PNAME'), 'small blind', m.group('SB'))
281 except: # no small blind
282 hand.addBlind(None, None, None)
283 for a in self.re_PostBB.finditer(hand.handText):
284 hand.addBlind(a.group('PNAME'), 'big blind', a.group('BB'))
285 for a in self.re_PostBoth.finditer(hand.handText):
286 hand.addBlind(a.group('PNAME'), 'both', a.group('SBBB'))
288 def readHeroCards(self, hand):
289 # streets PREFLOP, PREDRAW, and THIRD are special cases beacause
290 # we need to grab hero's cards
291 for street in ('PREFLOP', 'DEAL'):
292 if street in hand.streets.keys():
293 m = self.re_HeroCards.finditer(hand.streets[street])
294 for found in m:
295 # if m == None:
296 # hand.involved = False
297 # else:
298 hand.hero = found.group('PNAME')
299 newcards = found.group('NEWCARDS').split(' ')
300 hand.addHoleCards(street, hand.hero, closed=newcards, shown=False, mucked=False, dealt=True)
302 for street, text in hand.streets.iteritems():
303 if not text or street in ('PREFLOP', 'DEAL'): continue # already done these
304 m = self.re_HeroCards.finditer(hand.streets[street])
305 for found in m:
306 player = found.group('PNAME')
307 if found.group('NEWCARDS') is None:
308 newcards = []
309 else:
310 newcards = found.group('NEWCARDS').split(' ')
311 if found.group('OLDCARDS') is None:
312 oldcards = []
313 else:
314 oldcards = found.group('OLDCARDS').split(' ')
316 if street == 'THIRD' and len(newcards) == 3: # hero in stud game
317 hand.hero = player
318 hand.dealt.add(player) # need this for stud??
319 hand.addHoleCards(street, player, closed=newcards[0:2], open=[newcards[2]], shown=False, mucked=False, dealt=False)
320 else:
321 hand.addHoleCards(street, player, open=newcards, closed=oldcards, shown=False, mucked=False, dealt=False)
324 def readAction(self, hand, street):
325 m = self.re_Action.finditer(hand.streets[street])
326 for action in m:
327 acts = action.groupdict()
328 #print "DEBUG: readAction: acts: %s" % acts
329 if action.group('ATYPE') == ' folds':
330 hand.addFold( street, action.group('PNAME'))
331 elif action.group('ATYPE') == ' checks':
332 hand.addCheck( street, action.group('PNAME'))
333 elif action.group('ATYPE') == ' calls':
334 # Amount in hand history is not cumulative
335 # ie. Player3 calls 0.08
336 # Player5 raises to 0.16
337 # Player3 calls 0.16 (Doh! he's only calling 0.08
338 # TODO: Going to have to write an addCallStoopid()
339 #print "DEBUG: addCall( %s, %s, None)" %(street,action.group('PNAME'))
340 hand.addCall( street, action.group('PNAME'), action.group('BET') )
341 elif action.group('ATYPE') == ' raises':
342 hand.addRaiseTo( street, action.group('PNAME'), action.group('BET') )
343 elif action.group('ATYPE') == ' bets':
344 hand.addBet( street, action.group('PNAME'), action.group('BET') )
345 elif action.group('ATYPE') == ' discards':
346 hand.addDiscard(street, action.group('PNAME'), action.group('BET'), action.group('DISCARDED'))
347 elif action.group('ATYPE') == ' stands pat':
348 hand.addStandsPat( street, action.group('PNAME'))
349 else:
350 print (_("DEBUG:") + _("Unimplemented %s: '%s' '%s'") % ("readAction", action.group('PNAME'), action.group('ATYPE')))
353 def readShowdownActions(self, hand):
354 # TODO: pick up mucks also??
355 for shows in self.re_ShowdownAction.finditer(hand.handText):
356 cards = shows.group('CARDS').split(' ')
357 #print "DEBUG: addShownCards(%s, %s)" %(cards, shows.group('PNAME'))
358 hand.addShownCards(cards, shows.group('PNAME'))
360 def readCollectPot(self,hand):
361 for m in self.re_CollectPot.finditer(hand.handText):
362 #print "DEBUG: addCollectPot(%s, %s)" %(m.group('PNAME'), m.group('POT'))
363 hand.addCollectPot(player=m.group('PNAME'),pot=m.group('POT'))
365 def readShownCards(self,hand):
366 for m in self.re_ShownCards.finditer(hand.handText):
367 if m.group('CARDS') is not None:
368 cards = m.group('CARDS')
369 cards = cards.split(' ') # needs to be a list, not a set--stud needs the order
371 (shown, mucked) = (False, False)
372 if m.group('SHOWED') == "showed": shown = True
373 elif m.group('SHOWED') == "mucked": mucked = True
375 hand.addShownCards(cards=cards, player=m.group('PNAME'), shown=shown, mucked=mucked)