Datasets:
Download quality_tools/check_generated_code.py from SEE7/AstheralDataset: direct link, hf CLI and curl.
- Browser
- Download file 6.69 kB
-
https://huggingface.co/datasets/SEE7/AstheralDataset/resolve/main/quality_tools/check_generated_code.py
- Command line
-
hf download hf://datasets/SEE7/AstheralDataset/quality_tools/check_generated_code.py
-
curl -L -o check_generated_code.py https://huggingface.co/datasets/SEE7/AstheralDataset/resolve/main/quality_tools/check_generated_code.py
6.69 kB
| import json,re,ast,sys,subprocess,concurrent.futures | |
| from pathlib import Path | |
| D=Path("dataset-repair");data=json.loads((D/"retained.json").read_text()) | |
| fixtures=[ | |
| ("remove consecutive duplicate readings",[([1,1,2,2,1],),([],)],[[1,2,1],[]]), | |
| ("find items shared by two lists",[(["b","a","c"],["a","b"]),(["x"],["y"])],[["b","a"],[]]), | |
| ("rotate a list by an integer offset",[([1,2,3,4],2),([],3)],[[3,4,1,2],[]]), | |
| ("rank distinct labels by descending frequency",[(["b","a","b","a","c"],)],[{"one_of":[["a","b","c"],[["a",2],["b",2],["c",1]]]}]), | |
| ("count distinct nonempty names",[([" Ana ","Ana"," Bo ",""," "],)], [2]), | |
| ("split a sequence into fixed-size chunks",[([1,2,3,4,5],2),([],2)],[[[1,2],[3,4],[5]],[]]), | |
| ("return the first missing positive integer",[([3,4,-1,1],),([],),([1,2,0],)],[2,1,3]), | |
| ("compute cumulative totals",[([1,-2,3],),([],)],[[1,-1,2],[]]), | |
| ("return indices where a sequence changes value",[([2,2,4,4,1],),([],)],[[2,4],[]]), | |
| ("validate a minutes:seconds duration",[("03:05",),("0:00",),("4:60",)],[185,0,{"raises":"ValueError"}]), | |
| ("calculate moving averages",[([1,2,3,4],2)],[ [1.5,2.5,3.5] ]), | |
| ("keep the first occurrence of every hashable item",[([1,1,2,1,3],)],[[1,2,3]]), | |
| ("flatten a list of lists",[([[],[1,2],[3]],)],[[1,2,3]]), | |
| ("parse nonempty comma-separated labels",[(" a, , b ",)],[["a","b"]]), | |
| ("merge overlapping closed integer intervals",[([(1,3),(2,4),(6,7)],),([],)],[[[1,4],[6,7]],[]]) | |
| ] | |
| harness=r''' | |
| import sys,json,ast,copy,math,statistics,collections,itertools,re,resource | |
| resource.setrlimit(resource.RLIMIT_CPU,(1,1)) | |
| resource.setrlimit(resource.RLIMIT_AS,(192*1024*1024,192*1024*1024)) | |
| payload=json.loads(sys.stdin.read());tree=ast.parse(payload["code"]) | |
| class StripTypes(ast.NodeTransformer): | |
| def visit_ImportFrom(self,node):return None if node.module in {"typing","__future__"} else node | |
| def visit_Import(self,node): | |
| node.names=[x for x in node.names if x.name!="typing"] | |
| return node if node.names else None | |
| def visit_arg(self,node):node.annotation=None;return node | |
| def visit_FunctionDef(self,node): | |
| node.returns=None;self.generic_visit(node);return node | |
| def visit_AnnAssign(self,node):return ast.Assign(targets=[node.target],value=node.value) if node.value is not None else ast.Pass() | |
| tree=ast.fix_missing_locations(StripTypes().visit(tree)) | |
| allowed_imports={"math":math,"statistics":statistics,"collections":collections,"itertools":itertools,"re":re} | |
| for node in ast.walk(tree): | |
| if isinstance(node,ast.Attribute) and node.attr.startswith("_"):raise RuntimeError("restricted attribute") | |
| if isinstance(node,ast.Name) and node.id.startswith("__"):raise RuntimeError("restricted name") | |
| if isinstance(node,(ast.ClassDef,ast.AsyncFunctionDef)):raise RuntimeError("unsupported construct") | |
| if isinstance(node,ast.Import) and any(x.name not in allowed_imports for x in node.names):print(json.dumps({"passed":None}));sys.exit(0) | |
| if isinstance(node,ast.ImportFrom) and node.module not in allowed_imports:print(json.dumps({"passed":None}));sys.exit(0) | |
| def importer(name,*a,**kw): | |
| if name not in allowed_imports:raise ImportError(name) | |
| return allowed_imports[name] | |
| import builtins | |
| names=["int","float","str","bool","dict","list","tuple","set","range","enumerate","len","zip","map","filter","any","all","min","max","sum","sorted","abs","round","isinstance","ValueError","TypeError","IndexError","Exception","iter","next","reversed"] | |
| scope={"__builtins__":{k:getattr(builtins,k) for k in names}} | |
| scope["__builtins__"]["__import__"]=importer | |
| exec(compile(tree,"sample.py","exec"),scope) | |
| def canonical(v): | |
| if isinstance(v,(tuple,list)) or (hasattr(v,"__iter__") and not isinstance(v,(str,bytes,dict))):return [canonical(x) for x in v] | |
| return v | |
| passed=False | |
| for node in tree.body: | |
| if not isinstance(node,ast.FunctionDef):continue | |
| fn=scope[node.name] | |
| try: | |
| matches=True | |
| for args,expected in zip(payload["args"],payload["expected"]): | |
| original=copy.deepcopy(args);callargs=copy.deepcopy(args) | |
| params=[p.arg.lower() for p in node.args.args] | |
| if len(callargs)==1 and isinstance(callargs[0],str) and re.fullmatch(r"\d+:\d+",callargs[0]) and len(params)>=2: | |
| callargs=[int(x) for x in callargs[0].split(":")] | |
| elif len(callargs)==2 and isinstance(callargs[0],list) and isinstance(callargs[1],int) and params and any(x in params[0] for x in ["size","window","width","chunk"]): | |
| callargs=callargs[::-1] | |
| expected_original=copy.deepcopy(callargs) | |
| try:result=fn(*callargs) | |
| except ValueError: | |
| if expected=={"raises":"ValueError"}:continue | |
| raise | |
| if expected=={"raises":"ValueError"}:matches=False;break | |
| if payload.get("immutable") and callargs!=expected_original:matches=False;break | |
| if isinstance(expected,dict) and "one_of" in expected: | |
| if not any(canonical(result)==canonical(v) for v in expected["one_of"]):matches=False;break | |
| elif canonical(result)!=canonical(expected):matches=False;break | |
| if matches:passed=True;break | |
| except Exception:continue | |
| print(json.dumps({"passed":passed})) | |
| ''' | |
| fence=chr(96)*3 | |
| tasks=[] | |
| for key,rows in data.items(): | |
| if not key.startswith("original/"):continue | |
| for row in rows: | |
| if row["category"]!="coding":continue | |
| for needle,args,expected in fixtures: | |
| if needle in row["instruction"].lower(): | |
| match=re.search(fence+r"(?:python)?\s*(.*?)"+fence,row["response"],re.S) | |
| code=match.group(1).strip() if match else row["response"] | |
| tasks.append((row["id"],{"code":code,"args":args,"expected":expected,"immutable":"Do not mutate the supplied input" in row["instruction"]}));break | |
| def check(item): | |
| ident,payload=item | |
| try: | |
| r=subprocess.run([sys.executable,"-I","-c",harness],input=json.dumps(payload),capture_output=True,text=True,timeout=2,env={"PATH":"/usr/bin:/bin"}) | |
| outcome=json.loads(r.stdout) if r.returncode==0 else {"passed":False} | |
| return ident,outcome["passed"] | |
| except (ValueError,subprocess.TimeoutExpired):return ident,False | |
| with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:results=dict(pool.map(check,tasks)) | |
| failed={k for k,v in results.items() if v is False} | |
| for key,rows in data.items(): | |
| if key.startswith("original/"):data[key]=[r for r in rows if r["id"] not in failed] | |
| (D/"retained_semantic.json").write_text(json.dumps(data,ensure_ascii=False)) | |
| report={"tested_records":len(results),"passed":sum(v is True for v in results.values()),"unsupported":sum(v is None for v in results.values()),"failed":len(failed),"failed_ids":sorted(failed),"test_method":"Task-specific functional fixtures in restricted child processes with CPU, memory and wall-time limits"} | |
| (D/"code_quality.json").write_text(json.dumps(report,indent=2)) | |
| print(json.dumps({k:v for k,v in report.items() if k!="failed_ids"},indent=2)) | |