def test_ocr_ps1(): mongo = MongoManager() table_dict = mongo.get_table("Official Poker Stars") table_scraper = TableScraper(table_dict) table_scraper.screenshot = Image.open( os.path.join(get_dir('tests', 'screenshots'), 'ps473830744_Flop_1.png')) table_scraper.crop_from_top_left_corner() result = ocr(table_scraper.screenshot, 'total_pot_area', table_scraper.table_dict) assert result == 0.29 result = ocr(table_scraper.screenshot, 'call_value', table_scraper.table_dict) assert result == 0.04 result = ocr(table_scraper.screenshot, 'raise_value', table_scraper.table_dict) assert result == 0.08 result = ocr(table_scraper.screenshot, 'player_funds_area', table_scraper.table_dict, player='0') assert result == 1.67
def get_relevant_files(): """ Get relevant changed files of current branch vs target branch. check_all_files (bool): get all files if true, get changed files since comparison commit Filenames are filtered: - Files need to be in lint_extensions - Files cannot be in the exclude_folders list Returns: list of str: changed files """ filenames = [ y for x in os.walk(get_dir('codebase')) for y in glob(os.path.join(x[0], '*.py')) ] if os.name == 'nt': filenames = [filename.replace('/', """\\""") for filename in filenames] filenames = [filename for filename in filenames if filename] filenames = [ filename for filename in filenames if os.path.splitext(filename)[1] in LINT_EXTENSIONS ] filenames = [os.path.join(CODEBASE, filename) for filename in filenames] log.debug(filenames) return filenames
def test_ocr_pp1(): mongo = MongoManager() table_dict = mongo.get_table( "PartyPoker 6 Players Fast Forward $1-$2 NL Hold'em") table_scraper = TableScraper(table_dict) table_scraper.screenshot = Image.open( os.path.join(get_dir('tests', 'screenshots'), '173280759_PreFlop_0.png')) table_scraper.crop_from_top_left_corner() result = ocr(table_scraper.screenshot, 'total_pot_area', table_scraper.table_dict) assert result == 0.09 result = ocr(table_scraper.screenshot, 'call_value', table_scraper.table_dict) assert result == 0.04 result = ocr(table_scraper.screenshot, 'raise_value', table_scraper.table_dict) assert result == 0.1 result = ocr(table_scraper.screenshot, 'player_funds_area', table_scraper.table_dict, player='0') assert result == 1.32
def test_all(self): """Test table button""" self.table_name = self.ui.table_name.currentText() from poker.scraper.table_scraper import TableScraper table_dict = mongo.get_table(table_name=self.table_name) table_scraper = TableScraper(table_dict) table_scraper.nn_model = None if 'use_neural_network' in table_dict and table_dict['use_neural_network'] == '2': from tensorflow.keras.models import model_from_json table_scraper.nn_model = model_from_json(table_dict['_model']) mongo.load_table_nn_weights(self.table_name) table_scraper.nn_model.load_weights(get_dir('codebase') + '/loaded_model.h5') table_scraper.screenshot = self.original_screenshot table_scraper.crop_from_top_left_corner() table_scraper.is_my_turn() table_scraper.lost_everything() table_scraper.get_my_cards2() table_scraper.get_table_cards2() table_scraper.get_dealer_position2() table_scraper.get_players_in_game() table_scraper.get_pots() table_scraper.get_players_funds() table_scraper.get_player_pots() table_scraper.get_call_value() table_scraper.get_raise_value() table_scraper.has_all_in_call_button() table_scraper.has_call_button() table_scraper.has_raise_button() table_scraper.has_bet_button() log.info("Test finished.")
def test_cropping(): entire_screen_pil = Image.open( os.path.join(get_dir('tests', 'screenshots'), 'screenshot1.png')) top_left_corner = get_table_template_image('default', 'topleft_corner') img = cv2.cvtColor(np.array(entire_screen_pil), cv2.COLOR_BGR2RGB) count, points, bestfit, minimum_value = find_template_on_screen( top_left_corner, img, 0.01)
def test_crop_func(): entire_screen_pil = Image.open(os.path.join(get_dir('tests', 'screenshots'), 'test5.png')) top_left_corner = get_table_template_image('GG_TEST1', 'topleft_corner') # cv2.imshow('image', top_left_corner) # cv2.waitKey(0) cropped = crop_screenshot_with_topleft_corner(entire_screen_pil, top_left_corner, scale_m=1.0) assert cropped
def test_crop_func(): entire_screen_pil = Image.open( os.path.join(get_dir('tests', 'screenshots'), 'screenshot1.png')) top_left_corner = get_table_template_image('default', 'topleft_corner') cropped = crop_screenshot_with_topleft_corner(entire_screen_pil, top_left_corner) assert cropped
def test_ocr_pp1(): mongo = MongoManager() table_dict = mongo.get_table("Official Party Poker") table_scraper = TableScraper(table_dict) table_scraper.screenshot = Image.open( os.path.join(get_dir('tests', 'screenshots'), '53269218_PreFlop_0.png')) table_scraper.crop_from_top_left_corner() result = ocr(table_scraper.screenshot, 'total_pot_area', table_scraper.table_dict) assert result == 0.08 result = ocr(table_scraper.screenshot, 'call_value', table_scraper.table_dict) assert result == 0.03 result = ocr(table_scraper.screenshot, 'raise_value', table_scraper.table_dict) assert result == 0.08 result = ocr(table_scraper.screenshot, 'player_funds_area', table_scraper.table_dict, player='0') assert result == 1.98
def test_cropping(): entire_screen_pil = Image.open( os.path.join(get_dir('tests', 'screenshots'), '53269218_PreFlop_0.png')) top_left_corner = get_table_template_image("PartyPoker Old", 'topleft_corner') img = cv2.cvtColor(np.array(entire_screen_pil), cv2.COLOR_BGR2RGB) find_template_on_screen(top_left_corner, img, 0.01)
def test_cropping(): entire_screen_pil = Image.open( os.path.join(get_dir('tests', 'screenshots'), '173280759_PreFlop_0.png')) top_left_corner = get_table_template_image( "PartyPoker 6 Players Fast Forward $1-$2 NL Hold'em", 'topleft_corner') img = cv2.cvtColor(np.array(entire_screen_pil), cv2.COLOR_BGR2RGB) find_template_on_screen(top_left_corner, img, 0.01)
def test_crop_func(): entire_screen_pil = Image.open( os.path.join(get_dir('tests', 'screenshots'), '173280759_PreFlop_0.png')) top_left_corner = get_table_template_image( "PartyPoker 6 Players Fast Forward $1-$2 NL Hold'em", 'topleft_corner') cropped = crop_screenshot_with_topleft_corner(entire_screen_pil, top_left_corner) assert cropped
def test_crop_func(): entire_screen_pil = Image.open( os.path.join(get_dir('tests', 'screenshots'), '53269218_PreFlop_0.png')) top_left_corner = get_table_template_image("PartyPoker Old", 'topleft_corner') cropped = crop_screenshot_with_topleft_corner(entire_screen_pil, top_left_corner) assert cropped
def load_table_nn_weights(self, table_name: str): log.info("Downloading neural network weights for card recognition with tolerance...") weights_str = requests.post(URL + "get_tensorflow_weights", params={'table_name': table_name}).json() try: weights = base64.b64decode(weights_str) except TypeError: log.error("No Trained Neural Network found. The cards need to be trained first.") return with open(get_dir('codebase') + '/loaded_model.h5', 'wb') as fh: fh.write(weights) log.info("Download complete")
def test_preflop_sheet_utgX_range(): log = logging.getLogger(__name__) preflop_state = CurrentHandPreflopState() h = History() preflop_url = get_dir(os.path.join('tools', 'preflop.xlsx')) h.preflop_sheet = pd.read_excel(preflop_url, sheet_name=None) preflop_state.reset() for i in range(5): sheet_name = str(i + 1) ranges = preflop_state.get_rangecards_from_sheetname1(sheet_name, h) combos1 = mc_get_opponent_combos(opponent_range=ranges) log.info(f'{ranges}') log.info(f'UTG {i} : {len(combos1)}')
def get_my_cards_nn(self): left_card_area = self.table_dict['left_card_area'] right_card_area = self.table_dict['right_card_area'] left_card = self.screenshot.crop( (left_card_area['x1'], left_card_area['y1'], left_card_area['x2'], left_card_area['y2'])) right_card = self.screenshot.crop( (right_card_area['x1'], right_card_area['y1'], right_card_area['x2'], right_card_area['y2'])) self.my_cards = [] card1 = predict(left_card, self.nn_model, self.table_dict['_class_mapping']) card2 = predict(right_card, self.nn_model, self.table_dict['_class_mapping']) self.my_cards.append(card1) self.my_cards.append(card2) try: left_card.save(get_dir('log') + '/pics/' + card1 + '.png') except: pass try: right_card.save(get_dir('log') + '/pics/' + card2 + '.png') except: pass for i in range(2): if 'empty_card' in self.my_cards: self.my_cards.remove('empty_card') if len(self.my_cards) == 2: log.info("My cards: " + str(self.my_cards)) return True else: log.debug("Did not find two player cards: " + str(self.my_cards)) return False
def test_players_in_game11(): mongo = MongoManager() table_dict = mongo.get_table('GG_6TABLE') t = TableScraper(table_dict) t.screenshot = Image.open( get_dir(os.path.join('log', 'pics', 'table_c_2.png'))) # t.crop_from_top_left_corner2(select_table=0) if is_debug: t.screenshot.save('log/pics/players_in_game.png') t.get_players_in_game() t.get_dealer_position2() assert t.players_in_game == [0, 1, 2, 3, 4, 5] assert t.dealer_position == 3
def get_opponent_allowed_cards_list(self, opponent_ranges): ror = "-50" if self.use_range_of_range else "" with open( os.path.join(get_dir('codebase'), f'decisionmaker/preflop_equity{ror}.json')) as f: self.preflop_equities = json.load(f) peflop_equity_list = sorted(self.preflop_equities.items(), key=operator.itemgetter(1)) counts = len(peflop_equity_list) take_top = int(counts * opponent_ranges) allowed = set(list(peflop_equity_list)[-take_top:]) allowed_cards = [i[0] for i in allowed] # logger.debug("Allowed range: "+str(allowed_cards)) return set(allowed_cards)
def test_table_scraper(): mongo = MongoManager() table_dict = mongo.get_table("PartyPoker 6 Players Fast Forward $1-$2 NL Hold'em") table_scraper = TableScraper(table_dict) table_scraper.screenshot = Image.open(os.path.join(get_dir('tests', 'screenshots'), '173280759_PreFlop_0.png')) table_scraper.crop_from_top_left_corner() table_scraper.is_my_turn() table_scraper.lost_everything() table_scraper.get_my_cards2() table_scraper.get_table_cards2() table_scraper.get_dealer_position2() table_scraper.get_players_in_game() table_scraper.get_pots() table_scraper.get_players_funds() table_scraper.get_call_value() table_scraper.get_raise_value() table_scraper.has_all_in_call_button() table_scraper.has_call_button() table_scraper.has_raise_button()
def test_reverse_sheetname(): log = logging.getLogger(__name__) # Get table_dict table_scraper_name = 'GG_6TABLE' table_dict = mongo.get_table(table_scraper_name) # Mock signal gui_signals = MagicMock() # Game logger game_logger = GameLogger() preflop_state = CurrentHandPreflopState() h = History() preflop_url = get_dir(os.path.join('tools', 'preflop.xlsx')) # mongoclient = MongoClient(f'mongodb://*****:*****@dickreuter.com/neuron_poker') # mongodb = mongoclient.neuron_poker # cursor = mongodb.internal.find() # c = cursor.next() # preflop_url = c['preflop_url'] # log.info(f'preflop_url: {preflop_url}') h.preflop_sheet = pd.read_excel(preflop_url, sheet_name=None) p = StrategyHandler() p.read_strategy() # Read default strategy. t = TableScreenBased(p, table_dict, gui_signals, game_logger, 0.0) t.dealer_position = 4 t.position_utg_plus = t.get_utg_from_abs_pos(0, t.dealer_position) # 5 preflop_state.reset() # preflop_state.other_players = deepcopy(t.other_players) preflop_state.bot_preflop_position_utg = t.position_utg_plus # 5 preflop_state.bot_preflop_decision = 'Bet' preflop_state.preflop_raiser_positions.append(5) # preflop_state.preflop_raiser_positions.append(4) # preflop_state.preflop_caller_positions.append(5) preflop_state.rounds = 0 for abs_pos in [5]: sheet_name = preflop_state.get_reverse_sheetname(abs_pos, t, h) log.info(f'abs_pos:{abs_pos}, sheet_name: {sheet_name}') ranges = preflop_state.get_rangecards_from_sheetname( abs_pos, sheet_name, t, h, p) log.info(f'{ranges}')
def get_round_pot_value(self, h): self.round_pot_value = self.current_round_pot if self.round_pot_value != "": try: self.round_pot_value = float(self.round_pot_value) except: self.round_pot_value = 0 if self.round_pot_value == "": self.round_pot_value = 0 self.gui_signals.signal_status.emit( "Unable to get round pot value") log.warning("unable to get round pot value") # self.round_pot_value = h.previous_round_pot_value self.screenshot.save( os.path.join(get_dir('pics'), "ErrRoundPotValue.png")) self.gui_signals.signal_progressbar_increase.emit(5) return True
def test_table_scraper(): mongo = MongoManager() table_dict = mongo.get_table('default') table_scraper = TableScraper(table_dict) table_scraper.screenshot = Image.open( os.path.join(get_dir('tests', 'screenshots'), 'screenshot1.png')) table_scraper.crop_from_top_left_corner() table_scraper.is_my_turn() table_scraper.lost_everything() table_scraper.get_my_cards2() table_scraper.get_table_cards2() table_scraper.get_dealer_position2() table_scraper.get_players_in_game() table_scraper.get_pots() table_scraper.get_players_funds() table_scraper.get_call_value() table_scraper.get_raise_value() table_scraper.has_all_in_call_button() table_scraper.has_call_button() table_scraper.has_raise_button() table_scraper.get_game_number_on_screen2()
def getImage(name): filename = name + '.png'; image = cv2.imread(path.join(get_dir('cards', 'images'), filename)) image = screen.imageToBw(image) return image
def test_orc_problems2(): """Tricky OCR situations""" img = Image.open(os.path.join(get_dir('codebase'), r"tests/ocr/num2.png")) result = get_ocr_float(img) assert result == 3.94
import cv2 import numpy as np from PIL import Image, ImageGrab from pytesseract import pytesseract from tesserocr import PyTessBaseAPI, PSM, OEM from poker.tools.helper import memory_cache, get_dir from poker.tools.mongo_manager import MongoManager from poker.tools.vbox_manager import VirtualBoxController log = logging.getLogger(__name__) is_debug = False # used for saving images for debug purposes if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'): tesserpath = os.path.join(get_dir('codebase'), 'tessdata') else: tesserpath = os.path.join(get_dir('codebase'), '..', 'tessdata') api = PyTessBaseAPI(path=tesserpath, psm=PSM.SINGLE_LINE, oem=OEM.LSTM_ONLY) def find_template_on_screen(template, screenshot, threshold, extended=False): """Find template on screen""" res = cv2.matchTemplate(screenshot, template, cv2.TM_SQDIFF_NORMED) loc = np.where(res <= threshold) min_val, _, min_loc, _ = cv2.minMaxLoc(res) bestFit = min_loc count = 0 points = []
import io import json import logging import os import shutil import cv2 import numpy as np from PIL import Image from tqdm import tqdm from poker.tools.helper import get_dir from poker.tools.mongo_manager import MongoManager SCRAPER_DIR = get_dir('pics') TRAIN_FOLDER = get_dir('pics', "training_cards") VALIDATE_FOLDER = get_dir('pics', "validate_cards") TEST_FOLDER = get_dir('tests', "test_cards") log = logging.getLogger(__name__) def pil_to_cv2(img): return cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB) def binary_pil_to_cv2(img): return cv2.cvtColor(np.array(Image.open(io.BytesIO(img))), cv2.COLOR_BGR2RGB)
import os import sys from glob import glob from pydocstyle import Error, check from pydocstyle.cli import setup_stream_handlers, ReturnCode from pydocstyle.config import ConfigurationParser, IllegalConfiguration from pylint import lint from pylint.reporters.text import TextReporter from poker.tools.helper import get_dir # pylint: disable=anomalous-backslash-in-string,too-few-public-methods,inconsistent-return-statements log = logging.getLogger(__name__) CODEBASE = get_dir('codebase') REPOS = [name for name in os.listdir(CODEBASE) if os.path.isdir(name)] FOLDERS = [name for name in os.listdir(CODEBASE) if os.path.isdir(os.path.join(CODEBASE, name)) and '.' not in name[0] and '_' not in name[0]] LINT_EXTENSIONS = ['.py'] EXCLUDE_SUBFOLDERS = ['.idea', 'doc', 'mongodb-backup','mongodb-transfer2'] # To ignore specific rules, please disable it in your file or function, # or (if given broad consensus) ignore it globally by adding an exception to .pylintrc. # Full list of readable pylint message short-names can be found here: # https://github.com/janjur/readable-pylint-messages IGNORE_LIST = ["""\r\n""", # part of final output