CoolFace
Apppublic

translators-will/Syntax_Shift

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py241 linesDownload Raw Back to root
1# imports2import re3import os4from dotenv import load_dotenv5from openai import OpenAI6import streamlit as st7import subprocess8import tempfile9import shutil10import time11from timeit import default_timer as timer12 13def install_rust():14    subprocess.run("curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y", shell=True)15    subprocess.run("source $HOME/.cargo/env", shell=True)16 17install_rust()18 19# Load environment variables20os.environ['PATH'] += f':{os.path.expanduser("~/.cargo/bin")}'21 22load_dotenv()23os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY')24OPENAI_MODEL = "gpt-4o-mini"25 26class TranslateCode:27    def __init__(self, openai_client, model):28        self.openai = openai_client29        self.model = model30 31    def user_prompt_for(self, python, lang_select):32        user_prompt = f"Rewrite this Python code in {lang_select} with the fastest possible implementation that produces identical output in the least time. "33        user_prompt += f"Respond only with {lang_select} code; do not explain your work; only return {lang_select} code. "34        user_prompt += "Pay attention to number types to ensure no int overflows. Remember to include all necessary dependencies and libraries.\n\n"35        user_prompt += "If translating to Rust, make sure to include the necessary packages and crates."36        user_prompt += python37        return user_prompt38 39    def messages_for(self, python, lang_select):40        # System message for OpenAI API41        system_message = "You are an assistant that reimplements Python code in high performance code for a Windows PC. "42        system_message += "Respond only with code; do not provide any explanations. "43        system_message += "The response needs to produce an identical output in the fastest possible time."44 45        return [46            {"role": "system", "content": system_message},47            {"role": "user", "content": self.user_prompt_for(python, lang_select)}48        ]49 50    def translate_code(self, code_file, lang_select):51        stream = self.openai.chat.completions.create(model=self.model, messages=self.messages_for(code_file, lang_select), stream=True)52        code = ""53        for chunk in stream:54            fragment = chunk.choices[0].delta.content or ""55            code += fragment56        pattern = r"```(c|cpp|rust|javascript)\n"57        code = re.sub(pattern, "", code).replace("```", "")58        return code59 60 61class ExecuteCode:62    def __init__(self, translator):63        self.translator = translator64 65    def extract_dependencies(self, code):66        try:67            dependency_pattern = r"""68            (?:use\s+(?!std::)[a-zA-Z_][a-zA-Z0-9_]*::|extern\s+crate\s+(?!std)[a-zA-Z_][a-zA-Z0-9_]*);?69            |70            \#include\s*<([a-zA-Z_][a-zA-Z0-9_/.]*)>71            |72            (?:import\s+.*\s+from\s+['"]([a-zA-Z_][a-zA-Z0-9_/.]*)['"]73            |require\s*\(\s*['"]([a-zA-Z_][a-zA-Z0-9_/.]*)['"]\s*\))74        """75            matches = re.findall(dependency_pattern, code, re.VERBOSE)76            dependencies = [match for match in matches if any(match)]77            return dependencies if matches else []78        except re.error as e:79            raise ValueError(f"Regex error while extracting dependencies: {e}")80 81    def execute_code(self, code_file, lang_select):82        if lang_select == "Rust":83            rust_code = self.translator.translate_code(code_file, lang_select)84            try:85                dependencies = self.extract_dependencies(rust_code)86                temp_dir = tempfile.mkdtemp()87                src_dir = os.path.join(temp_dir, "src")88                os.makedirs(src_dir, exist_ok=True)89                cargo_toml = f"""90                [package]91                name = "temp_project"92                version = "0.1.0"93                edition = "2021"94 95                [dependencies]96            """97                for dependency in dependencies:98                    crate = dependency[0]99                    cargo_toml += f"{crate} = \"*\"\n"100                with open(os.path.join(temp_dir, "Cargo.toml"), "w") as f:101                    f.write(cargo_toml)102                main_rs_path = os.path.join(src_dir, "main.rs")103                with open(main_rs_path, "w", encoding="utf-8") as f:104                    f.write(rust_code)105                cargo_build = subprocess.run(["cargo", "build", "--release"],106                                                cwd=temp_dir,107                                                stdout=subprocess.PIPE,108                                                stderr=subprocess.PIPE,109                                                text=True)110                if cargo_build.returncode != 0:111                    return f"Cargo build failed:\n{cargo_build.stderr}", 0112                executable_path = os.path.join(temp_dir, "target", "release", "temp_project")113                start_time = timer()114                run_result = subprocess.run([executable_path],115                                            stdout=subprocess.PIPE,116                                            stderr=subprocess.PIPE,117                                            text=True)118                end_time = timer()119                execution_time = end_time - start_time120                if run_result.returncode != 0:121                    print(f"Execution failed: {run_result.stderr}")122                return run_result.stdout, execution_time123            finally:124                if temp_dir:125                    shutil.rmtree(temp_dir, ignore_errors=True)126        elif lang_select in ["C", "C++"]:127            code = self.translator.translate_code(code_file, lang_select)128            with tempfile.TemporaryDirectory() as temp_dir:129                file_extension = "c" if lang_select == "C" else "cpp"130                file_path = os.path.join(temp_dir, f"translated_code.{file_extension}")131                with open(file_path, "w") as f:132                    f.write(code)133                executable_path = os.path.join(temp_dir, "translated_code")134                compiler = "gcc" if lang_select == "C" else "g++"135                compile_result = subprocess.run([compiler, file_path, "-o", executable_path],136                                                stdout=subprocess.PIPE,137                                                stderr=subprocess.PIPE,138                                                text=True)139                if compile_result.returncode != 0:140                    return f"Compilation failed:\n{compile_result.stderr}", 0141                start_time = timer()142                run_result = subprocess.run([executable_path],143                                            stdout=subprocess.PIPE,144                                            stderr=subprocess.PIPE,145                                            text=True)146                end_time = timer()147                execution_time = end_time - start_time148                return run_result.stdout, execution_time149        elif lang_select == "Javascript":150            js_code = self.translator.translate_code(code_file, lang_select)151            with tempfile.NamedTemporaryFile(suffix='.js', delete=False) as js_file:152                js_file.write(js_code.encode("utf-8"))153                js_file.flush()154                js_file_path = js_file.name155            try:156                start_time = timer()157                run_result = subprocess.run(["node", js_file_path],158                                            stdout=subprocess.PIPE,159                                            stderr=subprocess.PIPE,160                                            text=True)161                end_time = timer()162                execution_time = end_time - start_time163                return run_result.stdout, execution_time164            finally:165                os.remove(js_file_path)166        else:167            return "Language not supported", 0168 169 170class StreamlitApp:171    def __init__(self, translator, executor):172        self.translator = translator173        self.executor = executor174 175    def main(self):176        st.title("SyntaxShift: Code Translator")177        st.write("It's like Google Translate, but for code.\n\nUpload a Python file to translate it to C, C++, Rust, or Javascript, and run the code.")178        with st.sidebar:179            st.write("Upload Python file here:")180            uploaded_file = st.file_uploader("Choose a Python file", type="py")181            lang_select = st.selectbox("Select the language to translate to:", ["C", "C++", "Rust", "Javascript"])182        if uploaded_file is not None and lang_select:183            source_code = uploaded_file.read().decode("utf-8")184            col1, col2 = st.columns(2)185            with col1:186                st.subheader("Original Python Code")187                st.code(source_code, language='python')188                if st.button("Run Python Code"):189                    try:190                        with tempfile.NamedTemporaryFile(delete=False, suffix=".py") as temp_py_file:191                            temp_py_file.write(source_code.encode('utf-8'))192                            temp_py_file_path = temp_py_file.name193                        start_time = time.time()194                        result = subprocess.run(["python", temp_py_file_path], capture_output=True, text=True)195                        end_time = time.time()196                        output = result.stdout if result.returncode == 0 else result.stderr197                        execution_time = end_time - start_time198                    except Exception as e:199                        output = str(e)200                        execution_time = 0201                    finally:202                        if os.path.exists(temp_py_file_path):203                            os.remove(temp_py_file_path)204                    st.subheader("Output")205                    st.code(output, language='text')206                    st.code(f"Execution time: {execution_time:4f} seconds", language='text')207            with col2:208                source_code_key = f"source_code_{lang_select}"209                translated_code_key = f"translated_code_{lang_select}"210                if source_code_key not in st.session_state or translated_code_key not in st.session_state:211                    translated_code = self.translator.translate_code(source_code, lang_select)212                    translated_code = translated_code.encode("utf-8").decode("utf-8")213                    translated_code = translated_code.replace("Â", "")214                    st.session_state[translated_code_key] = translated_code215                else:216                    translated_code = st.session_state[translated_code_key]217                lang_dict = {"C": "c", "C++": "cpp", "Rust": "rust", "Javascript": "javascript"}218                st.subheader(f"Translated {lang_select} Code")219                st.code(translated_code, language=lang_dict[lang_select])220                #suffix_dict = {"C": ".c", "C++": ".cpp", "Rust": ".rs", "Javascript": ".js"}221                if st.button(f"Run Translated {lang_select} Code"):222                    output_key = f"output_{lang_select}"223                    execution_time_key = f"execution_time_{lang_select}"224                    if output_key not in st.session_state or execution_time_key not in st.session_state:225                        output, execution_time = self.executor.execute_code(translated_code, lang_select)226                        st.session_state[output_key] = output227                        st.session_state[execution_time_key] = execution_time228                    else:229                        output = st.session_state[output_key]230                        execution_time = st.session_state[execution_time_key]231                    st.subheader("Output")232                    st.code(output.replace("Â", ""), language='text')233                    st.code(f"Execution time: {execution_time:4f} seconds", language='text')234 235 236if __name__ == "__main__":237    openai_client = OpenAI()238    translator = TranslateCode(openai_client, OPENAI_MODEL)239    executor = ExecuteCode(translator)240    app = StreamlitApp(translator, executor)241    app.main()