Spaces:
Sleeping
Sleeping
File size: 1,476 Bytes
c1216bb 45c61b1 c1216bb 45c61b1 4dfb3f4 45c61b1 4dfb3f4 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 |
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()
MODEL_ID = "codellama/CodeLlama-7b-Instruct-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\n{code_snippet}\n\n"
f"### {target_lang} Code:\n"
)
try:
response = requests.post(API_URL, headers=HEADERS, json={"inputs": prompt})
if response.status_code == 200:
result = response.json()
return result[0].get("generated_text", "⚠️ No translated code received.")
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)
|