-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path08_code_translation_cli.py
More file actions
60 lines (44 loc) · 1.59 KB
/
Copy path08_code_translation_cli.py
File metadata and controls
60 lines (44 loc) · 1.59 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import argparse
import os
import sys
from google import genai
from dotenv import load_dotenv
load_dotenv()
def translate_code(file_path):
if not os.path.exists(file_path):
print(f"Error: File {file_path} not found.")
return
with open(file_path, 'r', encoding='utf-8') as f:
python_code = f.read()
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
prompt = f"""
Translate the following Python code into idiomatic JavaScript (Node.js).
Maintain the same logic and functionality.
Return ONLY the JavaScript code.
Python Code:
{python_code}
"""
try:
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=prompt
)
js_code = response.text.replace("```javascript", "").replace("```js", "").replace("```", "").strip()
js_file_path = file_path.replace(".py", ".js")
if js_file_path == file_path:
js_file_path += ".js"
with open(js_file_path, 'w', encoding='utf-8') as f:
f.write(js_code)
print(f"Translated code saved to {js_file_path}")
except Exception as e:
print(f"Error: {e}")
def main():
parser = argparse.ArgumentParser(description="Code Translation CLI (Python -> JS)")
parser.add_argument("file", help="Path to the Python script")
args = parser.parse_args()
if not os.getenv("GEMINI_API_KEY"):
print("Error: GEMINI_API_KEY not found.")
sys.exit(1)
translate_code(args.file)
if __name__ == "__main__":
main()