massranker/main.py

100 lines
2.5 KiB
Python
Raw Normal View History

2024-11-17 06:15:51 +00:00
import sys
from datetime import datetime, UTC
from functools import cmp_to_key
2024-11-17 06:15:51 +00:00
from typing import Optional
import os.path
from massranker.state import StateT, ItemT
from massranker.storage import Storage
def main():
if len(sys.argv) != 2:
print("massranker <ontology>")
exit(1)
ontology = sys.argv[1]
def _ontology_path(fname):
return os.path.join("ontologies", ontology, fname)
def _write_rankings(state: StateT):
with open(_ontology_path("rankings.txt"), "wt") as f:
for ix, (name, elo) in enumerate(state.dump_rankings(), start=1):
f.write("{: >4}. {} ({})\n".format(ix, name, elo))
names = []
with open(_ontology_path("names.txt"), "rt") as f:
for line in f.read().split("\n"):
if line.strip() == "":
continue
names.append(line)
with Storage.transact(_ontology_path("rankings.db")) as storage:
state: StateT = storage.fetch_last_state()
_write_rankings(state)
while True:
state: StateT = storage.fetch_last_state()
state.do_tournament(names, _rerank)
2024-11-17 06:15:51 +00:00
storage.store_state(state)
_write_rankings(state)
def _rerank(items: list[ItemT]) -> list[ItemT]:
results = []
remaining = {ix: value for ix, value in enumerate(items, 1)}
2024-11-17 06:15:51 +00:00
while len(remaining) > 1:
print("Pick your favorite(s): ")
for ix, i in remaining.items():
print(f"{ix: >4}. {i.name}")
while True:
choices = input("> ")
for choice in choices:
try:
choice_ix = int(choice)
except ValueError:
print(f"not a number: {choice}")
continue
if choice_ix not in remaining:
print(f"not a valid index: {choice_ix}")
continue
results.append(remaining.pop(choice_ix))
if len(choices) > 0:
break
assert len(remaining) <= 1
if remaining:
results.append(next(iter(remaining.values())))
return results
def _ask(item0: ItemT, item1: ItemT) -> int:
2024-11-17 06:15:51 +00:00
print("Which do you prefer?")
print(f" 0: {item0.name}")
print(f" 1: {item1.name}")
print(f" 2: neither")
while True:
i = input("0/1/2> ")
if i == "0":
return -1
2024-11-17 06:15:51 +00:00
elif i == "1":
return 1
2024-11-17 06:15:51 +00:00
elif i == "2":
return 0
2024-11-17 06:15:51 +00:00
print(f"unexpected input: {i}")
if __name__ == "__main__":
main()