62 lines
1.6 KiB
Python
62 lines
1.6 KiB
Python
|
|
import yaml, json
|
||
|
|
import random
|
||
|
|
from db import Database
|
||
|
|
|
||
|
|
def pick_order(orders):
|
||
|
|
picked = random.choices(orders,
|
||
|
|
weights=[o['weight'] for o in orders],
|
||
|
|
k=1)[0]
|
||
|
|
|
||
|
|
result = []
|
||
|
|
repeat = 0.0
|
||
|
|
|
||
|
|
if('text' in picked):
|
||
|
|
result.append(picked['text'])
|
||
|
|
|
||
|
|
if('repeat' in picked):
|
||
|
|
repeat = picked['repeat']
|
||
|
|
|
||
|
|
if('add' in picked):
|
||
|
|
for addition in picked['add']:
|
||
|
|
if addition['probability'] > random.random():
|
||
|
|
result.append(addition['text'])
|
||
|
|
|
||
|
|
if('pick' in picked):
|
||
|
|
(new_result, new_repeat) = pick_order(picked['pick'])
|
||
|
|
result += new_result
|
||
|
|
if new_repeat > 0.0:
|
||
|
|
repeat = new_repeat
|
||
|
|
|
||
|
|
return (result, repeat)
|
||
|
|
|
||
|
|
def generate(filename="orders.yml"):
|
||
|
|
with open(filename) as stream:
|
||
|
|
# Do we want to repeat?
|
||
|
|
db = Database()
|
||
|
|
repeat = db.repeat_get()
|
||
|
|
if repeat is not None:
|
||
|
|
if repeat['probability'] > random.random():
|
||
|
|
db.repeat_increment()
|
||
|
|
return {
|
||
|
|
"orders": json.loads(repeat['orders']),
|
||
|
|
"count": repeat['count']
|
||
|
|
}
|
||
|
|
else:
|
||
|
|
db.repeat_clear()
|
||
|
|
|
||
|
|
# Pick a new order
|
||
|
|
try:
|
||
|
|
orders = yaml.safe_load(stream)
|
||
|
|
except yaml.YAMLError as exc:
|
||
|
|
print(exc)
|
||
|
|
|
||
|
|
(result, repeat_p) = pick_order(orders['orders'])
|
||
|
|
|
||
|
|
# Log the repeat
|
||
|
|
if repeat_p > 0.0:
|
||
|
|
db.repeat_put(repeat_p, json.dumps(result))
|
||
|
|
|
||
|
|
return {
|
||
|
|
"orders": result
|
||
|
|
}
|