DEV Community

Cover image for Simplifying Code Translation with Lyzr Automata
harshit-lyzr
harshit-lyzr

Posted on

Simplifying Code Translation with Lyzr Automata

In today’s interconnected world, developers often find themselves needing to translate code from one programming language to another. Whether it’s for compatibility reasons, platform migration, or simply to leverage the strengths of a different language, code translation can be a challenging task. However, with the advent of advanced AI technologies, such as the Lyzr Code Convertor, this process is becoming more accessible and efficient than ever before.

Key Features
Multi-Language Support: Lyzr Code Convertor supports a wide range of programming languages, including Python, JavaScript, Java, C, C++, C#, and more. Whatever your preferred language, Lyzr has you covered.
Simple Interface: With a clean and intuitive interface, Lyzr makes it easy to input your code snippet and select the target language for translation.
AI-powered Translation: Leveraging state-of-the-art AI models, Lyzr accurately translates code snippets while preserving their functionality and structure.

Let’s Start
Imports and Environment Setup:

import streamlit as st
from lyzr_automata.ai_models.openai import OpenAIModel
from lyzr_automata import Agent,Task
from lyzr_automata.pipelines.linear_sync_pipeline import LinearSyncPipeline
from PIL import Image
from dotenv import load_dotenv
import os

load_dotenv()
api = os.getenv("OPENAI_API_KEY")
Enter fullscreen mode Exit fullscreen mode

The code starts by importing necessary libraries:
streamlit as st: Used for building the web app interface.
lyzr_automata libraries: Provide functionalities for interacting with OpenAI API and building the conversion pipeline.
PIL.Image: Used for handling images.
dotenv: Used for loading environment variables (likely the OpenAI API key).
load_dotenv() reads the .env file (assuming it exists) and sets environment variables.
api = os.getenv("OPENAI_API_KEY") retrieves the OpenAI API key from the environment variable.

OpenAI Model and Language Options:


open_ai_text_completion_model = OpenAIModel(
    api_key=api,
    parameters={
        "model": "gpt-4-turbo-preview",
        "temperature": 0.2,
        "max_tokens": 1500,
    },
)
languages=["Python","Javascript","Java","C","C++","C#","Ruby","Swift","Kotlin","PHP","TypeScript","Go,","Rust","Perl","R","Haskell","Scala"]
Enter fullscreen mode Exit fullscreen mode

open_ai_text_completion_model creates an instance of the OpenAIModel class with the API key and sets parameters for the GPT-4 model:
Temperature: 0.2 (controls randomness in generated text)
Maximum tokens: 1500 (limits the output length)
A list of supported programming languages (languages) is defined.

User Input and Selection:

topic = st.sidebar.text_area("Enter Code Here",height=200,placeholder="print('Hello World!!')")
output_lang = st.sidebar.selectbox("Select Language",options=languages,index=None,placeholder="Programming Language")
Enter fullscreen mode Exit fullscreen mode

topic = st.sidebar.text_area creates a text area in the sidebar for users to enter their code. It sets a height of 200 pixels and a placeholder text "print('Hello World!!')".
output_lang = st.sidebar.selectbox creates a dropdown menu in the sidebar for users to select the target programming language for conversion. It provides the languages list as options and allows a placeholder "Programming Language".

Agent Creation:

developer_agent = Agent(
        role="Code expert",
        prompt_persona=f"You are an Expert developer in every language."
    )
Enter fullscreen mode Exit fullscreen mode

developer_agent creates an Agent object representing the role of a "Code expert" with a prompt persona describing their expertise in various languages.

Task and Pipeline Creation:

prompt=(f"Convert the below code snippet to {output_lang}: {topic}.[!IMPORTANT] only generate code nothing else."
f"If code conversion is not possible then write code conversion not possible message in 20 words")

 code_conversion_task = Task(
        name="Code Conversion",
        model=open_ai_text_completion_model,
        agent=developer_agent,
        instructions=prompt,
    )

    output = LinearSyncPipeline(
            name="Code Conversion Pipeline",
            completion_message="Code Converted",
            tasks=[code_conversion_task],
    ).run()
Enter fullscreen mode Exit fullscreen mode

code_conversion_task creates a Task object named "Code Conversion".
It assigns the open_ai_text_completion_model, developer_agent, and the defined prompt to the task.
LinearSyncPipeline creates a pipeline named "Code Conversion Pipeline" with the following properties:
completion_message: "Code Converted" (displayed after successful conversion)
tasks: A list containing the single code_conversion_task

Displaying Output:

st.markdown(output[0]['task_output'])
Enter fullscreen mode Exit fullscreen mode

st.markdown(output[0]['task_output']) retrieves the task output (converted code) from the first element (index 0) of the output list and displays it as markdown text.

The Code Convertor using Lyzr Automata represents a significant advancement in code translation technology, offering developers a fast, reliable, and user-friendly solution for converting code between different programming languages. Whether you’re a seasoned developer or just starting your coding journey, Code Convertor using Lyzr is an invaluable tool for simplifying the complexities of code translation.

try it now: https://lyzr-code-convertor.streamlit.app/

For more information explore the website: Lyzr

Top comments (0)