Skip to content

Commit 767adea

Browse files
committed
Added code conversion functionality
1 parent e77d426 commit 767adea

File tree

5 files changed

+219
-14
lines changed

5 files changed

+219
-14
lines changed

libs/geminiai.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,3 +197,56 @@ def fix_generated_code(self, code, code_language, fix_instructions=""):
197197
except Exception as exception:
198198
st.toast(f"Error in code fixing: {exception}", icon="❌")
199199
logger.error(f"Error in code fixing: {traceback.format_exc()}")
200+
201+
def convert_generated_code(self, code, code_language):
202+
"""
203+
Function to convert the generated code to a different language using the palm API.
204+
"""
205+
try:
206+
# Check for valid code
207+
if not code or len(code) == 0:
208+
logger.error("Error in code conversion: Please enter a valid code.")
209+
return
210+
211+
logger.info(f"Converting code")
212+
if code and len(code) > 0:
213+
logger.info(f"Converting code {code[:100]}... to language {code_language}")
214+
215+
# Improved instructions template
216+
template = f"""
217+
Task: Convert the code snippet provided below to the {code_language} programming language, following the given instructions:
218+
219+
{code}
220+
221+
Instructions for Conversion:
222+
1. Identify the functionality of the original code.
223+
2. Translate the code into the {code_language} programming language, maintaining the same functionality.
224+
3. Verify that the converted code is displayed in the output.
225+
226+
Please make sure only the converted code should be included in the output.
227+
"""
228+
229+
# Prompt Templates
230+
code_template = template
231+
232+
# LLM Chains definition
233+
# Create a chain that generates the code
234+
gemini_completion = self.model.generate_content(code_template)
235+
logger.info("Text generation completed successfully.")
236+
237+
if gemini_completion:
238+
# Extracted code from the palm completion
239+
code = gemini_completion.text
240+
extracted_code = self.utils.extract_code(code)
241+
242+
# Check if the code or extracted code is not empty or null
243+
if not code or not extracted_code:
244+
raise Exception("Error: Generated code or extracted code is empty or null.")
245+
else:
246+
return extracted_code
247+
else:
248+
raise Exception("Error in code conversion: Please enter a valid code.")
249+
else:
250+
logger.error("Error in code conversion: Please enter a valid code and language.")
251+
except Exception as exception:
252+
logger.error(f"Error in code conversion: {traceback.format_exc()}")

libs/general_utils.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -122,11 +122,11 @@ def check_compilers(self, language):
122122

123123
compilers = {
124124
"python": ["python", "--version"],
125-
"nodejs": ["node", "--version"],
125+
"javascript": ["node", "--version"],
126126
"c": ["gcc", "--version"],
127127
"c++": ["g++", "--version"],
128-
"csharp": ["csc", "--version"],
129-
"go": ["go", "version"],
128+
"c#": ["csc", "--version"],
129+
"go": ["go", "--version"],
130130
"ruby": ["ruby", "--version"],
131131
"java": ["java", "--version"],
132132
"kotlin": ["kotlinc", "--version"],
@@ -135,8 +135,8 @@ def check_compilers(self, language):
135135
}
136136

137137
if language not in compilers:
138-
logger.error("Invalid language selected.")
139-
st.toast("Invalid language selected.", icon="❌")
138+
logger.error(f"Invalid language selected. {language} not found in compilers list.")
139+
st.toast(f"Invalid language selected. {language} not found in compilers list.", icon="❌")
140140
return False
141141

142142
compiler = subprocess.run(compilers[language], capture_output=True, text=True)
@@ -171,9 +171,11 @@ def run_code(self,code, language):
171171
return output.stdout + output.stderr
172172

173173
elif language == "C" or language == "C++":
174+
174175
ext = ".c" if language == "C" else ".cpp"
175176
compiler = "gcc" if language == "C" else "g++"
176177
std = "-std=c11" if language == "C" else "-std=c++17"
178+
177179
with tempfile.NamedTemporaryFile(mode="w", suffix=ext, delete=True) as src_file:
178180
src_file.write(code)
179181
src_file.flush()

libs/openai_langchain.py

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,4 +229,78 @@ def fix_generated_code(self, code_snippet, code_language, fix_instructions=""):
229229
logger.error("Error in code fixing: Please enter a valid code and language.")
230230
except Exception as exception:
231231
st.toast(f"Error in code fixing: {exception}", icon="❌")
232-
logger.error(f"Error in code fixing: {traceback.format_exc()}")
232+
logger.error(f"Error in code fixing: {traceback.format_exc()}")
233+
234+
def convert_generated_code(self, code_snippet, code_language):
235+
"""
236+
Function to convert the generated code to a different language using the palm API.
237+
"""
238+
try:
239+
# Check for valid code
240+
if not code_snippet or len(code_snippet) == 0:
241+
logger.error("Error in code conversion: Please enter a valid code.")
242+
return
243+
244+
logger.info(f"Converting code")
245+
if code_snippet and len(code_snippet) > 0:
246+
logger.info(f"Converting code {code_snippet[:100]}... to language {code_language}")
247+
248+
# Improved instructions template
249+
template = f"""
250+
Task: Convert the code snippet provided below to the {code_language} programming language, following the given instructions:
251+
252+
{code_snippet}
253+
254+
Instructions for Conversion:
255+
1. Identify the functionality of the original code.
256+
2. Translate the code into the {code_language} programming language, maintaining the same functionality.
257+
3. Verify that the converted code is displayed in the output.
258+
259+
Please make sure only the converted code should be included in the output.
260+
"""
261+
262+
# Prompt Templates
263+
code_template = template
264+
265+
# LLM Chains definition
266+
# Create a chain that fixed the code
267+
fix_generated_template = PromptTemplate(
268+
input_variables=['code_prompt', 'code_language'],
269+
template=code_template
270+
)
271+
272+
fix_generated_chain = LLMChain(
273+
llm=self.lite_llm,
274+
prompt=fix_generated_template,
275+
output_key='fixed_code',
276+
memory=self.memory,
277+
verbose=True
278+
)
279+
280+
# Prepare the input for the chain
281+
input_data = {
282+
'code_prompt': code_snippet,
283+
'code_language': code_language
284+
}
285+
286+
# Run the chain
287+
output = fix_generated_chain.run(input_data)
288+
289+
logger.info("Text generation completed successfully.")
290+
291+
if output:
292+
# Extracted code from the palm completion
293+
fixed_code = output['code_fix']
294+
extracted_code = self.utils.extract_code(fixed_code)
295+
296+
# Check if the code or extracted code is not empty or null
297+
if not code_snippet or not extracted_code:
298+
raise Exception("Error: Generated code or extracted code is empty or null.")
299+
else:
300+
return extracted_code
301+
else:
302+
raise Exception("Error in code conversion: Please enter a valid code.")
303+
else:
304+
logger.error("Error in code conversion: Please enter a valid code and language.")
305+
except Exception as exception:
306+
logger.error(f"Error in code conversion: {traceback.format_exc()}")

libs/palmai.py

Lines changed: 62 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -204,8 +204,7 @@ def fix_generated_code(self, code, code_language, fix_instructions=""):
204204
max_output_tokens=self.max_output_tokens,
205205
top_k=self.top_k,
206206
top_p=self.top_p,
207-
stop_sequences=[],
208-
safety_settings=[{"category":"HARM_CATEGORY_DEROGATORY","threshold":1},{"category":"HARM_CATEGORY_TOXICITY","threshold":1},{"category":"HARM_CATEGORY_VIOLENCE","threshold":2},{"category":"HARM_CATEGORY_SEXUAL","threshold":2},{"category":"HARM_CATEGORY_MEDICAL","threshold":2},{"category":"HARM_CATEGORY_DANGEROUS","threshold":2}],
207+
stop_sequences=[]
209208
)
210209

211210
if palm_completion:
@@ -225,4 +224,64 @@ def fix_generated_code(self, code, code_language, fix_instructions=""):
225224
logger.error("Error in code fixing: Please enter a valid code and language.")
226225
except Exception as exception:
227226
st.toast(f"Error in code fixing: {exception}", icon="❌")
228-
logger.error(f"Error in code fixing: {traceback.format_exc()}")
227+
logger.error(f"Error in code fixing: {traceback.format_exc()}")
228+
229+
def convert_generated_code(self, code, code_language):
230+
"""
231+
Function to convert the generated code to a different language using the palm API.
232+
"""
233+
try:
234+
# Check for valid code
235+
if not code or len(code) == 0:
236+
logger.error("Error in code conversion: Please enter a valid code.")
237+
return
238+
239+
logger.info(f"Converting code")
240+
if code and len(code) > 0:
241+
logger.info(f"Converting code {code[:100]}... to language {code_language}")
242+
243+
# Improved instructions template
244+
template = f"""
245+
Task: Convert the code snippet provided below to the {code_language} programming language, following the given instructions:
246+
247+
{code}
248+
249+
Instructions for Conversion:
250+
1. Identify the functionality of the original code.
251+
2. Translate the code into the {code_language} programming language, maintaining the same functionality.
252+
3. Verify that the converted code is displayed in the output.
253+
254+
Please make sure only the converted code should be included in the output.
255+
"""
256+
257+
# Prompt Templates
258+
code_template = template
259+
260+
# LLM Chains definition
261+
# Create a chain that generates the code
262+
palm_completion = palm.generate_text(
263+
model=self.model,
264+
prompt=code_template,
265+
temperature=self.temperature,
266+
max_output_tokens=self.max_output_tokens,
267+
top_k=self.top_k,
268+
top_p=self.top_p,
269+
stop_sequences=[]
270+
)
271+
272+
if palm_completion:
273+
# Extracted code from the palm completion
274+
code = palm_completion.result
275+
extracted_code = self.utils.extract_code(code)
276+
277+
# Check if the code or extracted code is not empty or null
278+
if not code or not extracted_code:
279+
raise Exception("Error: Generated code or extracted code is empty or null.")
280+
else:
281+
return extracted_code
282+
else:
283+
raise Exception("Error in code conversion: Please enter a valid code.")
284+
else:
285+
logger.error("Error in code conversion: Please enter a valid code and language.")
286+
except Exception as exception:
287+
logger.error(f"Error in code conversion: {traceback.format_exc()}")

script.py

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@ def main():
281281

282282
with st.form('code_controls_form'):
283283
# Create columns for alignment
284-
file_name_col, save_code_col,generate_code_col,run_code_col,fix_code_col = st.columns(5)
284+
file_name_col, save_code_col,generate_code_col,run_code_col,debug_code_col,convert_code_col = st.columns(6)
285285

286286
# Input Box (for entering the file name) in the first column
287287
with file_name_col:
@@ -352,11 +352,11 @@ def main():
352352
st.session_state.generated_code = ""
353353
logger.error(f"Please select a valid AI option selected '{st.session_state.ai_option}' option")
354354

355-
# Fix Code button in the fourth column
356-
with fix_code_col:
357-
fix_submitted = st.form_submit_button("Debug")
355+
# Debug Code button in the fourth column
356+
with debug_code_col:
357+
debug_submitted = st.form_submit_button("Debug")
358358
ai_llm_selected = None
359-
if fix_submitted:
359+
if debug_submitted:
360360
# checking for the selected AI option
361361
if st.session_state.ai_option == "Palm AI":
362362
ai_llm_selected = st.session_state.palm_langchain
@@ -372,6 +372,23 @@ def main():
372372
logger.info(f"Fixing code with instructions: {st.session_state.code_fix_instructions}")
373373
st.session_state.generated_code = ai_llm_selected.fix_generated_code(st.session_state.generated_code, st.session_state.code_language,st.session_state.code_fix_instructions)
374374

375+
# Debug Code button in the fourth column
376+
with convert_code_col:
377+
convert_submitted = st.form_submit_button("Convert")
378+
ai_llm_selected = None
379+
if convert_submitted:
380+
# checking for the selected AI option
381+
if st.session_state.ai_option == "Palm AI":
382+
ai_llm_selected = st.session_state.palm_langchain
383+
elif st.session_state.ai_option == "Gemini AI":
384+
ai_llm_selected = st.session_state.gemini_langchain
385+
elif st.session_state.ai_option == "Open AI":
386+
ai_llm_selected = st.session_state.openai_langchain
387+
388+
logger.info(f"Converting code with instructions: {st.session_state.code_fix_instructions}")
389+
st.session_state.generated_code = ai_llm_selected.convert_generated_code(st.session_state.generated_code, st.session_state.code_language)
390+
391+
375392
# Run Code button in the fourth column
376393
with run_code_col:
377394
execute_submitted = st.form_submit_button("Execute")

0 commit comments

Comments
 (0)