Use debian 2.7 only
[fpbd-bostik.git] / pyfpdb / PacificPokerToFpdb.py
blobff6ee4663545f790423bdb7f2eaf6cf3ed11158e
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
4 # Copyright 2008-2010, 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 *
26 from decimal_wrapper import Decimal
28 # PacificPoker HH Format
30 class PacificPoker(HandHistoryConverter):
32 # Class Variables
34 sitename = "PacificPoker"
35 filetype = "text"
36 codepage = ("utf8", "cp1252")
37 siteId = 13 # Needs to match id entry in Sites database
39 mixes = { 'HORSE': 'horse', '8-Game': '8game', 'HOSE': 'hose'} # Legal mixed games
40 sym = {'USD': "\$", 'CAD': "\$", 'T$': "", "EUR": "\xe2\x82\xac", "GBP": "\xa3", "play": ""} # ADD Euro, Sterling, etc HERE
41 substitutions = {
42 'LEGAL_ISO' : "USD|EUR|GBP|CAD|FPP", # legal ISO currency codes
43 'LS' : u"\$|\xe2\x82\xac|\u20ac|" # legal currency symbols - Euro(cp1252, utf-8)
46 # translations from captured groups to fpdb info strings
47 # not needed for PacificPoker
48 #Lim_Blinds = { '0.01': ('0.01', '0.02'),
49 # '0.02': ('0.02', '0.04'),
50 # '0.03': ('0.03', '0.06'),
51 # '0.05': ('0.05', '0.10'),
52 # '0.12': ('0.12', '0.25'),
53 # '0.25': ('0.25', '0.50'),
54 # '0.50': ('0.50', '1.00'),
55 # '1.00': ('1.00', '2.00'), '1': ('1.00', '2.00'),
56 # '2.00': ('2.00', '4.00'), '2': ('2.00', '4.00'),
57 # '3.00': ('3.00', '6.00'), '3': ('3.00', '6.00'),
58 # '5.00': ('5.00', '10.00'), '5': ('5.00', '10.00'),
59 # '10.00': ('10.00', '20.00'), '10': ('10.00', '20.00'),
60 # '15.00': ('15.00', '30.00'), '15': ('15.00', '30.00'),
61 # '30.00': ('30.00', '60.00'), '30': ('30.00', '60.00'),
62 # '50.00': ('50.00', '100.00'), '50': ('50.00', '100.00'),
63 # '75.00': ('75.00', '150.00'), '75': ('75.00', '150.00'),
64 # '100.00': ('100.00', '200.00'), '100': ('100.00', '200.00'),
65 # '200.00': ('200.00', '400.00'), '200': ('200.00', '400.00'),
66 # '250.00': ('250.00', '500.00'), '250': ('250.00', '500.00')
67 # }
69 limits = { 'No Limit':'nl', 'Pot Limit':'pl', 'Limit':'fl', 'LIMIT':'fl', 'Fix Limit':'fl' }
71 games = { # base, category
72 "Hold'em" : ('hold','holdem'),
73 'Holdem' : ('hold','holdem'),
74 'Omaha' : ('hold','omahahi'),
75 'Omaha Hi/Lo' : ('hold','omahahilo'),
76 'OmahaHL' : ('hold','omahahilo'),
77 'Razz' : ('stud','razz'),
78 'RAZZ' : ('stud','razz'),
79 '7 Card Stud' : ('stud','studhi'),
80 '7 Card Stud Hi/Lo' : ('stud','studhilo'),
81 'Badugi' : ('draw','badugi'),
82 'Triple Draw 2-7 Lowball' : ('draw','27_3draw'),
83 'Single Draw 2-7 Lowball' : ('draw','27_1draw'),
84 '5 Card Draw' : ('draw','fivedraw')
87 currencies = { u'€':'EUR', '$':'USD', '':'T$' }
89 # Static regexes
90 re_GameInfo = re.compile(u"""
91 \#Game\sNo\s:\s(?P<HID>[0-9]+)\\n
92 \*\*\*\*\*\sCassava\sHand\sHistory\sfor\sGame\s[0-9]+\s\*\*\*\*\*\\n
93 (?P<CURRENCY>%(LS)s)?(?P<SB>[.,0-9]+)/(%(LS)s)?(?P<BB>[.,0-9]+)\sBlinds\s
94 (?P<LIMIT>No\sLimit|Fix\sLimit|Pot\sLimit)\s
95 (?P<GAME>Holdem|Omaha|OmahaHL|Hold\'em|Omaha\sHi/Lo|OmahaHL|Razz|RAZZ|7\sCard\sStud|7\sCard\sStud\sHi/Lo|Badugi|Triple\sDraw\s2\-7\sLowball|Single\sDraw\s2\-7\sLowball|5\sCard\sDraw)
96 \s-\s\*\*\*\s
97 (?P<DATETIME>.*$)\s
98 (Tournament\s\#(?P<TOURNO>\d+))?
99 """ % substitutions, re.MULTILINE|re.VERBOSE)
101 re_PlayerInfo = re.compile(u"""
102 ^Seat\s(?P<SEAT>[0-9]+):\s
103 (?P<PNAME>.*)\s
104 \(\s(%(LS)s)?(?P<CASH>[.,0-9]+)\s\)""" % substitutions,
105 re.MULTILINE|re.VERBOSE)
107 re_HandInfo = re.compile("""
109 (Table\s(?P<TABLE>[-\ \#a-zA-Z\d]+)\s)
111 (Tournament\s\#(?P<TOURNO>\d+)\s
112 (?P<BUYIN>(?P<BIAMT>[%(LS)s\d\.]+)?\s\+\s?(?P<BIRAKE>[%(LS)s\d\.]+))\s-\s
113 Table\s\#(?P<TABLENO>\d+)\s
116 (\(Real\sMoney\))?
117 (?P<PLAY>\(Practice\sPlay\))?
119 Seat\s(?P<BUTTON>[0-9]+)\sis\sthe\sbutton
120 """ % substitutions, re.MULTILINE|re.VERBOSE)
122 re_SplitHands = re.compile('\n\n+')
123 re_TailSplitHands = re.compile('(\n\n\n+)')
124 re_Button = re.compile('Seat (?P<BUTTON>\d+) is the button', re.MULTILINE)
125 re_Board = re.compile(r"\[\s(?P<CARDS>.+)\s\]")
127 re_DateTime = re.compile("""(?P<D>[0-9]{2})\s(?P<M>[0-9]{2})\s(?P<Y>[0-9]{4})[\- ]+(?P<H>[0-9]+):(?P<MIN>[0-9]+):(?P<S>[0-9]+)""", re.MULTILINE)
129 short_subst = {'PLYR': r'(?P<PNAME>.+?)', 'CUR': '\$?'}
130 re_PostSB = re.compile(r"^%(PLYR)s posts small blind \[%(CUR)s(?P<SB>[.,0-9]+)\]" % short_subst, re.MULTILINE)
131 re_PostBB = re.compile(r"^%(PLYR)s posts big blind \[%(CUR)s(?P<BB>[.,0-9]+)\]" % short_subst, re.MULTILINE)
132 re_Antes = re.compile(r"^%(PLYR)s posts the ante \[%(CUR)s(?P<ANTE>[.,0-9]+)\]" % short_subst, re.MULTILINE)
133 # TODO: unknown in available hand histories for pacificpoker:
134 re_BringIn = re.compile(r"^%(PLYR)s: brings[- ]in( low|) for %(CUR)s(?P<BRINGIN>[.,0-9]+)" % short_subst, re.MULTILINE)
135 re_PostBoth = re.compile(r"^%(PLYR)s posts dead blind \[%(CUR)s(?P<SBBB>[.,0-9]+)\s\+\s%(CUR)s[.,0-9]+\]" % short_subst, re.MULTILINE)
136 re_HeroCards = re.compile(r"^Dealt to %(PLYR)s( \[\s(?P<NEWCARDS>.+?)\s\])" % short_subst, re.MULTILINE)
137 re_Action = re.compile(r"""
138 ^%(PLYR)s(?P<ATYPE>\sbets|\schecks|\sraises|\scalls|\sfolds|\sdiscards|\sstands\spat)
139 (\s\[(%(CUR)s)?(?P<BET>[.,0-9]+)\])?
140 (\s*and\sis\sall.in)?
141 (\s*and\shas\sreached\sthe\s[%(CUR)s\d\.]+\scap)?
142 (\s*cards?(\s\[(?P<DISCARDED>.+?)\])?)?\s*$"""
143 % short_subst, re.MULTILINE|re.VERBOSE)
144 re_ShowdownAction = re.compile(r"^%s shows \[(?P<CARDS>.*)\]" % short_subst['PLYR'], re.MULTILINE)
145 re_sitsOut = re.compile("^%s sits out" % short_subst['PLYR'], re.MULTILINE)
146 re_ShownCards = re.compile("^%s ?(?P<SHOWED>shows|mucks) \[ (?P<CARDS>.*) \]$" % short_subst['PLYR'], re.MULTILINE)
147 re_CollectPot = re.compile(r"^%(PLYR)s collected \[ %(CUR)s(?P<POT>[.,0-9]+) \]$" % short_subst, re.MULTILINE)
149 def compilePlayerRegexs(self, hand):
150 pass
152 def readSupportedGames(self):
153 return [["ring", "hold", "nl"],
154 ["ring", "hold", "pl"],
155 ["ring", "hold", "fl"],
157 ["ring", "stud", "fl"],
159 ["ring", "draw", "fl"],
160 ["ring", "draw", "pl"],
161 ["ring", "draw", "nl"],
163 ["tour", "hold", "nl"],
164 ["tour", "hold", "pl"],
165 ["tour", "hold", "fl"],
167 ["tour", "stud", "fl"],
169 ["tour", "draw", "fl"],
170 ["tour", "draw", "pl"],
171 ["tour", "draw", "nl"],
174 def determineGameType(self, handText):
175 info = {}
176 m = self.re_GameInfo.search(handText)
177 if not m:
178 tmp = handText[0:200]
179 log.error(_("PacificPokerToFpdb.determineGameType: '%s'") % tmp)
180 raise FpdbParseError
182 mg = m.groupdict()
183 #print "DEBUG: mg: ", mg
184 if 'LIMIT' in mg:
185 #print "DEBUG: re_GameInfo[LIMIT] \'", mg['LIMIT'], "\'"
186 info['limitType'] = self.limits[mg['LIMIT']]
187 if 'GAME' in mg:
188 #print "DEBUG: re_GameInfo[GAME] \'", mg['GAME'], "\'"
189 (info['base'], info['category']) = self.games[mg['GAME']]
190 if 'SB' in mg:
191 #print "DEBUG: re_GameInfo[SB] \'", mg['SB'], "\'"
192 info['sb'] = self.clearMoneyString(mg['SB'])
193 if 'BB' in mg:
194 #print "DEBUG: re_GameInfo[BB] \'", mg['BB'], "\'"
195 info['bb'] = self.clearMoneyString(mg['BB'])
196 if 'CURRENCY' in mg:
197 #print "DEBUG: re_GameInfo[CURRENCY] \'", mg['CURRENCY'], "\'"
198 info['currency'] = self.currencies[mg['CURRENCY']]
200 if 'TOURNO' in mg and mg['TOURNO'] is not None:
201 info['type'] = 'tour'
202 else:
203 info['type'] = 'ring'
205 # Pacific Poker includes the blind levels in the gametype, the following is not needed.
206 #if info['limitType'] == 'fl' and info['bb'] is not None and info['type'] == 'ring' and info['base'] != 'stud':
207 # try:
208 # info['sb'] = self.Lim_Blinds[mg['BB']][0]
209 # info['bb'] = self.Lim_Blinds[mg['BB']][1]
210 # except KeyError:
211 # log.error(_("determineGameType: Lim_Blinds has no lookup for '%s'" % mg['BB']))
212 # log.error(_("determineGameType: Raising FpdbParseError"))
213 # raise FpdbParseError(_("Lim_Blinds has no lookup for '%s'") % mg['BB'])
215 return info
217 def readHandInfo(self, hand):
218 info = {}
219 m = self.re_HandInfo.search(hand.handText,re.DOTALL)
220 m2 = self.re_GameInfo.search(hand.handText)
221 if m is None or m2 is None:
222 tmp = hand.handText[0:200]
223 log.error(_("PacificPokerToFpdb.readHandInfo: '%s'") % tmp)
224 raise FpdbParseError
226 info.update(m.groupdict())
227 info.update(m2.groupdict())
229 #log.debug("readHandInfo: %s" % info)
230 for key in info:
231 if key == 'DATETIME':
232 # 28 11 2011 19:05:11
233 m1 = self.re_DateTime.finditer(info[key])
234 datetimestr = "2000/01/01 00:00:00" # default used if time not found
235 for a in m1:
236 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'))
237 hand.startTime = datetime.datetime.strptime(datetimestr, "%Y/%m/%d %H:%M:%S")
238 hand.startTime = HandHistoryConverter.changeTimezone(hand.startTime, "ET", "UTC")
239 if key == 'HID':
240 hand.handid = info[key]
241 if key == 'TOURNO':
242 hand.tourNo = info[key]
243 hand.isKO = False
244 if key == 'BUYIN' and info['BUYIN'] != None:
245 #print "DEBUG: info['BUYIN']: %s" % info['BUYIN']
246 #print "DEBUG: info['BIAMT']: %s" % info['BIAMT']
247 #print "DEBUG: info['BIRAKE']: %s" % info['BIRAKE']
248 if info[key] == 'Freeroll':
249 hand.buyin = 0
250 hand.fee = 0
251 hand.buyinCurrency = "FREE"
252 else:
253 if info[key].find("$")!=-1:
254 hand.buyinCurrency="USD"
255 else:
256 #FIXME: handle other currencies, FPP, play money
257 log.error(_("PacificPokerToFpdb.readHandInfo: Failed to detect currency.") + " Hand ID: %s: '%s'" % (hand.handid, info[key]))
258 raise FpdbParseError
260 info['BIAMT'] = info['BIAMT'].strip(u'$€')
261 info['BIRAKE'] = info['BIRAKE'].strip(u'$€')
263 hand.buyin = int(100*Decimal(info['BIAMT']))
264 hand.fee = int(100*Decimal(info['BIRAKE']))
266 if key == 'TABLE' and info['TABLE'] != None:
267 hand.tablename = info[key]
268 if key == 'TABLEID' and info['TABLEID'] != None:
269 hand.tablename = info[key]
270 if key == 'BUTTON':
271 hand.buttonpos = info[key]
273 if key == 'PLAY' and info['PLAY'] is not None:
274 # hand.currency = 'play' # overrides previously set value
275 hand.gametype['currency'] = 'play'
277 def readButton(self, hand):
278 m = self.re_Button.search(hand.handText)
279 if m:
280 hand.buttonpos = int(m.group('BUTTON'))
281 else:
282 log.info('readButton: ' + _('not found'))
284 def readPlayerStacks(self, hand):
285 log.debug("readPlayerStacks")
286 m = self.re_PlayerInfo.finditer(hand.handText)
287 for a in m:
288 #print "DEBUG: Seat[", a.group('SEAT'), "]; PNAME[", a.group('PNAME'), "]; CASH[", a.group('CASH'), "]"
289 hand.addPlayer(int(a.group('SEAT')), a.group('PNAME'), a.group('CASH'))
291 def markStreets(self, hand):
292 # PREFLOP = ** Dealing down cards **
293 # This re fails if, say, river is missing; then we don't get the ** that starts the river.
294 if hand.gametype['base'] in ("hold"):
295 m = re.search(r"\*\* Dealing down cards \*\*(?P<PREFLOP>.+(?=\*\* Dealing flop \*\*)|.+)"
296 r"(\*\* Dealing flop \*\* (?P<FLOP>\[ \S\S, \S\S, \S\S \].+(?=\*\* Dealing turn \*\*)|.+))?"
297 r"(\*\* Dealing turn \*\* (?P<TURN>\[ \S\S \].+(?=\*\* Dealing river \*\*)|.+))?"
298 r"(\*\* Dealing river \*\* (?P<RIVER>\[ \S\S \].+?(?=\*\* Summary \*\*)|.+))?"
299 , hand.handText,re.DOTALL)
300 if m is None:
301 log.error(_("PacificPokerToFpdb.markStreets: Unable to recognise streets"))
302 raise FpdbParseError
303 else:
304 #print "DEBUG: Matched markStreets"
305 mg = m.groupdict()
306 # if 'PREFLOP' in mg:
307 # print "DEBUG: PREFLOP: ", [mg['PREFLOP']]
308 # if 'FLOP' in mg:
309 # print "DEBUG: FLOP: ", [mg['FLOP']]
310 # if 'TURN' in mg:
311 # print "DEBUG: TURN: ", [mg['TURN']]
312 # if 'RIVER' in mg:
313 # print "DEBUG: RIVER: ", [mg['RIVER']]
315 hand.addStreets(m)
317 def readCommunityCards(self, hand, street): # street has been matched by markStreets, so exists in this hand
318 if street in ('FLOP','TURN','RIVER'): # a list of streets which get dealt community cards (i.e. all but PREFLOP)
319 #print "DEBUG readCommunityCards:", street, hand.streets.group(street)
320 m = self.re_Board.search(hand.streets[street])
321 hand.setCommunityCards(street, m.group('CARDS').split(', '))
323 def readAntes(self, hand):
324 log.debug(_("reading antes"))
325 m = self.re_Antes.finditer(hand.handText)
326 for player in m:
327 #~ logging.debug("hand.addAnte(%s,%s)" %(player.group('PNAME'), player.group('ANTE')))
328 hand.addAnte(player.group('PNAME'), player.group('ANTE'))
330 def readBringIn(self, hand):
331 m = self.re_BringIn.search(hand.handText,re.DOTALL)
332 if m:
333 #~ logging.debug("readBringIn: %s for %s" %(m.group('PNAME'), m.group('BRINGIN')))
334 hand.addBringIn(m.group('PNAME'), m.group('BRINGIN'))
336 def readBlinds(self, hand):
337 liveBlind = True
338 for a in self.re_PostSB.finditer(hand.handText):
339 if a.group('PNAME') in hand.stacks:
340 if liveBlind:
341 hand.addBlind(a.group('PNAME'), 'small blind', a.group('SB'))
342 liveBlind = False
343 else:
344 # Post dead blinds as ante
345 hand.addBlind(a.group('PNAME'), 'secondsb', a.group('SB'))
346 else:
347 raise FpdbHandPartial("Partial hand history: %s" % hand.handid)
348 for a in self.re_PostBB.finditer(hand.handText):
349 if a.group('PNAME') in hand.stacks:
350 hand.addBlind(a.group('PNAME'), 'big blind', a.group('BB'))
351 else:
352 raise FpdbHandPartial("Partial hand history: %s" % hand.handid)
353 for a in self.re_PostBoth.finditer(hand.handText):
354 if a.group('PNAME') in hand.stacks:
355 hand.addBlind(a.group('PNAME'), 'both', a.group('SBBB'))
356 else:
357 raise FpdbHandPartial("Partial hand history: %s" % hand.handid)
359 def readHeroCards(self, hand):
360 # streets PREFLOP, PREDRAW, and THIRD are special cases beacause
361 # we need to grab hero's cards
362 for street in ('PREFLOP', 'DEAL'):
363 if street in hand.streets.keys():
364 m = self.re_HeroCards.finditer(hand.streets[street])
365 for found in m:
366 # if m == None:
367 # hand.involved = False
368 # else:
369 hand.hero = found.group('PNAME')
370 newcards = found.group('NEWCARDS').split(', ')
371 hand.addHoleCards(street, hand.hero, closed=newcards, shown=False, mucked=False, dealt=True)
373 for street, text in hand.streets.iteritems():
374 if not text or street in ('PREFLOP', 'DEAL'): continue # already done these
375 m = self.re_HeroCards.finditer(hand.streets[street])
376 for found in m:
377 player = found.group('PNAME')
378 if found.group('NEWCARDS') is None:
379 newcards = []
380 else:
381 newcards = found.group('NEWCARDS').split(', ')
382 if found.group('OLDCARDS') is None:
383 oldcards = []
384 else:
385 oldcards = found.group('OLDCARDS').split(', ')
387 if street == 'THIRD' and len(newcards) == 3: # hero in stud game
388 hand.hero = player
389 hand.dealt.add(player) # need this for stud??
390 hand.addHoleCards(street, player, closed=newcards[0:2], open=[newcards[2]], shown=False, mucked=False, dealt=False)
391 else:
392 hand.addHoleCards(street, player, open=newcards, closed=oldcards, shown=False, mucked=False, dealt=False)
395 def readAction(self, hand, street):
396 m = self.re_Action.finditer(hand.streets[street])
397 for action in m:
398 acts = action.groupdict()
399 #print "DEBUG: acts: %s" %acts
400 if action.group('PNAME') in hand.stacks:
401 if action.group('ATYPE') == ' folds':
402 hand.addFold( street, action.group('PNAME'))
403 elif action.group('ATYPE') == ' checks':
404 hand.addCheck( street, action.group('PNAME'))
405 elif action.group('ATYPE') == ' calls':
406 hand.addCall( street, action.group('PNAME'), action.group('BET').replace(',','') )
407 elif action.group('ATYPE') == ' raises':
408 hand.addCallandRaise( street, action.group('PNAME'), action.group('BET').replace(',','') )
409 elif action.group('ATYPE') == ' bets':
410 hand.addBet( street, action.group('PNAME'), action.group('BET').replace(',','') )
411 elif action.group('ATYPE') == ' discards':
412 hand.addDiscard(street, action.group('PNAME'), action.group('BET').replace(',',''), action.group('DISCARDED'))
413 elif action.group('ATYPE') == ' stands pat':
414 hand.addStandsPat( street, action.group('PNAME'))
415 else:
416 print (_("DEBUG:") + " " + _("Unimplemented %s: '%s' '%s'") % ("readAction", action.group('PNAME'), action.group('ATYPE')))
417 else:
418 raise FpdbHandPartial("Partial hand history: '%s', '%s' not in hand.stacks" % (hand.handid, action.group('PNAME')))
421 def readShowdownActions(self, hand):
422 # TODO: pick up mucks also??
423 for shows in self.re_ShowdownAction.finditer(hand.handText):
424 cards = shows.group('CARDS').split(', ')
425 hand.addShownCards(cards, shows.group('PNAME'))
427 def readCollectPot(self,hand):
428 for m in self.re_CollectPot.finditer(hand.handText):
429 #print "DEBUG: hand.addCollectPot(player=", m.group('PNAME'), ", pot=", m.group('POT'), ")"
430 hand.addCollectPot(player=m.group('PNAME'),pot=m.group('POT').replace(',',''))
432 def readShownCards(self,hand):
433 for m in self.re_ShownCards.finditer(hand.handText):
434 if m.group('CARDS') is not None:
435 cards = m.group('CARDS')
436 cards = cards.split(', ') # needs to be a list, not a set--stud needs the order
438 (shown, mucked) = (False, False)
439 if m.group('SHOWED') == "showed": shown = True
440 elif m.group('SHOWED') == "mucked": mucked = True
442 #print "DEBUG: hand.addShownCards(%s, %s, %s, %s)" %(cards, m.group('PNAME'), shown, mucked)
443 hand.addShownCards(cards=cards, player=m.group('PNAME'), shown=shown, mucked=mucked)