Spaces:
Sleeping
Sleeping
| import requests | |
| import os | |
| # Retrieve Hugging Face API token from environment variable | |
| API_TOKEN = os.getenv("HF_API_TOKEN") | |
| if not API_TOKEN: | |
| raise ValueError("⚠️ Error: Hugging Face API token is missing! Set the HF_API_TOKEN environment variable.") | |
| # Define model and API endpoint | |
| MODEL_ID = "bigcode/starcoder" | |
| 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 Hugging Face API. | |
| """ | |
| prompt = f"Translate the following {source_lang} code to {target_lang}:\n\n{code_snippet}\n\nTranslated {target_lang} Code:\n" | |
| try: | |
| response = requests.post(API_URL, headers=HEADERS, json={"inputs": prompt}) | |
| if response.status_code == 200: | |
| response_json = response.json() | |
| if isinstance(response_json, list) and len(response_json) > 0: | |
| generated_text = response_json[0].get("generated_text", "") | |
| translated_code = generated_text.split(f"Translated {target_lang} Code:\n")[-1].strip() | |
| return translated_code | |
| else: | |
| return "⚠️ Error: Unexpected response format from API." | |
| elif response.status_code == 400: | |
| return "⚠️ Error: Invalid request. Check input format." | |
| 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 access to this model." | |
| elif response.status_code == 503: | |
| return "⚠️ Error: Model is loading. Please wait a moment and try again." | |
| else: | |
| return f"⚠️ 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) | |