Spaces:
Sleeping
Sleeping
| 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) | |