markey/generate.py

74 lines
1.5 KiB
Python
Raw Permalink Normal View History

2024-02-23 12:05:37 +00:00
import chain
import sys
import requests
import json
import os
2024-02-23 12:05:37 +00:00
import secrets__
import config__
2024-02-23 12:05:37 +00:00
dir_path = os.path.dirname(os.path.realpath(__file__))
# Import previous post log
log_path = dir_path + "/posts_log.json"
try:
with open(log_path, "r") as infile:
posts_log = json.loads(infile.read())
except FileNotFoundError:
with open(log_path, "w") as outfile:
outfile.write('[""]')
posts_log = []
# Import Markov model
with open(dir_path + "/" + config__.model_file) as model_f:
model = chain.Text.from_json(model_f.read())
# Generate sentence
2024-02-23 12:05:37 +00:00
generated = False
text = None
while not generated:
text = model.make_short_sentence(config__.character_limit, tries=900, min_words=3)
2024-02-23 12:05:37 +00:00
generated = text is not None
if generated:
if text in posts_log:
generated = False
# Output
posts_log.append(text)
with open(log_path, "w") as outfile:
outfile.write(json.dumps(posts_log[-config__.log_length:]))
2024-02-23 12:05:37 +00:00
text = text.replace('@','@').replace('#','#')
print(text)
# Post to instance
apicreate = "https://" + config__.instance_url + "/api/notes/create"
2024-02-23 12:05:37 +00:00
if(config__.cw == ""):
requests.post(apicreate, json={
'i': secrets__.TOKEN,
2024-02-23 12:05:37 +00:00
'visibility': 'home',
'noExtractMentions': True,
'noExtractHashtags': True,
'text': text,
})
else:
requests.post(apicreate, json={
'i': secrets__.TOKEN,
'visibility': 'home',
'noExtractMentions': True,
'noExtractHashtags': True,
'text': text,
'cw': config__.cw
})