小型数据生成器 Ithea

· · 科技·工程

Update Logs 见最后。

剪贴板复制入口 (直接复制即可)

使用例子:线段树 2 可以采用下面代码生成数据:

[n=integer(2,100);q=integer(1,100);m=571373]
{[op=integer(1,3)] (op==1 or op==2)?{[x=integer(1,n-1);y=integer(x+1,n);k=integer(1,10000)]}(op==3)?{[x=integer(1,n-1);y=integer(x+1,n)]}
}*$q

存入 test.txt,

命令行 ithea test.txt [出错程序].cpp [正解].cpp 即可对拍。

命令行 ithea test.txt 可以输出生成数据。

命令行 ithea xxx.cpp 可以运行程序(输入来自 input.txt,输出到 output.txt)

命令行 ithea [出错程序].cpp [正解].cpp 可由给定 input.txt 比较两者输出。

控制台选项:

Special Judge 程序应当使用 testlib(接收 输入文件 输出文件 答案文件 参数,AC 时返回 0,UNAC 时返回非 0 值)。

使用时注意:变量名不能相同(否则是未定义行为),此时 [] 语句可能不输出。

#!/usr/bin/python3
# Ithea Data Generator and Cross-Checker for C++ (using GCC)
# by steambird 2024

import sys
import os
import random
import colorama

colorama.init()

PROGRAM_SUFFIX = ["c","cpp"]
TRY_SUFFIX = ["", ".cpp", ".txt", ".c"]
DEFAULT_COMPILE = "g++ {source} -o {target} --std=c++14 -O2 "
USAGE = "Usage: Ithea generator | program [wa program | comparer] [ac program] compile options ...\nProgram should have " + ",".join(PROGRAM_SUFFIX) + " suffix."
ADDHELP = """

Additional operations for Ithea:

-h                     -- Show this help message.
-c:xxx                 -- Specify compile option (shall have -- or - suffix provided).
-s:xx                  -- Use a program for special judge (its return code will be read).
-i:xx, -w:xx, -a:xx, -wl:xx, -al:xx, -t:xx, --tl:xx
                       -- Specify options for the executor.

-d                     -- Start debug mode of this application.
-r                     -- Reserve executable files after execution.
-n                     -- Do not compile. (Will raise exception if doesn't exist)
-v:LEVEL               -- For wrong answer conditions, output detailed error.
    LEVEL = 0          -- Default output ("Failed" only).
    LEVEL = 1          -- Have one comparison.
    LEVEL = 2          -- Have complete comparison.

Special Judge codes (refer to testlib.h):

AC          0
Others will be considered WA:
WA          1
PE          2 (Format error)
FAIL        3

Grammar:

<> -- variable definitions
[] -- variable output
() -- expression output
{} -- segment
$ -- single variable output
*$xxx (or *...) -- repeater

"""
DEBUG = False
RESERVE = False
NOCOMP = False

ITARGET = "input.txt"
WTARGET = "wa.txt"
WLOG = "wa.log"
ATARGET = "ac.txt"
ALOG = "ac.log"

TTARGET = "output.txt"
TLOG = "error.log"

RUNCALL = "type "+ITARGET+" | {program} 1>{output} 2>{log}"
SPJ = ""
SPJEXEC = ""
SPJCALL = "{spj} {input} {wa} {ac} 1>nul 2>nul"
RUN_SUFFIX = ""
GEN = ""
if sys.platform != "win32":
    RUNCALL = "cat "+ITARGET+" | ./{program} 1>{output} 2>{log}"
    SPJCALL = "{spj} {input} {wa} {ac} 1>/dev/null 2>/dev/null"
else:
    RUN_SUFFIX = ".exe"

CMPLEVEL = 0

def refresh_info():
    global RUNCALL, SPJ, SPJEXEC, SPJCALL, RUN_SUFFIX
    RUNCALL = "type "+ITARGET+" | {program} 1>{output} 2>{log}"
    if sys.platform != "win32":
        RUNCALL = "cat "+ITARGET+" | ./{program} 1>{output} 2>{log}"

# Return proceed arguments.
def preprocess_arg():
    global CMPLEVEL, DEBUG, RESERVE, NOCOMP, USAGE, ADDHELP, ITARGET, WTARGET, ATARGET, WLOG, ALOG, TTARGET, TLOG, DEFAULT_COMPILE, SPJ
    res = []
    for it in range(1, len(sys.argv)):
        i = sys.argv[it]
        if i[:1] == "-":
            sps = i.split(":",1)
            if i == "-h":
                print(USAGE)
                print(ADDHELP)
                exit(0)
            elif i == "-d":
                DEBUG = True
            elif i == "-r":
                RESERVE = True
            elif i == "-n":
                NOCOMP = True
            elif i[:2] == "-i":
                ITARGET = sps[1]
                pass
            elif i[:2] == "-w":
                WTARGET = sps[1]
                pass
            elif i[:2] == "-a":
                ATARGET = sps[1]
                pass
            elif i[:3] == "-wl":
                WLOG = sps[1]
                pass
            elif i[:3] == "-al":
                ALOG = sps[1]
                pass
            elif i[:2] == "-t":
                TTARGET = sps[1]
                pass
            elif i[:3] == "-tl":
                TLOG = sps[1]
                pass
            elif i[:2] == "-c":
                DEFAULT_COMPILE += sps[1]
                pass
            elif i[:2] == "-s":
                SPJ = sps[1]
                pass
            elif i[:2] == "-v":
                CMPLEVEL = int(sps[1])
        else:
            res.append(i)
    return res

def try_file(incomplete):
    for i in TRY_SUFFIX:
        if os.path.exists(incomplete+i):
            return incomplete+i
    raise FileNotFoundError(filename=incomplete)

def get_target(source):
    rf = source.rfind(".")
    return (source + RUN_SUFFIX) if rf < 0 else (source[:rf] + RUN_SUFFIX)

def get_extension(source):
    rf = source.rfind(".")
    return "" if rf < 0 else source[rf+1:]

def comparison(text1, text2):
    global SPJ, SPJEXEC, ITARGET, WTARGET, ATARGET, CMPLEVEL
    flag = True
    if SPJ != "":
        res = os.system(SPJCALL.format(spj=SPJEXEC, input=ITARGET, wa=WTARGET, ac=ATARGET))
        if res != 0:
            print("\033[33mSpecial Judge returned {}\033[0m".format(res))
        return res == 0
    else:
        sp1 = text1.split('\n')
        sp2 = text2.split('\n')
        pt1 = 0
        pt2 = 0
        while pt1 < len(sp1) and pt2 < len(sp2):
            sl1 = ""
            sl2 = ""
            while pt1 < len(sp1) and sl1.strip() == "":
                sl1 = sp1[pt1]
                pt1 += 1
            while pt2 < len(sp2) and sl2.strip() == "":
                sl2 = sp2[pt2]
                pt2 += 1
            if not (pt1 <= len(sp1) and pt2 <= len(sp2)):
                break
            if sl1.strip() != sl2.strip():
                flag = False
                if CMPLEVEL > 0:
                    print("\033[33mOn Line {}, Read:\n{}\nExpected:\n{}\033[0m".format(pt1, sl1, sl2))
                if CMPLEVEL != 2:
                    return False
        if not flag:
            return False
        while pt1 < len(sp1) and sp1[pt1].strip() == "":
            pt1 += 1
        while pt2 < len(sp2) and sp2[pt2].strip() == "":
            pt2 += 1
        if pt1 == len(sp1) and pt2 == len(sp2):
            return True
        else:
            if CMPLEVEL > 0:
                print("\033[33mToo many/few output\033[0m")
            return False

if len(sys.argv) < 2 and (not DEBUG):
    print(USAGE)
    exit(1)

CLOSURE = {'<':'>','(':')','{':'}','[':']'}
VAREND = ['\n',' ','\t',':','$','%','!','@','#','^','&','*','(',')','-','+','=','{','}',"|","[","]",":",";","\"","\'",'<','>','?','/',',','.']
WHITESPACE = ' '
LINE = '\n'

def integer(lo, hi):
    return random.randint(lo, hi)

def float(lo, hi):
    return random.uniform(lo, hi)

def string(charset, length=1):
    val = ""
    for i in range(length):
        val += random.choice(charset)
    return val

GRAPH_OUTPUT = 0
FATHER_OUTPUT = 1

uniques = {}
varlib = {}

def lt(a, b):
    return a < b

def le(a, b):
    return a <= b

def gt(a, b):
    return a > b

def ge(a, b):
    return a >= b

def index(a, b):
    return a[b]

def unique(val, name="", dry=False, other_cond=True):
    if name not in uniques:
        uniques[name] = set()
    if not other_cond:
        return False
    if val in uniques[name]:
        return False
    else:
        if not dry:
            uniques[name].add(val)
        return True

def store(name, value):
    varlib[name] = value
    return value

def read(name):
    return varlib[name]

class disjoint_set():
    def __init__(self):
        self.refs = {}
    def query(self, x):
        if (x not in self.refs) or (self.refs[x] == x):
            return x
        else:
            self.refs[x] = self.query(self.refs[x])
            return self.refs[x]
    def merge(self, x, y):
        self.refs[self.query(y)] = self.query(x)

import random

WHITESPACE = ' '
LINE = '\n'

GRAPH_OUTPUT = 0
FATHER_OUTPUT = 1

class disjoint_set():
    def __init__(self):
        self.refs = {}
    def query(self, x):
        if (x not in self.refs) or (self.refs[x] == x):
            return x
        else:
            self.refs[x] = self.query(self.refs[x])
            return self.refs[x]
    def merge(self, x, y):
        self.refs[self.query(y)] = self.query(x)

class tree():
    def __init__(self, n, extra=lambda:"", idstart=1, output=GRAPH_OUTPUT, guarantee_root=-1):
        self.idstart = idstart
        self.n = n
        self.extra = extra
        self.fa = {idstart:idstart}
        for i in range(idstart+1,idstart+n):
            self.fa[i] = random.randint(idstart, i-1)
        # Remapping
        # mapper[x]: the original position of new [x]
        self.mapper = [i for i in range(idstart,idstart+n)]
        random.shuffle(self.mapper)
        if guarantee_root >= idstart:
            #print("Guarantee ",guarantee_root,self.mapper)
            self.mapper[self.mapper.index(idstart)] = self.mapper[guarantee_root-idstart]
            self.mapper[guarantee_root-idstart] = idstart
        self.afa = dict()
        for i in range(idstart,idstart+n):
            #print(i," originally was ",self.mapper[i-idstart])
            #print("its father is ",self.fa[self.mapper[i-idstart]])
            #print("its remapped father is ",self.mapper.index(self.fa[self.mapper[i-idstart]])+idstart)
            self.afa[i] = self.mapper.index(self.fa[self.mapper[i-idstart]])+idstart
        self.omode = output
    def refer_edges(self):
        edges = []
        for i in range(self.idstart,self.idstart+self.n):
            if self.afa[i] == i:
                continue
            edges.append((self.afa[i], i))
        random.shuffle(edges)
        return edges
    def __str__(self):
        if self.omode == GRAPH_OUTPUT:
            edges = self.refer_edges()
            res = ""
            for i in edges:
                res += str(i[0]) + WHITESPACE + str(i[1]) + self.extra() + LINE
            return res[:-1]
        elif self.omode == FATHER_OUTPUT:
            res = ""
            for i in range(self.idstart,self.idstart+self.n):
                res += str(self.afa[i]) + WHITESPACE
            return res[:-1]
        else:
            raise Exception("Bad output mode")

class graph():
    # It is very possible to fail (!!) when connected=True and m is given.
    def __init__(self, n, m=None, idstart=1, extra=lambda:"", connected=True, noloop=False, bidirectional=False):
        self.idstart = idstart
        self.n = n
        self.m = m
        self.extra = extra
        mmax = n*(n-1)/(1 if bidirectional else 2)
        if m is None:
            if connected:
                m = random.randint(n-1, mmax)
            else:
                m = random.randint(1, mmax)
        if m > mmax:
            raise Exception("Cannot generate too much edges")
        eg = []
        cnt = 0
        dis = disjoint_set()
        if connected:
            st = tree(n, extra, idstart)
            eg = st.refer_edges()
            for i in eg:
                dis.merge(eg[0],eg[1])
            cnt = n-1
        #print("Basic edges: ",eg)
        while cnt < m:
            x = 0
            y = 0
            while True:
                x = random.randint(idstart, idstart+n-1)
                y = random.randint(idstart, idstart+n-1)
                #print("Try ",x,y)
                if x == y:
                    #print("Fail #1")
                    continue
                if (x,y) in eg:
                    #print("Fail #2")
                    continue
                if (not bidirectional) and ((y,x) in eg):
                    #print("Fail #3")
                    continue
                if noloop and (dis.query(x) == dis.query(y)):
                    #print("Fail #4")
                    continue
                break
            eg.append((x,y))
            cnt += 1
        random.shuffle(eg)
        self.edges = eg
        self.m = len(eg)
    def __str__(self):
        res = ""
        for i in self.edges:
            res += str(i[0]) + WHITESPACE + str(i[1]) + self.extra() + LINE
        return res



def panic(errinfo, code, lineid):
    print("\033[31mIn Line {}\n{}\nError: {}\033[0m".format("" if lineid == 0 else str(lineid), code, errinfo))
    sys.exit(1)

def saferun(code, env, lineid = 0, linecode = "", globals = None):
    try:
        exec(code, globals, env)
    except Exception as e:
        panic(str(e) + " (at saferun)", linecode, lineid)

def safeval(code, env, lineid = 0, linecode = ""):
    try:
        return eval(code, None, env)
    except Exception as e:
        panic(str(e), linecode, lineid)


def generate(code, varenv = dict()):
    output = ""
    tmp = ""                # Shouldn't include the initial brace
    opener = ''
    state = 0
    reint = False
    var = dict()
    for i in varenv:
        var[i] = varenv[i]
    lines = code.split("\n")
    lineid = 1
    nextpos = 0
    have_block = False
    tmpgen = ""
    while nextpos < len(code):
        i = code[nextpos]
        nextpos += 1            # Now stands for the NEXT position
        if i == '\r':
            continue
        if i == '\n':
            lineid += 1
        if reint:
            if state > 0:
                tmp += i
            else:
                output += i
            continue
        if i == '\\':
            reint = True
        if state == 0:
            if i == '{':
                if nextpos == 1 or code[nextpos-2] != '?':
                    have_block = True
            if i in '<[(':
                opener = i
                state = 1
                continue
            if i == '{':
                sts = 1
                #tmpgen = ""
                along = ""
                while nextpos < len(code):
                    j = code[nextpos]
                    nextpos += 1
                    if j == '{':
                        sts += 1
                    elif j == '}':
                        sts -= 1
                    if sts == 0:
                        break
                    along += j
                    if sts < 0:
                        panic("Unexpected unclosed braces", lines[lineid-1], lineid)
                #tmpgen = generate(along, verenv)
                if have_block:
                    nps = ""
                    repeater = 1
                    if nextpos < len(code) and code[nextpos] == '*':
                        nextpos += 1
                        # Read digits or '$' as variable
                        if nextpos < len(code):
                            if code[nextpos] == '$':
                                nps = ""
                                nextpos += 1
                                while nextpos < len(code) and code[nextpos] not in VAREND:
                                    nps += code[nextpos]
                                    nextpos += 1
                                #print("Read variable ", nps)
                                if nps == "" or nps not in var:
                                    panic("Unknown variable {}".format(nps), lines[lineid-1], lineid)
                                else:
                                    try:
                                        repeater = int(var[nps])
                                    except Exception as e:
                                        panic("Not a repeater value: {}".format(nps), lines[lineid-1], lineid)
                            else:
                                val = 0
                                # Already the number position
                                while nextpos < len(code) and '0' <= code[nextpos] <= '9':
                                    #print("Read character ",code[nextpos])
                                    val = (val * 10) + int(code[nextpos])
                                    nextpos += 1
                                repeater = val
                        else:
                            panic("Missing parameter for repeating counter", lines[lineid-1], lineid)
                    #output += generate(tmp)*repeater
                    #print("Read time: ",repeater," for ",tmp)
                    for i in range(repeater):
                        xvar = dict(var)
                        xvar["_" + nps] = i
                        ts = generate(along, xvar)
                        #print("Generated ",ts)
                        output += ts
                have_block = True
                continue
        else:
            if i == opener:
                state += 1
            if i == CLOSURE[opener]:
                state -= 1
                if state == 0:
                    if i == '>' or i == ']':
                        #print("Proceed RQ")
                        # Grammar: [var1=gen1(para...);var2=gen2(para...) || condition]
                        cond = tmp.split("||", 1)
                        seq = cond[0].split(";")
                        tvar = []
                        for j in seq:
                            sf = j.find('=')
                            if sf < 0:
                                continue
                            tvar.append(j[:sf])
                        while True:
                            saferun(cond[0], var, lineid, lines[lineid-1])
                            if len(cond) < 2:
                                break
                            else:
                                judge = safeval(cond[1], var, lineid, lines[lineid-1])
                                if judge:
                                    break
                        if i == ']':
                            for j in tvar:
                                output += str(var[j]) + WHITESPACE
                            #print("Generate for variable: ",output)
                            output = output[:-len(WHITESPACE)]
                    elif i == ')':
                        if nextpos < len(code) and code[nextpos] == '?':
                            have_block = bool(safeval(tmp, var, lineid, lines[lineid-1]))
                            nextpos += 1
                        else:
                            output += str(safeval(tmp, var, lineid, lines[lineid-1]))
                    tmp = ""
                    continue
        if i == '$':
            nps = ""
            # Directly go for NEXT position
            while nextpos < len(code) and code[nextpos] not in VAREND:
                nps += code[nextpos]
                nextpos += 1
            if nps == "" or nps not in var:
                panic("Unknown variable {}".format(nps), lines[lineid - 1], lineid)
            else:
                if state > 0:
                    tmp += str(var[nps])
                else:
                    output += str(var[nps])
        else:
            if state > 0:
                tmp += i
            else:
                output += i
    return output

sag = preprocess_arg()
refresh_info()
sag.insert(0, "ithea.py")

if DEBUG:
    print("Processing arguments:",sag)

def autocleanup(x):
    if not RESERVE:
        for i in x:
            if i.strip() == "":
                continue
            try:
                os.remove(i)
            except Exception as e:
                print("Ithea: Fatal Error while cleanup: ", e,"")
                break

if SPJ != "":
    SPJ = try_file(SPJ)

if len(sag) == 2:
    try:
        sf = try_file(sag[1])
        if get_extension(sf) in PROGRAM_SUFFIX:
            tgt = get_target(sf)
            if not NOCOMP:
                try:
                    os.system(DEFAULT_COMPILE.format(source = sf, target = tgt))
                except Exception as e:
                    print("\033[31mIthea: Fatal Error While Compiling: ", e, "\033[0m")
                    autocleanup([tgt])
                    sys.exit(4)
            try:
                os.system(RUNCALL.format(program=tgt, output=TTARGET, log=TLOG))
                os.remove(tgt)
            except Exception as e:
                print("\033[31mIthea: Fatal Error: ",e, "\033[0m")
                autocleanup([tgt])
                sys.exit(4)
        else:
            f = open(sf, "r")
            print(generate("".join(f.readlines())))
            f.close()
    except Exception as e:
        print("\033[31mIthea: Fatal Error: ",e,"\033[0m")
        sys.exit(3)
elif len(sag) == 3:
    af = ""
    bf = ""
    try:
        af = try_file(sag[1])
        bf = try_file(sag[2])
    except FileNotFoundError as e:
        print("\033[31mIthea: File Not Found: ",e.filename,"\033[0m")
        sys.exit(6)
    except Exception as e:
        print("\033[31mIthea: Fatal Error: ",e,"\033[0m")
        sys.exit(3)
    if get_extension(af) in PROGRAM_SUFFIX:
        was = get_target(af)
        acs = get_target(bf)
        if not NOCOMP:
            try:
                os.system(DEFAULT_COMPILE.format(source = af, target = was))
                os.system(DEFAULT_COMPILE.format(source = bf, target = acs))
                if SPJ != "":
                    SPJEXEC = get_target(SPJ)
                    os.system(DEFAULT_COMPILE.format(source = SPJ, target = SPJEXEC))
            except Exception as e:
                print("\033[31mIthea: Fatal Error While Compiling: ", e, "\033[0m")
                autocleanup([was, acs])
                sys.exit(4)
        try:
            os.system(RUNCALL.format(program=was, output=WTARGET, log=WLOG))
            os.system(RUNCALL.format(program=acs, output=ATARGET, log=ALOG))
            f1 = open(WTARGET, "r")
            wout = "".join(f1.readlines())
            f1.close()
            f2 = open(ATARGET, "r")
            aout = "".join(f2.readlines())
            f2.close()
            if not comparison(wout, aout):
                print("\n\033[33mCross-check failed!\033[0m")
            else:
                print("\n\033[32mAccepted!\033[0m")
            autocleanup([was, acs])
        except Exception as e:
            print("Ithea: Fatal Error: ", e,"")
            autocleanup([was, acs])
            sys.exit(4)
    else:
        print("\033[31mMissing Parameter for Ithea\033[0m\n"+USAGE)
        sys.exit(2)
else:
    af = ""
    bf = ""
    cf = ""
    special = False
    if sag[1][0] == "@":
        af = get_target(sag[1][1:])
        special = True
    try:
        if not special:
            af = try_file(sag[1])
        bf = try_file(sag[2])
        cf = try_file(sag[3])
    except FileNotFoundError as e:
        print("\033[31mIthea: File Not Found: ",e.filename,"\033[0m")
        sys.exit(6)
    except Exception as e:
        print("\033[31mIthea: Fatal Error: ",e,"\033[0m")
        sys.exit(3)
    gcode = ""
    if DEBUG and special:
        print("Special evaluation for",af)
    if not special:
        try:
            f = open(af, "r")
            gcode = "".join(f.readlines())
            f.close()
        except Exception as e:
            print("\033[31mIthea: Fatal Error: ",e,"\033[0m")
            sys.exit(3)
    was = get_target(bf)
    acs = get_target(cf)
    if not NOCOMP:
        try:
            os.system(DEFAULT_COMPILE.format(source = bf, target = was))
            os.system(DEFAULT_COMPILE.format(source = cf, target = acs))
            if SPJ != "":
                SPJEXEC = get_target(SPJ)
                os.system(DEFAULT_COMPILE.format(source = SPJ, target = SPJEXEC))
        except Exception as e:
            print("\033[31mIthea: Fatal Error While Compiling: ", e, "\033[0m")
            autocleanup([was, acs])
            sys.exit(4)
    groupid = 1
    while True:
        # Library cleanup!
        uniques = {}
        varlib = {}
        print("\r\033[36mCross-check attempt #",groupid,"\033[0m",end='')
        groupid += 1
        if special:
            os.system("{} > {}".format(af, ITARGET))
        else:
            f = open(ITARGET, "w")
            f.write(generate(gcode))
            f.close()
        try:
            os.system(RUNCALL.format(program=was, output=WTARGET, log=WLOG))
            os.system(RUNCALL.format(program=acs, output=ATARGET, log=ALOG))
            f1 = open(WTARGET, "r")
            wout = "".join(f1.readlines())
            f1.close()
            f2 = open(ATARGET, "r")
            aout = "".join(f2.readlines())
            f2.close()
            if not comparison(wout, aout):
                print("\n\033[33mCross-check failed!\033[0m")
                autocleanup([was, acs])
                sys.exit(0)
        except Exception as e:
            print("\033[31mIthea: Fatal Error: ", e, "\033[0m")
            autocleanup([was, acs])
            sys.exit(4)

Changelog

2024/10/31 修复对拍时含 unique 的生成脚本导致卡死的问题。

2024/10/13 {} 相关表达式的漏洞修复。

2024/10/6 漏洞修复。

2024/9/7 加入对图的生成的初步支持,支持 Special Judge 对拍。