Spaces:
Sleeping
Sleeping
Update translator.py
Browse files- translator.py +34 -35
translator.py
CHANGED
@@ -1,42 +1,41 @@
|
|
1 |
-
import streamlit as st
|
2 |
import requests
|
3 |
import os
|
4 |
-
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
5 |
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
|
|
|
|
10 |
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
prompt = f"Translate this {source_lang} code to {target_lang}:\n\n{code_snippet}"
|
16 |
-
|
17 |
-
# Tokenize and generate translation
|
18 |
-
inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=512)
|
19 |
-
outputs = model.generate(**inputs, max_length=512)
|
20 |
-
|
21 |
-
# Decode the output
|
22 |
-
translated_code = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
23 |
-
return translated_code
|
24 |
-
|
25 |
-
# Streamlit UI
|
26 |
-
st.title("🔄 Code Translator (Python, Java, C++, C)")
|
27 |
-
st.write("Translate code between Python, Java, C++, and C.")
|
28 |
|
29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
-
|
32 |
-
|
33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
|
|
|
|
1 |
import requests
|
2 |
import os
|
|
|
3 |
|
4 |
+
def get_api_token():
|
5 |
+
"""Fetch API token from environment variable."""
|
6 |
+
api_token = os.getenv("HF_API_TOKEN")
|
7 |
+
if not api_token:
|
8 |
+
raise ValueError("⚠️ API Token is missing! Please set HF_API_TOKEN as an environment variable.")
|
9 |
+
return api_token
|
10 |
|
11 |
+
API_TOKEN = get_api_token()
|
12 |
+
MODEL_ID = "codellama/CodeLlama-7b-Instruct-hf"
|
13 |
+
API_URL = f"https://api-inference.huggingface.co/models/{MODEL_ID}"
|
14 |
+
HEADERS = {"Authorization": f"Bearer {API_TOKEN}"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
+
def translate_code(code_snippet, source_lang, target_lang):
|
17 |
+
"""Translate code using the Hugging Face API."""
|
18 |
+
prompt = (
|
19 |
+
f"### Task: Convert {source_lang} code to {target_lang} code.\n\n"
|
20 |
+
f"### {source_lang} Code:\n\n{code_snippet}\n\n"
|
21 |
+
f"### {target_lang} Code:\n"
|
22 |
+
)
|
23 |
|
24 |
+
try:
|
25 |
+
response = requests.post(API_URL, headers=HEADERS, json={"inputs": prompt})
|
26 |
+
if response.status_code == 200:
|
27 |
+
result = response.json()
|
28 |
+
return result[0].get("generated_text", "⚠️ No translated code received.")
|
29 |
+
else:
|
30 |
+
return f"⚠️ API Error {response.status_code}: {response.text}"
|
31 |
+
except requests.exceptions.RequestException as e:
|
32 |
+
return f"⚠️ Network Error: {str(e)}"
|
33 |
|
34 |
+
# Example usage
|
35 |
+
if __name__ == "__main__":
|
36 |
+
source_code = """
|
37 |
+
def add(a, b):
|
38 |
+
return a + b
|
39 |
+
"""
|
40 |
+
translated_code = translate_code(source_code, "Python", "Java")
|
41 |
+
print("Translated Java Code:\n", translated_code)
|