utils.py 2 KB
import os
import re
import matplotlib.pyplot as plt

multi_line_comments = ["'''", '"""']

def remove_string(line):
    strIn = False
    strCh = None
    result = ''
    i = 0
    L = len(line)

    while i < L:
        if i + 3 < L:
            if line[i:i+3] in multi_line_comments:
                if not strIn:
                    strIn = True
                    strCh = line[i:i+3]
                elif line[i:i+3] == strCh:
                    strIn = False

                i += 2
                continue

        c = line[i]
        i += 1

        if c == '\'' or c == '\"':
            if not strIn:
                strIn = True
                strCh = c
            elif c == strCh:
                strIn = False
            continue

        if strIn:
            continue

        result += c

    return result
    
def is_extension(f, ext):
    return os.path.splitext(f)[1][1:] == ext

def _readdir_r(dirpath): # readdir for recursive
    ret = []
    for f in os.listdir(dirpath):
        ret.append(os.path.join(dirpath, f))
        
    return ret

def readdir(path): # read files from the directory
    pathList = [path]
    result = []
    i = 0
    
    while i < len(pathList):
        f = pathList[i]
        if os.path.isdir(f):
            pathList += _readdir_r(f)
        else:
            result.append(f)
            
        i += 1

    return result

def readAll(path):
    f = open(path, 'r', encoding='utf8')
    ret = f.read()
    f.close()
    return ret

def readLines(path):
    f = open(path, 'r', encoding='utf8')
    ret = f.readlines()
    f.close()
    return ret

def plot_training(H, plotPath):
  plt.style.use("ggplot")
  plt.figure()
  plt.plot(H.history["loss"], label="train_loss")
  plt.plot(H.history["val_loss"], label="val_loss")
  plt.plot(H.history["accuracy"], label="train_acc")
  plt.plot(H.history["val_accuracy"], label="val_acc")
  plt.title("Training Loss and Accuracy")
  plt.xlabel("Epoch #")
  plt.ylabel("Loss/Accuracy")
  plt.legend(loc="lower left")
  plt.savefig(plotPath)