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.

117 lines
3.1 KiB

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('word_file', help='File used for word selection')
  21. parser.add_argument('pos_file', help='File used to build part-of-speech Markov chain')
  22. args = parser.parse_args()
  23. nlp = spacy.load('en_core_web_sm')
  24. seed = 12345
  25. rng = np.random.default_rng(seed)
  26. words_text = ''
  27. with open(args.word_file, mode='r') as f:
  28. words_text = f.read()
  29. words_doc = nlp(words_text)
  30. words = {}
  31. for sent in words_doc.sents:
  32. for token in sent:
  33. if token.pos_ in ('SPACE', 'PUNCT', 'X'):
  34. continue
  35. state = token.tag_
  36. word = token.text
  37. if state in words:
  38. words[state].append(word)
  39. else:
  40. words[state] = [word]
  41. pos_text = ''
  42. with open(args.pos_file, mode='r') as f:
  43. pos_text = f.read()
  44. pos_doc = nlp(pos_text)
  45. edges = []
  46. for sent in pos_doc.sents:
  47. curr_state = 'START'
  48. for token in sent:
  49. if token.pos_ in ('SPACE', 'PUNCT', 'X'):
  50. continue
  51. next_state = token.tag_
  52. edges.append((curr_state, next_state))
  53. curr_state = next_state
  54. edges.append((curr_state, 'STOP'))
  55. transitions = {}
  56. for edge in edges:
  57. if edge[0] in transitions:
  58. transitions[edge[0]]['cnt'] += 1
  59. if edge[1] in transitions[edge[0]]['to']:
  60. transitions[edge[0]]['to'][edge[1]] += 1
  61. else:
  62. transitions[edge[0]]['to'][edge[1]] = 1
  63. else:
  64. transitions[edge[0]] = { 'cnt': 1, 'to': {edge[1]: 1}}
  65. chain = {}
  66. for key in transitions.keys():
  67. cnt = transitions[key]['cnt']
  68. choices = list(transitions[key]['to'])
  69. probs = []
  70. for choice in choices:
  71. probs.append(transitions[key]['to'][choice] / cnt)
  72. chain[key] = { 'choices': choices, 'probs': probs}
  73. sents = []
  74. for _ in range(10):
  75. choice = 'START'
  76. choices = []
  77. while True:
  78. next_choice = rng.choice(chain[choice]['choices'], p=chain[choice]['probs'])
  79. if choice == 'START' and next_choice == 'STOP':
  80. continue
  81. if next_choice == 'STOP':
  82. sents.append(' '.join(choices))
  83. break
  84. word = rng.choice(words[next_choice])
  85. choices.append(word)
  86. choice = next_choice
  87. print(os.linesep.join(sents))