Generate a novel using Markov chains
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

155 lines
4.4 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. '''
  2. markov.py - Gernerate a novel using Markov chains
  3. Copyright (C) 2020 Blink The Things
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU Affero General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Affero General Public License for more details.
  12. You should have received a copy of the GNU Affero General Public License
  13. along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. '''
  15. import argparse
  16. import numpy as np
  17. import os
  18. import spacy
  19. parser = argparse.ArgumentParser(description='Generate a novel using Markov chains.')
  20. parser.add_argument('input', nargs='+', help='used to construct Markov transition matrix')
  21. parser.add_argument('-c','--count', type=int, help='generate at least COUNT words')
  22. parser.add_argument('-s', '--seed', type=int, help='seed for random number generator')
  23. args = parser.parse_args()
  24. nlp = spacy.load('en_core_web_sm')
  25. rng = np.random.default_rng(args.seed or 12345)
  26. word_cnt = args.count or 100
  27. words = {}
  28. edges = []
  29. input_text = ''
  30. for infile in args.input:
  31. with open(infile, mode='r') as f:
  32. input_text = f.read()
  33. i = 1000000
  34. if len(input_text) > i:
  35. while input_text[i] != ' ':
  36. i -= 1
  37. doc = nlp(input_text[:i])
  38. for sent in doc.sents:
  39. cnt = 0
  40. for token in sent:
  41. if token.pos_ in ('SPACE', 'PUNCT', 'X'):
  42. continue
  43. cnt += 1
  44. word = token.text
  45. state = f'{token.tag_},{token.dep_}'
  46. if state in words:
  47. words[state].append(word)
  48. else:
  49. words[state] = [word]
  50. state = f'{token.tag_},{token.dep_}'
  51. if state in words:
  52. words[state].append(word)
  53. else:
  54. words[state] = [word]
  55. for sent in doc.sents:
  56. curr_state = 'START'
  57. cnt = 0
  58. for token in sent:
  59. if token.pos_ in ('SPACE', 'PUNCT', 'X'):
  60. continue
  61. cnt += 1
  62. next_state = f'{token.tag_},{token.dep_}'
  63. edges.append((curr_state, next_state))
  64. curr_state = next_state
  65. edges.append((curr_state, 'STOP'))
  66. transitions = {}
  67. for edge in edges:
  68. if edge[0] in transitions:
  69. transitions[edge[0]]['cnt'] += 1
  70. if edge[1] in transitions[edge[0]]['to']:
  71. transitions[edge[0]]['to'][edge[1]] += 1
  72. else:
  73. transitions[edge[0]]['to'][edge[1]] = 1
  74. else:
  75. transitions[edge[0]] = { 'cnt': 1, 'to': {edge[1]: 1}}
  76. chain = {}
  77. for key in transitions.keys():
  78. cnt = transitions[key]['cnt']
  79. choices = list(transitions[key]['to'])
  80. probs = []
  81. for choice in choices:
  82. probs.append(transitions[key]['to'][choice] / cnt)
  83. chain[key] = { 'choices': choices, 'probs': probs}
  84. sents = []
  85. paragraph_sent_cnt = rng.integers(5, 10)
  86. while word_cnt > 0:
  87. choice = 'START'
  88. choices = []
  89. sent_word_cnt = 0
  90. while True:
  91. next_choice = rng.choice(chain[choice]['choices'], p=chain[choice]['probs'])
  92. if choice == 'START' and next_choice == 'STOP':
  93. continue
  94. if next_choice == 'STOP':
  95. sents.append(' '.join(choices)
  96. .replace(" '", "'")
  97. .replace("", "")
  98. .replace(" `", "`")
  99. + '.'
  100. )
  101. word_cnt -= sent_word_cnt
  102. paragraph_sent_cnt -= 1
  103. if paragraph_sent_cnt < 0:
  104. sents.append(os.linesep)
  105. sents.append(os.linesep)
  106. paragraph_sent_cnt = rng.integers(5, 10)
  107. break
  108. try:
  109. word = rng.choice(words[next_choice])
  110. except KeyError:
  111. word = rng.choice(words[','.join(next_choice.split(',')[:-1])])
  112. if choice == 'START' or word == 'i':
  113. word = str.title(word)
  114. elif not (next_choice.startswith('PROPN') or word == 'I'):
  115. word = str.lower(word)
  116. choices.append(word)
  117. sent_word_cnt += 1
  118. choice = next_choice
  119. print(' '.join(sents))