-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenerateSentences.py
295 lines (251 loc) · 11.9 KB
/
generateSentences.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import argparse
import json
from enum import Enum, auto
import math
import re
from typing import List, Dict
from numpy import single
from pydantic import BaseModel
import random
class WordType(Enum):
Question = auto()
Pronoun = auto()
Verb = auto()
class PronounName(str, Enum):
I = "Я"
You = "Ты"
He = "Он"
She = "Она"
We = "Mы"
YouPlural = "Вы"
They = "Они"
class VerbQuestion(Enum):
ToWhom = auto()
Whom = auto()
WithWhom = auto()
AboutWhom = auto()
class SingleOrPlural(Enum):
Singular = auto()
Plural = auto()
class ConjugationType(Enum):
Infinitive = 3
First = 0
Second = 1
Third = 2
class WordForm(BaseModel):
conjugationType: ConjugationType
singleOrPlural: SingleOrPlural | None = None
class Word(BaseModel):
type: WordType
class QuestionWord(Word):
text: str
class PronounWord(Word):
pronounName: PronounName
class Conjugation(BaseModel):
singular: str
plural: str
class VerbForms(BaseModel):
infinitive: str
conjugations: List[Conjugation]
class VerbWord(Word):
forms: VerbForms
expectInfinitive: bool
questions: List[VerbQuestion]
class Words(BaseModel):
questionWords: List[QuestionWord] = []
pronouns: List[PronounWord] = []
verbs: List[VerbWord] = []
def textLowercase(func):
return lambda *args, **kwargs: func(*args, **kwargs).lower()
@textLowercase
def wordText(word: Word) -> str:
match (word):
case QuestionWord(text=text):
return text
case PronounWord(pronounName=pronounName):
return pronounName.value
case VerbWord(forms=forms):
return forms.infinitive
def pronounForm(pronoun: PronounWord) -> WordForm:
match(pronoun.pronounName):
case PronounName.I:
return WordForm(conjugationType=ConjugationType.First, singleOrPlural=SingleOrPlural.Singular)
case PronounName.You:
return WordForm(conjugationType=ConjugationType.Second, singleOrPlural=SingleOrPlural.Singular)
case PronounName.He | PronounName.She:
return WordForm(conjugationType=ConjugationType.Third, singleOrPlural=SingleOrPlural.Singular)
case PronounName.We:
return WordForm(conjugationType=ConjugationType.First, singleOrPlural=SingleOrPlural.Plural)
case PronounName.YouPlural:
return WordForm(conjugationType=ConjugationType.Second, singleOrPlural=SingleOrPlural.Plural)
case PronounName.They:
return WordForm(conjugationType=ConjugationType.Third, singleOrPlural=SingleOrPlural.Plural)
def pronounAtFormOfQuestion(pronounName: PronounName, verbQuestion: VerbQuestion) -> List[str]:
match verbQuestion:
case VerbQuestion.ToWhom:
match pronounName:
case PronounName.I: return ["мне"]
case PronounName.We: return ["нам"]
case PronounName.You: return ["тебе"]
case PronounName.YouPlural: return ["вам"]
case PronounName.He: return ["ему"]
case PronounName.She: return ["ей"]
case PronounName.They: return ["им"]
case VerbQuestion.Whom:
match pronounName:
case PronounName.I: return ["меня"]
case PronounName.We: return ["нас"]
case PronounName.You: return ["тебя"]
case PronounName.YouPlural: return ["вас"]
case PronounName.He: return ["его"]
case PronounName.She: return ["ее"]
case PronounName.They: return ["их"]
case VerbQuestion.WithWhom:
match pronounName:
case PronounName.I: return ["со", "мной"]
case PronounName.We: return ["с", "нами"]
case PronounName.You: return ["с", "тобой"]
case PronounName.YouPlural: return ["с", "вами"]
case PronounName.He: return ["с", "ним"]
case PronounName.She: return ["с", "ней"]
case PronounName.They: return ["с", "ними"]
case VerbQuestion.AboutWhom:
match pronounName:
case PronounName.I: return ["обо", "мне"]
case PronounName.We: return ["о", "нас"]
case PronounName.You: return ["о", "тебе"]
case PronounName.YouPlural: return ["о", "вас"]
case PronounName.He: return ["о", "нем"]
case PronounName.She: return ["о", "ней"]
case PronounName.They: return ["о", "них"]
@textLowercase
def verbTextInForm(verb: VerbWord, form: WordForm) -> str:
match form.conjugationType:
case ConjugationType.Infinitive:
return verb.forms.infinitive
case _:
conjugation = verb.forms.conjugations[form.conjugationType.value]
return conjugation.singular if form.singleOrPlural == SingleOrPlural.Singular else conjugation.plural
def makeWordsByText(words: Words) -> Dict[str, Word]:
wordTextToWord = {}
for wordList in [words.questionWords, words.pronouns, words.verbs]:
for word in wordList:
wordTextToWord[wordText(word)] = word
return wordTextToWord
def randomWordFromList(wordList: List[Word]) -> Word:
return wordList[random.randrange(0, len(wordList))]
def newOrAnyWord(wordList: List[Word], wordTextToWord: Dict[str, Word], wordsToLearn: List[str]) -> Word:
type = wordList[0].type
wordsToLearnOfType = [wordTextToWord[wordText] for wordText in wordsToLearn if wordTextToWord[wordText].type == type]
if len(wordsToLearnOfType) > 0:
return randomWordFromList(wordsToLearnOfType)
return randomWordFromList(wordList)
def newOrAnyVerb(verbList: List[Word], wordTextToWord: Dict[str, Word], wordsToLearn: List[str]) -> Word:
verbsToLearn = [wordTextToWord[wordText] for wordText in wordsToLearn if wordTextToWord[wordText].type == WordType.Verb]
if len(verbsToLearn) > 0:
if any([verb for verb in verbsToLearn if verb.expectInfinitive]) or bool(random.getrandbits(1)):
return randomWordFromList(verbsToLearn)
else:
return randomWordFromList([verb for verb in verbList if verb.expectInfinitive])
return randomWordFromList(verbList)
def newOrAnyNotExpectsInfinitiveVerb(verbList: List[VerbWord], wordTextToWord: Dict[str, Word], wordsToLearn: List[str]) -> VerbWord:
verbsToLearn = [wordTextToWord[wordText] for wordText in wordsToLearn if wordTextToWord[wordText].type == WordType.Verb and not wordTextToWord[wordText].expectInfinitive]
if len(verbsToLearn) > 0:
return randomWordFromList(verbsToLearn)
return randomWordFromList([verb for verb in verbList if not verb.expectInfinitive])
class NextPartType(Enum):
Word = auto()
VerbQuestion = auto()
class NextPart(BaseModel):
type: NextPartType
wordType: WordType | None = None
wordForm: WordForm | None = None
verbQuestion: VerbQuestion | None = None
class SentenceGenerator:
def __init__(self, startWithQuestion: bool) -> None:
self.startWithQuestion = startWithQuestion
self.sentence = []
if self.startWithQuestion:
self.nextPart = NextPart(type=NextPartType.Word, wordType=WordType.Question)
else:
self.nextPart = NextPart(type=NextPartType.Word, wordType=WordType.Pronoun)
def generateNextPart(self, words: Words, wordTextToWord: Dict[str, Word], wordsToLearn: List[str]) -> bool:
match self.nextPart.type:
case NextPartType.Word:
match self.nextPart.wordType:
case WordType.Question:
self.sentence.append(wordText(
newOrAnyWord(words.questionWords, wordTextToWord, wordsToLearn)
))
self.nextPart = NextPart(type=NextPartType.Word, wordType=WordType.Pronoun)
case WordType.Pronoun:
pronoun = newOrAnyWord(words.pronouns, wordTextToWord, wordsToLearn)
self.sentence.append(wordText(pronoun))
self.nextPart = NextPart(type=NextPartType.Word, wordType=WordType.Verb, wordForm=pronounForm(pronoun))
case WordType.Verb:
wordForm = self.nextPart.wordForm
if wordForm.conjugationType == ConjugationType.Infinitive:
newVerb = newOrAnyNotExpectsInfinitiveVerb(words.verbs, wordTextToWord, wordsToLearn)
self.sentence.append(wordText(newVerb))
if len(newVerb.questions) > 0 and bool(random.getrandbits(1)):
option = random.randrange(0, len(newVerb.questions))
self.nextPart = NextPart(type=NextPartType.VerbQuestion, verbQuestion=newVerb.questions[option])
else:
self.nextPart = None
else:
newVerb: VerbWord = newOrAnyVerb(words.verbs, wordTextToWord, wordsToLearn)
self.sentence.append(verbTextInForm(newVerb, wordForm))
nextOptionsCount = len(newVerb.questions) + (1 if newVerb.expectInfinitive else 0)
if nextOptionsCount > 0:
option = random.randrange(0, nextOptionsCount)
if option < len(newVerb.questions):
self.nextPart = NextPart(type=NextPartType.VerbQuestion, verbQuestion=newVerb.questions[option])
else:
self.nextPart = NextPart(type=NextPartType.Word, wordType=WordType.Verb, wordForm=WordForm(conjugationType=ConjugationType.Infinitive))
else:
self.nextPart = None
case NextPartType.VerbQuestion:
pronounName = list(PronounName)[random.randrange(0, len(PronounName))]
words = pronounAtFormOfQuestion(pronounName, self.nextPart.verbQuestion)
self.sentence += words
self.nextPart = None
return self.nextPart != None
def generateSentence(words: Words, wordTextToWord: Dict[str, Word], wordsToLearn: List[str]):
startWithQuestion = any(
[wordTextToWord[wordText].type == WordType.Question for wordText in wordsToLearn]
) or bool(random.getrandbits(1))
sentenceGenerator = SentenceGenerator(startWithQuestion)
while sentenceGenerator.generateNextPart(words, wordTextToWord, wordsToLearn):
pass
sentence = sentenceGenerator.sentence
sentence[0] = sentence[0].capitalize()
return " ".join(sentence)
def parseAgrs():
parser = argparse.ArgumentParser(description='generate sentences')
parser.add_argument('--wordsConfig', help='path to config with words', type=str, required=True)
args = parser.parse_args()
return args
def main():
args = parseAgrs()
with open(args.wordsConfig, "rt") as f:
config = json.load(f)
words = Words()
for questionWord in config["words"]["questionWords"]:
words.questionWords.append(QuestionWord(type = WordType.Question, **questionWord))
for pronounName in PronounName:
words.pronouns.append(PronounWord(type = WordType.Pronoun, pronounName=pronounName))
for verb in config["words"]["verbs"]:
verb["questions"] = [VerbQuestion[question] for question in verb["questions"]]
words.verbs.append(VerbWord(type = WordType.Verb, **verb))
wordTextToWord = makeWordsByText(words)
learn = config["learn"]
wordsToLearn: List[str] = learn["words"]
wordsToLearn = [word.lower() for word in wordsToLearn]
sentence = generateSentence(
words,
wordTextToWord,
random.sample(wordsToLearn, min(len(wordsToLearn), 2))
)
print(sentence)
if __name__ == "__main__":
main()