Download completion.py from dotlabs/smolscript: direct link, hf CLI and curl.
- Browser
- Download file 7.52 kB
-
https://huggingface.co/datasets/dotlabs/smolscript/resolve/main/completion.py
- Command line
-
hf download hf://datasets/dotlabs/smolscript/completion.py
-
curl -L -o completion.py https://huggingface.co/datasets/dotlabs/smolscript/resolve/main/completion.py
7.52 kB
| """Fixed base-model code completion. No reference/test fields are read.""" | |
| import io | |
| import re | |
| import tokenize | |
| PROMPT_VERSION='smolscript-base-completion-v3' | |
| SIGNATURES={ | |
| 'python':{'scalar':'def solve(n):','string':'def solve(s):','array':'def solve(values):'}, | |
| 'javascript':{'scalar':'function solve(n)','string':'function solve(s)','array':'function solve(values)','dom':'function setup()'}, | |
| 'cpp':{'scalar':'long long solve(long long n)','string':'std::string solve(std::string s)','array':'long long solve(const std::vector<long long>& values)'}, | |
| 'c':{'scalar':'long long solve(long long n)','string':'const char *solve(const char *input)','array':'long long solve(const long long *values, int length)'}, | |
| 'lua':{'scalar':'function solve(n)','string':'function solve(s)','array':'function solve(values)'}, | |
| 'csharp':{'scalar':'public static long Solve(long n)','string':'public static string Solve(string s)','array':'public static long Solve(long[] values)'}, | |
| 'rust':{'scalar':'fn solve(mut n: i64) -> i64','string':'fn solve(mut s: String) -> String','array':'fn solve(values: Vec<i64>) -> i64'}, | |
| } | |
| def prefix(row): | |
| lang=row['language'];kind=row['metadata']['family'] | |
| if lang=='html':return '<' | |
| if lang=='css':return '' | |
| header=SIGNATURES[lang][kind] | |
| if lang=='python':return header+'\n' | |
| if lang=='lua':return header+'\n' | |
| if kind=='dom':return header+' {\n' | |
| if lang=='csharp':return 'public class Solution {\n'+header+' {\n' | |
| return header+' {\n' | |
| def prompt(row): | |
| from runners.protocol import HEADERS | |
| lang=row['language'];meta=row['metadata'] | |
| task=re.sub(r'^In [^,]+,\s*','',row['prompt']) | |
| task=task.replace(' Return CSS only.','').replace(' Return an HTML fragment.','') | |
| task=task.removeprefix('Implement setup(). ') | |
| details=[task] | |
| if meta.get('input_domain'):details.append(meta['input_domain']) | |
| context=[] | |
| if meta.get('fixture'):context.append('HTML fixture: '+meta['fixture']) | |
| if meta.get('base_css'):context.append('Existing CSS: '+meta['base_css']) | |
| details=context+details | |
| if lang=='html':comment='<!-- '+ ' '.join(details).replace('-->','-- >')+' -->\n' | |
| elif lang=='css':comment='/* '+ ' '.join(details).replace('*/','* /')+' */\n' | |
| else: | |
| marker='#' if lang=='python' else '--' if lang=='lua' else '//' | |
| comment='\n'.join(marker+' '+line for line in details)+'\n' | |
| return comment+HEADERS.get(lang,'')+prefix(row) | |
| def _brace_end(source): | |
| """First complete braced function/class, ignoring quoted strings/comments. | |
| Lexer-only delimiting: never evaluate, fix or choose code by test success. | |
| """ | |
| depth=0;opened=False;i=0;previous='' | |
| while i<len(source): | |
| if source.startswith('//',i): | |
| end=source.find('\n',i);i=len(source) if end<0 else end+1;continue | |
| if source.startswith('/*',i): | |
| end=source.find('*/',i+2) | |
| if end<0:return len(source) | |
| i=end+2;continue | |
| # C/C++/C#/JS/Rust strings and character literals; Rust lifetimes are | |
| # identifiers, not single-quoted characters. | |
| ch=source[i] | |
| raw=re.match(r'(?:u8|u|U|L)?R"([^\s()\\]{0,16})\(',source[i:]) | |
| if raw: | |
| end=source.find(')'+raw.group(1)+'"',i+raw.end()) | |
| if end<0:return len(source) | |
| i=end+len(raw.group(1))+2;previous='v';continue | |
| word=re.match(r'[A-Za-z_$][\w$]*',source[i:]) | |
| if word: | |
| previous=word.group();i+=len(previous);continue | |
| if ch in ('"','`') or (ch=="'" and re.match(r"'(?:\\.|[^'\\\n])'",source[i:])): | |
| quote=ch;verbatim=quote=='"' and i>0 and source[i-1]=='@';i+=1 | |
| while i<len(source): | |
| if source[i]=='\\' and not verbatim:i+=2;continue | |
| if source[i]==quote: | |
| if quote=='"' and i+1<len(source) and source[i+1]=='"' and verbatim: | |
| i+=2;continue | |
| i+=1;break | |
| i+=1 | |
| previous='v';continue | |
| # JS regular-expression literals occurring where an expression begins. | |
| if ch=='/' and previous in ('=', '(', ',', ':', '[', '!', '?', 'return', 'throw', 'case', '=>'): | |
| j=i+1;inside=False | |
| while j<len(source) and source[j]!='\n': | |
| if source[j]=='\\':j+=2;continue | |
| if source[j]=='[':inside=True | |
| if source[j]==']':inside=False | |
| if source[j]=='/' and not inside:i=j+1;break | |
| j+=1 | |
| else:i+=1 | |
| previous='v';continue | |
| if ch=='{':depth+=1;opened=True | |
| elif ch=='}': | |
| depth-=1 | |
| if opened and depth==0:return i+1 | |
| if not ch.isspace():previous='=>' if ch=='>' and previous=='=' else ch | |
| i+=1 | |
| return len(source) | |
| def _python_end(source): | |
| depth=0;body=False | |
| try: | |
| for token in tokenize.generate_tokens(io.StringIO(source).readline): | |
| if token.type==tokenize.INDENT:depth+=1;body=True | |
| elif token.type==tokenize.DEDENT: | |
| depth-=1 | |
| if body and depth==0:return sum(len(x) for x in source.splitlines(keepends=True)[:token.start[0]-1]) | |
| except (tokenize.TokenError,IndentationError):pass | |
| return len(source) | |
| def _lua_end(source): | |
| # Tokenize strings/comments first, then count Lua's block delimiters. | |
| pattern=r'--\[\[.*?\]\]|--[^\n]*|\[(=*)\[.*?\]\1\]|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'|\b(?:function|if|for|while|do|repeat|end|until)\b' | |
| depth=0;loops=0 | |
| for match in re.finditer(pattern,source,re.S): | |
| word=match.group() | |
| if word in ('function','if','repeat'):depth+=1 | |
| elif word in ('for','while'):depth+=1;loops+=1 | |
| elif word=='do': | |
| if loops:loops-=1 | |
| else:depth+=1 | |
| elif word in ('end','until'): | |
| depth-=1 | |
| if depth==0:return match.end() | |
| return len(source) | |
| def assemble(row,continuation): | |
| """Attach the supplied header; keep the first completed entry-point scope. | |
| No indentation, expressions, missing delimiters or return values are repaired. | |
| A complete function emitted from scratch is accepted as a format alternative. | |
| """ | |
| lang=row['language'] | |
| text=continuation | |
| if text.lstrip().startswith('```'): | |
| from runners.common import extract_code | |
| text=extract_code(text,preserve_indentation=True) | |
| expected=prefix(row) | |
| starts={ | |
| 'python':r'^def\s+solve\s*\(', 'javascript':r'^(?:async\s+)?function\s+(?:solve|setup)\s*\(', | |
| 'lua':r'^function\s+solve\s*\(', 'csharp':r'^public\s+class\s+Solution\b', | |
| 'rust':r'^fn\s+solve\s*\(', 'cpp':r'^(?:long\s+long|std::string)\s+solve\s*\(', | |
| 'c':r'^(?:long\s+long|const\s+char\s*\*)\s*solve\s*\(', | |
| } | |
| complete_python=False | |
| if lang=='python': | |
| import ast | |
| try:complete_python=any(isinstance(n,ast.FunctionDef) and n.name=='solve' for n in ast.parse(text).body) | |
| except SyntaxError:pass | |
| if complete_python:code=text.lstrip() | |
| elif lang in starts and re.match(starts[lang],text.lstrip()):code=text.lstrip() | |
| elif lang=='html' and text.lstrip().startswith('<'):code=text.lstrip() | |
| else:code=expected+text | |
| if lang=='python' and not complete_python: | |
| import ast | |
| try:ast.parse(code) | |
| except SyntaxError:code=code[:_python_end(code)] | |
| elif lang=='lua':code=code[:_lua_end(code)] | |
| elif lang not in ('html','css','python'):code=code[:_brace_end(code)] | |
| return code.rstrip()+'\n' | |