translators-will commited on
Commit
b8a000d
·
verified ·
1 Parent(s): 69f9c5f

Create app.py

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