repl.it
@joshwood/

Poe v0.3

Python

The Autonomous Poet

fork
loading
Files
  • main.py
  • texts
  • datamuse.py
  • datamuseAPI.pickle
  • fileHandler.py
  • poems.txt
  • sonnetMaker.py
  • textReader.py
main.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
from sonnetMaker import SonnetMaker
from fileHandler import FileHandler
import replit, time, glob, datetime


class UserInterface:
    def __init__(self, mSonnetMaker):
        replit.clear()
        self.sonnetMaker = mSonnetMaker
        self.readTexts = []
        self.state = 1
        self.status = "Welcome"
        self.trained = False
        self.running = True
        self.getInput = True

        self.__getTexts()

        longestText = 0
        minWidth = 61
        for eachText in self.texts:
            if len(eachText) > longestText:
                longestText = len(eachText)
        if longestText < minWidth:
            longestText = minWidth
        self.width = longestText + 7

    def __drawHeader(self, title=None):
        print("╔{}╗".format("═" * self.width))
        if title:
            self.__printLine(title)
            print("╠{}╣".format("═" * self.width))

    def __drawFooter(self, status=None):
        if status:
            print("╠{}╣".format("═" * self.width))
            self.__printLine(status)
        print("╚{}╝".format("═" * self.width))

    def __drawBox(self, text):
        print("╔{}╗".format("═" * self.width))
        self.__printLine(text)
        print("╚{}╝".format("═" * self.width))

    def __drawBigBox(self, lines):
        print("╔{}╗".format("═" * self.width))
        for string in lines:
            self.__printLine(string)
        print("╚{}╝".format("═" * self.width))

    def __printLine(self, string):
        print("║ {}{} ║".format(string, " " * (self.width - len(string) - 2)))

    def __drawOptions(self, options):
        for count in range(len(options)):
            self.__printLine("{}. {}".format(str(count + 1), options[count]))

    def __drawLearnMenu(self):
        replit.clear()
        self.__drawHeader(
            "Select file to train Poe (you may select more than one):")
        self.__drawOptions([text[6:-4] for text in self.texts] + ["Return"])
        self.__drawFooter(self.status)

    def __drawHaikuMenu(self):
        replit.clear()
        self.__drawBox("What would you like your haiku to be about?")
        topic = input(": ")
        if self.sonnetMaker.topicRecognized(topic):
            replit.clear()
            self.__drawBox("Generating haiku... (this can take a bit)")
            try:
                startTime = time.time()
                haiku = mSonnetMaker.genHaiku(topic.lower())
                currentTime = datetime.datetime.now()
                currentTime = currentTime.strftime("%I:%M:%S %m/%d/%Y")
                FileHandler.writeToText(
                    '\n\n Haiku about "{}" ({})'.format(topic, currentTime),
                    "poems.txt")
                replit.clear()
                self.__drawHeader(
                    "Haiku about {} (generated in {} sec)".format(
                        topic, str(round(time.time() - startTime, 2))))
                for line in haiku:
                    self.__printLine(line)
                    FileHandler.writeToText(line, "poems.txt")
                self.__drawFooter("Press enter to return")
                self.status = "Haiku has been saved to poems.txt"
            except Exception as e:
                self.status = "Something went wrong. Try again with a different topic"
                self.getInput = False
                self.state = 1

    def __drawSonnetMenu(self):
        replit.clear()
        self.__drawBox("What would you like your sonnet to be about?")
        topic = input(": ")
        if self.sonnetMaker.topicRecognized(topic):
            replit.clear()
            self.__drawBox("Generating sonnet... (this can take a bit)")
            try:
                startTime = time.time()
                sonnet = mSonnetMaker.genSonnet(topic.lower())
                currentTime = datetime.datetime.now()
                currentTime = currentTime.strftime("%I:%M:%S %m/%d/%Y")
                FileHandler.writeToText(
                    '\n\nSonnet about "{}" ({})'.format(topic, currentTime),
                    "poems.txt")
                replit.clear()
                self.__drawHeader(
                    "Sonnet about {} (generated in {} sec)".format(
                        topic, str(round(time.time() - startTime, 2))))
                for line in sonnet:
                    self.__printLine(line)
                    FileHandler.writeToText(line, "poems.txt")
                self.__drawFooter("Press enter to return")
                self.status = "Sonnet has been saved to poems.txt"
            except Exception as e:
                self.status = "Something went wrong. Try again with a diferent topic."
                self.getInput = False
                self.state = 1
        else:
            self.state = 1
            self.status = "Error: Topic must be one word and recognized by the Datamuse API"
            self.getInput = False

    def __drawMainMenu(self):
        replit.clear()
        self.__drawHeader("Poe - The Autonomous Poet")
        if self.trained:
            self.__drawOptions([
                "Generate sonnet", "Generate haiku", "Train Poe", "Show stats",
                "Reset Poe", "Exit"
            ])
        else:
            self.__drawOptions(["Train Poe", "Show stats", "Exit"])
        self.__drawFooter(self.status)

    def __getInput(self):
        userInput = input(":")
        if self.state == 1:  # Main Menu
            if self.trained:  # If at least one text has been read by Poe (so he is prepared to generate poetry)
                if userInput == "1":  # Generate Sonnet
                    self.state = 3
                elif userInput == "2":  # Generate Haiku
                    self.state = 4
                elif userInput == "3":  # Train Poe
                    self.state = 2
                elif userInput == "4":  # Show Stats
                    self.status = "API Calls Made: {}".format(
                        str(mSonnetMaker.getApiCalls()))
                elif userInput == "5":  # Reset Poe
                    self.sonnetMaker.reset()
                    self.trained = False
                    self.status = "Poe has been reset. All text data has been deleted."
                elif userInput == "6":  # Exit
                    self.running = False
                else:
                    self.status = "Error: Invalid Input"
            else:  # If Poe hasn't yet been trained yet (incapable of generating poetry)
                if userInput == "1":  # Train Poe
                    self.state = 2
                elif userInput == "2":  # View Stats
                    self.status = "API Calls Made: {}".format(
                        str(mSonnetMaker.getApiCalls()))
                elif userInput == "3":  # Exit
                    self.running = False
                else:
                    self.status = "Error: Invalid Input"
        elif self.state == 2:  # Learn Menu
            if userInput.isnumeric() and len(userInput) == 1:
                if int(userInput) <= len(self.texts) and int(
                        userInput) > 0:  # If the input corresponds to a text
                    replit.clear()
                    textName = self.texts[int(userInput) - 1][6:-4]
                    self.__drawBox(
                        "Learning from {}... (This shouldn't take long)".
                        format(textName))
                    mSonnetMaker.learnData(self.texts[int(userInput) - 1])
                    self.trained = True
                    self.state = 2
                    self.status = "{} has been learned.".format(textName)
                elif int(userInput) == len(self.texts) + 1:
                    self.state = 1
                else:
                    self.status = "Error: Invalid Input"
        else:  # poem is being displayed
            self.state = 1

    def __getTexts(self, directory="texts"):
        self.texts = glob.glob(directory + "/*.txt")

    def runInterface(self):
        while self.running:
            self.getInput = True
            if self.state == 1:
                self.__drawMainMenu()
            elif self.state == 2:
                self.__drawLearnMenu()
            elif self.state == 3:
                self.__drawSonnetMenu()
            elif self.state == 4:
                self.__drawHaikuMenu()
            if self.getInput:
                self.__getInput()
        replit.clear()
        self.__drawHeader("Credits")
        self.__printLine("Texts taken from Project Gutenberg")
        self.__printLine("  -  www.gutenburg.org")
        self.__printLine(
            "Rhyme, topic and syllable data came from the Datamuse API")
        self.__printLine("  -  www.datamuse.com/api")
        self.__printLine("")
        self.__printLine('Created by Josh "skiboyec" Wood')
        self.__drawFooter()


mSonnetMaker = SonnetMaker("datamuseAPI.pickle")
mUI = UserInterface(mSonnetMaker)
mUI.runInterface()
?