-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlanguage_model.py
171 lines (136 loc) · 5.45 KB
/
language_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
'''
Language submodel
Collect all the code needed to generate random names for people, places, ships
'''
import string
import random
import json
from collections import defaultdict
import numpy as np
import tracery
from utils import weighted_random
class RandomLanguageModel:
''' A language model defined by a random syllable distribution
'''
# Tracery grammar for naming things:
grammar = {
"virtue": ["Courage", "Kindness", "Wisdom", "Cunning", "Charity",
"Mercy", "Love", "Pride", "Glory"],
"title": ["Prince", "Princess", "Duke", "President", "Exilarch",
"Duchess", "Elector", "Senator"],
"ship_name": ["#virtue# of #place#", "#place# #virtue#",
"#title# of #place#", "#place# #title#",
"#virtue# #virtue#", "#title#'s #virtue#"],
"place": []
}
def __init__(self, n_prefixes=3):
self.syllable_weights = {}
self._make_weighted_syllables()
# Place name parameters
self.prob_prefix = 0.3
self.n_prefixes = n_prefixes
self.place_name_prefixes = [
weighted_random(self.syllable_weights).title()
for _ in range(self.n_prefixes) ]
self.place_name_syllables = {1: 1, 2: 3, 3: 3, 4: 1}
def _make_weighted_syllables(self, zipf_param=3):
''' Create a dictionary of syllables with weights
'''
syllables = []
vowels = "aeiouy"
for a in vowels:
for b in string.ascii_lowercase:
syllables.append(a+b)
syllables.append(b+a)
self.syllable_weights = {k: np.random.zipf(3)
for k in syllables}
def make_word(self, syl_count=3, p_odd=0.5):
''' Make a random word
'''
word = "".join([weighted_random(self.syllable_weights)
for i in range(syl_count)])
if len(word) > 2 and random.random() < p_odd:
word = word[:-1]
return word.title()
def make_place_name(self):
name = ""
if random.random() < self.prob_prefix:
name += random.choice(self.place_name_prefixes).title() + " "
syl_count = weighted_random(self.place_name_syllables)
name += self.make_word(syl_count).title()
return name
def add_place_name(self, place_name):
''' Add a place-name to the Tracery grammar used for ship-naming
Ensures that ships can be named after in-world cities
'''
self.grammar["place"].append(place_name)
def make_ship_name(self):
''' Generate a random ship name
'''
grammar = tracery.Grammar(self.grammar)
return grammar.flatten("#ship_name#")
class MarkovChain:
''' Train an n-order Markov chain and generate words from it.
(The order is simply how many characters to use to choose the next one)
Transitions are stored as a defaultdict with the structure
{token: [char, char, ...], token: ...}
Special tokens "<START>" and "<END>" designate the beginning and end of
a string.
'''
def __init__(self, order=1, vocabulary=None):
self.transitions = defaultdict(list)
self.order = order
if vocabulary is not None:
self.train(vocabulary)
def train(self, vocabulary, replace=False):
if replace:
self.transitions = defaultdict(list)
for word in vocabulary:
self.transitions["<START>"].append(word[:self.order])
for i in range(self.order, len(word)):
self.transitions[word[i-self.order:i]].append(word[i])
self.transitions[word[-self.order:]].append("<END>")
def generate(self):
word = ""
token = "<START>"
while True:
next_char = random.choice(self.transitions[token])
if next_char == "<END>":
return word
word += next_char
token = word[-self.order:]
return word
class MarkovLanguage:
''' Use Markov Chain models to generate names and places.
'''
def __init__(self, name_corpus, place_corpus, order=2):
''' Create a new language model
Args:
name_corpus: List of words to use as (first) names
place_corpus: List of words to use for place-names
'''
self.order = order
self.name_model = MarkovChain(order, name_corpus)
self.place_model = MarkovChain(order, place_corpus)
def make_place_name(self):
return self.place_model.generate()
def make_ship_name(self):
if random.random() < 0.5:
return "The " + self.name_model.generate()
else:
return "The " + self.make_place_name()
def add_place_name(self, place_name):
''' TODO: populate this
'''
pass
@classmethod
def make_psuedo_english(cls, order=2):
''' Make Markov chain of English names from hard-coded corpora
'''
with open("corpora/english_towns_cities.json") as f:
place_corpus = json.load(f)
town_names = place_corpus["towns"] + place_corpus["cities"]
with open("corpora/firstNames.json") as f:
name_corpus = json.load(f)
first_names = name_corpus["firstNames"]
return cls(first_names, town_names, order)