-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgpt_translator.py
More file actions
157 lines (140 loc) · 5.47 KB
/
gpt_translator.py
File metadata and controls
157 lines (140 loc) · 5.47 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import os
import json
from openai import OpenAI
class GPTTranslator:
def __init__(self, src, dest):
self.src = src.capitalize()
self.dest = dest.capitalize()
# Create a client using the environment variable
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise EnvironmentError(
"Please set the OPENAI_API_KEY environment variable."
)
self.client = OpenAI(api_key=api_key)
# Define the function (tool) schema for word translation
self.tools_word = [
{
"type": "function",
"function": {
"name": "translate",
"description": (
f"Gets the dictionary form of a {self.src} word and provides "
f"its common translations into {self.dest}. "
"If the word is unclear, guess the most likely interpretation."
),
"parameters": {
"type": "object",
"properties": {
"base_form": {
"type": "string",
"description": (
"The base (dictionary) form of the word in "
f"{self.src}."
),
},
"translations": {
"type": "array",
"items": {"type": "string"},
"description": (
f"Likely {self.dest} translations of the base "
f"{self.src} word, even if the word is rare or "
"has multiple meanings."
),
},
},
"required": ["base_form", "translations"],
},
},
}
]
# Define the function (tool) schema for phrase translation
self.tools_phrase = [
{
"type": "function",
"function": {
"name": "translate",
"description": (
f"Translates a phrase or sentence from {self.src} into "
f"{self.dest}."
),
"parameters": {
"type": "object",
"properties": {
"translation": {
"type": "string",
"description": f"Accurate and natural-sounding "
f"{self.dest} translation of the original {self.src} "
"sentence.",
},
},
"required": ["translation"],
},
},
}
]
def translate(self, word: str):
num_words = len(word.split())
if num_words == 1:
tools = self.tools_word
temperature = 0.1
top_p = 1.0
message = (
f"Given the {self.src} word {repr(word)}, identify its base "
f"(dictionary) form in {self.src} and provide several common "
f"translations into {self.dest}. "
"If there are multiple possible meanings, list the most likely ones. "
"If you are unsure, make a best guess based on similar words."
)
else:
tools = self.tools_phrase
temperature = 0.5
top_p = 0.9
message = (
f"Translate the following sentence from {self.src} to {self.dest}: "
f"{repr(word)}. Return only the translation, without explanation. Use "
f"natural, idiomatic {self.dest}."
)
try:
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": message,
}
],
tools=tools,
tool_choice="auto",
temperature=temperature,
top_p=top_p,
)
tool_calls = response.choices[0].message.tool_calls
if not tool_calls:
return {"error": "No tool call returned."}
arguments = json.loads(tool_calls[0].function.arguments)
return arguments
except Exception as e:
return {"error": str(e)}
def run_language_lookup_loop():
src = "Croatian"
dest = "Swedish"
print(f"Enter {src} words to see their base form and {dest} translations.")
print("Type 'exit' to quit.\n")
translator = GPTTranslator(src, dest)
while True:
word = input(f"{src} word: ").strip()
if word.lower() == "exit":
print("Goodbye!")
break
if not word:
continue
result = translator.translate(word)
if "error" in result:
print("Error:", result["error"])
else:
print(f"Base form: {result['base_form']}")
print("Translations:", ", ".join(result["translations"]))
print()
if __name__ == "__main__":
run_language_lookup_loop()