markov.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import os.path
  2. import re
  3. import atexit
  4. import string
  5. import spacy
  6. import ujson
  7. import markovify
  8. from config import config
  9. class Markov:
  10. def __init__(self):
  11. self.counter = 0
  12. self.corpus = []
  13. self.chain = None
  14. self.nlp = spacy.load("xx_sent_ud_sm")
  15. self.load()
  16. atexit.register(self.save)
  17. @property
  18. def is_ready(self):
  19. return self.chain is not None
  20. def generate(self, init_state=None):
  21. orig_init_state = init_state
  22. if init_state is not None:
  23. init_state = self.tokenize(init_state)
  24. init_state = tuple(init_state)
  25. size = len(init_state)
  26. if size < config.MARKOV_STATE_SIZE:
  27. init_state = (markovify.chain.BEGIN,) * (config.MARKOV_STATE_SIZE - size) + init_state
  28. words = self.chain.walk(init_state)
  29. if not words:
  30. return self.generate()
  31. text = orig_init_state if orig_init_state is not None else ""
  32. for word in words:
  33. if word in "-–—" or not all(c in string.punctuation for c in word):
  34. text += " "
  35. text += word
  36. return text.strip()
  37. def rebuild(self):
  38. self.chain = markovify.Chain(self.corpus, config.MARKOV_STATE_SIZE).compile()
  39. self.counter = 0
  40. def tokenize(self, text):
  41. text = re.sub(r"(@[A-Za-z0-9_]+,?)", "", text)
  42. text = re.sub(
  43. "https?:\\/\\/(?:www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)",
  44. "",
  45. text,
  46. )
  47. text = self.nlp(text)
  48. text = map(lambda word: str(word).strip(), text)
  49. text = filter(bool, text)
  50. return list(text)
  51. def extend_corpus(self, text):
  52. text = text.strip()
  53. if not text:
  54. return
  55. if "\n" in text:
  56. for line in text.split("\n"):
  57. self.extend_corpus(line)
  58. return
  59. text = self.tokenize(text)
  60. if text not in self.corpus:
  61. self.corpus.insert(0, text)
  62. if len(self.corpus) > config.MARKOV_CORPUS_SIZE:
  63. self.corpus.pop(-1)
  64. self.counter += 1
  65. if self.counter % config.MARKOV_REBUILD_RATE == 0:
  66. self.rebuild()
  67. def load(self):
  68. if os.path.isfile(config.MARKOV_CHAIN_PATH):
  69. with open(config.MARKOV_CHAIN_PATH, "r") as f:
  70. self.chain = markovify.Chain.from_json(f.read())
  71. if os.path.isfile(config.MARKOV_CORPUS_PATH):
  72. with open(config.MARKOV_CORPUS_PATH, "r") as f:
  73. self.corpus = ujson.load(f)
  74. def save(self):
  75. if self.chain:
  76. with open(config.MARKOV_CHAIN_PATH, "w") as f:
  77. f.write(self.chain.to_json())
  78. with open(config.MARKOV_CORPUS_PATH, "w") as f:
  79. ujson.dump(self.corpus, f)