<file_sep>#!/usr/bin/env python3
import os
from reportlab.platypus import SimpleDocTemplate
from reportlab.platypus import Paragraph
from reportlab.lib.styles import getSampleStyleSheet
styles = getSampleStyleSheet()
report = SimpleDocTemplate("/tmp/processed.pdf")

dir = "./supplier-data/descriptions/"

long_text = []
for i in os.listdir(dir):
    with open(os.path.join(dir,i)) as f:
        long_text.append('name: ' + f.readline().strip() + '<br/>')
        long_text.append('weight: ' + f.readline().strip() + '<br/>')
    long_text.append(' <br/>')

paragraph_fruit = "".join(long_text)
report_title = Paragraph("Supplied inventory", styles['h1'])
report_body = Paragraph(paragraph_fruit, styles['Normal'])
if __name__ == "__main__":
    report.build([report_title,report_body])
<file_sep>#!/usr/bin/env python3
import os
import requests
from collections import OrderedDict

def open_file(directory,file):
    dict_text = OrderedDict()
    keys = ["name","weight","description"]
    count = 0
    with open(os.path.join(directory,file)) as f:
        for line in f:
            if line.strip() != "":
                dict_text[keys[count]] = line.strip()
                if keys[count] == 'weight':
                    dict_text[keys[count]] = line[:-5]
                count += 1
        dict_text['image_name'] = file[:-4]+'.jpeg'

    return dict_text

def main():
    dir = "./supplier-data/descriptions/"
    dir_img = "./supplier-data/images/"
    url = "http://35.202.121.162/fruits/"
    for i in os.listdir(dir):
        if i[-3:] == "txt":
            comp_dict =  open_file(dir,i)
            requests.post(url, data=comp_dict)

if __name__ == '__main__':
    main()
<file_sep>#!/usr/bin/env python3

import email.message
import mimetypes
import os.path
import smtplib
import psutil
import shutil

def generate(sender, recipient, subject, body):
    message = email.message.EmailMessage()
    message["From"] = sender
    message["To"] = recipient
    message["Subject"] = subject
    message.set_content(body)
    return message

def send(message):
    mail_server = smtplib.SMTP('localhost')
    mail_server.send_message(message)
    mail_server.quit()

class cpu_too_high(Error):
   """Raised when the CPU is too high """
   pass

def check_cpu():
    if psutil.cpu_percent() > 80:
        raise cpu_too_high

try:
    check_cpu()
except cpu_too_high:
    from1 = '<EMAIL>'
    to1 = '<EMAIL>'
    subject1 = 'Error - CPU too high'
    body1 = 'Please check your system and resolve the issue as soon as possible.'
    message = generate(from1,to1,subject1,body1)
    send(message)
except:
    print('Unknown error')
<file_sep>
from mastermind_code_class import colour_choice, mastermind_code


class player:

    def __init__(self, code_size = 4, num_col_choice = 6, *args, **kwargs):
        self.guesses = []
        self.feedback_all = []
        self.round = 1
        self.num_col_choice = num_col_choice
        self.code_size = code_size
        self.SECRET_CODE = mastermind_code(
            col_selection_class = colour_choice,
            code_size = code_size,
            numcols = num_col_choice)


    def add_guess(self, code_input = None):
        guess = mastermind_code(
            col_selection_class = colour_choice,
            code_size = self.code_size,
            numcols = self.num_col_choice,
            code = code_input)
        self.guesses.append(guess)
        self.round += 1

    def check_score(self):
        feedback = [0] * self.code_size
        taken_1_point = []
        for i in range(self.code_size):
            if self.guesses[-1][i] == self.SECRET_CODE[i]:
                feedback[i] = 2
            else:
                for j in [num for num in range(self.code_size) if num != i ]:
                    if self.guesses[-1][i] == self.SECRET_CODE[j]:
                        if self.guesses[-1][j] != self.SECRET_CODE[j]:
                            if j not in taken_1_point:
                                feedback[i] =  1
                                taken_1_point.append(j)

        self.feedback_all.append(feedback)


if __name__ == "__main__":

    tom = player(code_size = 5, num_col_choice=2)
    print(tom.num_col_choice)
"""
    tom.add_guess()
    print(tom.guesses[-1])

    tom.check_score()
    print(tom.feedback_all)

    tom.add_guess(code_input = ["black","white","yellow","yellow","grunge"])
    print(tom.guesses[-1])

    tom.check_score()
    print(tom.feedback_all)

    tom.add_guess()
    print(tom.guesses[-1])

    tom.check_score()
    print(tom.feedback_all)

    print(tom.SECRET_CODE)
"""
<file_sep>"""
This script creates a class to store mastermind codes.
Firstly it defines a class colour_choice which specifice each code entry.
It then uses this as part of mastermind_code to form the total code
"""


import random

colour_choices = ["red","blue","yellow","green","black","white"]

def colours_included(num_col):
    colour_choice_now = colour_choices[0:num_col]
    return colour_choice_now

def choose_colour(colours_included):
    return "".join(random.sample(colours_included, 1))

class colour_choice:
    def __init__(self, num_colours , value = ""):
        if not isinstance(num_colours,int):
            raise ValueError("num_colours must be a number")
        elif not ( (num_colours > 1) & (num_colours <= 6) ):
            raise ValueError("num_colours must be between 2 and 6")
        elif not isinstance(value,str):
            raise ValueError("value must be a string")
        colours = colours_included(num_colours)
        if value:
            if value not in colours:
                raise ValueError("""
The value you entered wasn't part of the game:
You entered {}.
The allowed colours are {}""".format(value,colours))
            else:
                self.value = value
        else:
            self.value = choose_colour(colours)


class mastermind_code(list):
    def __init__(self, code_size = 4, numcols = 6,
                col_selection_class = None, code = None, *args, **kwargs):
        if not col_selection_class:
            raise ValueError("You must provide a class to select colours")
        elif not isinstance(code_size,int):
            raise ValueError("code_size must be a number")
        elif not ( (code_size > 1) & (code_size <= 6) ):
            raise ValueError("code_size must be between 2 and 6")
        super().__init__()
        if code:
            if not code_size == len(code):
                raise ValueError("Make sure your entry is the same length as the code you are trying to break!")
            else:
                for i in range(code_size):
                    self.append(col_selection_class(num_colours = numcols,
                    value = code[i]).value)
        else:
            for _ in range(code_size):
                self.append(col_selection_class(num_colours = numcols).value)

"""
code_test1 = mastermind_code(col_selection_class = colour_choice,
                            code = None, numcols = 2)
print(code_test1)

code_test2 = mastermind_code(col_selection_class = colour_choice,
                            code = ["red","blue","purple","green","purple"],
                            code_size = 5)
print(code_test2)
"""
<file_sep>from mastermind_code_class import colour_choice, mastermind_code, colour_choices
from mastermind_player_class import  player
import time
import csv

print("\n")
print("Welcome to Mastermind!")
time.sleep(1)
print("Mastermind is a code-breaking game for two players.")
time.sleep(1)
print("However, in this version it will be 1 player vs the computer!")
time.sleep(1)
print("Type 'Help' at any time to get instructions")
time.sleep(1)
print("\n")
time.sleep(1)
print("I will generate a code, which you have to break!")
time.sleep(1)
print("\n")
time.sleep(1)

game_status = "begin"

def pre_game(game_status):
    while game_status != 'start':
        game_status = input("'Start' to begin, 'Help' for help, 'Exit' for exit: \n").lower()

        if game_status == 'help':
            time.sleep(1)
            print("\nVisit the following link for full rules & strategies: https://en.wikipedia.org/wiki/Mastermind_(board_game)#Gameplay_and_rules")
            time.sleep(1)
            print("\nContact <EMAIL> with any issues with the application.\n")
        if game_status == 'exit':
            print("\nThanks for playing! \n")
            exit()
    return game_status

def num_colours_in_game():
    colours = ""
    while not colours:
        try:
            colours = int(input(
    """
How many colours do you want to use as part of the game?
Minimum 2, Maximum 6:  """))
            time.sleep(1)
        except:
            print("Error: Integer only, between 2 and 6")
    return colours

def num_entries_in_code():
    code_entry = ""
    while not code_entry:
        try:
            code_entry = int(input(
        """
And what should the length of the code be?
Minimum 2 Maximum 6:  """))
            time.sleep(1)
        except:
            print("Error: Code length is a whole number > 2")
    return code_entry


def game_start():

    name = input("What's your name? (for high score credit purposes!) ")
    time.sleep(1)
    colours = num_colours_in_game()
    code_length = num_entries_in_code()
    try:
        player_go = player(code_size = code_length, num_col_choice = colours)
    except Exception as err:
        print(err)
        return "start",  "", ""
    time.sleep(1)
    print(
    """

Time to play {}! I have created a secret code, good luck guessing it!
I'll keep track of your score and attempts.
""".format(name))
    time.sleep(2)
    return "long_options", name, player_go

def instructions(name_input):
    print(
        """
{} - it's your turn to add a code.
Here are the colours the computer made their code from.
{}
Remember, the code length is {}
""".format(name_input, colour_choices[:player_details.num_col_choice], player_details.code_size))
    time.sleep(3)
    print("""
If you get the right colour in the right slot, you get 2 points.
If you get the right colour in the wrong slot, you get 1 point.
        """)
    time.sleep(3)


while game_status != "finished":
    if game_status == "begin":
        game_status  = pre_game(game_status)
    elif game_status == "start":
        game_status, name, player_details  = game_start()
    elif game_status == "long_options":
        instructions(name)
        game_status = "short_options"
    elif game_status == "short_options":
        user_go = input("""
'guess' to guess a code, 'view' to view guesses, 'exit' to exit, 'more' for detailed instructions
""").lower()
        if user_go == 'exit':
            game_status = "begin"
        elif user_go == 'more':
            game_status = "long_options"
        elif user_go == 'view':
            print("Your guesses so far")
            guess_list = list(zip(player_details.guesses,player_details.feedback_all))
            for i in guess_list:
                print(i)
        elif user_go == 'guess':
            list_guess = list(map(str.strip,input("Add your guess here, comma seperated:  ").split(",")))
            try:
                player_details.add_guess(code_input = list_guess)
                player_details.check_score()
                time.sleep(2)
                print("""
Good guess, here is your score:
{}""".format(player_details.feedback_all[-1]))
                if player_details.feedback_all[-1] == [2]*player_details.code_size:
                    print("Congratulations! You broke the code!")
                    print("It took you {} attempts".format(player_details.round))
                    time.sleep(2)
                    play_again = input("Play again? Y/N: ").lower()
                    if play_again == "y":
                        game_status = "begin"
                    else:
                        game_status = "finished"
            except ValueError as err:
                time.sleep(1)
                print("something went wrong..")
                print("check the below error message and try again")
                time.sleep(1)
                print(err)
                time.sleep(2)
                user_go == "short_options"


new_score = [name, player_details.round]

with open('scores.csv','r') as scoreboard:
    reader = list(csv.reader(scoreboard, delimiter=','))
    if int(reader[-1][1]) > int(new_score[1]):
        for row in reader[1:]:
            if int(row[1]) > int(new_score[1]):
                new_entry_row = reader.index(row)
                reader.insert(new_entry_row,new_score)
                break
    else:
        reader.append(new_score)
    reader = reader[:5]

print("Latest High Scores!:")
time.sleep(1)
if new_entry_row < 5:
    print("New entry at position {}!!!!".format(new_entry_row))
    time.sleep(1)
for row in reader:
    print(row)

with open('scores.csv', "w") as outfile:
    writer = csv.writer(outfile)
    for line in reader:
        writer.writerow(line)


# Todo
# seperate score boards depending on size of code and number of colours_included
# Log rounds, colours & difficulty in log file, use for statistics on players
# need to imrpvoe view score so its visual plug in based
# need to add pip style guide and check
<file_sep>#!/usr/bin/env python3
import requests
import os

dir = "./supplier-data/images/"
url = "http://localhost/upload/"
for i in os.listdir(dir):
    if i[-4:] == 'jpeg':
        with open(os.path.join(dir,i), 'rb') as opened:
            r = requests.post(url, files={'file': opened})
<file_sep>#!/usr/bin/env python3

from PIL import Image
import os
from pathlib import Path

# task 1: user enters relative location of images, we locate
#  absolute path of images
"""
rel_path = "./supplier-data/images"

posix_path = Path(rel_path)
print(posix_path.resolve())
"""
def main():
    path_images = confirm_correct_path()
    imgs = find_images_convert(path_images)

def confirm_correct_path():
    confirm_path = 'no'
    while confirm_path.lower() != 'yes':
        rel_path = input(
        "\nInput relative position of images in following form: ./directory/subdirectory/   \nThey are usually found in ./supplier-data/images: \n" )
        full_path = str(Path(rel_path).resolve())
        confirm_path = input("\n Is this the correct folder? (yes/no/quit)  \n "+ full_path + "   ")
        if confirm_path.lower() == "quit":
            exit()
    return full_path

def find_images_convert(img_folder):
    images = os.listdir(img_folder)
    print('Dealing with ' + str(len(images)) + ' files')
    count = 0
    for i in images:
        if i[-4:] == 'tiff':
            count += 1
            im = Image.open(os.path.join(img_folder,i)).convert('RGB').resize((600,400))
            im.save(os.path.join(img_folder,i[:-4]+'jpeg'),"JPEG")
    print('Processed '+str(count)+' tiff images')

if __name__ == '__main__':
    main()

# task friendly

"""
#!/usr/bin/env python3
from PIL import Image
import os

def main():
    find_images_convert("./supplier-data/images/")

def find_images_convert(img_folder):
    images = os.listdir(img_folder)
    print('Dealing with ' + str(len(images)) + ' files')
    count = 0
    for i in images:
        if i[-4:] == 'tiff':
            count += 1
            im = Image.open(os.path.join(img_folder,i)).convert('RGB').resize((600,400))
            im.save(os.path.join(img_folder,i[:-4]+'jpeg'),"JPEG")
    print('Processed '+str(count)+' tiff images')

if __name__ == '__main__':
    main()


"""
<file_sep># all-things - my public repo


## final_google_project (IT automation with Python - Coursera)

This repo contains most of my final project code for the Google IT Automation course. The course covered python/bash/unix, the final project included:
- image manipulation
- working with text files and dictionaries
- JSON posting 
- DJANGO frameworks
- email automation

## Mastermind (I developed a application to play the game 'Mastermind')

I wanted to recreate a game I enjoy using Python and OOP. I built classes to represent players, and the rules for playing hands built as methods in those classes.

The application allows you to:
- Play mastermind vs the computer 
- Error handling to avoid crashing based on user input
- Class inheritance between code entries and full codes.
- High score file as a csv which is updated each game
- Algorithm logic to score each guess (complex if and for/while loops)



