Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import MarianMTModel, MarianTokenizer
|
3 |
+
|
4 |
+
model_name_en_to_ja = "Helsinki-NLP/opus-mt-en-jap"
|
5 |
+
model_en_to_ja = MarianMTModel.from_pretrained(model_name_en_to_ja)
|
6 |
+
tokenizer_en_to_ja = MarianTokenizer.from_pretrained(model_name_en_to_ja)
|
7 |
+
|
8 |
+
model_name_ja_to_en = "Helsinki-NLP/opus-mt-jap-en"
|
9 |
+
model_ja_to_en = MarianMTModel.from_pretrained(model_name_ja_to_en)
|
10 |
+
tokenizer_ja_to_en = MarianTokenizer.from_pretrained(model_name_ja_to_en)
|
11 |
+
|
12 |
+
# 日本語と英語の判定はできるが、翻訳精度は高くないです。
|
13 |
+
# 日本語と英語を両方入力した場合も挙動がおかしいです。
|
14 |
+
def translate(text):
|
15 |
+
# 文字列がアルファベットは判定
|
16 |
+
if text.strip()[0].isalpha():
|
17 |
+
inputs = tokenizer_en_to_ja(text, return_tensors="pt", padding=True)
|
18 |
+
translated = model_en_to_ja.generate(**inputs)
|
19 |
+
translated_text = tokenizer_en_to_ja.batch_decode(translated, skip_special_tokens=True)
|
20 |
+
else:
|
21 |
+
inputs = tokenizer_ja_to_en(text, return_tensors="pt", padding=True)
|
22 |
+
translated = model_ja_to_en.generate(**inputs)
|
23 |
+
translated_text = tokenizer_ja_to_en.batch_decode(translated, skip_special_tokens=True)
|
24 |
+
return translated_text[0]
|
25 |
+
|
26 |
+
gr.Interface(fn=translate, inputs="textbox", outputs="textbox", title="日⇔英 相互翻訳").launch()
|