382 lines
13 KiB
Python
382 lines
13 KiB
Python
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
# #
|
|
# UI helpers for the OpenBench website. #
|
|
# #
|
|
# Kept out of views.py / utils.py so the presentation logic ( time control #
|
|
# buckets, PGN and log parsing for the event viewer ) is easy to find, #
|
|
# test, and extend. Nothing in here touches the database schema. #
|
|
# #
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
|
|
import re
|
|
|
|
from functools import lru_cache
|
|
|
|
from django.db.models import Sum
|
|
|
|
from OpenBench.models import Profile, Result
|
|
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
# TIME CONTROLS #
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
|
|
# Fischer time controls with a base time below this many seconds are STC, and
|
|
# anything at or above it is LTC. ( 10+0.1 is STC, 60+0.6 is LTC )
|
|
STC_MAX_BASE_SECONDS = 30
|
|
|
|
BUCKETS = ('STC', 'LTC', 'OTHER')
|
|
|
|
START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
|
|
|
|
@lru_cache(maxsize=512)
|
|
def classify_time_control(time_control):
|
|
|
|
# Imported here, since utils.py imports views.py which imports this module
|
|
from OpenBench.utils import TimeControl
|
|
|
|
try:
|
|
tc = str(time_control or '')
|
|
|
|
# Fixed nodes, depth, movetime, and cyclic controls are not STC or LTC
|
|
if TimeControl.control_type(tc) != TimeControl.FISCHER:
|
|
return 'OTHER'
|
|
|
|
base = TimeControl.control_base(tc)
|
|
return 'STC' if base < STC_MAX_BASE_SECONDS else 'LTC'
|
|
|
|
except Exception:
|
|
return 'OTHER'
|
|
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
# USERS PAGE #
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
|
|
SORT_KEYS = {
|
|
'total' : lambda row: (-row['total'], -row['tests']),
|
|
'stc' : lambda row: (-row['stc' ], -row['total']),
|
|
'ltc' : lambda row: (-row['ltc' ], -row['total']),
|
|
'tests' : lambda row: (-row['tests'], -row['total']),
|
|
}
|
|
|
|
def _share(part, whole):
|
|
# Returned as a string, so templates never localise it into "63,20"
|
|
return '%.2f' % (100.0 * part / whole) if whole else '0.00'
|
|
|
|
def users_context(request):
|
|
|
|
sort = request.GET.get('sort', 'total')
|
|
if sort not in SORT_KEYS:
|
|
sort = 'total'
|
|
|
|
# Games are credited to whoever's machines played them, which is not
|
|
# necessarily the author of the test. Results hold one row per (test, machine)
|
|
# so grouping by user and time control in the database stays cheap.
|
|
|
|
per_user = {}
|
|
grouped = Result.objects.values('machine__user__username', 'test__dev_time_control')
|
|
grouped = grouped.annotate(total=Sum('games'))
|
|
|
|
for entry in grouped:
|
|
buckets = per_user.setdefault(entry['machine__user__username'], dict.fromkeys(BUCKETS, 0))
|
|
buckets[classify_time_control(entry['test__dev_time_control'])] += entry['total'] or 0
|
|
|
|
rows = []
|
|
for profile in Profile.objects.select_related('user'):
|
|
|
|
if not (profile.games or profile.tests or profile.approver):
|
|
continue
|
|
|
|
buckets = per_user.get(profile.user.username, dict.fromkeys(BUCKETS, 0))
|
|
split = sum(buckets.values())
|
|
|
|
rows.append({
|
|
'username' : profile.user.username,
|
|
'approver' : profile.approver,
|
|
'engine' : profile.engine,
|
|
'joined' : profile.user.date_joined,
|
|
'total' : profile.games,
|
|
'tests' : profile.tests,
|
|
'stc' : buckets['STC' ],
|
|
'ltc' : buckets['LTC' ],
|
|
'other' : buckets['OTHER'],
|
|
'stc_share' : _share(buckets['STC' ], split),
|
|
'ltc_share' : _share(buckets['LTC' ], split),
|
|
'oth_share' : _share(buckets['OTHER'], split),
|
|
})
|
|
|
|
rows.sort(key=lambda row: SORT_KEYS[sort](row) + (row['username'].lower(),))
|
|
|
|
stc = sum(row['stc' ] for row in rows)
|
|
ltc = sum(row['ltc' ] for row in rows)
|
|
other = sum(row['other'] for row in rows)
|
|
whole = stc + ltc + other
|
|
|
|
summary = {
|
|
'users' : len(rows),
|
|
'total' : sum(row['total'] for row in rows),
|
|
'stc' : stc,
|
|
'ltc' : ltc,
|
|
'other' : other,
|
|
'stc_share' : _share(stc, whole),
|
|
'ltc_share' : _share(ltc, whole),
|
|
'oth_share' : _share(other, whole),
|
|
}
|
|
|
|
return {
|
|
'rows' : rows,
|
|
'summary' : summary,
|
|
'sort' : sort,
|
|
'show_other' : other > 0,
|
|
'stc_limit' : STC_MAX_BASE_SECONDS,
|
|
}
|
|
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
# EVENT VIEWER #
|
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
|
|
|
def event_tone(summary):
|
|
|
|
# Colour used for badges: bad ( red ), warn ( amber ), info ( blue )
|
|
text = (summary or '').lower()
|
|
|
|
bad = ('illegal', 'disconnect', 'crash', 'fail', 'bad bench', 'missing', 'error')
|
|
if any(word in text for word in bad):
|
|
return 'bad'
|
|
|
|
if any(word in text for word in ('stall', 'timeout', 'timeloss', 'warn')):
|
|
return 'warn'
|
|
|
|
return 'info'
|
|
|
|
# When a worker reports an Illegal Move, Disconnect, or Stalled game, the client
|
|
# uploads the PGN of that game ( see PGNHelper.pretty_format in Client/worker.py ).
|
|
# Other events ( build failures, bad benches, ... ) carry plain text logs.
|
|
|
|
PGN_PROBE_RE = re.compile(r'^\s*\[Event\s+"', re.MULTILINE)
|
|
HEADER_RE = re.compile(r'^\[(\w+)\s+"(.*)"\]\s*$')
|
|
TOKEN_RE = re.compile(r'\{[^}]*\}|\([^)]*\)|\$\d+|\d+\.(?:\.\.)?|1-0|0-1|1/2-1/2|\*|[^\s{}()]+')
|
|
NUMBER_RE = re.compile(r'^\d+\.(?:\.\.)?$')
|
|
EVAL_RE = re.compile(r'^(?P<score>[+-]?(?:M\d+|\d+(?:\.\d+)?))/(?P<depth>\d+)(?:\s+(?P<time>\d+(?:\.\d+)?)s)?')
|
|
|
|
RESULT_TOKENS = ('1-0', '0-1', '1/2-1/2', '*')
|
|
|
|
def _eval_tone(score):
|
|
|
|
if score.startswith('-'):
|
|
return 'neg'
|
|
|
|
if score.lstrip('+') in ('0', '0.0', '0.00'):
|
|
return ''
|
|
|
|
return 'pos'
|
|
|
|
def parse_pgn(text):
|
|
|
|
# Split the first game into its headers, and its movetext
|
|
|
|
headers, body, reading_headers = [], [], True
|
|
|
|
for raw in text.splitlines():
|
|
line = raw.strip()
|
|
|
|
if body and line.startswith('[Event '):
|
|
break # A second game, which we do not show
|
|
|
|
if reading_headers:
|
|
match = HEADER_RE.match(line)
|
|
if match:
|
|
headers.append((match.group(1), match.group(2)))
|
|
continue
|
|
if not line:
|
|
reading_headers = not headers
|
|
continue
|
|
reading_headers = False
|
|
|
|
if line:
|
|
body.append(line)
|
|
|
|
header_map = dict(headers)
|
|
|
|
# Games from a FEN, or from a Black to move book entry, number differently
|
|
|
|
start_black, first_number = False, 1
|
|
fen = header_map.get('FEN', '')
|
|
|
|
if fen:
|
|
fields = fen.split()
|
|
start_black = len(fields) >= 2 and fields[1] == 'b'
|
|
if len(fields) >= 6 and fields[5].isdigit():
|
|
first_number = int(fields[5])
|
|
|
|
moves, final_note = [], ''
|
|
|
|
for token in TOKEN_RE.findall(' '.join(body)):
|
|
|
|
if token.startswith('{'):
|
|
|
|
comment = token[1:-1].strip()
|
|
if not comment or not moves:
|
|
continue
|
|
|
|
match = EVAL_RE.match(comment)
|
|
|
|
if match:
|
|
score = match.group('score')
|
|
if score[0] not in '+-':
|
|
score = '+' + score
|
|
moves[-1]['eval' ] = score
|
|
moves[-1]['tone' ] = _eval_tone(score)
|
|
moves[-1]['depth'] = match.group('depth')
|
|
moves[-1]['time' ] = (match.group('time') or '') and match.group('time') + 's'
|
|
|
|
elif comment.lower() == 'book':
|
|
moves[-1]['eval'] = 'book'
|
|
|
|
else:
|
|
final_note = comment
|
|
if not moves[-1]['note']:
|
|
moves[-1]['note'] = comment
|
|
|
|
continue
|
|
|
|
# Variations, NAGs, move numbers, and results are not moves
|
|
if token.startswith(('(', '$')) or token in RESULT_TOKENS or NUMBER_RE.match(token):
|
|
continue
|
|
|
|
index = len(moves) + (1 if start_black else 0)
|
|
|
|
moves.append({
|
|
'ply' : len(moves),
|
|
'num' : first_number + index // 2,
|
|
'color' : 'w' if index % 2 == 0 else 'b',
|
|
'san' : token,
|
|
'eval' : '',
|
|
'tone' : '',
|
|
'depth' : '',
|
|
'time' : '',
|
|
'note' : '',
|
|
'final' : False,
|
|
})
|
|
|
|
if moves:
|
|
moves[-1]['final'] = True
|
|
|
|
# One row per full move, for the move list
|
|
|
|
rows = []
|
|
for move in moves:
|
|
if not rows or rows[-1]['num'] != move['num']:
|
|
rows.append({ 'num' : move['num'], 'w' : None, 'b' : None })
|
|
rows[-1][move['color']] = move
|
|
|
|
return {
|
|
'white' : header_map.get('White', '?'),
|
|
'black' : header_map.get('Black', '?'),
|
|
'result' : header_map.get('Result', '*'),
|
|
'termination' : header_map.get('Termination', ''),
|
|
'time_control' : header_map.get('TimeControl', ''),
|
|
'date' : header_map.get('Date', ''),
|
|
'duration' : header_map.get('GameDuration', ''),
|
|
'fen' : fen,
|
|
'start_fen' : fen or START_FEN,
|
|
'variant' : header_map.get('Variant', ''),
|
|
'chess960' : 'fischer' in header_map.get('Variant', '').lower() or '960' in header_map.get('Variant', ''),
|
|
'headers' : headers,
|
|
'rows' : rows,
|
|
'moves' : moves,
|
|
'ply_count' : len(moves),
|
|
'final_note' : final_note,
|
|
}
|
|
|
|
# Plain text logs ( compiler output, bench failures, ... )
|
|
|
|
MAX_LOG_LINES = 5000
|
|
|
|
CLEAN_RE = re.compile(r'\b0\s+(errors?|warnings?)\b', re.IGNORECASE)
|
|
ERROR_RE = re.compile(
|
|
r'\b(errors?|fatal|failed|failure|undefined reference|segmentation fault|traceback|exception|illegal move)\b',
|
|
re.IGNORECASE)
|
|
WARN_RE = re.compile(r'\b(warnings?|deprecated|stalled|timed? ?out|disconnect\w*)\b', re.IGNORECASE)
|
|
|
|
def classify_log_line(text):
|
|
|
|
if CLEAN_RE.search(text):
|
|
return 'info'
|
|
|
|
if ERROR_RE.search(text):
|
|
return 'bad'
|
|
|
|
if WARN_RE.search(text):
|
|
return 'warn'
|
|
|
|
return 'info'
|
|
|
|
def parse_log(content):
|
|
|
|
lines = content.splitlines()
|
|
total = len(lines)
|
|
skipped = max(0, total - MAX_LOG_LINES) # Errors are usually at the end
|
|
lines = lines[skipped:]
|
|
|
|
parsed, errors, warnings = [], 0, 0
|
|
|
|
for number, text in enumerate(lines, start=skipped + 1):
|
|
level = classify_log_line(text)
|
|
errors += level == 'bad'
|
|
warnings += level == 'warn'
|
|
parsed.append({ 'n' : number, 'text' : text, 'level' : level })
|
|
|
|
return {
|
|
'lines' : parsed,
|
|
'total' : total,
|
|
'errors' : errors,
|
|
'warnings' : warnings,
|
|
'skipped' : skipped,
|
|
}
|
|
|
|
def event_context(event, content):
|
|
|
|
kind = 'empty'
|
|
if content and content.strip():
|
|
kind = 'pgn' if PGN_PROBE_RE.search(content) else 'log'
|
|
|
|
context = {
|
|
'event' : event,
|
|
'content' : content,
|
|
'kind' : kind,
|
|
'tone' : event_tone(event.summary),
|
|
'back_url' : '/errors/' if event.machine_id else '/events/',
|
|
'back_label' : 'Errors' if event.machine_id else 'Events',
|
|
'game' : None,
|
|
'moves_json' : [],
|
|
'game_json' : None,
|
|
'log' : None,
|
|
'download_name' : 'event%d.%s' % (event.id, 'pgn' if kind == 'pgn' else 'log'),
|
|
}
|
|
|
|
try:
|
|
if kind == 'pgn':
|
|
context['game'] = parse_pgn(content)
|
|
context['moves_json'] = context['game']['moves']
|
|
context['game_json'] = {
|
|
'startFen' : context['game']['start_fen'],
|
|
'chess960' : context['game']['chess960'],
|
|
'white' : context['game']['white'],
|
|
'black' : context['game']['black'],
|
|
'note' : context['game']['final_note'] or context['game']['termination'],
|
|
}
|
|
|
|
elif kind == 'log':
|
|
context['log'] = parse_log(content)
|
|
|
|
except Exception:
|
|
|
|
# A strange log should never break the page. Fall back to plain text
|
|
context['kind'] = 'log'
|
|
context['game'] = None
|
|
context['moves_json'] = []
|
|
context['game_json'] = None
|
|
context['log'] = parse_log(content)
|
|
|
|
return context
|