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.

128 lines
3.5 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
  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. doc = nlp(input_text)
  32. for sent in doc.sents:
  33. cnt = 0
  34. for token in sent:
  35. if token.pos_ in ('SPACE', 'PUNCT', 'X'):
  36. continue
  37. cnt += 1
  38. word = token.text
  39. state = f'{token.tag_},{token.dep_}'
  40. if state in words:
  41. words[state].append(word)
  42. else:
  43. words[state] = [word]
  44. state = f'{token.tag_},{token.dep_},{str(cnt)}'
  45. if state in words:
  46. words[state].append(word)
  47. else:
  48. words[state] = [word]
  49. for sent in doc.sents:
  50. curr_state = 'START'
  51. cnt = 0
  52. for token in sent:
  53. if token.pos_ in ('SPACE', 'PUNCT', 'X'):
  54. continue
  55. cnt += 1
  56. next_state = f'{token.tag_},{token.dep_},{str(cnt)}'
  57. edges.append((curr_state, next_state))
  58. curr_state = next_state
  59. edges.append((curr_state, 'STOP'))
  60. transitions = {}
  61. for edge in edges:
  62. if edge[0] in transitions:
  63. transitions[edge[0]]['cnt'] += 1
  64. if edge[1] in transitions[edge[0]]['to']:
  65. transitions[edge[0]]['to'][edge[1]] += 1
  66. else:
  67. transitions[edge[0]]['to'][edge[1]] = 1
  68. else:
  69. transitions[edge[0]] = { 'cnt': 1, 'to': {edge[1]: 1}}
  70. chain = {}
  71. for key in transitions.keys():
  72. cnt = transitions[key]['cnt']
  73. choices = list(transitions[key]['to'])
  74. probs = []
  75. for choice in choices:
  76. probs.append(transitions[key]['to'][choice] / cnt)
  77. chain[key] = { 'choices': choices, 'probs': probs}
  78. sents = []
  79. for _ in range(10):
  80. choice = 'START'
  81. choices = []
  82. while True:
  83. next_choice = rng.choice(chain[choice]['choices'], p=chain[choice]['probs'])
  84. if choice == 'START' and next_choice == 'STOP':
  85. continue
  86. if next_choice == 'STOP':
  87. sents.append(' '.join(choices))
  88. break
  89. try:
  90. word = rng.choice(words[next_choice])
  91. except KeyError:
  92. word = rng.choice(words[','.join(next_choice.split(',')[:-1])])
  93. choices.append(word)
  94. choice = next_choice
  95. print(os.linesep.join(sents))