diff --git a/Client/Client.py b/Client/Client.py index e64afb4..b7cb4fb 100644 --- a/Client/Client.py +++ b/Client/Client.py @@ -44,7 +44,7 @@ from concurrent.futures import ThreadPoolExecutor TIMEOUT_HTTP = 30 # Timeout in seconds for HTTP requests TIMEOUT_ERROR = 10 # Timeout in seconds when any errors are thrown TIMEOUT_WORKLOAD = 30 # Timeout in seconds between workload requests -CLIENT_VERSION = '10' # Client version to send to the Server +CLIENT_VERSION = '11' # Client version to send to the Server IS_WINDOWS = platform.system() == 'Windows' # Don't touch this IS_LINUX = platform.system() != 'Windows' # Don't touch this @@ -433,7 +433,7 @@ class Cutechess(object): return '-openings file=Books/%s format=%s order=random plies=16' % (book_name, book_suffix) @staticmethod - def engine_settings(config, command, branch, nps): + def engine_settings(config, command, branch, scale_factor): # Extract configuration from the Workload options = config.workload['test'][branch]['options'] @@ -443,7 +443,7 @@ class Cutechess(object): # Human-readable name, and scale the time control name = command.removesuffix('.exe') - control = scale_time_control(config.workload, nps, branch) + control = scale_time_control(config.workload, scale_factor, branch) # Private engines, when using Networks, must set them via UCI if private and network and network != 'None': @@ -665,7 +665,7 @@ def run_bench(engine, outqueue, private_net=None): outqueue.put(parse_bench_output(stdout)) except Exception: outqueue.put((0, 0)) -def scale_time_control(workload, nps, branch): +def scale_time_control(workload, scale_factor, branch): # Extract everything from the workload dictionary reference_nps = workload['test'][branch]['nps'] @@ -687,7 +687,7 @@ def scale_time_control(workload, nps, branch): # Scale the time based on this machine's NPS. Add a time Margin to avoid time losses. if results: mode, value = results.group('mode', 'value') - return 'st=%.2f timemargin=100' % ((float(value) * reference_nps) / (1000 * nps)) + return 'st=%.2f timemargin=100' % ((float(value) * scale_factor / 1000)) # Searching for "X/Y+Z" time controls pattern = '(?P(\d+/)?)(?P\d*(\.\d+)?)(?P\+(\d+\.)?\d+)?' @@ -699,8 +699,8 @@ def scale_time_control(workload, nps, branch): inc = 0.0 if inc is None else inc.lstrip('+') # Scale the time based on this machine's NPS - base = float(base) * reference_nps / nps - inc = float(inc ) * reference_nps / nps + base = float(base) * scale_factor + inc = float(inc ) * scale_factor # Format the time control for cutechess if moves is None: return 'tc=%.2f+%.2f' % (base, inc) @@ -883,12 +883,22 @@ def complete_workload(config): if not dev_nps or not base_nps: return ServerReporter.report_nps(config, dev_nps, base_nps) + # Scale the engines together, using their NPS relative to expected + dev_factor = config.workload['test']['dev' ]['nps'] / dev_nps + base_factor = config.workload['test']['base']['nps'] / base_nps + avg_factor = (dev_factor + base_factor) / 2 + + print () # Record this information + print ('Scale Factor Dev : %.4f' % (dev_factor )) + print ('Scale Factor Base : %.4f' % (base_factor)) + print ('Scale Factor Avg : %.4f' % (avg_factor )) + # Launch and manage all of the Cutechess workers with ThreadPoolExecutor(max_workers=config.sockets) as executor: tasks = [] # Create each of the Cutechess workers for x in range(config.sockets): - cmd = build_cutechess_command(config, dev_name, base_name, dev_nps, base_nps, x) + cmd = build_cutechess_command(config, dev_name, base_name, avg_factor, x) tasks.append(executor.submit(run_and_parse_cutechess, config, cmd, x)) # Await the completion of all Cutechess workers @@ -933,29 +943,30 @@ def download_opening_book(config): def download_network_weights(config, branch): # Some tests may not use Neural Networks - network_name = config.workload['test'][branch]['network'] - if not network_name or network_name == 'None': return None + engine_name = config.workload['test'][branch]['engine'] + network_sha = config.workload['test'][branch]['network'] + if not network_sha or network_sha == 'None': return None # Log that we are obtaining a Neural Network pattern = 'Fetching Neural Network [ %s, %-4s ]' - print(pattern % (network_name, branch.upper())) + print(pattern % (network_sha, branch.upper())) # Fetch the Netural Network if we do not already have it - network_path = os.path.join('Networks', network_name) + network_path = os.path.join('Networks', network_sha) if not os.path.isfile(network_path): target = url_join(config.server, 'clientGetNetwork') payload = { 'username' : config.username, 'password' : config.password } - download_file(url_join(target, network_name), network_path, payload) + download_file(url_join(target, engine_name, network_sha), network_path, payload) # Verify the download and delete partial or corrupted ones with open(network_path, 'rb') as network: sha256 = hashlib.sha256(network.read()).hexdigest() sha256 = sha256[:8].upper() - if network_name != sha256: os.remove(network_path) + if network_sha != sha256: os.remove(network_path) # We have to have the correct Neural Network to continue - if network_name != sha256: - raise Exception('Invalid SHA for %s' % (network_name)) + if network_sha != sha256: + raise Exception('Invalid SHA for %s' % (network_sha)) return network_path @@ -1051,6 +1062,7 @@ def download_engine(arguments, branch, network): ServerReporter.report_build_fail(config, branch, cxx_output) return None + def run_benchmarks(config, branch, engine, network): queue = multiprocessing.Queue() @@ -1080,20 +1092,13 @@ def run_benchmarks(config, branch, engine, network): # Set NPS to 0 if we had any errors return 0 if not bench or error else nps -def build_cutechess_command(config, dev_cmd, base_cmd, dev_nps, base_nps, socket): - - dev_engine = config.workload['test']['dev' ]['engine'] - base_engine = config.workload['test']['base']['engine'] - - # Average the time control scalings for self-play only - if dev_engine == base_engine: - dev_nps = base_nps = (dev_nps + base_nps) / 2 +def build_cutechess_command(config, dev_cmd, base_cmd, scale_factor, socket): flags = ' ' + Cutechess.basic_settings(config, socket) flags += ' ' + Cutechess.concurrency_settings(config) flags += ' ' + Cutechess.adjudication_settings(config) - flags += ' ' + Cutechess.engine_settings(config, dev_cmd, 'dev', dev_nps) - flags += ' ' + Cutechess.engine_settings(config, base_cmd, 'base', base_nps) + flags += ' ' + Cutechess.engine_settings(config, dev_cmd, 'dev', scale_factor) + flags += ' ' + Cutechess.engine_settings(config, base_cmd, 'base', scale_factor) flags += ' ' + Cutechess.book_settings(config) flags += ' ' + Cutechess.pgnout_settings(config, dev_cmd, base_cmd, socket) @@ -1199,3 +1204,4 @@ if __name__ == '__main__': except Exception: traceback.print_exc() + time.sleep(TIMEOUT_ERROR) diff --git a/OpenBench/config.py b/OpenBench/config.py index 45fe611..a246856 100644 --- a/OpenBench/config.py +++ b/OpenBench/config.py @@ -42,7 +42,7 @@ REQUIRE_MANUAL_REGISTRATION = False # Disable the public facing registration pag OPENBENCH_CONFIG = { # Server Client version control - 'client_version' : '10', + 'client_version' : '11', # Generic Error Messages useful to those setting up their own instance 'error' : { diff --git a/OpenBench/static/networks.js b/OpenBench/static/networks.js new file mode 100644 index 0000000..1df1d2d --- /dev/null +++ b/OpenBench/static/networks.js @@ -0,0 +1,36 @@ + +var Networks = JSON.parse(document.getElementById('json-networks').textContent); + +var Network_Sorting; + +function swap_networks(index1, index2) { + + var temp = Networks[index1]; + Networks[index1] = Networks[index2]; + Networks[index2] = temp; + + var table = document.getElementById("network-table"); + var temp_row = table.rows[index1+1].innerHTML + table.rows[index1+1].innerHTML = table.rows[index2+1].innerHTML; + table.rows[index2+1].innerHTML = temp_row; +} + +function invert_networks() { + for (let i = 0; Networks.length > i * 2; i++) + swap_networks(i, Networks.length-i-1); +} + +function sort_networks(field) { + + console.log(field); + + if (Network_Sorting == field) + return invert_networks(); + + for (let i = 0; i != Networks.length; i++) + for (let j = i + 1; j != Networks.length; j++) + if (Networks[j][field] > Networks[i][field]) + swap_networks(i, j); + + Network_Sorting = field; +}; diff --git a/OpenBench/static/style.css b/OpenBench/static/style.css index 830bc1f..8d91512 100644 --- a/OpenBench/static/style.css +++ b/OpenBench/static/style.css @@ -129,14 +129,20 @@ body, html, main{ background-color: var(--color1); } -/* Tables that are too long can wrap words*/ +/* Tables that are too long can wrap words */ -#content .wrappable td{ +#content .wrappable td { white-space: pre-wrap; word-break: break-word; word-wrap: break-word; } +/* Things which enable a Cursor Pointer event */ + +#content .cursor { + cursor: pointer; +} + /* Table Headers in General */ #content .table-header th:first-child { diff --git a/OpenBench/urls.py b/OpenBench/urls.py index 324fb13..0492411 100644 --- a/OpenBench/urls.py +++ b/OpenBench/urls.py @@ -56,8 +56,10 @@ urlpatterns = [ # Links for viewing and managing Networks django.urls.path(r'networks/', OpenBench.views.networks), - django.urls.path(r'networks//', OpenBench.views.networks), - django.urls.path(r'networks///', OpenBench.views.networks), + django.urls.path(r'networks//', OpenBench.views.networks), + django.urls.path(r'networks///', OpenBench.views.networks), + django.urls.path(r'networks////', OpenBench.views.networks), + django.urls.path(r'newNetwork/', OpenBench.views.network_form), # Links for interacting with OpenBench via scripting django.urls.path(r'scripts/', OpenBench.views.scripts), @@ -67,8 +69,7 @@ urlpatterns = [ django.urls.path(r'clientGetBuildInfo/', OpenBench.views.client_get_build_info), django.urls.path(r'clientWorkerInfo/', OpenBench.views.client_worker_info), django.urls.path(r'clientGetWorkload/', OpenBench.views.client_get_workload), - django.urls.path(r'clientGetNetwork//', OpenBench.views.client_get_network), - django.urls.path(r'clientGetNetwork///', OpenBench.views.client_get_network), + django.urls.path(r'clientGetNetwork///', OpenBench.views.client_get_network), django.urls.path(r'clientWrongBench/', OpenBench.views.client_wrong_bench), django.urls.path(r'clientSubmitNPS/', OpenBench.views.client_submit_nps), django.urls.path(r'clientSubmitError/', OpenBench.views.client_submit_error), diff --git a/OpenBench/utils.py b/OpenBench/utils.py index c0ad287..9f6dd5b 100644 --- a/OpenBench/utils.py +++ b/OpenBench/utils.py @@ -18,18 +18,29 @@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -import math, re, requests, random, datetime, os, json +import datetime +import hashlib +import json +import math +import os +import random +import re +import requests -import OpenBench.models, OpenBench.stats - -import django.utils.timezone - -from django.utils import timezone -from django.db.models import F from django.contrib.auth import authenticate +from django.core.files.base import ContentFile +from django.core.files.storage import FileSystemStorage +from django.db.models import F +from django.http import FileResponse +from django.utils import timezone +from wsgiref.util import FileWrapper -from OpenBench.config import * -from OpenBench.models import Engine, Profile, Machine, Result, Test, Network +from OpenSite.settings import MEDIA_ROOT + +from OpenBench.config import OPENBENCH_CONFIG +from OpenBench.models import * +from OpenBench.stats import SPRT +from OpenBench.views import redirect def path_join(*args): @@ -78,25 +89,25 @@ def parse_time_control(time_control): def get_pending_tests(): - t = OpenBench.models.Test.objects.filter(approved=False) + t = Test.objects.filter(approved=False) t = t.exclude(finished=True) t = t.exclude(deleted=True) return t.order_by('-creation') def get_active_tests(): - t = OpenBench.models.Test.objects.filter(approved=True) + t = Test.objects.filter(approved=True) t = t.exclude(awaiting=True) t = t.exclude(finished=True) t = t.exclude(deleted=True) return t.order_by('-priority', '-currentllr') def get_completed_tests(): - t = OpenBench.models.Test.objects.filter(finished=True) + t = Test.objects.filter(finished=True) t = t.exclude(deleted=True) return t.order_by('-updated') def get_awaiting_tests(): - t = OpenBench.models.Test.objects.filter(awaiting=True) + t = Test.objects.filter(awaiting=True) t = t.exclude(finished=True) t = t.exclude(deleted=True) return t.order_by('-creation') @@ -104,7 +115,7 @@ def get_awaiting_tests(): def getRecentMachines(minutes=5): target = datetime.datetime.utcnow() - target = target.replace(tzinfo=django.utils.timezone.utc) + target = target.replace(tzinfo=timezone.utc) target = target - datetime.timedelta(minutes=minutes) return Machine.objects.filter(updated__gte=target) @@ -313,7 +324,7 @@ def verify_test_creation(request): except: errors.append('"{0}" needs to be at least 1 for {1}'.format(option, field_name)) def verify_configuration(field, field_name, parent): - try: assert request.POST[field] in OpenBench.config.OPENBENCH_CONFIG[parent].keys() + try: assert request.POST[field] in OPENBENCH_CONFIG[parent].keys() except: errors.append('{0} was not found in the configuration'.format(field_name)) def verify_time_control(field, field_name): @@ -337,11 +348,11 @@ def verify_test_creation(request): try: assert re.match(pattern, request.POST[field]) except: errors.append('Sources must be found on https://github.com//') - def verify_network(field, fieldName): + def verify_network(field, field_name, engine_field): try: if request.POST[field] == '': return - Network.objects.get(sha256=request.POST[field]) - except: errors.append('Unknown Network Provided for {0}'.format(fieldName)) + Network.objects.get(engine=request.POST[engine_field], sha256=request.POST[field]) + except: errors.append('Unknown Network Provided for {0}'.format(field_name)) def verify_test_mode(field): try: assert request.POST[field] in ['SPRT', 'GAMES'] @@ -380,7 +391,7 @@ def verify_test_creation(request): # Verify everything about the Dev Engine (verify_configuration, 'dev_engine', 'Dev Engine', 'engines'), (verify_github_repo , 'dev_repo'), - (verify_network , 'dev_network', 'Dev Network'), + (verify_network , 'dev_network', 'Dev Network', 'dev_engine'), (verify_options , 'dev_options', 'Threads', 'Dev Options'), (verify_options , 'dev_options', 'Hash', 'Dev Options'), (verify_time_control , 'dev_time_control', 'Dev Time Control'), @@ -388,7 +399,7 @@ def verify_test_creation(request): # Verify everything about the Base Engine (verify_configuration, 'base_engine', 'Base Engine', 'engines'), (verify_github_repo , 'base_repo'), - (verify_network , 'base_network', 'Base Network'), + (verify_network , 'base_network', 'Base Network', 'base_engine'), (verify_options , 'base_options', 'Threads', 'Base Options'), (verify_options , 'base_options', 'Hash', 'Base Options'), (verify_time_control , 'base_time_control', 'Base Time Control'), @@ -474,10 +485,10 @@ def create_new_test(request): test.max_games = int(request.POST['test_max_games']) if test.dev_network: - test.dev_netname = Network.objects.get(sha256=test.dev_network ).name + test.dev_netname = Network.objects.get(engine=test.dev_engine, sha256=test.dev_network).name if test.base_network: - test.base_netname = Network.objects.get(sha256=test.base_network).name + test.base_netname = Network.objects.get(engine=test.base_engine, sha256=test.base_network).name test.save() @@ -525,6 +536,94 @@ def get_workload(machine): return { 'workload' : workload_to_dictionary(test, result) } +# Purely Helper functions for Networks views + +def network_disambiguate(engine, identifier): + + candidates = Network.objects.filter(engine=engine) + + # Identifier actually refers to the Network name + if (network := candidates.filter(name=identifier).first()): + return network + + # Identifier actually refers to the Network SHA + if (network := candidates.filter(sha256=identifier).first()): + return network + + # No Network exists with engine this Name or Sha + return None + +def network_upload(request, engine, name): + + # Extract and process the Network file to produce a SHA + netfile = request.FILES['netfile'] + sha256 = hashlib.sha256(netfile.file.read()).hexdigest()[:8].upper() + + # Rejecct Networks with strange characters + if not re.match(r'^[a-zA-Z0-9_.-]+$', name): + return redirect(request, '/networks/', error='Valid characters are [a-zA-Z0-9_.-]') + + # Don't allow duplicate uploads for the same engine + if Network.objects.filter(engine=engine, sha256=sha256): + return redirect(request, '/networks/', error='Network with that hash already exists for that engine') + + # Don't allow duplicate uploads for the same engine + if Network.objects.filter(engine=engine, name=name): + return redirect(request, '/networks/', error='Network with that name already exists for that engine') + + # Filter out anyone who has used an unknown engine + if engine not in OPENBENCH_CONFIG['engines'].keys(): + return redirect(request, '/networks/', error='No Engine found with matching name') + + # Save the file locally into /Media/ if we don't already have this file + if not Network.objects.filter(sha256=sha256): + FileSystemStorage().save('%s' % (sha256), netfile) + + # Create the Network object mapping to the saved local file + Network.objects.create( + sha256=sha256, name=name, + engine=engine, author=request.user.username) + + # Redirect to Engine specific view, to add clarity + return redirect(request, '/networks/%s/' % (engine), status='Uploaded %s for %s' % (name, engine)) + +def network_default(request, engine, network): + + # Update default to False for all Networks, except this one + Network.objects.filter(engine=engine).update(default=False) + network.default = True; network.save() + + # Report this, and refer to the Engine specific view + status = 'Set %s as default for %s' % (network.name, network.engine) + return redirect(request, '/networks/%s/' % (network.engine), status=status) + +def network_delete(request, engine, network): + + # Save information before deleting the Network Model + status = 'Deleted %s for %s' % (network.name, network.engine) + sha256 = network.sha256; network.delete() + + # Only delete the actual file if no other engines use it + if not Network.objects.filter(sha256=sha256): + FileSystemStorage().delete(sha256) + + # Report this, and refer to the Engine specific view + return redirect(request, '/networks/%s/' % (engine), status=status) + +def network_download(request, engine, network): + + # Craft the download HTML response + netfile = os.path.join(MEDIA_ROOT, network.sha256) + fwrapper = FileWrapper(open(netfile, 'rb'), 8192) + response = FileResponse(fwrapper, content_type='application/octet-stream') + + # Set all headers and return response + response['Expires'] = (datetime.datetime.utcnow() + datetime.timedelta(days=7)).ctime() + response['Content-Length'] = os.path.getsize(netfile) + response['Content-Disposition'] = 'attachment; filename=' + network.sha256 + return response + + # Purely Helper functions for get_workload() def get_valid_workloads(machine): @@ -587,7 +686,7 @@ def select_workload(machine, tests, variance=0.25): # therefore we may have this machine repeat its existing workload again ideal_ratio = sum([x['cores'] for x in table.values()]) / sum([x['throughput'] for x in table.values()]) if min(ratios) / ideal_ratio > 1 - variance: - return OpenBench.models.Test.objects.get(id=machine.workload) + return Test.objects.get(id=machine.workload) # Fallback to simply doing the least attention given test return tests[random.choice(lowest_idxs)] @@ -673,7 +772,7 @@ def update_test(request, machine): # Compute a new LLR for the updated results WLD = (swins, slosses, sdraws) - sprt = OpenBench.stats.SPRT(*WLD, test.elolower, test.eloupper) + sprt = SPRT(*WLD, test.elolower, test.eloupper) # Check for H0 or H1 being accepted passed = sprt > test.upperllr diff --git a/OpenBench/views.py b/OpenBench/views.py index 6c65292..2c0f7d4 100644 --- a/OpenBench/views.py +++ b/OpenBench/views.py @@ -33,9 +33,8 @@ from OpenBench.models import * from django.contrib.auth.models import User from OpenSite.settings import MEDIA_ROOT -from wsgiref.util import FileWrapper from django.db.models import F -from django.http import HttpResponse, FileResponse, JsonResponse +from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from django.core.files.storage import FileSystemStorage from django.core.files.base import ContentFile @@ -438,102 +437,54 @@ def create_test(request): # NETWORK MANAGEMENT VIEWS # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -def networks(request, target=None, sha256=None, client=False): +def networks(request, engine=None, action=None, name=None, client=False): - # *** GET Requests: - # [1] Fetch a view of all the Networks on the framework (/networks/) - # [2] Fetch a view of all Networks for a given engine (/networks//) - # [3] Download the contents of a Network if allowed (/networks/download//) - # - # *** POST Requests: - # [1] Upload a Network to the framework (/networks/upload/) - # [2] Set as default a Network on the framework (/networks/default//) - # [3] Delete a Network from the framework (/networks/delete//) - # - # *** Rights: - # Any user may look at the list of Networks, for all or some engines - # Only authenticated and approved Users may interact in the remaining ways - - if not target or target.upper() not in ['UPLOAD', 'DEFAULT', 'DELETE', 'DOWNLOAD']: + # Without an identifier and a valid action, all we can do is view the list + if not name or action.upper() not in ['UPLOAD', 'DEFAULT', 'DELETE', 'DOWNLOAD']: networks = Network.objects.all() - if target: networks = networks.filter(engine=target) - return render(request, 'networks.html', { 'networks' : networks.order_by('-id') }) + if engine and engine in OPENBENCH_CONFIG['engines'].keys(): + networks = networks.filter(engine=engine) + return render(request, 'networks.html', { 'networks' : list(networks.order_by('-id').values()) }) + # Require logins. Clients will be artifically logged in if not request.user.is_authenticated: return django.http.HttpResponseRedirect('/login/') + # Require approver credentials, unless downloading as a client if not client and not Profile.objects.get(user=request.user).approver: return django.http.HttpResponseRedirect('/index/') - if target.upper() == 'UPLOAD': + # Split out Uploads, since there is no logic to disambiguate the name + if action.upper() == 'UPLOAD': + return OpenBench.utils.network_upload(request, engine, name) - if request.method == 'GET': - return render(request, 'uploadnet.html', {}) + # Push off all the actual effort to OpenBench.utils for all actions + actions = { + 'DEFAULT' : OpenBench.utils.network_default, + 'DELETE' : OpenBench.utils.network_delete, + 'DOWNLOAD' : OpenBench.utils.network_download, + } - name = request.POST['name'] - engine = request.POST['engine'] - netfile = request.FILES['netfile'] - sha256 = hashlib.sha256(netfile.file.read()).hexdigest()[:8].upper() + # Update the Network, if we can find one for the given name/sha256 + if (network := OpenBench.utils.network_disambiguate(engine, name)): + return actions[action.upper()](request, engine, network) - if not re.match(r'^[a-zA-Z0-9_.-]+$', name): - return redirect(request, '/uploadnet/', error='Valid characters are [a-zA-Z0-9_.-]') + # Otherwise we could not find the Network, and cannot do anything + return redirect(request, '/networks/', error='No network found with matching Sha') - if Network.objects.filter(sha256=sha256): - return redirect(request, '/uploadnet/', error='Network with that hash already exists') +def network_form(request): - if Network.objects.filter(engine=engine, name=name): - return redirect(request, '/uploadnet/', error='Network with that name already exists for that engine') + # Require logins. Clients will be artifically logged in + if not request.user.is_authenticated: + return django.http.HttpResponseRedirect('/login/') - if engine not in OPENBENCH_CONFIG['engines'].keys(): - return redirect(request, '/uploadnet/', error='No Engine found with matching name') - - FileSystemStorage().save(sha256, netfile) - - Network.objects.create( - sha256=sha256, name=name, - engine=engine, author=request.user.username) - - return redirect(request, '/networks/', status='Uploaded %s for %s' % (engine, name)) - - if target.upper() == 'DEFAULT': - - if not Network.objects.filter(sha256=sha256): - return redirect(request, '/networks/', error='No network found with matching Sha') - - network = Network.objects.get(sha256=sha256) - Network.objects.filter(engine=network.engine).update(default=False) - network.default = True; network.save() - - status = 'Set %s as default for %s' % (network.name, network.engine) - return redirect(request, '/networks/', status=status) - - if target.upper() == 'DELETE': - - if not Network.objects.filter(sha256=sha256): - return redirect(request, '/networks/', error='No network found with matching Sha') - - network = Network.objects.get(sha256=sha256) - status = 'Deleted %s for %s' % (network.name, network.engine) - - network.delete() - FileSystemStorage().delete(sha256) - - return redirect(request, '/networks/', status=status) - - if target.upper() == 'DOWNLOAD': - - if not Network.objects.filter(sha256=sha256): - return redirect(request, '/networks/', error='No network found with matching Sha') - - netfile = os.path.join(MEDIA_ROOT, sha256) - fwrapper = FileWrapper(open(netfile, 'rb'), 8192) - response = FileResponse(fwrapper, content_type='application/octet-stream') - - response['Expires'] = (datetime.datetime.utcnow() + datetime.timedelta(days=7)).ctime() - response['Content-Length'] = os.path.getsize(netfile) - response['Content-Disposition'] = 'attachment; filename=' + sha256 - return response + # Require approver credentials, unless downloading as a client + if not Profile.objects.get(user=request.user).approver: + return django.http.HttpResponseRedirect('/index/') + # Get requests should not be reaching this point + if request.method == 'GET': + return render(request, 'uploadnet.html', {}) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # OPENBENCH SCRIPTING # @@ -544,8 +495,13 @@ def scripts(request): login(request) # All requests are attached to a User - if request.POST['action'] == 'UPLOAD': - return networks(request, target='UPLOAD') + if request.POST['action'] == 'UPLOAD_NETWORK': + engine = request.POST['engine'] + name = request.POST['name'] + import sys + sys.stdout.write(engine + ' ' + name + '\n') + sys.stdout.flush() + return networks(request, engine, 'upload', name) if request.POST['action'] == 'CREATE_TEST': return newTest(request) @@ -654,19 +610,14 @@ def client_get_workload(request): return JsonResponse(OpenBench.utils.get_workload(machine)) @csrf_exempt -def client_get_network(request, identifier, engine=None): +def client_get_network(request, engine, name): # Verify the User's credentials try: django.contrib.auth.login(request, authenticate(request, True)) except UnableToAuthenticate: return HttpResponse('Bad Credentials') - # Return the requested Neural Network, after resolving the Network name - if engine is not None: - try: identifier = Network.objects.get(name=identifier, engine=engine).sha256 - except: return HttpResponse('Unable to find associated Network') - # Return the requested Neural Network file for the Client - return networks(request, target='DOWNLOAD', sha256=identifier, client=True) + return networks(request, engine, 'DOWNLOAD', name, client=True) @csrf_exempt def client_wrong_bench(request): diff --git a/Scripts/bench_all.py b/Scripts/bench_all.py deleted file mode 100755 index b0cf49d..0000000 --- a/Scripts/bench_all.py +++ /dev/null @@ -1,139 +0,0 @@ -import argparse -import hashlib -import multiprocessing -import os -import re -import requests -import subprocess -import sys - -sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) - -from bench_engine import run_benchmark -from OpenBench.config import OPENBENCH_CONFIG - -USE_OLD_BINARIES = True -OPENBENCH_USERNAME = None -OPENBENCH_PASSWORD = None -OPENBENCH_SERVER = 'http://chess.grantnet.us' -BENCHMARK_THREADS = None -BENCHMARK_SETS = None - -def download_network(engine, sha256): - - if not os.path.isdir('Networks'): - os.mkdir('Networks') - - if not os.path.isfile('Networks/%s' % (sha256)): - - print ('Downloading %s for %s...' % (sha256, engine)) - - target = '%s/clientGetNetwork/%s/' % (OPENBENCH_SERVER, sha256) - payload = { 'username' : OPENBENCH_USERNAME, 'password' : OPENBENCH_PASSWORD } - request = requests.post(data=payload, url=target) - - with open('Networks/%s' % (sha256), 'wb') as fout: - for chunk in request.iter_content(chunk_size=1024): - if chunk: fout.write(chunk) - fout.flush() - - with open('Networks/%s' % (sha256), 'rb') as network: - assert sha256 == hashlib.sha256(network.read()).hexdigest()[:8].upper() - -def download_default_networks(): - - target = '%s/networks/' % (OPENBENCH_SERVER) - information = requests.get(url=target) - - pattern = r'class="fas fa-star">.*? # +# # +# OpenBench is free software: you can redistribute it and/or modify # +# it under the terms of the GNU General Public License as published by # +# the Free Software Foundation, either version 3 of the License, or # +# (at your option) any later version. # +# # +# OpenBench is distributed in the hope that it will be useful, # +# but WITHOUT ANY WARRANTY; without even the implied warranty of # +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # +# GNU General Public License for more details. # +# # +# You should have received a copy of the GNU General Public License # +# along with this program. If not, see . # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -OPENBENCH_SERVER = 'http://chess.grantnet.us' +import argparse +import hashlib +import os +import requests -def download_network(username, password, sha256): +def url_join(*args): + # Join a set of URL paths while maintaining the correct format + return '/'.join([f.lstrip('/').rstrip('/') for f in args]) + '/' - print ('Downloading %s...' % (sha256)) +def download_network(username, password, server, engine, name): - # Check if we already have the Network file by looking at SHA256 - if os.path.isfile(sha256): - with open(sha256, 'rb') as network: - if sha256 == hashlib.sha256(network.read()).hexdigest()[:8].upper(): - return + print ('Downloading %s for %s...' % (name, engine)) - target = '%s/clientGetNetwork/%s/' % (OPENBENCH_SERVER, sha256) + target = url_join(server, 'clientGetNetwork', engine, name) payload = { 'username' : username, 'password' : password } request = requests.post(data=payload, url=target) - with open(sha256, 'wb') as fout: + with open(name, 'wb') as fout: for chunk in request.iter_content(chunk_size=1024): if chunk: fout.write(chunk) fout.flush() - with open(sha256, 'rb') as network: - if sha256 != hashlib.sha256(network.read()).hexdigest()[:8].upper(): - print ('Failed to Download...') - if __name__ == '__main__': - req_user = required=('OPENBENCH_USERNAME' not in os.environ) - req_pass = required=('OPENBENCH_PASSWORD' not in os.environ) - help_user = 'Username. May also be passed as OPENBENCH_USERNAME environment variable' - help_pass = 'Password. May also be passed as OPENBENCH_PASSWORD environment variable' + # We can use ENV variables for Username, Password, and Server + req_user = required=('OPENBENCH_USERNAME' not in os.environ) + req_pass = required=('OPENBENCH_PASSWORD' not in os.environ) + req_server = required=('OPENBENCH_SERVER' not in os.environ) + # For clarity, seperate out this help text + help_user = 'Username. May also be passed as OPENBENCH_USERNAME environment variable' + help_pass = 'Password. May also be passed as OPENBENCH_PASSWORD environment variable' + help_server = ' Server. May also be passed as OPENBENCH_SERVER environment variable' + + # Parse all arguments, all of which must exist in some form p = argparse.ArgumentParser() - p.add_argument('-U', '--username', help=help_user , required=req_user) - p.add_argument('-P', '--password', help=help_pass , required=req_pass) - p.add_argument('-N', '--network', help='Network SHA256', required=True) - arguments = p.parse_args() + p.add_argument('-U', '--username', help=help_user , required=req_user ) + p.add_argument('-P', '--password', help=help_pass , required=req_pass ) + p.add_argument('-S', '--server' , help=help_server , required=req_server) + p.add_argument('-E', '--engine' , help='Engine' , required=True ) + p.add_argument('-N', '--network' , help='Name or Sha', required=True ) + args = p.parse_args() - if arguments.username is None: arguments.username = os.environ['OPENBENCH_USERNAME'] - if arguments.password is None: arguments.password = os.environ['OPENBENCH_PASSWORD'] + # Fallback on ENV variables for Username, Password, and Server + args.username = args.username if args.username else os.environ['OPENBENCH_USERNAME'] + args.password = args.password if args.password else os.environ['OPENBENCH_PASSWORD'] + args.server = args.server if args.server else os.environ['OPENBENCH_SERVER' ] - download_network(arguments.username, arguments.password, arguments.network) + download_network(args.username, args.password, args.server, args.engine, args.network) diff --git a/Scripts/upload_net.py b/Scripts/upload_net.py index 2a9ebce..255a587 100755 --- a/Scripts/upload_net.py +++ b/Scripts/upload_net.py @@ -1,17 +1,87 @@ +#!/bin/python3 + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# OpenBench is a chess engine testing framework by Andrew Grant. # +# # +# # +# OpenBench is free software: you can redistribute it and/or modify # +# it under the terms of the GNU General Public License as published by # +# the Free Software Foundation, either version 3 of the License, or # +# (at your option) any later version. # +# # +# OpenBench is distributed in the hope that it will be useful, # +# but WITHOUT ANY WARRANTY; without even the implied warranty of # +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # +# GNU General Public License for more details. # +# # +# You should have received a copy of the GNU General Public License # +# along with this program. If not, see . # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +import argparse +import os +import re import requests -URL = 'http://chess.grantnet.us/scripts/' -FILENAME = '' +def url_join(*args): + # Join a set of URL paths while maintaining the correct format + return '/'.join([f.lstrip('/').rstrip('/') for f in args]) + '/' -data = { - 'engine' : '', - 'name' : '', - 'username' : '', - 'password' : '', - 'action' : 'UPLOAD', -} +def upload_network(): -with open(FILENAME, 'rb') as file: - r = requests.post(URL, data=data, files={'netfile' : file}) + # We can use ENV variables for Username, Password, and Server + req_user = required=('OPENBENCH_USERNAME' not in os.environ) + req_pass = required=('OPENBENCH_PASSWORD' not in os.environ) + req_server = required=('OPENBENCH_SERVER' not in os.environ) -print(r.text) \ No newline at end of file + # For clarity, seperate out this help text + help_user = 'Username. May also be passed as OPENBENCH_USERNAME environment variable' + help_pass = 'Password. May also be passed as OPENBENCH_PASSWORD environment variable' + help_server = ' Server. May also be passed as OPENBENCH_SERVER environment variable' + + # Parse all arguments, all of which must exist in some form + p = argparse.ArgumentParser() + p.add_argument('-U', '--username', help=help_user , required=req_user ) + p.add_argument('-P', '--password', help=help_pass , required=req_pass ) + p.add_argument('-S', '--server' , help=help_server , required=req_server) + p.add_argument('-E', '--engine' , help='Engine' , required=True ) + p.add_argument('-N', '--name' , help='Network Name', required=True ) + p.add_argument('-F', '--file' , help='File Name' , required=True ) + args = p.parse_args() + + # Fallback on ENV variables for Username, Password, and Server + args.username = args.username if args.username else os.environ['OPENBENCH_USERNAME'] + args.password = args.password if args.password else os.environ['OPENBENCH_PASSWORD'] + args.server = args.server if args.server else os.environ['OPENBENCH_SERVER' ] + + # All scripts connect through this API point, with an action in the POST data + url = url_join(args.server, 'scripts') + + # POST payload must contain an action value + data = { + 'username' : args.username, + 'password' : args.password, + 'engine' : args.engine, + 'name' : args.name, + 'action' : 'UPLOAD_NETWORK', + } + + # Upload the file and report the status code + with open(args.file, 'rb') as network: + r = requests.post(url, data=data, files={ 'netfile' : network }) + print ('Code : %s' % (r.status_code)) + + # Report any error messages + pattern = r'
\s*
(.*?)
\s*
' + if matches := re.findall(pattern, r.text, re.DOTALL): + print ('Error : %s' % (matches[0].strip())) + + # Report any status messages + pattern = r'
\s*
(.*?)
\s*
' + if matches := re.findall(pattern, r.text, re.DOTALL): + print ('Status: %s' % (matches[0].strip())) + +if __name__ == '__main__': + upload_network() \ No newline at end of file diff --git a/Templates/OpenBench/base.html b/Templates/OpenBench/base.html index 69be0c8..f4dff8b 100644 --- a/Templates/OpenBench/base.html +++ b/Templates/OpenBench/base.html @@ -70,7 +70,7 @@

diff --git a/Templates/OpenBench/networks.html b/Templates/OpenBench/networks.html index eeab85f..d5265c9 100644 --- a/Templates/OpenBench/networks.html +++ b/Templates/OpenBench/networks.html @@ -1,59 +1,22 @@ {% extends "OpenBench/base.html" %} -{% block style %} -{% endblock %} +{% load static %} {% block scripts %} + {{ networks|json_script:"json-networks" }} + + + {% endblock %} @@ -62,31 +25,34 @@ - - - - - + + + + + {% for network in networks %} - {% if network.default %} {% else %} - {% endif %} - - + + - + {% endfor %} diff --git a/Templates/OpenBench/uploadnet.html b/Templates/OpenBench/uploadnet.html index 3291df3..ca2853a 100644 --- a/Templates/OpenBench/uploadnet.html +++ b/Templates/OpenBench/uploadnet.html @@ -1,39 +1,59 @@ {% extends "OpenBench/base.html" %} +{% block scripts %} + + + +{% endblock %} + {% block content %} - - {% csrf_token %} - -
-
-
- + + {% csrf_token %} +
+
+
+ +
+
+ +
+
+ + +
+
-
- -
-
- - -
- - -
-
- - - - {% endblock %}
EngineUploaderNameHashEngineAuthorNameHash
+ {{network.engine}}{{network.author|capfirst}}{{network.name}}{{network.author|capfirst}}{{network.name}} {{network.sha256}} - + + +