File size: 3,969 Bytes
60d789c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import os
import gradio as gr
from langchain_groq import ChatGroq
from langchain_core.prompts import ChatPromptTemplate
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# List of programming languages
LANGUAGES = [
    'Python', 'JavaScript', 'Java', 'C++', 'Ruby', 
    'Go', 'Rust', 'Swift', 'Kotlin', 'TypeScript', 
    'PHP', 'C#', 'Scala', 'Dart', 'Perl'
]

class CodeConverter:
    def __init__(self):
        """

        Initialize the Groq language model and prompt template

        """
        # Initialize Groq ChatModel
        self.llm = ChatGroq(
            temperature=0,
            model_name="llama3-groq-8b-8192-tool-use-preview",
            groq_api_key=os.getenv('GROQ_API_KEY')
        )

        # Create a prompt template for code conversion
        self.prompt = ChatPromptTemplate.from_messages([
            ("system", """You are an expert code translator. 

            Your task is to convert code from one programming language to another.

            

            Guidelines:

            - Preserve the original logic and structure

            - Maintain the same functionality

            - Use idiomatic code for the target language

            - Handle any language-specific nuances

            - Provide clean, readable, and efficient code

            

            If direct translation is not possible, provide the most equivalent implementation."""),
            ("human", """Convert the code from {source_language} to {target_language}:



Code to convert:

```{source_language}

{input_code}

```



Please provide the converted code in {target_language}.""")
        ])

    def convert_code(self, input_code, source_lang, target_lang):
        """

        Convert code between programming languages

        """
        try:
            # Limit input code to 200 lines
            input_lines = input_code.split('\n')
            if len(input_lines) > 200:
                return "Error: Code exceeds 200 lines limit"
            
            # Create the chain
            chain = self.prompt | self.llm
            
            # Generate the conversion
            result = chain.invoke({
                "source_language": source_lang,
                "target_language": target_lang,
                "input_code": input_code
            })
            
            # Extract and clean the converted code
            converted_code = result.content.strip()
            
            # Remove potential code block markdown
            if converted_code.startswith('```') and converted_code.endswith('```'):
                converted_code = converted_code.strip('```').strip()
            
            return converted_code
        
        except Exception as e:
            return f"An error occurred: {str(e)}"

def create_code_converter():
    """

    Create Gradio interface for code conversion

    """
    # Initialize code converter
    converter = CodeConverter()
    
    # Create Gradio interface
    demo = gr.Interface(
        fn=converter.convert_code,
        inputs=[
            gr.Textbox(
                label="Enter your code", 
                lines=10, 
                placeholder="Paste your code here (max 200 lines)"
            ),
            gr.Dropdown(
                choices=LANGUAGES, 
                label="Source Language"
            ),
            gr.Dropdown(
                choices=LANGUAGES, 
                label="Target Language"
            )
        ],
        outputs=gr.Textbox(
            label="Converted Code", 
            lines=10
        ),
        title="🖥️ Code Converter",
        description="Convert code between different programming languages using Groq and Langchain"
    )
    
    return demo

# Launch the Gradio app
if __name__ == "__main__":
    converter = create_code_converter()
    converter.launch(share=True)