CoolFace
Apppublic

MLDeveloper/code_compiler

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
translator.py33 linesDownload Raw Back to root
1import requests2import os3 4# Your Hugging Face API token (Replace 'your_token_here' with your actual token)5 6API_TOKEN = os.getenv("HF_API_TOKEN") 7 8# Define model and API endpoint9MODEL_ID = "bigcode/starcoder"10API_URL = f"https://api-inference.huggingface.co/models/{MODEL_ID}"11HEADERS = {"Authorization": f"Bearer {API_TOKEN}"}12 13def translate_code(code_snippet, source_lang, target_lang):14    """15    Translate code using Hugging Face API (No local download needed).16    """17    prompt = f"Translate the following {source_lang} code to {target_lang}:\n\n{code_snippet}\n\nTranslated {target_lang} Code:"18 19    response = requests.post(API_URL, headers=HEADERS, json={"inputs": prompt})20 21    if response.status_code == 200:22        return response.json()[0]["generated_text"]23    else:24        return f"Error: {response.status_code}, {response.text}"25 26# Example usage27source_code = """28def add(a, b):29    return a + b30"""31translated_code = translate_code(source_code, "Python", "Java")32print("Translated Java Code:\n", translated_code)33