Hello! I was thinking about some specific tasks for davinci-codex and asked it to rewrite openvr_api to python.
It started with a comment to GitHub openvr_api SDK and then started writing code that I would never understand.
Params:
- temperature: 0.5,
- Top P: 1,
- Frequency penalty: 0.5,
- Presence penalty: 0
Python code:
import re
import os
import sys
import shutil
from pprint import pprint
def convert_camel_case_to_underscore(name):s1=re.sub('(.)([A-Z][a-z]+)','\\1_\\2',name);return re.sub('([a-z0-9])([A-Z])','\\1_\\2',s1).lower()
def convert_camel_case_to_underscore2(name):s1=re.sub('(.)([A-Z][a-z]+)','\\1 \\2',name);return re.sub('([a-z0-9])([A-Z])','\\1 \\2',s1).lower()
def convert_underscore_to_camelcase(name):return ''.join((x.capitalize()or' 'for x in name.split(' ')))
def convert_openvr_function_signature(function,isStatic=False):
if isStatic:function=function.replace('static ','')
function=function.replace('const ','');function=function.replace('*',' * ');function=re.sub('\\s+',' ',function);return function
def convert_openvr_parameter_type(parameter):parameter=parameter.replace('const ','');parameter=parameter.replace('*',' * ');parameter=re.sub('\\s+',' ',parameter);return parameter
def convert_openvr_return_type(returnType):returnType=re.sub('\\s+',' ',returnType);return returnType
def get_raw_openvr_comment(comment):
comment=comment.strip()
if comment:
comment=comment.replace('///','').strip()
if not comment:0
elif comment.startswith('@note'):0
elif comment.startswith('@warning'):0
elif comment.startswith('@remark'):0
else:return comment
return None
def get_openvr_comment(comment):
result='';rawComment=get_raw_openvr_comment(comment)
if rawComment:result+='"""\n'+rawComment+'\n"""\n'
return result
def generate_openvr_function(function,isStatic=False):
functionName=function['name'];functionSignature=convert_openvr_function_signature(function['signature'],isStatic)+':'+convert_openvr_return_type(function['returnType'])
if not isStatic:functionSignature='self, '+functionSignature
if not isStatic and len(function['parameters'])>1:functionSignature+=', '
result=''
if not isStatic:result+=get_openvr_comment(function['comment'])
result+=functionSignature+'\n';result+=' """\n'+function['comment']+'\n """\n'
if not isStatic:result+=' pass\n'
return result
def generate_openvr_class(className,classData):
classComment=get_openvr_comment(classData['comment']);staticFunctions=[];nonStaticFunctions=[]
for function in classData['functions']:
if not function['static']:nonStaticFunctions.append(function)
else:staticFunctions.append(function)
if className=='IVRSystem':nonStaticFunctions=[x for x in nonStaticFunctions if not x['name']=='getRecommendedRenderTargetSize']
result='';result+=classComment+'\n'
if len(staticFunctions)>0:
result+='class %s:\n'%(className,);result+=' """\n'+classComment+'\n """\n'
for function in staticFunctions:result+=generate_openvr_function(function,True)
result+='\n def __init__(self):\n';result+=' """\n Constructor for %s.\n """\n'%(className,);result+=' pass\n'
if len(nonStaticFunctions)>0:result+=' \n'
if len(nonStaticFunctions)>0:
for function in nonStaticFunctions:result+=generate_openvr_function(function)
if className=='IVRSystem':result+=get_openvr_comment('@note This is a singleton')+'\ndef VRSystem(): return IVRSystem()'
return result
def generate_openvr_classes(data):
result=''
for (className,classData) in data.items():
if className=='functions':continue
result+=generate_openvr_class(className,classData)
return result
def convert_openvr_function(function):
functionName=function['name'];functionSignature=convert_openvr_function_signature(function['signature'])+':'+convert_openvr_return_type(function['returnType']);parameters=[]
for parameter in function['parameters']:
parameterType=convert_openvr_parameter_type(parameter['type'])
if parameterType=='VREventCallback':parameters.append('VREventCallback')
elif parameterType=='VROverlayErrorCallback':parameters.append('VROverlayErrorCallback')
else:parameters.append('%s %s'%(parameterType,parameter['name']))
if len(parameters)>1:parameters[-1]='*args,'+parameters[-1]
result='';result+=get_raw_openvr_comment(function['comment'])+'\n'
if len(parameters)>1:result+='def %s(%s):\n'%(functionName,', '.join(parameters))
else:result+='def %s():\n'%(functionName,)
result+=' """\n %s\n """\n'%(function['comment'],)
if len(parameters)>1:result+=' pass\n'
return result
def generate_openvr_functions(data):
result=''
for function in data['functions']:
if not function['static']or function['name']=='VR_Init':continue
result+=convert_openvr_function(function)+'\n'
return result
def convert_openvr_typedef(typedef):
typedefType=typedef['type']
if typedefType.startswith('enum')or typedefType.startswith('flag')or typedefType.startswith('class')or typedefType.startswith('struct')or typedefType.startswith('union')or typedefType.startswith('const char *'):return None,None,None,None,None,None,None,None,True
if not re.match('^[A-Za-z0-9]+$',typedefType):return None,None,None,None,None,None,''+typedefType+',',False,False
if re.match('^[A-Za-z0-9]+$',typedef['name']):return typedef['name']+',',False,False,False,False,True,'',True
return typedef['name']+',',False,False,False,False,True,'',True
def convert_openvr_typedefs(data):
result=''
for typedef in data['typedefs']:
typedefType=convert_openvr_typedef(typedef)
if not typedefType:continue
result+=get_raw_openvr_comment(typedef['comment'])+'\n';result+=typedefType[0]+'\n'
return result
def generate_openvr_header(data):
result='''#ifndef OPENVR_FNTABLE_H
#define OPENVR_FNTABLE_H
#include <stdint.h>
typedef struct {
const char * pchName;
void ( *)(void);
} VRFunctionInfo;
typedef struct {'''+get_raw_openvr_comment(data['comment'])+'''\n} VRMainHandle;
''';result+=generate_openvr_classes(data);result+=generate_openvr_functions(data);result+=convert_openvr_typedefs(data)
return result+'''\n#endif //OPENVR_FNTABLE_H\n'''
def generate_openvr_source(data):
result='''#include "openvr.h"
#include <stdio.h>
#include <string.h>
#include <malloc.h>
''';result+=generate_openvr_classes(data);result+=generate_openvr_functions(data)
return result+'''\n'''
def generate_openvr():
if not os.path.exists('headers/openvr/headers/openvr_capi.h'):sys.exit('ERROR: Unable to find headers/openvr/headers/openvr_capi.h')
if not os.path.exists('headers/openvr/headers/openvr.h'):sys.exit('ERROR: Unable to find headers/openvr/headers/openvr.h')
shutil.copyfile('headers/openvr/headers/openvr_capi.h','headers/openvr/openvr_capi.h')
shutil.copyfile('headers/openvr/headers/openvr.h','headers/openvr/openvr.h')
shutil.move('headers/openvr/openvr_capi.h','include/openvr_capi.h');shutil.move('headers/openvr/openvr.h','include/OpenVRWrapper.h')
with open('headers/include-guard-prefix','rb')as f:guardPrefix=f.read().decode('utf-8').strip()+'OPENVR';with open('include\\'+guardPrefix+'HEADERS','w',encoding='utf-8')as f:f.write(guardPrefix+'HEADERS =');fileList=[];for root,dirs,files in os.walk("include"):fileList+=['\\'.join((root,x))for x in files];fileList=[x for x in fileList if x[-2:]in['.c','.C','.cpp','.CPP']];fileList=sorted(set(fileList));for file in fileList:f.write(' \\\n '+file);print(('''Header files have been generated in "'''+os.getcwd()+'''/include".\nYou must manually merge these files with your existing header files.'''))
def generate_docs():
if not os.path.exists('docs\\index-body'):sys.exit('ERROR: Unable to find docs\\index-body')
if not os.path.exists('docs\\api-body'):sys.exit('ERROR: Unable to find docs\\api-body')
outputPath='docs\\index';outputPathApi='docs\\api';outputPathClasses='docs\\classes'
if os.path.exists(outputPath):shutil.rmtree(outputPath)
if os.path.exists(outputPathApi):shutil.rmtree(outputPathApi)
if os.path.exists(outputPathClasses):shutil.rmtree(outputPathClasses)
os.makedirs(outputPath);os.makedirs(outputPathApi);os.makedirs(outputPathClasses)
for file in ['index-body','api-body']:shutil.copyfile('docs\\'+file,'docs\\index\\'+file);shutil.copyfile('docs\\'+file,'docs\\api\\'+file)
for root,dirs,files in os.walk("include"):
for file in files:
if not file[-2:]in['.h','.c']:continue
path='\\'.join((root,file))
with open(path,'rb')as f:data=f.read().decode('utf-8');data=re.sub('^\s*//.*$','',data,0,re.MULTILINE);data=re.sub('/\*+/','/*',data);data=re.sub('/\*+([^/])','/*\\1',data);data=re.sub('\*+/','*/',data);with open(path,'w',encoding='utf-8')as f:f.write(data)
path=path.replace('include','docs\\classes');path=path.replace('.c','.html').replace('.h','.html');os.makedirs(os.path.dirname(path),exist_ok=True)
with open(path,'w',encoding='utf-8')as f:f.write(data)
path=path.replace('.html','.js');with open(path,'w',encoding='utf-8')as f:f.write('''document.write("<pre>")''')
path=path.replace('.js','.css');with open(path,'w',encoding='utf-8')as f:f.write('''body {font-family:Courier New}''')
print(('''Documentation has been generated in "'''+os.getcwd()+'''/docs".'''))
def generate_config():
if not os.path.exists('include\\OpenVRWrapper\\OpenVRWrapper.h'):sys.exit('ERROR: Unable to find include\\OpenVRWrapper\\OpenVRWrapper.h')
if not os.path.exists('include\\openvr.h'):sys.exit('ERROR: Unable to find include\\openvr.h')
shutil.copyfile('include\\OpenVRWrapper\\OpenVRWrapper.h','include\\OpenVRWrapper.h');shutil.copyfile('include\\openvr.h','include\\OpenVR.h')
print(('''Configuration has been generated in "'''+os.getcwd()+'''/include".'''))
def main():
if len(sys.argv)==1:sys.exit('ERROR: No command specified')
if sys.argv[1]in['docs','doc','documentation','documents']:generate_docs()
elif sys.argv[1]in['config','conf','configuration']:generate_config()
elif sys.argv[1]in['header','head','hdr','header-file','header-files','include','include-file','include-files','includes']:generate_openvr_header(load_openvr_json())
elif sys.argv[1]in['source','src','code','source-file','source-files','source-code','sources']:generate_openvr_source(load_openvr_json())
else:sys.exit('ERROR: Unknown command: "%s"'%(sys.argv[1],))
if __name__=='__main__':main()
Unfortunately, I can’t run this code but it seems that Codex did really well for that specific task.