Skip to content

Commit

Permalink
Merge pull request #78 from Capstone-Projects-2024-Spring/Allen
Browse files Browse the repository at this point in the history
CS2STT-61 created endpoint function and adjusted parameters and retur…
  • Loading branch information
ereizas committed May 1, 2024
2 parents a3a9dc2 + c7e4918 commit b65becc
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 49 deletions.
24 changes: 23 additions & 1 deletion app.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#permanent import
import os
import sentence_generator
import uuid
from dotenv import load_dotenv
from flask import Flask, jsonify, redirect, render_template, request, url_for, session
Expand Down Expand Up @@ -380,6 +381,28 @@ def update_db():
return "Not successful"
return "Successful"
return "Not successful"

@_app.route("/generate_text/",methods=["GET"])
def generate_text():
"""
Sends back text for the requestor to use
:param difficulty
:param form : Specifies the form of text generated. Values: 'sentences' or 'word_list'
"""
difficulty = request.args.get("difficulty")
wpm = request.args.get("wpm")
if wpm:
wpm = int(wpm)
if wpm>=0 and wpm<=45:
difficulty="easy"
elif wpm>=46 and wpm<=80:
difficulty="medium"
else:
difficulty="hard"
return sentence_generator.generate_sentences(difficulty)
if not difficulty:
difficulty=""
return Text_Generator.generate_text(difficulty,request.args.get("form"),request.args.get("amount"))


@_app.route('/raceData/<username>', methods=['GET', 'POST'])
Expand All @@ -402,7 +425,6 @@ def getUserRaceData(username):
except Exception as e:
return jsonify({'error': str(e)}), 500


class Database:
"""
A class representing a database connection and operations.
Expand Down
89 changes: 41 additions & 48 deletions sentence_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,9 @@


def main():
sentences = generate_sentences()
sentences = generate_sentences("hard")

#File names for each difficulty level
file_names = ['easy_sentences.txt', 'medium_sentences.txt', 'hard_sentences.txt']

#Write sentences to their respective files
for i, difficulty_level in enumerate(sentences):
with open(file_names[i], 'w') as file:
for sentence in difficulty_level:
file.write(sentence + '\n')
print(sentences)

def is_valid_characters(sentence):
allowed_characters = set(string.ascii_letters + string.punctuation + " ")
Expand All @@ -40,47 +33,47 @@ def is_similar(new_sentence, existing_sentences, first_three_words_set):

return False

def generate_sentences():
sentences_per_difficulty = 10
sentences = [[], [], []]
unique_checks = set() #Using a set to track unique sentences
first_three_words_set = set() #Set to track first three words of each sentence
def generate_sentences(difficulty):
difficulty_mapping = {"easy": 1, "medium": 2, "hard": 3}
if difficulty not in difficulty_mapping:
return "Invalid difficulty level"

difficulty_index = difficulty_mapping[difficulty] - 1
num_sentences = 10
sentences = []
unique_checks = set()
first_three_words_set = set()

prompt = "Create a sentence that has "
if difficulty_index == 0:
prompt += "short and simple words that have letters that are easy to type in sequence."
elif difficulty_index == 1:
prompt += "of medium length, with moderate vocabulary and one comma that have letters that are moderately difficult to type in sequence."
elif difficulty_index == 2:
prompt += "long and complex, using advanced vocabulary, including commas, semicolons, and at least one capitalized proper noun with words that have letters that are difficult to type in sequence."

for i in range(sentences_per_difficulty):
for difficulty in range(1, 4):
prompt = "Create a sentence that has "
if difficulty == 1:
prompt += "short and simple words that have letters that are easy to type in sequence."
elif difficulty == 2:
prompt += "of medium length, with moderate vocabulary and one comma that have letters that are moderately difficult to type in sequence."
elif difficulty == 3:
prompt += "long and complex, using advanced vocabulary, including commas, semicolons, and at least one capitalized proper noun with words that have letters that are difficult to type in sequence."

attempts = 0
while attempts < 5:
try:
response = openai.Completion.create(
engine="gpt-3.5-turbo-instruct",
prompt=prompt,
temperature=1.0,
max_tokens=100,
top_p=1,
frequency_penalty=2.0,
presence_penalty=2.0
)
generated_sentence = response.choices[0].text.strip()

#Check if the sentence is valid based on characters and if it is similar
if is_valid_characters(generated_sentence) and not is_similar(generated_sentence, unique_checks, first_three_words_set):
unique_checks.add(generated_sentence)
sentences[difficulty - 1].append(generated_sentence)
first_three_words_set.add(' '.join(generated_sentence.lower().translate(str.maketrans('', '', string.punctuation)).split()[:3]))
break
except Exception as e:
print(f"An error occurred: {e}")
attempts += 1
attempts = 0
while len(sentences) < num_sentences and attempts < 50:
try:
response = openai.Completion.create(
engine="gpt-3.5-turbo-instruct",
prompt=prompt,
temperature=1.0,
max_tokens=100,
top_p=1,
frequency_penalty=2.0,
presence_penalty=2.0
)
generated_sentence = response.choices[0].text.strip()
if is_valid_characters(generated_sentence) and not is_similar(generated_sentence, unique_checks, first_three_words_set):
unique_checks.add(generated_sentence)
sentences.append(generated_sentence)
first_three_words_set.add(' '.join(generated_sentence.lower().translate(str.maketrans('', '', string.punctuation)).split()[:3]))
except Exception as e:
print(f"An error occurred: {e}")
attempts += 1

return sentences
return ' '.join(sentences)

if __name__ == "__main__":
main()

0 comments on commit b65becc

Please sign in to comment.