File size: 2,522 Bytes
c1216bb
 
 
45c61b1
 
 
 
 
 
c1216bb
45c61b1
07ad560
 
 
45c61b1
 
4dfb3f4
45c61b1
 
 
 
07ad560
 
45c61b1
4dfb3f4
45c61b1
 
07ad560
45c61b1
 
07ad560
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45c61b1
 
07ad560
45c61b1
 
4dfb3f4
45c61b1
 
 
 
 
 
 
 
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
import requests
import os

def get_api_token():
    """Fetch API token from environment variable."""
    api_token = os.getenv("HF_API_TOKEN")
    if not api_token:
        raise ValueError("⚠️ API Token is missing! Please set HF_API_TOKEN as an environment variable.")
    return api_token

API_TOKEN = get_api_token()

# Use StarCoder or CodeLlama for better code translation
MODEL_ID = "bigcode/starcoder"  # Alternative: "codellama/CodeLlama-7b-hf"
API_URL = f"https://api-inference.huggingface.co/models/{MODEL_ID}"
HEADERS = {"Authorization": f"Bearer {API_TOKEN}"}

def translate_code(code_snippet, source_lang, target_lang):
    """Translate code using the Hugging Face API."""
    prompt = (
        f"### Task: Convert {source_lang} code to {target_lang} code.\n\n"
        f"### {source_lang} Code:\n```{source_lang.lower()}\n{code_snippet}\n```\n\n"
        f"### {target_lang} Code:\n```{target_lang.lower()}\n"
    )

    try:
        response = requests.post(API_URL, headers=HEADERS, json={"inputs": prompt})

        if response.status_code == 200:
            result = response.json()

            # Ensure we extract the generated code correctly
            if isinstance(result, list) and result:
                generated_text = result[0].get("generated_text", "")
                
                # Extract translated code properly
                translated_code = generated_text.split(f"### {target_lang} Code:")[-1].strip()
                return translated_code if translated_code else "⚠️ No translated code received."
            
            return "⚠️ Unexpected API response format."

        elif response.status_code == 400:
            return "⚠️ Error: Bad request. Check your input."
        elif response.status_code == 401:
            return "⚠️ Error: Unauthorized. Check your API token."
        elif response.status_code == 403:
            return "⚠️ Error: Access Forbidden. You may need special model access."
        elif response.status_code == 503:
            return "⚠️ Error: Model is loading. Please wait and try again."
        else:
            return f"⚠️ API Error {response.status_code}: {response.text}"

    except requests.exceptions.RequestException as e:
        return f"⚠️ Network Error: {str(e)}"

# Example usage
if __name__ == "__main__":
    source_code = """
def add(a, b):
    return a + b
"""
    translated_code = translate_code(source_code, "Python", "Java")
    print("Translated Java Code:\n", translated_code)