markov.py 2.9 KB

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