markov: Reply chance is loaded lazily

Just like the actual chain data structure, this value is now loaded
lazily, since it's stored in the filesystem.

Signed-off-by: Alek Ratzloff <alekratz@gmail.com>
This commit is contained in:
2022-06-04 16:16:52 -07:00
parent 171b4bea81
commit ed9c3ddaa2

View File

@@ -38,7 +38,7 @@ def windows(items: Sequence[Any], size: int):
class Chain: class Chain:
def __init__(self, order: int, chance: float, path: Path): def __init__(self, order: int, chance: float, path: Path):
self.order = order self.order = order
self.reply_chance = chance self.__reply_chance = chance
self.path = path self.path = path
self.__cache = chain_default() self.__cache = chain_default()
self.__last_access = 0.0 self.__last_access = 0.0
@@ -47,6 +47,19 @@ class Chain:
def __touch(self): def __touch(self):
self.__last_access = asyncio.get_running_loop().time() self.__last_access = asyncio.get_running_loop().time()
@property
def reply_chance(self) -> float:
self.__load()
return self.__reply_chance
@reply_chance.setter
def reply_chance(self, val: float):
if not (isinstance(val, float) or isinstance(val, int)):
return NotImplemented
self.__load()
self.__reply_chance = val
self.__dirty = True
@property @property
def last_access(self) -> float: def last_access(self) -> float:
return self.__last_access return self.__last_access
@@ -95,7 +108,7 @@ class Chain:
obj = json.load(fp) obj = json.load(fp)
# Load the save object # Load the save object
self.reply_chance = obj["reply_chance"] self.__reply_chance = obj["reply_chance"]
self.__cache = defaultdict( self.__cache = defaultdict(
chain_inner_default, chain_inner_default,
{ {
@@ -119,7 +132,7 @@ class Chain:
self.path.parent.mkdir(parents=True, exist_ok=True) self.path.parent.mkdir(parents=True, exist_ok=True)
# Build the save object # Build the save object
obj = { obj = {
"reply_chance": self.reply_chance, "reply_chance": self.__reply_chance,
"chain": { "chain": {
key: { key: {
("" if word is None else word): weight ("" if word is None else word): weight
@@ -239,6 +252,13 @@ class Markov(Plugin):
message = chain.generate() message = chain.generate()
if message: if message:
self.send_to(conn, channel, f"{who.nick}: {message}") self.send_to(conn, channel, f"{who.nick}: {message}")
case ["chance"]:
chain = self.get_chain(channel, who.nick)
self.send_to(
conn,
channel,
f"{who.nick}: current reply chance is {chain.reply_chance}",
)
case ["chance", chance]: case ["chance", chance]:
chain = self.get_chain(channel, who.nick) chain = self.get_chain(channel, who.nick)
try: try: