Don't allow the start date to be later than the end date. If it is, modify whichever...
[fpdb-dooglus.git] / pyfpdb / CakeToFpdb.py
blob61ecff0aefc43848def8bfc228c441509794b9f4
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
4 # Copyright 2008-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 from HandHistoryConverter import *
25 from decimal_wrapper import Decimal
28 class Cake(HandHistoryConverter):
30 # Class Variables
32 sitename = "Cake"
33 filetype = "text"
34 codepage = ("utf8", "cp1252")
35 siteId = 17
36 sym = {'USD': "\$", 'CAD': "\$", 'T$': "", "EUR": "\xe2\x82\xac", "GBP": "\xa3", "play": ""}
37 substitutions = {
38 'LEGAL_ISO' : "USD|EUR|GBP|CAD|FPP", # legal ISO currency codes
39 'LS' : u"\$|\xe2\x82\xac|\u20ac|", # legal currency symbols - Euro(cp1252, utf-8)
40 'PLYR': r'(?P<PNAME>.+?)',
41 'CUR': u"(\$|\xe2\x82\xac|\u20ac|)",
44 # translations from captured groups to fpdb info strings
45 Lim_Blinds = { '0.04': ('0.01', '0.02'), '0.08': ('0.02', '0.04'),
46 # '0.10': ('0.02', '0.05'), '0.20': ('0.05', '0.10'),
47 # '0.40': ('0.10', '0.20'), '0.50': ('0.10', '0.25'),
48 # '1.00': ('0.25', '0.50'), '1': ('0.25', '0.50'),
49 # '2.00': ('0.50', '1.00'), '2': ('0.50', '1.00'),
50 # '4.00': ('1.00', '2.00'), '4': ('1.00', '2.00'),
51 # '6.00': ('1.00', '3.00'), '6': ('1.00', '3.00'),
52 # '8.00': ('2.00', '4.00'), '8': ('2.00', '4.00'),
53 # '10.00': ('2.00', '5.00'), '10': ('2.00', '5.00'),
54 # '20.00': ('5.00', '10.00'), '20': ('5.00', '10.00'),
55 # '30.00': ('10.00', '15.00'), '30': ('10.00', '15.00'),
56 # '40.00': ('10.00', '20.00'), '40': ('10.00', '20.00'),
57 # '60.00': ('15.00', '30.00'), '60': ('15.00', '30.00'),
58 # '80.00': ('20.00', '40.00'), '80': ('20.00', '40.00'),
59 # '100.00': ('25.00', '50.00'), '100': ('25.00', '50.00'),
60 # '200.00': ('50.00', '100.00'), '200': ('50.00', '100.00'),
61 # '400.00': ('100.00', '200.00'), '400': ('100.00', '200.00'),
62 # '800.00': ('200.00', '400.00'), '800': ('200.00', '400.00'),
63 # '1000.00': ('250.00', '500.00'),'1000': ('250.00', '500.00')
66 limits = { 'NL':'nl', 'PL':'pl', 'FL':'fl' }
67 games = { # base, category
68 "Hold'em" : ('hold','holdem'),
69 'Omaha' : ('hold','omahahi'),
70 'Omaha Hi/Lo' : ('hold','omahahilo'),
72 currencies = { u'€':'EUR', '$':'USD', '':'T$' }
74 # Static regexes
75 re_GameInfo = re.compile(u"""
76 Hand\#(?P<HID>[0-9]+)\s+-\s+
77 (?P<TABLE>[-\ \#a-zA-Z\d\']+)\s
78 \(Turbo\s(?P<MAX>\d+)-max\)\s\d+\s\--\s
79 (?P<CURRENCY>%(LS)s|)?
80 (?P<SB>[.0-9]+)/(%(LS)s)?
81 (?P<BB>[.0-9]+)\s
82 (?P<LIMIT>NL|FL||PL)\s
83 (?P<GAME>Hold\'em|Omaha|Omaha\sHi/Lo)\s--\s
84 (?P<DATETIME>.*$)
85 """ % substitutions, re.MULTILINE|re.VERBOSE)
87 re_PlayerInfo = re.compile(u"""
88 ^Seat\s(?P<SEAT>[0-9]+):\s
89 (?P<PNAME>.*)\s
90 \((%(LS)s)?(?P<CASH>[.0-9]+)\sin\schips\)""" % substitutions,
91 re.MULTILINE|re.VERBOSE)
93 re_SplitHands = re.compile('\n\n+')
94 re_Button = re.compile('Seat #(?P<BUTTON>\d+) is the button', re.MULTILINE)
95 re_Board = re.compile(r"\[(?P<CARDS>.+)\]")
97 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)
98 re_PostSB = re.compile(r"^%(PLYR)s: posts small blind %(CUR)s(?P<SB>[.0-9]+)$" % substitutions, re.MULTILINE)
99 re_PostBB = re.compile(r"^%(PLYR)s: posts big blind %(CUR)s(?P<BB>[.0-9]+)$" % substitutions, re.MULTILINE)
100 re_Antes = re.compile(r"^%(PLYR)s: posts the ante %(CUR)s(?P<ANTE>[.0-9]+)" % substitutions, re.MULTILINE)
101 re_BringIn = re.compile(r"^%(PLYR)s: brings[- ]in( low|) for %(CUR)s(?P<BRINGIN>[.0-9]+)" % substitutions, re.MULTILINE)
102 re_PostBoth = re.compile(r"^%(PLYR)s:posts dead blind %(CUR)s(?P<SB>[.0-9]+) and big blind %(CUR)s(?P<BB>[.0-9]+)" % substitutions, re.MULTILINE)
103 re_HeroCards = re.compile(r"^Dealt to %(PLYR)s(?: \[(?P<OLDCARDS>.+?)\])?( \[(?P<NEWCARDS>.+?)\])" % substitutions, re.MULTILINE)
104 re_Action = re.compile(r"""
105 ^%(PLYR)s:(?P<ATYPE>\sbets|\schecks|\sraises|\scalls|\sfolds|\sis\sall\sin)
106 (\s(%(CUR)s)?(?P<BET>[.\d]+))?(\sto\s%(CUR)s(?P<BETTO>[.\d]+))?$
108 % substitutions, re.MULTILINE|re.VERBOSE)
109 re_ShowdownAction = re.compile(r"^%s: shows \[(?P<CARDS>.*)\]" % substitutions['PLYR'], re.MULTILINE)
110 re_sitsOut = re.compile("^%s sits out" % substitutions['PLYR'], re.MULTILINE)
111 re_ShownCards = re.compile("^Seat (?P<SEAT>[0-9]+): %s (\(.*\) )?(?P<SHOWED>showed|mucked) \[(?P<CARDS>.*)\]( and won \([.\d]+\) with (?P<STRING>.*))?" % substitutions['PLYR'], re.MULTILINE)
112 re_CollectPot = re.compile(r"%(PLYR)s wins %(CUR)s(?P<POT>[.\d]+)" % substitutions, re.MULTILINE)
113 re_WinningRankOne = re.compile(u"^%(PLYR)s wins the tournament and receives %(CUR)s(?P<AMT>[\.0-9]+) - congratulations!$" % substitutions, re.MULTILINE)
114 re_WinningRankOther = re.compile(u"^%(PLYR)s finished the tournament in (?P<RANK>[0-9]+)(st|nd|rd|th) place and received %(CUR)s(?P<AMT>[.0-9]+)\.$" % substitutions, re.MULTILINE)
115 re_RankOther = re.compile(u"^%(PLYR)s finished the tournament in (?P<RANK>[0-9]+)(st|nd|rd|th) place$" % substitutions, re.MULTILINE)
117 def compilePlayerRegexs(self, hand):
118 pass
120 def readSupportedGames(self):
121 return [["ring", "hold", "nl"],
122 ["ring", "hold", "pl"],
123 ["ring", "hold", "fl"],
127 def determineGameType(self, handText):
128 info = {}
129 m = self.re_GameInfo.search(handText)
130 if not m:
131 tmp = handText[0:150]
132 log.error(_("Unable to recognise gametype from: '%s'") % tmp)
133 log.error("determineGameType: " + _("Raising FpdbParseError"))
134 raise FpdbParseError(_("Unable to recognise gametype from: '%s'") % tmp)
136 mg = m.groupdict()
137 #print "DEBUG: mg: %s" % mg
138 if 'LIMIT' in mg:
139 info['limitType'] = self.limits[mg['LIMIT']]
140 if 'GAME' in mg:
141 (info['base'], info['category']) = self.games[mg['GAME']]
142 if 'SB' in mg:
143 info['sb'] = mg['SB']
144 if 'BB' in mg:
145 info['bb'] = mg['BB']
146 if 'CURRENCY' in mg:
147 info['currency'] = self.currencies[mg['CURRENCY']]
148 if 'MIXED' in mg:
149 if mg['MIXED'] is not None: info['mix'] = self.mixes[mg['MIXED']]
151 info['type'] = 'ring'
153 if info['limitType'] == 'fl' and info['bb'] is not None and info['type'] == 'ring':
154 try:
155 info['sb'] = self.Lim_Blinds[mg['BB']][0]
156 info['bb'] = self.Lim_Blinds[mg['BB']][1]
157 except KeyError:
158 log.error(_("Lim_Blinds has no lookup for '%s'") % mg['BB'])
159 log.error("determineGameType: " + _("Raising FpdbParseError"))
160 raise FpdbParseError(_("Lim_Blinds has no lookup for '%s'") % mg['BB'])
162 return info
164 def readHandInfo(self, hand):
165 info = {}
166 m = self.re_GameInfo.search(hand.handText)
167 if m is None:
168 log.error(_("No match in readHandInfo: '%s'") % hand.handText[0:100])
169 raise FpdbParseError(_("No match in readHandInfo: '%s'") % hand.handText[0:100])
171 info.update(m.groupdict())
173 log.debug("readHandInfo: %s" % info)
174 for key in info:
175 if key == 'DATETIME':
176 m1 = self.re_DateTime.finditer(info[key])
177 datetimestr = "2000/01/01 00:00:00" # default used if time not found
178 for a in m1:
179 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'))
180 hand.startTime = datetime.datetime.strptime(datetimestr, "%Y/%m/%d %H:%M:%S")
181 hand.startTime = HandHistoryConverter.changeTimezone(hand.startTime, "ET", "UTC")
182 if key == 'HID':
183 hand.handid = info[key]
184 if key == 'TABLE':
185 hand.tablename = info[key]
186 if key == 'BUTTON':
187 hand.buttonpos = info[key]
188 if key == 'MAX' and info[key] != None:
189 hand.maxseats = int(info[key])
191 def readButton(self, hand):
192 m = self.re_Button.search(hand.handText)
193 if m:
194 hand.buttonpos = int(m.group('BUTTON'))
195 else:
196 log.info(_('readButton: not found'))
198 def readPlayerStacks(self, hand):
199 log.debug("readPlayerStacks")
200 m = self.re_PlayerInfo.finditer(hand.handText)
201 for a in m:
202 hand.addPlayer(int(a.group('SEAT')), a.group('PNAME'), a.group('CASH'))
204 def markStreets(self, hand):
205 # PREFLOP = ** Dealing down cards **
206 # This re fails if, say, river is missing; then we don't get the ** that starts the river.
207 if hand.gametype['base'] in ("hold"):
208 m = re.search(r"(?P<PREFLOP>.+(?=\*\*\* FLOP \*\*\*)|.+)"
209 r"(\*\*\* FLOP \*\*\*(?P<FLOP> \[\S\S,\S\S,\S\S\].+(?=\*\*\* TURN \*\*\*)|.+))?"
210 r"(\*\*\* TURN \*\*\* (?P<TURN>\[\S\S\].+(?=\*\*\* RIVER \*\*\*)|.+))?"
211 r"(\*\*\* RIVER \*\*\* (?P<RIVER>\[\S\S\].+))?", hand.handText,re.DOTALL)
212 hand.addStreets(m)
214 def readCommunityCards(self, hand, street):
215 if street in ('FLOP','TURN','RIVER'):
216 #print "DEBUG readCommunityCards:", street, hand.streets.group(street)
217 m = self.re_Board.search(hand.streets[street])
218 hand.setCommunityCards(street, m.group('CARDS').split(' '))
220 def readAntes(self, hand):
221 log.debug(_("reading antes"))
222 m = self.re_Antes.finditer(hand.handText)
223 for player in m:
224 #~ logging.debug("hand.addAnte(%s,%s)" %(player.group('PNAME'), player.group('ANTE')))
225 hand.addAnte(player.group('PNAME'), player.group('ANTE'))
227 def readBringIn(self, hand):
228 m = self.re_BringIn.search(hand.handText,re.DOTALL)
229 if m:
230 #~ logging.debug("readBringIn: %s for %s" %(m.group('PNAME'), m.group('BRINGIN')))
231 hand.addBringIn(m.group('PNAME'), m.group('BRINGIN'))
233 def readBlinds(self, hand):
234 liveBlind = True
235 for a in self.re_PostSB.finditer(hand.handText):
236 if liveBlind:
237 hand.addBlind(a.group('PNAME'), 'small blind', a.group('SB'))
238 liveBlind = False
239 else:
240 # Post dead blinds as ante
241 hand.addBlind(a.group('PNAME'), 'secondsb', a.group('SB'))
242 for a in self.re_PostBB.finditer(hand.handText):
243 hand.addBlind(a.group('PNAME'), 'big blind', a.group('BB'))
244 for a in self.re_PostBoth.finditer(hand.handText):
245 sb = Decimal(a.group('SB'))
246 bb = Decimal(a.group('BB'))
247 sbbb = sb + bb
248 hand.addBlind(a.group('PNAME'), 'both', str(sbbb))
250 def readHeroCards(self, hand):
251 for street in ('PREFLOP', 'DEAL'):
252 if street in hand.streets.keys():
253 m = self.re_HeroCards.finditer(hand.streets[street])
254 for found in m:
255 hand.hero = found.group('PNAME')
256 newcards = found.group('NEWCARDS').split(',')
257 hand.addHoleCards(street, hand.hero, closed=newcards, shown=False, mucked=False, dealt=True)
259 def readAction(self, hand, street):
260 m = self.re_Action.finditer(hand.streets[street])
261 for action in m:
262 acts = action.groupdict()
263 #print "DEBUG: acts: %s" %acts
264 amount = action.group('BET') if action.group('BET') else None
265 actionType = action.group('ATYPE')
267 if actionType == ' raises':
268 hand.addRaiseTo( street, action.group('PNAME'), action.group('BETTO') )
269 elif actionType == ' calls':
270 hand.addCall( street, action.group('PNAME'), action.group('BET') )
271 elif actionType == ' bets':
272 hand.addBet( street, action.group('PNAME'), action.group('BET') )
273 elif actionType == ' folds':
274 hand.addFold( street, action.group('PNAME'))
275 elif actionType == ' checks':
276 hand.addCheck( street, action.group('PNAME'))
277 elif actionType == ' is all in':
278 hand.addAllIn(street, action.group('PNAME'), action.group('BET'))
279 else:
280 print (_("DEBUG:") + " " + _("Unimplemented %s: '%s' '%s'") % ("readAction", action.group('PNAME'), action.group('ATYPE')))
283 def readShowdownActions(self, hand):
284 for shows in self.re_ShowdownAction.finditer(hand.handText):
285 cards = shows.group('CARDS').split(' ')
286 hand.addShownCards(cards, shows.group('PNAME'))
288 def readCollectPot(self,hand):
289 for m in self.re_CollectPot.finditer(hand.handText):
290 hand.addCollectPot(player=m.group('PNAME'),pot=m.group('POT'))
292 def readShownCards(self,hand):
293 for m in self.re_ShownCards.finditer(hand.handText):
294 if m.group('CARDS') is not None:
295 cards = m.group('CARDS')
296 cards = cards.split(' ') # needs to be a list, not a set--stud needs the order
297 string = m.group('STRING')
299 (shown, mucked) = (False, False)
300 if m.group('SHOWED') == "showed": shown = True
301 elif m.group('SHOWED') == "mucked": mucked = True
303 #print "DEBUG: hand.addShownCards(%s, %s, %s, %s)" %(cards, m.group('PNAME'), shown, mucked)
304 hand.addShownCards(cards=cards, player=m.group('PNAME'), shown=shown, mucked=mucked, string=string)