Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
|
| 4 |
+
# Translation pipeline (mBART)
|
| 5 |
+
translation_pipeline = pipeline(
|
| 6 |
+
"translation", model="facebook/mbart-large-50-many-to-many-mmt"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
# Text generation pipeline (GPT-2)
|
| 10 |
+
generation_pipeline = pipeline(
|
| 11 |
+
"text-generation", model="gpt2"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
LANG_CODES = {
|
| 15 |
+
"English": "en_XX",
|
| 16 |
+
"Spanish": "es_XX",
|
| 17 |
+
"Portuguese": "pt_XX",
|
| 18 |
+
"Italian": "it_IT",
|
| 19 |
+
"Korean": "ko_KR",
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
def translate(text, src, tgt):
|
| 23 |
+
if src == tgt:
|
| 24 |
+
return text
|
| 25 |
+
out = translation_pipeline(text, src_lang=LANG_CODES[src], tgt_lang=LANG_CODES[tgt])
|
| 26 |
+
return out[0]["translation_text"]
|
| 27 |
+
|
| 28 |
+
def generate(text, max_length=100, temperature=1.0, top_p=0.95):
|
| 29 |
+
out = generation_pipeline(
|
| 30 |
+
text, max_length=int(max_length), temperature=float(temperature), top_p=float(top_p)
|
| 31 |
+
)
|
| 32 |
+
return out[0]["generated_text"]
|
| 33 |
+
|
| 34 |
+
with gr.Blocks() as demo:
|
| 35 |
+
gr.Markdown("## 🌎 Translation & Text Generation Demo")
|
| 36 |
+
with gr.Tab("Translation"):
|
| 37 |
+
src_lang = gr.Dropdown(list(LANG_CODES.keys()), label="Source Language", value="English")
|
| 38 |
+
tgt_lang = gr.Dropdown(list(LANG_CODES.keys()), label="Target Language", value="Spanish")
|
| 39 |
+
inp = gr.Textbox(label="Text to Translate")
|
| 40 |
+
out = gr.Textbox(label="Translation")
|
| 41 |
+
btn = gr.Button("Translate")
|
| 42 |
+
btn.click(fn=translate, inputs=[inp, src_lang, tgt_lang], outputs=out)
|
| 43 |
+
with gr.Tab("Text Generation"):
|
| 44 |
+
prompt = gr.Textbox(label="Prompt")
|
| 45 |
+
gen_out = gr.Textbox(label="Generated Text")
|
| 46 |
+
max_len = gr.Slider(10, 256, value=100, label="Max Length")
|
| 47 |
+
temp = gr.Slider(0.5, 1.5, value=1.0, label="Temperature")
|
| 48 |
+
topp = gr.Slider(0.5, 1.0, value=0.95, label="Top-p")
|
| 49 |
+
gen_btn = gr.Button("Generate")
|
| 50 |
+
gen_btn.click(
|
| 51 |
+
fn=generate,
|
| 52 |
+
inputs=[prompt, max_len, temp, topp],
|
| 53 |
+
outputs=gen_out,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
demo.launch()
|