Spaces:
Running
Running
Upload translator.py
Browse files- translator.py +35 -0
translator.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
import os
|
3 |
+
|
4 |
+
# Your Hugging Face API token (Replace 'your_token_here' with your actual token)
|
5 |
+
|
6 |
+
API_TOKEN = os.getenv("HF_API_TOKEN")
|
7 |
+
|
8 |
+
# Define model and API endpoint
|
9 |
+
MODEL_ID = "bigcode/starcoder"
|
10 |
+
API_URL = f"https://api-inference.huggingface.co/models/{MODEL_ID}"
|
11 |
+
HEADERS = {"Authorization": f"Bearer {API_TOKEN}"}
|
12 |
+
|
13 |
+
def 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 usage
|
27 |
+
source_code = """
|
28 |
+
def add(a, b):
|
29 |
+
return a + b
|
30 |
+
"""
|
31 |
+
translated_code = translate_code(source_code, "Python", "Java")
|
32 |
+
print("Translated Java Code:\n", translated_code)
|
33 |
+
|
34 |
+
|
35 |
+
|