import openai import os import gradio as gr import requests import json openai.api_key = "your_openai_api_key" def translate_code(code, from_language, to_language): context = f"Translate the following {from_language} code snippet to {to_language}:\n\n{code}\n\nKeep the translation accurate and idiomatic, considering language-specific best practices." data = { "model": "gpt-3.5-turbo", "messages": [{"role": "system", "content": "You are a code translator assistant that translates code snippets between programming languages."}, {"role": "user", "content": context}], "max_tokens": 300, "temperature": 0.6, "top_p": 1, "frequency_penalty": 0, "presence_penalty": 0, } headers = { "Content-Type": "application/json", "Authorization": f"Bearer {openai.api_key}", } try: response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, data=json.dumps(data)) response.raise_for_status() result = response.json() return result["choices"][0]["message"]["content"].strip() except requests.exceptions.HTTPError as e: return f"Error: {str(e)}\nResponse: {response.text}" inputs = [ gr.inputs.Textarea(placeholder="Enter your code here...", label="Code"), gr.inputs.Dropdown(choices=["Python", "JavaScript", "Java", "C++", "C#", "Ruby", "Go", "PHP"], label="From Language"), gr.inputs.Dropdown(choices=["Python", "JavaScript", "Java", "C++", "C#", "Ruby", "Go", "PHP"], label="To Language"), ] outputs = gr.outputs.Textarea(label="Translated Code") gr.Interface(fn=translate_code, inputs=inputs, outputs=outputs, title="Code Translator", description="Translate code between different programming languages. Note that the translations might not always be perfect and may require some manual adjustments.", theme="compact").launch()