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.

133 lines
3.6 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 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('-s', '--seed', type=int, help='seed for random number generator')
  22. args = parser.parse_args()
  23. nlp = spacy.load('en_core_web_sm')
  24. rng = np.random.default_rng(args.seed or 12345)
  25. words = {}
  26. edges = []
  27. input_text = ''
  28. for infile in args.input:
  29. with open(infile, mode='r') as f:
  30. input_text = f.read()
  31. i = 1000000
  32. if len(input_text) > i:
  33. while input_text[i] != ' ':
  34. i -= 1
  35. doc = nlp(input_text[:i])
  36. for sent in doc.sents:
  37. cnt = 0
  38. for token in sent:
  39. if token.pos_ in ('SPACE', 'PUNCT', 'X'):
  40. continue
  41. cnt += 1
  42. word = token.text
  43. state = f'{token.tag_},{token.dep_}'
  44. if state in words:
  45. words[state].append(word)
  46. else:
  47. words[state] = [word]
  48. state = f'{token.tag_},{token.dep_},{str(cnt)}'
  49. if state in words:
  50. words[state].append(word)
  51. else:
  52. words[state] = [word]
  53. for sent in doc.sents:
  54. curr_state = 'START'
  55. cnt = 0
  56. for token in sent:
  57. if token.pos_ in ('SPACE', 'PUNCT', 'X'):
  58. continue
  59. cnt += 1
  60. next_state = f'{token.tag_},{token.dep_},{str(cnt)}'
  61. edges.append((curr_state, next_state))
  62. curr_state = next_state
  63. edges.append((curr_state, 'STOP'))
  64. transitions = {}
  65. for edge in edges:
  66. if edge[0] in transitions:
  67. transitions[edge[0]]['cnt'] += 1
  68. if edge[1] in transitions[edge[0]]['to']:
  69. transitions[edge[0]]['to'][edge[1]] += 1
  70. else:
  71. transitions[edge[0]]['to'][edge[1]] = 1
  72. else:
  73. transitions[edge[0]] = { 'cnt': 1, 'to': {edge[1]: 1}}
  74. chain = {}
  75. for key in transitions.keys():
  76. cnt = transitions[key]['cnt']
  77. choices = list(transitions[key]['to'])
  78. probs = []
  79. for choice in choices:
  80. probs.append(transitions[key]['to'][choice] / cnt)
  81. chain[key] = { 'choices': choices, 'probs': probs}
  82. sents = []
  83. for _ in range(10):
  84. choice = 'START'
  85. choices = []
  86. while True:
  87. next_choice = rng.choice(chain[choice]['choices'], p=chain[choice]['probs'])
  88. if choice == 'START' and next_choice == 'STOP':
  89. continue
  90. if next_choice == 'STOP':
  91. sents.append(' '.join(choices))
  92. break
  93. try:
  94. word = rng.choice(words[next_choice])
  95. except KeyError:
  96. word = rng.choice(words[','.join(next_choice.split(',')[:-1])])
  97. choices.append(word)
  98. choice = next_choice
  99. print(os.linesep.join(sents))