File size: 4,482 Bytes
43fabf7 | 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 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | import os
import numpy as np
import onnxruntime as ort
import sentencepiece as spm
# =========================
# PATH
# =========================
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ENCODER_PATH = os.path.join(BASE_DIR, "encoder_model.onnx")
DECODER_PATH = os.path.join(BASE_DIR, "decoder_model.onnx")
SPM_PATH = os.path.join(BASE_DIR, "spm.model")
# =========================
# SETTINGS
# =========================
MAX_INPUT_LEN = 256
MAX_OUTPUT_LEN = 256
PAD_ID = 0
UNK_ID = 1
BOS_ID = 2
EOS_ID = 3
# =========================
# CHECK FILES
# =========================
for path in [ENCODER_PATH, DECODER_PATH, SPM_PATH]:
if not os.path.exists(path):
raise FileNotFoundError(f"Không tìm thấy file: {path}")
# =========================
# LOAD TOKENIZER
# =========================
print("Đang load tokenizer...")
sp = spm.SentencePieceProcessor()
sp.load(SPM_PATH)
print(
f"Tokenizer: vocab={sp.get_piece_size()} | "
f"PAD={sp.pad_id()} BOS={sp.bos_id()} EOS={sp.eos_id()}"
)
# =========================
# ONNX RUNTIME
# =========================
print("Đang load ONNX model...")
providers = ["CPUExecutionProvider"]
encoder_session = ort.InferenceSession(
ENCODER_PATH,
providers=providers
)
decoder_session = ort.InferenceSession(
DECODER_PATH,
providers=providers
)
# =========================
# SHOW MODEL INFO
# =========================
print("\nEncoder inputs:")
for x in encoder_session.get_inputs():
print(" ", x.name, x.shape, x.type)
print("\nDecoder inputs:")
for x in decoder_session.get_inputs():
print(" ", x.name, x.shape, x.type)
# =========================
# TRANSLATE
# =========================
def translate(text):
text = text.strip()
if not text:
return ""
# ---------------------------------
# 1. ENCODE INPUT
# ---------------------------------
src_ids = sp.encode(text, out_type=int)
# Giới hạn context
src_ids = src_ids[:MAX_INPUT_LEN - 2]
# BART format
src_ids = [BOS_ID] + src_ids + [EOS_ID]
input_ids = np.array(
[src_ids],
dtype=np.int64
)
attention_mask = np.ones_like(
input_ids,
dtype=np.int64
)
# ---------------------------------
# 2. ENCODER
# ---------------------------------
encoder_outputs = encoder_session.run(
None,
{
"input_ids": input_ids,
"attention_mask": attention_mask
}
)
encoder_hidden_states = encoder_outputs[0]
# ---------------------------------
# 3. DECODER GREEDY
# ---------------------------------
generated = [BOS_ID]
for _ in range(MAX_OUTPUT_LEN):
decoder_input_ids = np.array(
[generated],
dtype=np.int64
)
decoder_inputs = {}
# Tự map input để tránh lệch tên
for inp in decoder_session.get_inputs():
name = inp.name
if name == "input_ids":
decoder_inputs[name] = decoder_input_ids
elif "encoder_hidden_states" in name:
decoder_inputs[name] = encoder_hidden_states
elif "encoder_attention_mask" in name:
decoder_inputs[name] = attention_mask
decoder_outputs = decoder_session.run(
None,
decoder_inputs
)
# Output đầu tiên là logits
logits = decoder_outputs[0]
# Lấy token cuối
next_token_logits = logits[0, -1, :]
next_token = int(
np.argmax(next_token_logits)
)
generated.append(next_token)
if next_token == EOS_ID:
break
# ---------------------------------
# 4. DECODE
# ---------------------------------
output_ids = generated[1:]
if EOS_ID in output_ids:
output_ids = output_ids[
:output_ids.index(EOS_ID)
]
result = sp.decode(output_ids)
return result
# =========================
# INTERACTIVE CLI
# =========================
print("\nEN → VI translator v2 ready")
print("Type 'exit' để thoát\n")
while True:
try:
text = input("EN > ").strip()
except (KeyboardInterrupt, EOFError):
print("\nBye")
break
if text.lower() in ["exit", "quit", "q"]:
print("Bye")
break
if not text:
continue
result = translate(text)
print("VI >", result)
print() |