Example #1
0
def insertFolders(parentDir) :
  dirs = fs.listDirectories(parentDir)
  for dir in dirs :
    # 作者名
    parts = Text.split("/", dir)
    creator = parts[len(parts) - 1]
    # 作品名s
    subdirs = fs.listDirectories(dir)
    if len(subdirs) == 0 :
      p = Text.split(' ', creator)
      creator = p[0]
      insertData(dir, creator)
    else :
      for subdir in subdirs :
        insertData(subdir, creator)
  return
Example #2
0
def insertData(dir, creator) :
  global mark
  global cmd
  parts = Text.split('/', dir)
  title = parts[len(parts) - 1]
  cmd = f"INSERT INTO Pictures(TITLE, CREATOR, `PATH`, MARK) VALUES('{title}', '{creator}', '{dir}', '{mark}');"
  print(cmd)
  return
Example #3
0
def main():
    print("** Videos テーブル用ビデオファイル一覧を作成または挿入する。**")
    # path 取得
    if Common.count_args() == 0:
        Common.stop(1, "使用方法: python3 InsVideos.py path insert")
    path = Common.args(0)
    # print/insert オプション取得
    insoption = False
    if Common.count_args() == 2:
        insoption = True
    # 確認
    if not insoption:
        print(f"Path = {path}, Videos テーブルに挿入 = {insoption}")
        a = Common.readline("Confirm (Y/N) > ")
        if Text.tolower(a) != 'y':
            Common.stop(2, "実行を中止しました。")
    else:
        pass
    # ビデオファイル一覧を取得する。
    vfiles = getVideoFiles(path)
    # INSERT 文を作成する。
    sql = "INSERT INTO Videos VALUES"
    for p in vfiles:
        p = p.replace("'", "''")
        fileName = FileSystem.getFileName(p)
        title = Text.left(fileName, len(fileName) - 4)
        sql += f"(NULL, '0', '{title}', '{p}', '', '', '', '', 0, 0, 0, 0, 0),\n"
        print(p)
    sql = Text.left(sql, len(sql) - 2) + ";"
    if not insoption:
        print(sql)
    if insoption:
        # INSERT 文を実行する。
        try:
            mysql = MySQL.MySQL(UID, PWD, UID)
            mysql.execute(sql)
            # 終了メッセージ
            if not insoption:
                print("正常に終了しました。")
        except Error as e:
            Common.stop("MySQL のエラーにより終了。接続条件やSQL をチェックしてください。" + e.message)
    return
Example #4
0
def insertBinaries(filePath):
    ext = fs.getExtension(filePath)
    size = fs.getFileSize(filePath)
    name = fs.getFileName(filePath)
    filePath = filePath.replace("\\", "/")
    hexa = bin2hex(filePath)
    sn = mysql_client.getValue("SELECT max(sn) FROM BINDATA") + 1
    sql = Text.format(INSERT, name, filePath, ext, hexa, size, sn)
    mysql_client.execute(sql)
    lastId = mysql_client.getValue("SELECT max(id) FROM BINDATA")
    return lastId
Example #5
0
def api_quick_age(convert, year) :
  mysql = MySQL.MySQL()
  if convert == "age" :
    # 年齢から誕生年
    rows = mysql.query("SELECT year, gengo FROM QuickAge WHERE age = {0}".format(year))
    if len(rows) == 0 :
      result = "エラー: 年齢が不正"
    else :
      row = rows[0]
      result = str(row[0]) + "," + row[1]
  elif convert == "born" :
    # 誕生年から年齢
    if Text.isdigit(year) :
      # age は西暦
      rows = mysql.query("SELECT age FROM QuickAge WHERE year={0}".format(year))
      if len(rows) == 0 :
        result = "エラー: 西暦が不正"
      else :
        result = rows[0]
    else :
      # year は和暦
      if year.startswith('T') :
        year = "大正" + Text.substring(year, 1) + "年";
      elif year.startswith('S') :
        if Text.substring(year, 1) == '1' :
          year = "昭和元年";
        else :
          year = "昭和" + Text.substring(year, 1) + "年";
      elif year.startswith('H') :
        if Text.substring(year, 1) == '1' :
          year = "平成元年";
        else :
          year = "平成" + Text.substring(year, 1) + "年";
      elif year.startswith('R') :
        if Text.substring(year, 1) == '1' :
          year = "令和元年"
        else :
          year = "令和" + Text.substring(year, 1) + "年";
      else :
        result = "エラー: 和暦文字が不正"
        return result
      print(year)
      rows = mysql.query("SELECT age FROM QuickAge WHERE gengo='{0}'".format(year))
      if len(rows) == 0 :
        result = "エラー: 和暦が不正"
      else :
        result = rows[0]     
  else :
    # エラー
    result = "エラー: 不正な変換"
  return result
Example #6
0
def find():
    folder = request.args.get("folder")
    findstr = request.args.get("findstr")
    files = fs.listDirectories(folder, asstr=True) + fs.listFiles(folder,
                                                                  asstr=True)
    items = []
    for f in files:
        if Text.contain(findstr, f):
            items.append(getFileInfo(f))
        else:
            pass
    return jsonify(items)
Example #7
0
def api_bindata_insert(folder) :
  files = fs.listFiles(folder, asstr=True)
  count = 0
  try :
    for f in files :
      ext = Text.tolower(fs.getExtension(f))
      if ext in [".jpg", ".jpeg", ".png", ".gif"] :
        util.insertBinaries(f)
        count += 1
  except Exception as e :
    print(str(e))
  return count
Example #8
0
def api_image_resize(folder, size) :
  files = fs.listFiles(folder, asstr=True)
  count = 0
  try :
    for f in files :
      ext = Text.tolower(fs.getExtension(f))
      if ext in [".jpg", ".jpeg", ".png", ".gif"] :
        util.resizeImage(f, size)
        count += 1
  except Exception as e:
    print(str(e))
  return count
Example #9
0
def insertBinaries(filePath):
    INSERT = "INSERT INTO BINDATA(`title`, `original`, `datatype`, `data`, `info`, `size`) VALUES('{0}', '{1}', '{2}', {3}, '', {4})"
    ext = fs.getExtension(filePath)
    size = fs.getFileSize(filePath)
    fileName = fs.getFileName(filePath)
    filePath = filePath.replace("\\", "/")
    filePath = filePath.replace("'", "''")
    hexa = bin2hex(filePath)
    sql = Text.format(INSERT, fileName, filePath, ext, hexa, size)
    client = MySQL.MySQL()
    client.execute(sql)
    return
Example #10
0
def insertBinaries(filePath, origin):
    ext = fs.getExtension(filePath)
    size = fs.getFileSize(filePath)
    parts = origin.split("/")
    n = len(parts)
    name = parts[n - 3] + " " + parts[n - 2]
    filePath = filePath.replace("\\", "/")
    filePath = filePath.replace("'", "''")
    hexa = bin2hex(filePath)
    sql = Text.format(INSERT, name, origin, ext, hexa, size)
    mysql_client.execute(sql)
    lastId = mysql_client.getValue("SELECT max(id) FROM BINDATA")
    return lastId
Example #11
0
def doChangeCreator():
    sql = Text.format(
        "SELECT id, creator, path FROM Pictures WHERE id BETWEEN {0} AND {1}",
        id_start, id_end)
    Common.esc_print("cyan", sql)
    UPDATE = "UPDATE Pictures SET creator='{0}' WHERE id={1}"
    client = mysql.MySQL()
    rows = client.query(sql)
    for row in rows:
        id = row[0]
        creator = row[1]
        path = row[2]
        if creator == "作者":
            ppath = Text.split('/', path)
            lenpath = len(ppath)
            new_creator = ppath[lenpath - 2]
            sql = Text.format(UPDATE, new_creator, id)
            print(sql)
            client.execute(sql)
            print(sql)
        else:
            pass
    return
Example #12
0
def renameAll(args):
    dir = args[0]
    wild = args[1]
    fix = args[2]
    cols = args[3]
    i = 1
    files = fs.listFiles(dir, wild)
    sortedFiles = sorted(files)
    for fold in sortedFiles:
        ext = fs.getExtension(fold)
        fmt = "{0:0" + cols + "d}"
        fnew = dir + "/" + fix + Text.format(fmt, i) + ext
        cmd = f"mv -v {fold} {fnew}"
        print(cmd)
        i += 1
Example #13
0
def getMenuItems():
    menuitems = ""
    menuflag = False
    menufirst = True
    rows = fs.readCsv(MENU, False)
    for row in rows:
        if Text.isdigit(row[0]):
            # サブタイトル
            if row[0] != "1":
                menuitems += "\n</ul>"
            menuitems += "\n<h2>" + row[0] + ". " + row[1] + "</h2>\n<ul>\n"
        else:
            # メニュー項目
            url = row[0]
            text = row[1]
            link = f'<a href="{url}">' + text + "</a>"
            menuitems += "<li>" + link + "</li>\n"
    menuitems += "</ul>\n"
    return menuitems
Example #14
0
            sql = Text.format(UPDATE, new_creator, id)
            print(sql)
            client.execute(sql)
            print(sql)
        else:
            pass
    return


#
#  メイン
# ID の範囲を決める。
id_start = 1
id_end = 1000000
id_range = Common.readline("id の範囲 (nnnn-nnnn) を入力してください。(省略時はすべて)")
if id_range == "":
    Common.esc_print("yellow", "すべての id に対して実行します。(y/n)")
    a = Common.readline(">")
    if y != "y":
        Common.stop(9, "実行を中止しました。")
else:
    nn = Text.split('-', id_range)
    if len(nn) == 2:
        id_start = int(nn[0])
        id_end = int(nn[1])
    else:
        Common.stop(9, "範囲が正しくありません。実行を中止しました。")
    # Pictures テーブルからクエリーを行って対象のデータを得る。
    doChangeCreator()
    print("完了")
Example #15
0
#!/usr/bin/env python3

# サブディレクトリ内にあるファイルを自ディレクトリに名前を変えてコピーする。
from Py365Lib import Common, FileSystem as fs, Text

# START
# パラメータ確認
if Common.count_args() < 1:
    Common.stop("Usage : copy_subdir_files.py directory")
mydir = Common.args(0)

# サブディレクトリ一覧を得る。
dirs = fs.listDirectories(mydir, True)

# サブディレクトリごとに繰り返す。
for d in dirs:
    print(d)
    files = fs.listFiles(d, "*", True)
    parts = Text.split("/", d)
    h = parts[len(parts) - 1]
    for f in files:
        f1 = Text.replace("/", "\\", mydir + "/" + h + "/" + fs.getFileName(f))
        f2 = Text.replace("/", "\\", mydir + "/" + h + fs.getFileName(f))
        print(f"copy \"{f1}\" \"{f2}\"")

# 終わり
print("Done.")
Example #16
0
#!/usr/bin/python3
from Py365Lib import Common, Text

# 元号を西暦に変換する。
if Common.count_args() == 0:
    Common.stop(
        9,
        "Enter Japanese Gengo year. like s20, h10 where characters must be 3.",
        Common.ESC_FG_YELLOW)

g = Common.args()[0]

if Text.tolower(g[0]) == 's':
    y0 = 1926
elif Text.tolower(g[0]) == 'h':
    y0 = 1989
else:
    y0 = 1912

gengo = Text.Text(g)

if gengo.length == 3:
    y = int(gengo.right(2))
    x = y + y0 - 1
    print(x)
else:
    Common.stop(1, "Error: Inpur length must be 3.")
Example #17
0
#!/usr/bin/env python3

#  YJFX_Asset テーブルにデータを挿入する。
from Py365Lib import Common, MySQL, Text


mysql = MySQL.MySQL()

sql = "SELECT * FROM VW_YJFX_Asset"
result = mysql.query(sql)

print("ID       Date            Asset         ProfitLoss")
for row in result :
  print("{0}\t{1}\t{2}\t{3}".format(row[0], row[1], Text.money(row[2]), Text.money(row[3])))

print("Done.")
Example #18
0
# サブディレクトリが ^\[.+\] .+ なら \[.+\] を取る。

from Py365Lib import Common, FileSystem as fs, Text

# START
# パラメータ確認
if Common.count_args() < 1:
    Common.stop("Usage : change_dirnames.py directory")

# ディレクトリ一覧を得る。
parent = Common.args(0)
dirs = fs.listDirectories(parent, True)

# ディレクトリ名 [.+] を見つける。
for d in dirs:
    if Text.re_contain(r".+\[.+\]$", d):
        d2 = Text.replace("[", "", d)
        d2 = Text.replace("]", "", d2)
        fs.move(d, d2)
        print(d2)
print("**************")
# サブディレクトリに ^\[.+\] .+ を見つける。
dirs = fs.listDirectories(parent, True)
for d in dirs:
    dirs2 = fs.listDirectories(d, True)
    for d2 in dirs2:
        d3 = Text.re_replace(r"\[.+\]\s+", "", d2)
        fs.move(d2, d3)
        print(d3)

# 終わり
Example #19
0
def rename_files(folder):
    # 画像ファイル一覧を得る。
    print(folder)
    files = fs.listFiles(folder, asstr=True)
    # 画像ファイルをリネーム
    for fpath in files:
        #fpath = Common.from_bytes(f)
        ext = fs.getExtension(fpath).lower()
        # 画像ファイルのみを対象にする。
        if ext == ".jpg" or ext == ".png" or ext == ".gif":
            # ファイル名が nnnnnnn_pnn[.jpg] か
            fname = fs.getFileName(fpath)
            ff = Text.split("_", fname)
            if not (ext in ff[1]):
                ff[1] += ext
            if len(ff) == 3:
                # 3分割できて 'master' が含まれる場合は 'master..' 部分を削除する。
                #fname_old = fname
                fname = ff[0] + '_' + ff[1]
                #print(fname_old + " to " + fname)
            elif len(ff) != 2:
                # _ で2分割できない場合(ファイル名の形式が異なる場合)はスキップする。
                print("Skipped " + fname)
                continue
            else:
                # その他の場合は何もしない。(2分割できた場合)
                pass
            # 連続番号部分の形式を確認する。
            sf = ff[1]
            if ff[1].startswith('p'):
                if len(ff[1]) == 6 or (len(ff) == 3 and len(ff[1]) == 2):
                    # 連続番号が1桁の場合
                    sf = "p0" + Text.substring(ff[1], 1)
                    newname = folder + "/" + ff[0] + "_" + sf
                    fs.move(fpath, newname)
                    print("Renamed: " + newname)
                elif len(ff) == 3 and len(ff[1]) == 7:
                    # _master1200 があり連続番号が2桁の場合
                    newname = folder + "/" + fname
                    fs.move(fpath, newname)
                elif len(ff[1]) == 8 or (len(ff) == 3 and len(ff[1]) == 4):
                    # 連続番号が3桁または連続番号が3桁かつ _master1200 がある場合
                    sn = Text.substring(ff[1], 1)
                    if sn == '1':
                        # 連続番号が3桁かつ100番台の場合
                        sf = "q" + Text.substring(ff[1], 2)
                        newname = folder + "/" + ff[0] + "_" + sf
                        fs.move(fpath, newname)
                        print("Renamed: " + newname)
                    elif sn == '2':
                        # 連続番号が3桁かつ200番台の場合
                        sf = "r" + Text.substring(ff[1], 2)
                        newname = folder + "/" + ff[0] + "_" + sf
                        fs.move(fpath, newname)
                        print("Renamed: " + newname)
                    else:
                        # 連続番号が3桁かつ300番台以上の場合はサポートしない(スキップする)
                        pass
                else:
                    # 連続番号が2桁の場合
                    #print("Passed: " + fpath)
                    pass
        else:
            #fs.move(fpath, fpath + ".jpg")
            print("Non image passed: " + fpath)
    return
Example #20
0
    return


# 条件入力
fileName = ""
interpreterNo = 1
if Common.count_args() < 2:
    fileName = Common.readline("対象のファイル・フォルダを指定してください。> ")
    print(INTERPRETERS)
    interpreterNo = int(Common.readline("番号を選択してください。> "))
else:
    fileName = Common.args(0)
    interpreterNo = int(Common.args(1))

interpreterLines = INTERPRETERS.split('\n')
interpreter = Text.substring(interpreterLines[interpreterNo - 1], 3)
print(interpreter + " が " + fileName + " に適用されます。")
a = Common.readline("実行しますか? (y/n)")
if a != 'y':
    Common.stop(9, "実行が取り消されました。")

# インタプリタ適用
if fs.isFile(fileName):
    apply(fileName, interpreter)
else:
    files = fs.listFiles2(fileName)
    for f in files:
        print(f)
        ext = fs.getExtension(f)
        if ext == ".cgi":
            apply(f, interpreter)
Example #21
0
def updateBinaries(filePath, id):
    filePath = filePath.replace("\\", "/")
    hexa = bin2hex(filePath)
    sql = Text.format(UPDATE, hexa, id)
    mysql_client.execute(sql)
    return
Example #22
0
def rename(fp) :
    result = Text.replace('[', '', fp)
    result = Text.replace(']', '', result)
    result = Text.replace('#', '_', result)
    result = Text.replace("'", "", result)
    return result
Example #23
0
#!/usr/bin/env python3

# ディレクトリの名前が [.+] で始まっていたら、その文字列を削除した名前にする。

from Py365Lib import Common, FileSystem as fs, Text


# START
# パラメータ確認
if Common.count_args() < 1 :
  Common.stop("Usage : remove_paren.py directory")

parent = Common.args(0)
print("cd " + parent)
dirs = fs.listDirectories(parent, True)

for d in dirs :
  parts = Text.split("/", d)
  oldname = parts[len(parts)-1]
  if Text.re_contain(r"^\[.+\].+", oldname) :
    d2 = Text.re_replace(r"\[.+\]\s", "", d)
    d2 = Text.trim(d2)
    parts = Text.split("/", d2)
    newname = parts[len(parts)-1]
    print("ren \"{0}\" \"{1}\"".format(oldname, newname))

print("echo Done.")

Example #24
0
def run_command():
    c = request.args.get("command")
    cmds = Text.re_split("\s+", c)
    return Common.shell(cmds)