markov.py 2.6 KB

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