File size: 1,227 Bytes
ccfb540
 
 
 
 
 
 
 
 
 
 
 
 
0ec4113
ccfb540
 
 
 
 
 
 
0ec4113
 
ccfb540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3f7d78
0e1a02b
 
ccfb540
0ec4113
ccfb540
 
 
 
0e1a02b
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
import os
import openai
import gradio as gr

# Read the OpenAI API key from the environment variable
openai.api_key = os.environ["OPENAI_API_KEY"]

def translate_code(code, from_language, to_language):
    prompt = f"Translate the following {from_language} code to {to_language}:\n{code}\n---\nTranslated code:\n"

    response = openai.Completion.create(
        engine="davinci-codex",
        prompt=prompt,
        max_tokens=200,
        n=1,
        stop=None,
        temperature=0.5,
    )

    translated_code = response.choices[0].text.strip()
    return translated_code
   except Exception as e:
        return f"Error: {str(e)}"

languages = [
    "Python",
    "Javascript",
    "PHP",
    "Java",
    "Ruby",
    "Golang",
    "C#",
    "SQL",
    "Perl",
]

iface = gr.Interface(
    fn=translate_code,
    inputs=[
        gr.inputs.Textbox(lines=20, label="Original Code"),
        gr.inputs.Dropdown(choices=languages, label="From Language"),
        gr.inputs.Dropdown(choices=languages, label="To Language"),
    ],
    outputs=gr.outputs.Textbox(label="Translated Code"),
    title="Code Translator",
    description="Translate code between different programming languages using OpenAI.",
)

iface.launch()