Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import MarianMTModel, MarianTokenizer
|
| 3 |
+
|
| 4 |
+
# Modèle de traduction : anglais → français par défaut
|
| 5 |
+
model_name = "Helsinki-NLP/opus-mt-en-fr"
|
| 6 |
+
tokenizer = MarianTokenizer.from_pretrained(model_name)
|
| 7 |
+
model = MarianMTModel.from_pretrained(model_name)
|
| 8 |
+
|
| 9 |
+
def translate(text, target_lang):
|
| 10 |
+
# Choisir le modèle selon la langue cible
|
| 11 |
+
if target_lang == "fr":
|
| 12 |
+
model_name = "Helsinki-NLP/opus-mt-en-fr"
|
| 13 |
+
elif target_lang == "en":
|
| 14 |
+
model_name = "Helsinki-NLP/opus-mt-fr-en"
|
| 15 |
+
else:
|
| 16 |
+
return "Langue non supportée pour l'instant"
|
| 17 |
+
|
| 18 |
+
# Recharger modèle si changé
|
| 19 |
+
global tokenizer, model
|
| 20 |
+
if model_name != model.name_or_path:
|
| 21 |
+
tokenizer = MarianTokenizer.from_pretrained(model_name)
|
| 22 |
+
model = MarianMTModel.from_pretrained(model_name)
|
| 23 |
+
model.name_or_path = model_name
|
| 24 |
+
|
| 25 |
+
# Traduction
|
| 26 |
+
batch = tokenizer([text], return_tensors="pt", padding=True)
|
| 27 |
+
gen = model.generate(**batch)
|
| 28 |
+
translated = tokenizer.batch_decode(gen, skip_special_tokens=True)[0]
|
| 29 |
+
return translated
|
| 30 |
+
|
| 31 |
+
# Interface Gradio
|
| 32 |
+
iface = gr.Interface(
|
| 33 |
+
fn=translate,
|
| 34 |
+
inputs=[
|
| 35 |
+
gr.Textbox(lines=2, placeholder="Tapez le texte ici..."),
|
| 36 |
+
gr.Dropdown(["fr", "en"], label="Langue cible")
|
| 37 |
+
],
|
| 38 |
+
outputs="text",
|
| 39 |
+
title="MyTranslator",
|
| 40 |
+
description="Traduction simple avec détection de langue."
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
iface.launch()
|