"""Command-template validator against the multivendor command base. verified = output matches (vendor, os) base entry as a *template*: literal words must be equal, numbers/IPs/MACs are wildcards, base placeholders (, UPPER_CASE, {a|b}, [opt]) are wildcards. Multi-line outputs verify if the whole text matches one base entry, or every non-comment line matches some base line of that vendor. strict_template = identical template key (vendor, template string) exists in the base. exact_in_base = the output string itself is a base command (after the same light normalization). Limits: verified means "shape exists in the base", NOT "correct for the intent" or "safe to run". """ import re,json,collections from pathlib import Path IP4=re.compile(r'^\d{1,3}(?:\.\d{1,3}){3}(?:/\d{1,2})?$') IP6=re.compile(r'^(?:[0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}(?:/\d{1,3})?$') MAC=re.compile(r'^(?:[0-9a-fA-F]{2}[:.-]){5}[0-9a-fA-F]{2}$|^(?:[0-9a-fA-F]{4}\.){2}[0-9a-fA-F]{4}$') def norm_cmd(c): c=re.sub(r'^\[[^\]]+\]\s*','',c); c=c.replace('\\"','"'); return c.strip() def _ws(s): return re.sub(r'[ \t]+',' ',s.strip()) def kind(t): """token kind in a BASE command: 'opt' | 'var' | 'alt' | 'lit'""" if re.fullmatch(r'\[[^\]]*\]',t): return 'opt' if re.search(r'<[^>]*>',t) or re.fullmatch(r'\{[^}]*\}',t) or t.endswith('...') : return 'var' if '|' in t and not re.search(r'[a-z]\|[a-z]',t[:0]): return 'alt' if re.fullmatch(r'[A-Z][A-Z0-9_]+',t) and re.search(r'[A-Z]{2}',t): return 'var' return 'lit' def tok_class(t): if IP4.match(t) or IP6.match(t): return '' if MAC.match(t): return '' return re.sub(r'\d+','',t) def template(cmd): out=[] for line in norm_cmd(cmd).split('\n'): line=_ws(line) if not line: continue ts=[] for t in line.split(' '): k=kind(t) ts.append('' if k in('var','opt','alt') else tok_class(t).lower() if True else t) out.append(' '.join(ts)) return '\n'.join(out) def _tok_rx(t): k=kind(t) if k=='var': return r'\S+' if k=='opt': return r'(?:\S+)?' # optional token(s) -> handled by joining if k=='alt': return r'\S+' c=tok_class(t) if c=='': return r'\S+' if c=='': return r'\S+' parts=re.split(r'(\d+)',t) return ''.join(r'\d+' if p.isdigit() else re.escape(p) for p in parts) def line_rx(line): ts=_ws(line).split(' ');rx='' for i,t in enumerate(ts): r=_tok_rx(t); opt=(kind(t)=='opt') if i==0: rx+=r else: rx+=(r'(?: \S+)?' if opt else ' '+r) return re.compile('^'+rx+'$') def strip_q(s): return s.replace('"','').replace("'",'') class Validator: def __init__(self,base_rows,exclude_templates=None): """base_rows: iterable of dicts with vendor, os, command. exclude_templates: set of (vendor,template) to drop (held-out mode).""" self.rows=[];self.strict=set();self.exact=set();self.idx=collections.defaultdict(list);self.lidx=collections.defaultdict(list);self._seenl=set() for r in base_rows: c=norm_cmd(r['command']);tp=template(c) if exclude_templates and (r['vendor'],tp) in exclude_templates: continue v=(r['vendor'],r['os']);self.rows.append(r) self.strict.add((r['vendor'],tp));self.exact.add((r['vendor'],_ws(c))) lines=[_ws(l) for l in c.split('\n') if _ws(l)] if not lines: continue if len(lines)==1 or True: self.idx[(r['vendor'],lines[0].split(' ')[0].lower())].append(('\n'.join(lines),None)) for l in lines: if l.startswith('!') or l.startswith('#'): continue key=(r['vendor'],l) if key in self._seenl: continue self._seenl.add(key);self.lidx[(r['vendor'],l.split(' ')[0].lower())].append([l,None]) self._cache={} def _match_line(self,vendor,line): for ent in self.lidx.get((vendor,line.split(' ')[0].lower()),[]): if ent[1] is None: ent[1]=line_rx(ent[0]) if ent[1].match(line): return True return False def check(self,vendor,cmd): c=norm_cmd(cmd);lines=[_ws(l) for l in c.split('\n') if _ws(l)] if not lines: return {'verified':False,'level':'empty','strict':False,'exact':False} full='\n'.join(lines);strict=(vendor,template(c)) in self.strict;exact=(vendor,_ws(c)) in self.exact if exact or strict: return {'verified':True,'level':'exact' if exact else 'template','strict':strict,'exact':exact} # single-line whole match, base entry may be multi-line: compare line 1 shape only for single-line outputs if all(self._match_line(vendor,l) for l in lines if not l.startswith('!') and not l.startswith('#')) and any(not l.startswith(('!','#')) for l in lines): return {'verified':True,'level':'wildcard-lines','strict':strict,'exact':exact} return {'verified':False,'level':'none','strict':strict,'exact':exact} def load_base(path='/workspace/hf-profile/ds/data/train.parquet'): import pyarrow.parquet as pq return pq.read_table(path).to_pylist()