Spaces:
Sleeping
Sleeping
Challenge AI as color from handicap position (#118)
Browse files- Use Fairy-Stockfish to ease CI setup and Linux development setup
- Fix recent CI regressions
- Fix challenge timeout creating many games
- Fix engine not receiving depth etc. parameters (go commands) causing engine to lose on time
- .github/workflows/lishogi-bot-build.yml +3 -3
- config.yml.default +5 -5
- engine_ctrl/usi.py +2 -3
- engine_wrapper.py +7 -5
- lishogi-bot.py +2 -2
- lishogi.py +10 -6
- requirements.txt +4 -0
- tests.py +10 -28
.github/workflows/lishogi-bot-build.yml
CHANGED
|
@@ -14,7 +14,7 @@ env:
|
|
| 14 |
jobs:
|
| 15 |
build:
|
| 16 |
|
| 17 |
-
runs-on:
|
| 18 |
|
| 19 |
steps:
|
| 20 |
- uses: actions/checkout@v3
|
|
@@ -22,10 +22,10 @@ jobs:
|
|
| 22 |
uses: actions/setup-python@v4
|
| 23 |
with:
|
| 24 |
python-version: "3.11"
|
|
|
|
| 25 |
- name: Install dependencies
|
| 26 |
run: |
|
| 27 |
-
|
| 28 |
-
pip install pytest pytest-timeout
|
| 29 |
pip install -r requirements.txt
|
| 30 |
- name: Test with pytest
|
| 31 |
run: |
|
|
|
|
| 14 |
jobs:
|
| 15 |
build:
|
| 16 |
|
| 17 |
+
runs-on: ubuntu-latest
|
| 18 |
|
| 19 |
steps:
|
| 20 |
- uses: actions/checkout@v3
|
|
|
|
| 22 |
uses: actions/setup-python@v4
|
| 23 |
with:
|
| 24 |
python-version: "3.11"
|
| 25 |
+
cache: "pip"
|
| 26 |
- name: Install dependencies
|
| 27 |
run: |
|
| 28 |
+
sudo apt install fairy-stockfish
|
|
|
|
| 29 |
pip install -r requirements.txt
|
| 30 |
- name: Test with pytest
|
| 31 |
run: |
|
config.yml.default
CHANGED
|
@@ -23,10 +23,10 @@ engine: # Engine Settings.
|
|
| 23 |
# Move Overhead: 500 # Increase if your bot flags games too often.
|
| 24 |
Threads: 1 # Max CPU threads the engine can use.
|
| 25 |
# USI_Hash: 256 # Max memory (in megabytes) the engine can allocate.
|
| 26 |
-
|
| 27 |
-
#
|
| 28 |
-
#
|
| 29 |
-
#
|
| 30 |
silence_stderr: false # Some engines are very noisy.
|
| 31 |
|
| 32 |
abort_time: 30 # Time in seconds after which the engine will abort the game if there is no activity.
|
|
@@ -72,4 +72,4 @@ greeting:
|
|
| 72 |
# {me} to insert bot's name.
|
| 73 |
# Any other words in curly braces will be removed.
|
| 74 |
hello: "Hi! I'm {me}. Good luck! Type !help for a list of commands I can respond to." # Message to send to chat at the start of a game.
|
| 75 |
-
goodbye: "Good game!" # Message to send to chat at the end of a game.
|
|
|
|
| 23 |
# Move Overhead: 500 # Increase if your bot flags games too often.
|
| 24 |
Threads: 1 # Max CPU threads the engine can use.
|
| 25 |
# USI_Hash: 256 # Max memory (in megabytes) the engine can allocate.
|
| 26 |
+
go_commands: # Additional options to pass to the USI go command.
|
| 27 |
+
# nodes: 1 # Search so many nodes only.
|
| 28 |
+
# depth: 5 # Search depth ply only.
|
| 29 |
+
# movetime: 1000 # Integer. Search exactly movetime milliseconds.
|
| 30 |
silence_stderr: false # Some engines are very noisy.
|
| 31 |
|
| 32 |
abort_time: 30 # Time in seconds after which the engine will abort the game if there is no activity.
|
|
|
|
| 72 |
# {me} to insert bot's name.
|
| 73 |
# Any other words in curly braces will be removed.
|
| 74 |
hello: "Hi! I'm {me}. Good luck! Type !help for a list of commands I can respond to." # Message to send to chat at the start of a game.
|
| 75 |
+
goodbye: "Good game!" # Message to send to chat at the end of a game.
|
engine_ctrl/usi.py
CHANGED
|
@@ -8,10 +8,9 @@ logger = logging.getLogger(__name__)
|
|
| 8 |
|
| 9 |
|
| 10 |
class Engine:
|
| 11 |
-
def __init__(self,
|
| 12 |
self.info = {}
|
| 13 |
self.id = {}
|
| 14 |
-
self.variants = variants
|
| 15 |
cwd = cwd or os.path.realpath(os.path.expanduser("."))
|
| 16 |
self.proccess = self.open_process(command, cwd)
|
| 17 |
self.go_commands = None
|
|
@@ -261,4 +260,4 @@ class Engine:
|
|
| 261 |
logger.info("ponderhit")
|
| 262 |
|
| 263 |
def quit(self):
|
| 264 |
-
self.send("quit")
|
|
|
|
| 8 |
|
| 9 |
|
| 10 |
class Engine:
|
| 11 |
+
def __init__(self, command, cwd=None):
|
| 12 |
self.info = {}
|
| 13 |
self.id = {}
|
|
|
|
| 14 |
cwd = cwd or os.path.realpath(os.path.expanduser("."))
|
| 15 |
self.proccess = self.open_process(command, cwd)
|
| 16 |
self.go_commands = None
|
|
|
|
| 260 |
logger.info("ponderhit")
|
| 261 |
|
| 262 |
def quit(self):
|
| 263 |
+
self.send("quit")
|
engine_wrapper.py
CHANGED
|
@@ -20,6 +20,7 @@ def create_engine(config):
|
|
| 20 |
if engine_options:
|
| 21 |
for k, v in engine_options.items():
|
| 22 |
commands.append(f"--{k}={v}")
|
|
|
|
| 23 |
|
| 24 |
silence_stderr = cfg.get("silence_stderr", False)
|
| 25 |
|
|
@@ -32,7 +33,7 @@ def create_engine(config):
|
|
| 32 |
f"Invalid engine type: {engine_type}. Expected usi or homemade.")
|
| 33 |
|
| 34 |
logger.debug(f"Starting engine: {' '.join(commands)}")
|
| 35 |
-
return Engine(commands, usi_options, silence_stderr, cwd=engine_working_dir)
|
| 36 |
|
| 37 |
|
| 38 |
class Termination(str, Enum):
|
|
@@ -48,7 +49,8 @@ class Termination(str, Enum):
|
|
| 48 |
|
| 49 |
|
| 50 |
class EngineWrapper:
|
| 51 |
-
def __init__(self,
|
|
|
|
| 52 |
pass
|
| 53 |
|
| 54 |
def search_for(self, board, game, movetime):
|
|
@@ -124,9 +126,9 @@ class EngineWrapper:
|
|
| 124 |
|
| 125 |
|
| 126 |
class USIEngine(EngineWrapper):
|
| 127 |
-
def __init__(self, commands, options, silence_stderr=False, cwd=None):
|
| 128 |
commands = commands[0] if len(commands) == 1 else commands
|
| 129 |
-
self.
|
| 130 |
|
| 131 |
self.engine = usi.Engine(commands, cwd=cwd)
|
| 132 |
self.engine.usi()
|
|
@@ -162,4 +164,4 @@ class USIEngine(EngineWrapper):
|
|
| 162 |
|
| 163 |
def getHomemadeEngine(name):
|
| 164 |
import strategies
|
| 165 |
-
return eval(f"strategies.{name}")
|
|
|
|
| 20 |
if engine_options:
|
| 21 |
for k, v in engine_options.items():
|
| 22 |
commands.append(f"--{k}={v}")
|
| 23 |
+
go_commands = cfg.get("go_commands") or {}
|
| 24 |
|
| 25 |
silence_stderr = cfg.get("silence_stderr", False)
|
| 26 |
|
|
|
|
| 33 |
f"Invalid engine type: {engine_type}. Expected usi or homemade.")
|
| 34 |
|
| 35 |
logger.debug(f"Starting engine: {' '.join(commands)}")
|
| 36 |
+
return Engine(commands, usi_options, go_commands, silence_stderr, cwd=engine_working_dir)
|
| 37 |
|
| 38 |
|
| 39 |
class Termination(str, Enum):
|
|
|
|
| 49 |
|
| 50 |
|
| 51 |
class EngineWrapper:
|
| 52 |
+
def __init__(self, go_commands):
|
| 53 |
+
self.go_commands = go_commands
|
| 54 |
pass
|
| 55 |
|
| 56 |
def search_for(self, board, game, movetime):
|
|
|
|
| 126 |
|
| 127 |
|
| 128 |
class USIEngine(EngineWrapper):
|
| 129 |
+
def __init__(self, commands, options, go_commands, silence_stderr=False, cwd=None):
|
| 130 |
commands = commands[0] if len(commands) == 1 else commands
|
| 131 |
+
super(USIEngine, self).__init__(go_commands)
|
| 132 |
|
| 133 |
self.engine = usi.Engine(commands, cwd=cwd)
|
| 134 |
self.engine.usi()
|
|
|
|
| 164 |
|
| 165 |
def getHomemadeEngine(name):
|
| 166 |
import strategies
|
| 167 |
+
return eval(f"strategies.{name}")
|
lishogi-bot.py
CHANGED
|
@@ -245,7 +245,7 @@ def play_game(li, game_id, control_queue, user_profile, config, challenge_queue,
|
|
| 245 |
initial_state = json.loads(next(lines).decode("utf-8"))
|
| 246 |
game = model.Game(initial_state, user_profile["username"], li.baseUrl, config.get("abort_time", 20))
|
| 247 |
|
| 248 |
-
engine = engine_wrapper.create_engine(config
|
| 249 |
engine.get_opponent_info(game)
|
| 250 |
conversation = Conversation(game, engine, li, __version__, challenge_queue)
|
| 251 |
|
|
@@ -595,4 +595,4 @@ if __name__ == "__main__":
|
|
| 595 |
start_lishogi_bot()
|
| 596 |
except Exception as error:
|
| 597 |
logger.error(error)
|
| 598 |
-
logger.error(game_error_handler(error))
|
|
|
|
| 245 |
initial_state = json.loads(next(lines).decode("utf-8"))
|
| 246 |
game = model.Game(initial_state, user_profile["username"], li.baseUrl, config.get("abort_time", 20))
|
| 247 |
|
| 248 |
+
engine = engine_wrapper.create_engine(config)
|
| 249 |
engine.get_opponent_info(game)
|
| 250 |
conversation = Conversation(game, engine, li, __version__, challenge_queue)
|
| 251 |
|
|
|
|
| 595 |
start_lishogi_bot()
|
| 596 |
except Exception as error:
|
| 597 |
logger.error(error)
|
| 598 |
+
logger.error(game_error_handler(error))
|
lishogi.py
CHANGED
|
@@ -57,12 +57,14 @@ class Lishogi:
|
|
| 57 |
giveup=is_final,
|
| 58 |
backoff_log_level=logging.DEBUG,
|
| 59 |
giveup_log_level=logging.DEBUG)
|
| 60 |
-
def api_get(self, path, raise_for_status=True):
|
| 61 |
logging.getLogger("backoff").setLevel(self.logging_level)
|
| 62 |
url = urljoin(self.baseUrl, path)
|
| 63 |
-
|
|
|
|
| 64 |
if rate_limit_check(response) or raise_for_status:
|
| 65 |
response.raise_for_status()
|
|
|
|
| 66 |
return response.json()
|
| 67 |
|
| 68 |
@backoff.on_exception(backoff.constant,
|
|
@@ -72,12 +74,14 @@ class Lishogi:
|
|
| 72 |
giveup=is_final,
|
| 73 |
backoff_log_level=logging.DEBUG,
|
| 74 |
giveup_log_level=logging.DEBUG)
|
| 75 |
-
def api_post(self, path, data=None, raise_for_status=True):
|
| 76 |
logging.getLogger("backoff").setLevel(self.logging_level)
|
| 77 |
url = urljoin(self.baseUrl, path)
|
| 78 |
-
|
|
|
|
| 79 |
if rate_limit_check(response) or raise_for_status:
|
| 80 |
response.raise_for_status()
|
|
|
|
| 81 |
return response.json()
|
| 82 |
|
| 83 |
def get_game(self, game_id):
|
|
@@ -127,5 +131,5 @@ class Lishogi:
|
|
| 127 |
self.session.headers.update(self.header)
|
| 128 |
|
| 129 |
def challenge_ai(self):
|
| 130 |
-
|
| 131 |
-
return self.api_post(ENDPOINTS["challenge_ai"], data=
|
|
|
|
| 57 |
giveup=is_final,
|
| 58 |
backoff_log_level=logging.DEBUG,
|
| 59 |
giveup_log_level=logging.DEBUG)
|
| 60 |
+
def api_get(self, path, raise_for_status=True, timeout=2):
|
| 61 |
logging.getLogger("backoff").setLevel(self.logging_level)
|
| 62 |
url = urljoin(self.baseUrl, path)
|
| 63 |
+
logger.debug(url)
|
| 64 |
+
response = self.session.get(url, timeout=timeout)
|
| 65 |
if rate_limit_check(response) or raise_for_status:
|
| 66 |
response.raise_for_status()
|
| 67 |
+
logger.debug(response.json())
|
| 68 |
return response.json()
|
| 69 |
|
| 70 |
@backoff.on_exception(backoff.constant,
|
|
|
|
| 74 |
giveup=is_final,
|
| 75 |
backoff_log_level=logging.DEBUG,
|
| 76 |
giveup_log_level=logging.DEBUG)
|
| 77 |
+
def api_post(self, path, data=None, raise_for_status=True, timeout=2):
|
| 78 |
logging.getLogger("backoff").setLevel(self.logging_level)
|
| 79 |
url = urljoin(self.baseUrl, path)
|
| 80 |
+
logger.debug(url)
|
| 81 |
+
response = self.session.post(url, data=data, timeout=timeout)
|
| 82 |
if rate_limit_check(response) or raise_for_status:
|
| 83 |
response.raise_for_status()
|
| 84 |
+
logger.debug(response.json())
|
| 85 |
return response.json()
|
| 86 |
|
| 87 |
def get_game(self, game_id):
|
|
|
|
| 131 |
self.session.headers.update(self.header)
|
| 132 |
|
| 133 |
def challenge_ai(self):
|
| 134 |
+
challenge = {"level": 1, "clock.limit": 60, "clock.increment": 0, "clock.byoyomi": 2, "clock.periods": 1}
|
| 135 |
+
return self.api_post(ENDPOINTS["challenge_ai"], data=challenge, timeout=30)
|
requirements.txt
CHANGED
|
@@ -3,3 +3,7 @@ PyYAML==6.0
|
|
| 3 |
requests==2.28.2
|
| 4 |
backoff==2.2.1
|
| 5 |
rich==13.3.3
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
requests==2.28.2
|
| 4 |
backoff==2.2.1
|
| 5 |
rich==13.3.3
|
| 6 |
+
|
| 7 |
+
# Requirements for tests
|
| 8 |
+
pytest==7.2.2
|
| 9 |
+
pytest-timeout==2.1.0
|
tests.py
CHANGED
|
@@ -5,8 +5,6 @@ import requests
|
|
| 5 |
import time
|
| 6 |
import zipfile
|
| 7 |
import yaml
|
| 8 |
-
import shogi
|
| 9 |
-
import shogi.KIF as kif
|
| 10 |
import shutil
|
| 11 |
import importlib
|
| 12 |
lishogi_bot = importlib.import_module("lishogi-bot")
|
|
@@ -18,15 +16,6 @@ def test_nothing():
|
|
| 18 |
assert True
|
| 19 |
|
| 20 |
|
| 21 |
-
def download_yo():
|
| 22 |
-
response = requests.get("https://github.com/mizar/YaneuraOu/releases/download/v7.0.0/Suisho5-YaneuraOu-v7.0.0-windows.zip", allow_redirects=True)
|
| 23 |
-
with open("yo.zip", "wb") as file:
|
| 24 |
-
file.write(response.content)
|
| 25 |
-
with zipfile.ZipFile("yo.zip", "r") as zip_ref:
|
| 26 |
-
zip_ref.extractall(".")
|
| 27 |
-
shutil.copyfile(f"YaneuraOu_NNUE-tournament-clang++-sse42.exe", f"yo.exe")
|
| 28 |
-
|
| 29 |
-
|
| 30 |
def run_bot(CONFIG, logging_level):
|
| 31 |
lishogi_bot.logger.info(lishogi_bot.intro())
|
| 32 |
li = lishogi_bot.lishogi.Lishogi(CONFIG["token"], CONFIG["url"], lishogi_bot.__version__, logging_level)
|
|
@@ -65,16 +54,11 @@ def run_bot(CONFIG, logging_level):
|
|
| 65 |
@pytest.mark.timeout(300)
|
| 66 |
def run_test():
|
| 67 |
lishogi_bot.start(li, user_profile, CONFIG, logging_level, None, one_game=True)
|
| 68 |
-
|
| 69 |
-
response =
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
board = shogi.Board()
|
| 74 |
-
for move in summary["moves"]:
|
| 75 |
-
board.push_usi(move)
|
| 76 |
-
win = board.turn == (shogi.WHITE if starting else shogi.BLACK) and board.is_game_over()
|
| 77 |
-
assert win
|
| 78 |
|
| 79 |
run_test()
|
| 80 |
else:
|
|
@@ -92,17 +76,15 @@ def run_bot(CONFIG, logging_level):
|
|
| 92 |
def test_bot():
|
| 93 |
logging_level = lishogi_bot.logging.INFO # lishogi_bot.logging_level.DEBUG
|
| 94 |
lishogi_bot.logging_configurer(logging_level, None)
|
| 95 |
-
download_yo()
|
| 96 |
-
lishogi_bot.logger.info("Downloaded YaneuraOu for NNUE")
|
| 97 |
with open("./config.yml.default") as file:
|
| 98 |
CONFIG = yaml.safe_load(file)
|
| 99 |
CONFIG["token"] = TOKEN
|
| 100 |
-
CONFIG["engine"]["dir"] = "
|
| 101 |
-
CONFIG["engine"]["name"] = "
|
| 102 |
-
CONFIG["engine"]["
|
| 103 |
-
CONFIG["engine"]["
|
| 104 |
run_bot(CONFIG, logging_level)
|
| 105 |
|
| 106 |
|
| 107 |
if __name__ == "__main__":
|
| 108 |
-
test_bot()
|
|
|
|
| 5 |
import time
|
| 6 |
import zipfile
|
| 7 |
import yaml
|
|
|
|
|
|
|
| 8 |
import shutil
|
| 9 |
import importlib
|
| 10 |
lishogi_bot = importlib.import_module("lishogi-bot")
|
|
|
|
| 16 |
assert True
|
| 17 |
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
def run_bot(CONFIG, logging_level):
|
| 20 |
lishogi_bot.logger.info(lishogi_bot.intro())
|
| 21 |
li = lishogi_bot.lishogi.Lishogi(CONFIG["token"], CONFIG["url"], lishogi_bot.__version__, logging_level)
|
|
|
|
| 54 |
@pytest.mark.timeout(300)
|
| 55 |
def run_test():
|
| 56 |
lishogi_bot.start(li, user_profile, CONFIG, logging_level, None, one_game=True)
|
| 57 |
+
headers = {"Accept": "application/json"}
|
| 58 |
+
response = requests.get(f"https://lishogi.org/game/export/{game_id}?moves=false", headers=headers)
|
| 59 |
+
json = response.json()
|
| 60 |
+
winner = json["winner"]
|
| 61 |
+
assert "user" in json["players"][winner]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
run_test()
|
| 64 |
else:
|
|
|
|
| 76 |
def test_bot():
|
| 77 |
logging_level = lishogi_bot.logging.INFO # lishogi_bot.logging_level.DEBUG
|
| 78 |
lishogi_bot.logging_configurer(logging_level, None)
|
|
|
|
|
|
|
| 79 |
with open("./config.yml.default") as file:
|
| 80 |
CONFIG = yaml.safe_load(file)
|
| 81 |
CONFIG["token"] = TOKEN
|
| 82 |
+
CONFIG["engine"]["dir"] = "/usr/games"
|
| 83 |
+
CONFIG["engine"]["name"] = "fairy-stockfish"
|
| 84 |
+
CONFIG["engine"]["go_commands"] = {}
|
| 85 |
+
CONFIG["engine"]["go_commands"]["nodes"] = "100000"
|
| 86 |
run_bot(CONFIG, logging_level)
|
| 87 |
|
| 88 |
|
| 89 |
if __name__ == "__main__":
|
| 90 |
+
test_bot()
|