Skip to content

Commit

Permalink
Python3 support, refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
vonunwerth committed Jul 11, 2021
1 parent c1f1e71 commit 23ac169
Show file tree
Hide file tree
Showing 8 changed files with 103 additions and 79 deletions.
66 changes: 45 additions & 21 deletions create_cards.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def create_connection(db_file):
"""
Establishes a database connection
:param db_file: File of the database
:return: Successfull connection
:return: Successful connection
"""
try:
return sqlite3.connect(db_file)
Expand All @@ -24,7 +24,7 @@ def create_connection(db_file):

def split_lines(text, line_length):
"""
Split a text in mutliple lines at " " and returns the lines as list
Split a text in multiple lines at " " and returns the lines as list
:param text: Text to be split
:param line_length: Maximum length of each line
:return: List with all lines
Expand All @@ -44,7 +44,7 @@ def split_lines(text, line_length):
return lines


def get_questions_of_categoriy(conn, category):
def get_questions_of_category(conn, category):
"""
Gets all questions of a category from the database
:param conn: Database connection
Expand All @@ -59,6 +59,18 @@ def get_questions_of_categoriy(conn, category):
return question_rows # could also use dict_factory, but indexes are ok here


def get_question_ids(conn):
"""
Gets all ids of the questions in the database
:param conn: Database connection
:return: List of ids
"""
cur = conn.cursor()
cur.execute("SELECT id FROM qac")
ids = [item[0] for item in cur.fetchall()]
return ids


def create_cards():
"""
Creates question cards filled with the questions provided by the database
Expand All @@ -73,35 +85,47 @@ def create_cards():
with conn: # Keep connection open, as long as necessary
categories, categories_long = get_categories_from_file() # get categories and long name
card_count = 1

question_database = {}
for category in categories:
question_database[category] = get_questions_of_category(conn,
category) # Get all questions of those category from database before the loop because so they were just shuffled once
while True:
front = Image.open("assets/front.png") # Load assets
back = Image.open("assets/back.png")
dv = ImageDraw.Draw(front)
dh = ImageDraw.Draw(back)
y = 100
used_ids_for_current_card = []
for category in categories: # For each category
print category
questions = get_questions_of_categoriy(conn,
category) # Get all questions of those category from database
print(category)
questions = question_database[category]

if (len(questions) == 0): # if no new question was found
print("\nSuccessfully created " + str(card_count - 1) + " cards. Those can be found in ./out")
print(str(count_questions(conn) - 6 * (
card_count - 1)) + " Questions have been ignored. (Due to inapplicable categories)")
print("No more questions available to fill new card!")
print(
"Questions with the following id's were skipped: ")

used_ids = [item for item in used_ids if item not in used_ids_for_current_card]
used_ids.sort()
unused_used_cut = [item for item in get_question_ids(conn) if item not in used_ids]
for q_id in unused_used_cut:
print(q_id)
return # End script - cards have been created

for question_row in questions: # question_row[ ] represents one question 0 - ID, 1 - question,
# 2 - answer, 3 - category
print question_row # print full question_row
if (question_row[0] in used_ids) and (
questions.index(question_row) == (len(questions) - 1)): # if no new question was found
print "\nSuccessfully created " + str(card_count - 1) + " cards. Those can be found in ./out"
print str(count_questions(conn) - 6 * (
card_count - 1)) + " Questions have been ignored. (Due to inapplicable categories)"
print "No more questions available to fill new card!"
print "Questions with the following id's were skipped: "
used_ids.sort()
for q_id in used_ids:
print q_id
return # End scipt - cards have been created
if question_row[0] not in used_ids: # if there is a not used question
print(question_row) # print full question_row
if (question_row[0] not in used_ids): # if there is a not yet used question which have to be processed

used_ids.append(question_row[0]) # append to used list
used_ids_for_current_card.append(question_row[0])
question_database[category].remove(question_row)
question = question_row[
1].strip() # Get question and remove possible whitespace after questionsmark
1].strip() # Get question and remove possible whitespace after question mark
answer = question_row[2] # Get answer of the question_row

question_lines = split_lines(question, QUESTION_MAX_LINE_LENGTH)
Expand Down Expand Up @@ -143,7 +167,7 @@ def create_cards():
dh.text((620, y), answer_lines[0], font=fnt, fill=(0, 0, 0)) # Place the answer at y

y = y + NEXT_QUESTION_Y_SKIP # go to the next question
break
break # a new question is added, break and continue with the next category

front.save(
"./out/front" + str(card_count) + ".png") # save front and back of the card with texts written on it
Expand Down
14 changes: 7 additions & 7 deletions database_statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def get_categories_from_file():
def database_statistics():
"""
Generates interesting statistics about questions count, database entries, ...
:return: Successfull execution
:return: Successful execution
"""
conn = create_connection("python_sqlite.db")
categories, categories_long = get_categories_from_file()
Expand All @@ -66,12 +66,12 @@ def database_statistics():
for row in rows:
for number in row:
numbers.append(number)
print "There are " + str(number) + " questions of category " + categories_long[
categories.index(category)]
print "\n" + str(min(numbers)) + " complete question cards can be created.."
print "It exist " + str(count_questions(conn)) + " Questions."
print str(count_questions(conn) - 6 * (
min(numbers))) + " Questions will be ignored. (Due to inapplicable categories)"
print("There are " + str(number) + " questions of category " + categories_long[
categories.index(category)])
print("\n" + str(min(numbers)) + " complete question cards can be created..")
print("It exist " + str(count_questions(conn)) + " Questions.")
print(str(count_questions(conn) - 6 * (
min(numbers))) + " Questions will be ignored. (Due to inapplicable categories)")


if __name__ == '__main__':
Expand Down
46 changes: 23 additions & 23 deletions database_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def validate_questions():
Validates question entries on its length, if they have a questions mark at the end, ...
:return: Warning and Error count
"""
print "Validating question entries..."
print("Validating question entries...")
conn = create_connection("python_sqlite.db")
with conn:
cur = conn.cursor()
Expand All @@ -35,25 +35,25 @@ def validate_questions():
any_error_or_warning = False
if len(
question) > 3 * QUESTION_MAX_LINE_LENGTH:
print "\033[91mError: Question of entry with ID: " + str(
question_id) + " is to long! Cards will be ugly! \033[0m" + question + " \033[91mHas length: " + \
str(len(question)) + "/" + str(3 * QUESTION_MAX_LINE_LENGTH) + "\033[0m"
print("\033[91mError: Question of entry with ID: " + str(
question_id) + " is to long! Cards will be ugly! \033[0m" + question + " \033[91mHas length: " +
str(len(question)) + "/" + str(3 * QUESTION_MAX_LINE_LENGTH) + "\033[0m")
error_count = error_count + 1
any_error_or_warning = True
if question[-1] != "?" and question[-3:] != "...": # Question mark or citing ...s are missing
any_error_or_warning = True
warning_count = warning_count + 1 #
if question[-1] == " ":
print "\033[93mWarning: Question of entry with ID: " + str(
question_id) + " has spaces attached to the back. \033[0m" + question
print("\033[93mWarning: Question of entry with ID: " + str(
question_id) + " has spaces attached to the back. \033[0m" + question)
else:
print "\033[93mWarning: Question of entry with ID: " + str(
question_id) + " has not a ? or ... as last symbol! \033[0m" + question
print("\033[93mWarning: Question of entry with ID: " + str(
question_id) + " has not a ? or ... as last symbol! \033[0m" + question)
if any_error_or_warning:
print("") # Organize Errors and Warnings in blocks grouped by id

print "\033[1mQuestion-Report\n\033[0m\033[91m Errors found: \033[0m\033[1m" + str(
error_count) + "\n \033[0m\033[93m Warnings found: \033[0m\033[1m" + str(warning_count) + "\033[0m\n"
print("\033[1mQuestion-Report\n\033[0m\033[91m Errors found: \033[0m\033[1m" + str(
error_count) + "\n \033[0m\033[93m Warnings found: \033[0m\033[1m" + str(warning_count) + "\033[0m\n")
return warning_count, error_count


Expand All @@ -62,7 +62,7 @@ def validate_answers():
Validates the answer entries, if they are to long, ...
:return: Warning and Error count
"""
print "Validating answer entries..."
print("Validating answer entries...")
conn = create_connection("python_sqlite.db")
with conn:
cur = conn.cursor()
Expand All @@ -74,27 +74,27 @@ def validate_answers():
answer = entry[1]
any_error_or_warning = False
if len(answer.split("(")[0]) > 2 * ANSWER_MAX_LINE_LENGTH: # if both lines of the answer are to long in sum
print "\033[91mError: Answer of entry with ID: " + str(
print("\033[91mError: Answer of entry with ID: " + str(
answer_id) + " is too long! Cards will be ugly! \033[0m" + answer.split("(")[
0] + " \033[91mHas length: " + str(
len(answer.split("(")[0])) + "/" + str(
2 * ANSWER_MAX_LINE_LENGTH) + "\033[0m"
2 * ANSWER_MAX_LINE_LENGTH) + "\033[0m")
error_count = error_count + 1
any_error_or_warning = True
if len(answer.split("(")) > 1:
if len("(" + answer.split("(")[1]) > ANSWER_MAX_LINE_LENGTH: # if citation line is too long
print "\033[91mError: Citation of entry with ID: " + str(
print("\033[91mError: Citation of entry with ID: " + str(
answer_id) + " is too long! Cards will be ugly! \033[0m" + "(" + answer.split("(")[
1] + " \033[91mHas length: " + str(
len("(" + answer.split("(")[1])) + "/" + str(
ANSWER_MAX_LINE_LENGTH) + "\033[0m"
ANSWER_MAX_LINE_LENGTH) + "\033[0m")
error_count = error_count + 1
any_error_or_warning = True
if any_error_or_warning:
print("") # Organize Errors and Warnings in blocks grouped by id

print "\033[1mAnswer-Report\n\033[0m\033[91m Errors found: \033[0m\033[1m" + str(
error_count) + "\n \033[0m\033[93m Warnings found: \033[0m\033[1m" + str(warning_count) + "\033[0m\n"
print("\033[1mAnswer-Report\n\033[0m\033[91m Errors found: \033[0m\033[1m" + str(
error_count) + "\n \033[0m\033[93m Warnings found: \033[0m\033[1m" + str(warning_count) + "\033[0m\n")
return warning_count, error_count


Expand All @@ -103,7 +103,7 @@ def validate_categories():
Validates if any questions is applied to a valid category from the categories file
:return: Warning and Error count
"""
print "Validating category entries..."
print("Validating category entries...")
conn = create_connection("python_sqlite.db")
with conn:
cur = conn.cursor()
Expand All @@ -112,18 +112,18 @@ def validate_categories():
warning_count = 0
for entry in cur.fetchall():
question_id = entry[0]
category = entry[2]
category = entry[2] # only the letter, ignore \n or whats coming behind
any_error_or_warning = False
if category not in database_statistics.get_categories_from_file()[0]:
any_error_or_warning = True
error_count = error_count + 1
print "\033[91mError: Category of entry with ID: " + str(
question_id) + " is missing a correct category \033[0m Current Category: " + category
print("\033[91mError: Category of entry with ID: " + str(
question_id) + " is missing a correct category \033[0m Current Category: " + category)
if any_error_or_warning:
print("") # Organize Errors and Warnings in blocks grouped by id

print "\033[1mCategory-Report\n\033[0m\033[91m Errors found: \033[0m\033[1m" + str(
error_count) + "\n \033[0m\033[93m Warnings found: \033[0m\033[1m" + str(warning_count) + "\033[0m\n"
print("\033[1mCategory-Report\n\033[0m\033[91m Errors found: \033[0m\033[1m" + str(
error_count) + "\n \033[0m\033[93m Warnings found: \033[0m\033[1m" + str(warning_count) + "\033[0m\n")
return warning_count, error_count


Expand Down
8 changes: 4 additions & 4 deletions print_cards.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ def print_cards():

sheet_number = 1
while True:
print "Creating sheet number " + str(sheet_number)
print("Creating sheet number " + str(sheet_number))
card = Image.open("assets/back.png")
sheet = Image.new('RGB', (card.width * 2 + (x_gap * 1), card.height * 4 + (y_gap * 3)))
for i in range(1, 5): # ,(len([name for name in os.listdir('.') if os.path.isfile(name)])/2)):
Expand All @@ -17,12 +17,12 @@ def print_cards():
second_row_y = 2 * card.height
front = Image.open("out/front" + str(i + (sheet_number - 1) * 4) + ".png")
back = Image.open("out/back" + str(i + (sheet_number - 1) * 4) + ".png").rotate(180)
print "Paste front of card " + str(i + (sheet_number - 1) * 4) + " on sheet" + str(sheet_number)
print("Paste front of card " + str(i + (sheet_number - 1) * 4) + " on sheet" + str(sheet_number))
sheet.paste(front, ((i - 1) % 2 * card.width + (i - 1) % 2 * x_gap, 0 + second_row_y))
print "Paste back of card " + str(i + (sheet_number - 1) * 4) + " on sheet" + str(sheet_number)
print("Paste back of card " + str(i + (sheet_number - 1) * 4) + " on sheet" + str(sheet_number))
sheet.paste(back, ((i - 1) % 2 * card.width + (i - 1) % 2 * x_gap, card.height + y_gap + second_row_y))
except IOError:
print "No more cards found"
print("No more cards found")
sheet.save("prints/print" + str(sheet_number) + ".png")
return
sheet.save("prints/print" + str(sheet_number) + ".png")
Expand Down
Binary file modified prints/print1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion questions/questions.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ Q: Who played Obi-Wan Kenobi in George Lucas legendary space-opera film, Star Wa
A: Ewan McGregor
C: A

Q: The 2nd World War lasted from...
Q: The 2nd World War lasted from ...
A: 1939 to 1945
C: H
22 changes: 11 additions & 11 deletions questions_to_database.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def questions_to_database():

conn = create_connection("python_sqlite.db")
if not db_existing:
print "Created a new database for the questions! --> python_sqlite.db"
print("Created a new database for the questions! --> python_sqlite.db")
create_table(conn)
f = codecs.open("questions/questions.txt", "r", "utf-8")

Expand All @@ -71,26 +71,26 @@ def questions_to_database():
question_counter = 0
for line in f:
if line.find("Q: ") >= 0:
question = (line.split("Q: ")[1].split("\r\n")[0]) # All behind Q:, everything before \r\n
question = (line.split("Q: ")[1].split("\r\n")[0].split("\n")[0]) # All behind Q:, everything before \r\n or \n
qac_counter = qac_counter + 1
if line.find("A: ") >= 0:
answer = (line.split("A: ")[1].split("\r\n")[0])
answer = (line.split("A: ")[1].split("\r\n")[0].split("\n")[0])
qac_counter = qac_counter + 1
if line.find("C: ") >= 0:
category = (line.split("C: ")[1].split("\r\n")[0])
category = (line.split("C: ")[1].split("\r\n")[0].split("\n")[0])
qac_counter = qac_counter + 1
if qac_counter == 3: # on the same card
with conn: # Transaction
try:
print "\033[92mQuestion: \033[1m" + question + "\033[0m \033[92m was saved as ID: " \
+ str(create_qac(conn, (question, answer, category))) \
+ "\033[92m in the database ./python_sqlite.db."
except sqlite3.IntegrityError: # Integrity Error, wenn Unique Frage bereits enthalten ist.
print "\033[93mWarning: Question: \033[1m" + question + "\033[0m \033[93mwas skipped. Already " \
"found in database. "
print("\033[92mQuestion: \033[1m" + question + "\033[0m \033[92m was saved as ID: "
+ str(create_qac(conn, (question, answer, category)))
+ "\033[92m in the database ./python_sqlite.db.")
except sqlite3.IntegrityError: # Integrity Error, when unique question is already in the db
print("\033[93mWarning: Question: \033[1m" + question + "\033[0m \033[93m was skipped. Already "
"found in database. ")
qac_counter = 0
question_counter = question_counter + 1
print "\033[0m"
print("\033[0m")
conn.close()


Expand Down
Loading

0 comments on commit 23ac169

Please sign in to comment.