Spaces:
Sleeping
Sleeping
Sync from GitHub
Browse filesFiles changed (7)
- .gitignore+1
- src/__main__.py+18-5
- src/compiler.py+9-8
- src/interface.py+9-11
- src/optimizer.py+18-7
- src/prompts.py+21-4
- src/tester.py+8-4
8 unmodified lines910111213148 unmodified lines# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/8 unmodified lines91011121314158 unmodified lines# Distribution / packaging.Pythonbuild/compiled/develop-eggs/dist/downloads/
123456718 unmodified lines262728293031322 unmodified lines35363738394041424344454647"""Main entrypoint module for the AI Python C Extensions Generator application."""from logging import getLoggerfrom os import getenvfrom sys import platformfrom .compiler import compile_extension18 unmodified linesdefault_platform = "Linux"# Read compile stage flag from environment variable, defaulting to False if not set.compile_stage = getenv("COMPILE_STAGE", "False").lower() in ("true", "1", "yes")def main():2 unmodified lines_logger.info(f'AVAILABLE MODELS: {models}')# Prepare the interface configuration based.interface_config = {"models": models, "compile_stage": compile_stage,"optimize_function": optimize_function}if compile_stage:_logger.info('COMPILE STAGE ENABLED')interface_config.update({"compile_extension": compile_extension,"test_extension": test_extension})app = get_interface(**interface_config)app.launch(footer_links=[])# We return the app instance for potential use in autoreload scenarios.return app1234567818 unmodified lines272829303132333435363738394041424344452 unmodified lines48495051525354555657585960"""Main entrypoint module for the AI Python C Extensions Generator application."""from logging import getLoggerfrom os import getenv, sepfrom pathlib import Pathfrom sys import platformfrom .compiler import compile_extension18 unmodified linesdefault_platform = "Linux"# Read compile stage flag from environment variable, defaulting to False if not set.if compile_stage := getenv("COMPILE_STAGE", "False").lower() in ("true", "1", "yes"):# Define the build directory for compiled extensions.BUILD_DIR = Path("compiled")# BUILD_DIR.mkdir(parents=True, exist_ok=True)_logger.info('COMPILE STAGE ENABLED')_logger.info(f'COMPILE DIRECTORY SET TO: .{sep}{BUILD_DIR}')# CSS styles for the interface, defining background colors for C and Python code areas.css = """.c_ext {background-color: #050;}.python {background-color: #306998;}"""def main():2 unmodified lines_logger.info(f'AVAILABLE MODELS: {models}')# Prepare the interface configuration based.interface_config = {"models": models, "compile_stage": compile_stage,"optimize_function": optimize_function,"compile_path": BUILD_DIR}if compile_stage:interface_config.update({"compile_extension": compile_extension,"test_extension": test_extension})app = get_interface(**interface_config)app.launch(footer_links=[], css=css)# We return the app instance for potential use in autoreload scenarios.return app
9 unmodified lines10111213141516171819202122233 unmodified lines272829303132338 unmodified lines424344454647484950515253545556575859609 unmodified lines# Define a function to write outputs to a file with a given filename.def write_file(data, filename):"""Write data to a file with the specified filename."""with open(filename, "w") as file:file.write(data)# Extension compilation function.def build_extension():"""Compile the C extension using 'setup.py' and return the compilation output."""# Set default COMSPEC to cmd.exe on Windows to avoid issues with some C compilers.if sys.platform == "win32":3 unmodified linestry:_logger.info('STARTING COMPILATION PROCESS...')compile_cmd = ["python", "setup.py", "build_ext", "--inplace"]compile_result = subprocess.run(compile_cmd, env=os.environ,check=True, text=True, capture_output=True)except subprocess.CalledProcessError as ex:_logger.error(f"COMPILATION FAILED WITH ERROR:\n{ex.stdout}\n{ex.stderr}")8 unmodified lines# Extension compilation function.def compile_extension(c_code, setup_code, module_name):"""Build the C extension from the provided codes."""try: # Write the provided codes to their respective files._logger.info('WRITING GENERATED C CODE TO FILE...')write_file(c_code, f"{module_name}.c")_logger.info('WRITING GENERATED SETUP CODE TO FILE...')write_file(setup_code, "setup.py")except Exception as ex:_logger.error(f"ERROR WHILE WRITING FILES:\n{ex}")return f"An error occurred while writing files:\n{ex}"try: # Build the extension and capture the output._logger.info('BUILDING THE EXTENSION...')build_output = build_extension()except Exception as ex: # If build fails, return the error message._logger.error(f"ERROR WHILE BUILDING EXTENSION:\n{ex}")return str(ex)9 unmodified lines1011121314151617181920212223243 unmodified lines282930313233348 unmodified lines434445464748495051525354555657585960619 unmodified lines# Define a function to write outputs to a file with a given filename.def write_file(data, path):"""Write data to a file with the specified filename."""path.parent.mkdir(parents=True, exist_ok=True)with open(path, "w") as file:file.write(data)# Extension compilation function.def build_extension(compile_path):"""Compile the C extension using 'setup.py' and return the compilation output."""# Set default COMSPEC to cmd.exe on Windows to avoid issues with some C compilers.if sys.platform == "win32":3 unmodified linestry:_logger.info('STARTING COMPILATION PROCESS...')compile_cmd = ["python", "setup.py", "build_ext", "--inplace"]compile_result = subprocess.run(compile_cmd, env=os.environ, cwd=compile_path,check=True, text=True, capture_output=True)except subprocess.CalledProcessError as ex:_logger.error(f"COMPILATION FAILED WITH ERROR:\n{ex.stdout}\n{ex.stderr}")8 unmodified lines# Extension compilation function.def compile_extension(c_code, setup_code, module_name, compile_path):"""Build the C extension from the provided codes."""try: # Write the provided codes to their respective files._logger.info('WRITING GENERATED C CODE TO FILE...')write_file(c_code, compile_path / f"{module_name}.c")_logger.info('WRITING GENERATED SETUP CODE TO FILE...')write_file(setup_code, compile_path / "setup.py")except Exception as ex:_logger.error(f"ERROR WHILE WRITING FILES:\n{ex}")return f"An error occurred while writing files:\n{ex}"try: # Build the extension and capture the output._logger.info('BUILDING THE EXTENSION...')build_output = build_extension(compile_path)except Exception as ex: # If build fails, return the error message._logger.error(f"ERROR WHILE BUILDING EXTENSION:\n{ex}")return str(ex)
123456789101112131415166 unmodified lines23242526272829303125 unmodified lines5758596061626311 unmodified lines7576777879808182838485"""Interface module for the AI Python C Extensions Generator application."""from gradio import Blocks, Button, Dropdown, Examples, Markdown, Row, TextArea, Textboxfrom .examples import example_dictcss = """.c_ext {background-color: #050;}.python {background-color: #306998;}"""def _compile_extension():return "COMPILE_EXTENSION PLACEHOLDER"6 unmodified linescompile_extension=_compile_extension,test_extension=_test_extension,default_platform="Windows",models=["gpt-5.1-codex-mini"]):"""Get the Gradio Blocks interface for the AI Python C Extensions Generator."""with Blocks(css=css, title="AI Python C Extensions Generator") as ui:Markdown("## Convert code from Python to C Extension")with Row():25 unmodified linesbuttons=["copy"], elem_classes=["python"])get_extension.click(optimize_function,inputs=[python, module_name, platform, model],outputs=[c_code, setup_code, usage_code])# ######### BUILD AND TEST SECTIONS ######### #11 unmodified lineselem_classes=["python"])compile_ext.click(compile_extension,inputs=[c_code, setup_code, module_name],outputs=[c_ext_out])test_run.click(test_extension,inputs=[usage_code],outputs=[test_out])return ui12345678910116 unmodified lines181920212223242526272825 unmodified lines545556575859606111 unmodified lines7374757677787980818283"""Interface module for the AI Python C Extensions Generator application."""from gradio import Blocks, Button, Dropdown, Examples, Markdown, Row, State, TextAreafrom gradio import Textboxfrom .examples import example_dictdef _compile_extension():return "COMPILE_EXTENSION PLACEHOLDER"6 unmodified linescompile_extension=_compile_extension,test_extension=_test_extension,default_platform="Windows",compile_path="compile",models=["gpt-5.1-codex-mini"]):"""Get the Gradio Blocks interface for the AI Python C Extensions Generator."""with Blocks(title="AI Python C Extensions Generator") as ui:compile_path_st = State(value=compile_path)Markdown("## Convert code from Python to C Extension")with Row():25 unmodified linesbuttons=["copy"], elem_classes=["python"])get_extension.click(optimize_function,inputs=[python, module_name, platform,compile_path_st, model],outputs=[c_code, setup_code, usage_code])# ######### BUILD AND TEST SECTIONS ######### #11 unmodified lineselem_classes=["python"])compile_ext.click(compile_extension,inputs=[c_code, setup_code, module_name, compile_path_st],outputs=[c_ext_out])test_run.click(test_extension,inputs=[usage_code, compile_path_st],outputs=[test_out])return ui
3 unmodified lines4567891013 unmodified lines2425262728293031325 unmodified lines383940414243444546474849503 unmodified linesfrom dotenv import load_dotenvfrom openai import OpenAIfrom pydantic import BaseModelfrom .prompts import messages_for13 unmodified lines# Define Pydantic model class for GPT response parsing.class _extension_codes(BaseModel):c_code: strsetup: strusage: strdef __str__(self):"""Return a string representation of the optimization codes."""5 unmodified lines# Define optimization function using OpenAI's GPT model.def optimize_gpt(python_code, module_name, platform, model=OPENAI_MODEL):"""Generate an optimized C extension for Python."""schema = _extension_codes.model_json_schema()_logger.info('SENDING OPTIMIZATION REQUEST TO OPENAI... 'f'(MODEL: {model}, PLATFORM: {platform})')response = openai.responses.parse(model=model, text_format=_extension_codes,input=messages_for(python_code, module_name, schema, platform)).output_parsed_logger.info('RECEIVED OPTIMIZATION RESPONSE FROM OPENAI')return response.c_code, response.setup, response.usage3 unmodified lines4567891013 unmodified lines2425262728293031323334353637383940415 unmodified lines4748495051525354555657585960613 unmodified linesfrom dotenv import load_dotenvfrom openai import OpenAIfrom pydantic import BaseModel, Fieldfrom .prompts import messages_for13 unmodified lines# Define Pydantic model class for GPT response parsing.class _extension_codes(BaseModel):c_code: str = Field(...,description="Generated C extension source ""code for the Python module.")setup: str = Field(...,description="The generated setup.py build script ""used to compile the C extension module.""It must assume the module is in the current folder ""and not in any subfolder.")usage: str = Field(...,description="A Python usage example that imports the compiled ""extension and compares its execution time with the ""original Python implementation.")def __str__(self):"""Return a string representation of the optimization codes."""5 unmodified lines# Define optimization function using OpenAI's GPT model.def optimize_gpt(python_code, module_name, platform, compile_path, model=OPENAI_MODEL):"""Generate an optimized C extension for Python."""schema = _extension_codes.model_json_schema()_logger.info('SENDING OPTIMIZATION REQUEST TO OPENAI... 'f'(MODEL: {model}, PLATFORM: {platform}, 'f'MODULE: {module_name}, COMPILE PATH: {compile_path})')response = openai.responses.parse(model=model, text_format=_extension_codes,input=messages_for(python_code, module_name, schema, platform, compile_path)).output_parsed_logger.info('RECEIVED OPTIMIZATION RESPONSE FROM OPENAI')return response.c_code, response.setup, response.usage
9 unmodified lines10111213141516171819202122232425269 unmodified lines36373839404110 unmodified lines525354555657585960619 unmodified linesUse comments sparingly and do not provide any explanation other than occasional comments.The C extension for Python needs to produce an identical output in the fastest possibletime.Make sure the C extension for Python code is correct and can be compiled with'python setup.py build_ext' and used in Python.The usage example must include a time measurement and a comparison with the originalPython code.Do not include any additional text or explanation outside the JSON structure.Make sure the JSON is correctly formatted."""9 unmodified linesThe module name, used to import, must be "{module_name}", the generated C file willbe named "{module_name}.c".Pay attention to number types to ensure no int overflows.Remember to #include all necessary C packages such as iomanip or <python.h>10 unmodified lines# Define function to create the messages for the LLM.def messages_for(python_code, module_name, schema, platform):"""Create the messages given the Python code, module name, and platform."""return [{"role": "system", "content": system_message.format(schema=schema)},{"role": "user", "content": user_prompt.format(python_code=python_code,module_name=module_name,platform=platform)}]9 unmodified lines10111213141516171819202122232425262728299 unmodified lines3940414243444546474849505152535455565710 unmodified lines68697071727374757677789 unmodified linesUse comments sparingly and do not provide any explanation other than occasional comments.The C extension for Python needs to produce identical output in the fastest possibletime.Make sure the C extension for Python code is correct and can be compiled with'python setup.py build_ext' and used in Python.The usage example must include a time measurement and a comparison with the originalPython code, absolute and proportional difference.Do not include an `if __name__ == '__main__'` guard in the usage script.The usage script must be importable, and the usage example must invoke its functionsdirectly.Do not include any additional text or explanation outside the JSON structure.Make sure the JSON is correctly formatted."""9 unmodified linesThe module name, used to import, must be "{module_name}", the generated C file willbe named "{module_name}.c".The generated C extension module will be located in the "{compile_path}" folder.Only the usage example file should import the module from that folder:from {compile_path} import {module_name}Do not use "{compile_path}" inside the generated C source or in the generated setup.pyfile. The generated C source and setup.py must behave as if they are in the currentfolder and must not reference any external path.Do not include an `if __name__ == '__main__'` guard in the generated module or theusage example. The usage script must be importable, and the usage example must invokeits functions directly.Pay attention to number types to ensure no int overflows.Remember to #include all necessary C packages such as iomanip or <python.h>10 unmodified lines# Define function to create the messages for the LLM.def messages_for(python_code, module_name, schema, platform, compile_path):"""Create the messages given the Python code, module name, and platform."""return [{"role": "system", "content": system_message.format(schema=schema)},{"role": "user", "content": user_prompt.format(python_code=python_code,module_name=module_name,compile_path=compile_path,platform=platform)}]
8 unmodified lines910111213141516177 unmodified lines2526272829301 unmodified line323334353637383940418 unmodified lines# Define a function to write outputs to a file with a given filename.def write_file(data, filename):"""Write data to a file with the specified filename."""with open(filename, "w") as file:file.write(data)7 unmodified linessys.stdout = output# Execute the provided code in a clean global namespace.exec(code, {})finally:# Restore original stdout.sys.stdout = sys.__stdout__1 unmodified line# Extension testing function.def test_extension(usage_code):"""Test the C extension executing the code and capture its output."""try: # Write the code to file.write_file(usage_code, "usage_example.py")except Exception as ex:return f"An error occurred while writing test file:\n{ex}"try:8 unmodified lines91011121314151617187 unmodified lines2627282930313233341 unmodified line363738394041424344458 unmodified lines# Define a function to write outputs to a file with a given filename.def write_file(data, path):"""Write data to a file with the specified filename."""path.parent.mkdir(parents=True, exist_ok=True)with open(path, "w") as file:file.write(data)7 unmodified linessys.stdout = output# Execute the provided code in a clean global namespace.exec(code, {})except Exception as ex:_logger.error(f"ERROR WHILE EXECUTING TEST CODE:\n{ex}")return f"An error occurred while executing test code:\n{ex}"finally:# Restore original stdout.sys.stdout = sys.__stdout__1 unmodified line# Extension testing function.def test_extension(usage_code, compile_path):"""Test the C extension executing the code and capture its output."""try: # Write the code to file.write_file(usage_code, compile_path / "usage_example.py")except Exception as ex:return f"An error occurred while writing test file:\n{ex}"try:
.gitignore+1
src/__main__.py+18-5
src/compiler.py+9-8
src/interface.py+9-11
src/optimizer.py+18-7
src/prompts.py+21-4
src/tester.py+8-4