Update src/streamlit_app.py
Browse files- src/streamlit_app.py +75 -52
src/streamlit_app.py
CHANGED
|
@@ -1,47 +1,52 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
import transformers
|
| 3 |
from transformers import pipeline
|
| 4 |
import os
|
| 5 |
|
| 6 |
-
#
|
| 7 |
st.set_page_config(page_title="Kriolu AI Hub", layout="wide")
|
| 8 |
-
|
| 9 |
-
# Read token from environment
|
| 10 |
token = os.environ.get("token")
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
# This prevents the app from reloading the model every time you click a button
|
| 14 |
@st.cache_resource
|
| 15 |
def load_pipeline(task, model_path, **kwargs):
|
| 16 |
return pipeline(task, model=model_path, tokenizer=model_path, token=token, **kwargs)
|
| 17 |
|
| 18 |
-
|
|
|
|
| 19 |
model_path = f'Iscte-Sintra/{model_name}'
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
| 32 |
pipe = load_pipeline("fill-mask", f"Iscte-Sintra/{model_name}")
|
| 33 |
return pipe(text, top_k=top_k)
|
| 34 |
|
| 35 |
-
|
|
|
|
| 36 |
model_path = f'Iscte-Sintra/{model_name}'
|
| 37 |
-
|
| 38 |
-
#
|
| 39 |
-
# NLLB uses codes like 'por_Latn', MBart uses 'pt_XX'
|
| 40 |
if "nllb" in model_name:
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
elif "m2m100" in model_name:
|
| 46 |
pipe = pipeline(
|
| 47 |
"translation",
|
|
@@ -49,15 +54,27 @@ def instantiate_translation_model(model_name: str, text: str, src_lg: str, tgt_l
|
|
| 49 |
tokenizer=model_path,
|
| 50 |
token=token
|
| 51 |
)
|
| 52 |
-
|
| 53 |
pipe.tokenizer.src_lang = src_lg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
else:
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
|
|
|
| 61 |
def build_translation_page(model_name):
|
| 62 |
st.title(f"🌍 {model_name}: Tradução")
|
| 63 |
|
|
@@ -70,40 +87,46 @@ def build_translation_page(model_name):
|
|
| 70 |
elif "m2m100" in model_name:
|
| 71 |
lang_map = {
|
| 72 |
"Português": "pt",
|
| 73 |
-
"
|
| 74 |
}
|
| 75 |
|
| 76 |
else: # mBART
|
| 77 |
lang_map = {
|
| 78 |
"Português": "pt_XX",
|
| 79 |
-
"
|
| 80 |
}
|
| 81 |
|
| 82 |
col1, col2 = st.columns(2)
|
| 83 |
with col1:
|
| 84 |
-
src_label = st.selectbox("Língua de Origem", list(lang_map.keys())
|
| 85 |
with col2:
|
| 86 |
-
tgt_label = st.selectbox("Língua de Destino", list(lang_map.keys())
|
| 87 |
|
| 88 |
text = st.text_area("Texto de entrada", "Katxór sta trás di pórta.", height=100)
|
| 89 |
-
|
| 90 |
if st.button("Traduzir"):
|
| 91 |
if not text.strip():
|
| 92 |
st.warning("Introduza texto!")
|
| 93 |
return
|
| 94 |
-
|
| 95 |
with st.spinner("A traduzir..."):
|
| 96 |
try:
|
| 97 |
-
result = instantiate_translation_model(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
st.success("Resultado:")
|
| 99 |
st.write(result)
|
| 100 |
except Exception as e:
|
| 101 |
st.error(f"Erro: {e}")
|
| 102 |
|
|
|
|
| 103 |
def build_decoder_page(model_name):
|
| 104 |
st.title(f"✍️ {model_name}: Geração de Texto")
|
| 105 |
max_length = st.sidebar.slider("Máximo de Tokens", 10, 200, 50)
|
| 106 |
-
num_seq = st.sidebar.number_input(
|
| 107 |
text = st.text_area("Prompt", "Katxór sta trás di pórta.")
|
| 108 |
|
| 109 |
if st.button("Gerar"):
|
|
@@ -111,32 +134,32 @@ def build_decoder_page(model_name):
|
|
| 111 |
try:
|
| 112 |
results = instantiate_gpt2(model_name, max_length, num_seq, text)
|
| 113 |
for res in results:
|
| 114 |
-
st.info(res[
|
| 115 |
except Exception as e:
|
| 116 |
st.error(f"Erro: {e}")
|
| 117 |
|
|
|
|
| 118 |
def build_encoder_page(model_name):
|
| 119 |
st.title(f"🔍 {model_name}: Fill-Mask")
|
| 120 |
top_k = st.sidebar.slider("Top K sugestões", 1, 5, 3)
|
| 121 |
-
|
| 122 |
-
mask_token = "
|
| 123 |
st.write(f"Use o token **{mask_token}** para a palavra em falta.")
|
| 124 |
-
|
| 125 |
input_text = st.text_input("Frase", f"Katxór sta trás di {mask_token}.")
|
| 126 |
|
| 127 |
if st.button("Prever"):
|
| 128 |
try:
|
| 129 |
results = instantiate_encoder(model_name, top_k, input_text)
|
| 130 |
for res in results:
|
| 131 |
-
st.write(f"✅ **{res['token_str']}** (
|
| 132 |
-
except Exception
|
| 133 |
st.error(f"Certifique-se que usou o token {mask_token}")
|
| 134 |
|
| 135 |
-
#
|
| 136 |
-
|
| 137 |
model_dict = {
|
| 138 |
-
|
| 139 |
-
"GPT2_v1.18": "Decoder",
|
| 140 |
"LLM-kea-v1.0": "Decoder",
|
| 141 |
"Modelo-Traducao-kea-ptpt-v1.0": "Encoder-Decoder",
|
| 142 |
"nllb-v1.0": "Encoder-Decoder",
|
|
@@ -152,4 +175,4 @@ if arch == "Encoder":
|
|
| 152 |
elif arch == "Encoder-Decoder":
|
| 153 |
build_translation_page(selected_model)
|
| 154 |
else:
|
| 155 |
-
build_decoder_page(selected_model)
|
|
|
|
| 1 |
import streamlit as st
|
|
|
|
| 2 |
from transformers import pipeline
|
| 3 |
import os
|
| 4 |
|
| 5 |
+
# ---------------- CONFIG ----------------
|
| 6 |
st.set_page_config(page_title="Kriolu AI Hub", layout="wide")
|
|
|
|
|
|
|
| 7 |
token = os.environ.get("token")
|
| 8 |
|
| 9 |
+
# ---------------- CACHE ----------------
|
|
|
|
| 10 |
@st.cache_resource
|
| 11 |
def load_pipeline(task, model_path, **kwargs):
|
| 12 |
return pipeline(task, model=model_path, tokenizer=model_path, token=token, **kwargs)
|
| 13 |
|
| 14 |
+
# ---------------- DECODER ----------------
|
| 15 |
+
def instantiate_gpt2(model_name, max_length_, num_return_sequences, text):
|
| 16 |
model_path = f'Iscte-Sintra/{model_name}'
|
| 17 |
+
pipe = load_pipeline("text-generation", model_path)
|
| 18 |
+
|
| 19 |
+
return pipe(
|
| 20 |
+
text,
|
| 21 |
+
max_new_tokens=max_length_,
|
| 22 |
+
num_return_sequences=num_return_sequences,
|
| 23 |
+
do_sample=True,
|
| 24 |
+
top_p=0.95,
|
| 25 |
+
top_k=50
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# ---------------- ENCODER ----------------
|
| 29 |
+
def instantiate_encoder(model_name, top_k, text):
|
| 30 |
pipe = load_pipeline("fill-mask", f"Iscte-Sintra/{model_name}")
|
| 31 |
return pipe(text, top_k=top_k)
|
| 32 |
|
| 33 |
+
# ---------------- TRANSLATION ----------------
|
| 34 |
+
def instantiate_translation_model(model_name, text, src_lg, tgt_lg):
|
| 35 |
model_path = f'Iscte-Sintra/{model_name}'
|
| 36 |
+
|
| 37 |
+
# ---- NLLB ----
|
|
|
|
| 38 |
if "nllb" in model_name:
|
| 39 |
+
pipe = pipeline(
|
| 40 |
+
"translation",
|
| 41 |
+
model=model_path,
|
| 42 |
+
tokenizer=model_path,
|
| 43 |
+
token=token,
|
| 44 |
+
src_lang=src_lg,
|
| 45 |
+
tgt_lang=tgt_lg
|
| 46 |
+
)
|
| 47 |
+
return pipe(text)[0]["translation_text"]
|
| 48 |
+
|
| 49 |
+
# ---- M2M100 ----
|
| 50 |
elif "m2m100" in model_name:
|
| 51 |
pipe = pipeline(
|
| 52 |
"translation",
|
|
|
|
| 54 |
tokenizer=model_path,
|
| 55 |
token=token
|
| 56 |
)
|
| 57 |
+
|
| 58 |
pipe.tokenizer.src_lang = src_lg
|
| 59 |
+
result = pipe(
|
| 60 |
+
text,
|
| 61 |
+
forced_bos_token_id=pipe.tokenizer.get_lang_id(tgt_lg)
|
| 62 |
+
)
|
| 63 |
+
return result[0]["translation_text"]
|
| 64 |
+
|
| 65 |
+
# ---- MBART ----
|
| 66 |
else:
|
| 67 |
+
pipe = pipeline(
|
| 68 |
+
"translation",
|
| 69 |
+
model=model_path,
|
| 70 |
+
tokenizer=model_path,
|
| 71 |
+
token=token,
|
| 72 |
+
src_lang=src_lg,
|
| 73 |
+
tgt_lang=tgt_lg
|
| 74 |
+
)
|
| 75 |
+
return pipe(text)[0]["translation_text"]
|
| 76 |
|
| 77 |
+
# ---------------- UI: TRANSLATION ----------------
|
| 78 |
def build_translation_page(model_name):
|
| 79 |
st.title(f"🌍 {model_name}: Tradução")
|
| 80 |
|
|
|
|
| 87 |
elif "m2m100" in model_name:
|
| 88 |
lang_map = {
|
| 89 |
"Português": "pt",
|
| 90 |
+
"Inglês": "en" # m2m100 does NOT support kea
|
| 91 |
}
|
| 92 |
|
| 93 |
else: # mBART
|
| 94 |
lang_map = {
|
| 95 |
"Português": "pt_XX",
|
| 96 |
+
"Inglês": "en_XX"
|
| 97 |
}
|
| 98 |
|
| 99 |
col1, col2 = st.columns(2)
|
| 100 |
with col1:
|
| 101 |
+
src_label = st.selectbox("Língua de Origem", list(lang_map.keys()))
|
| 102 |
with col2:
|
| 103 |
+
tgt_label = st.selectbox("Língua de Destino", list(lang_map.keys()))
|
| 104 |
|
| 105 |
text = st.text_area("Texto de entrada", "Katxór sta trás di pórta.", height=100)
|
| 106 |
+
|
| 107 |
if st.button("Traduzir"):
|
| 108 |
if not text.strip():
|
| 109 |
st.warning("Introduza texto!")
|
| 110 |
return
|
| 111 |
+
|
| 112 |
with st.spinner("A traduzir..."):
|
| 113 |
try:
|
| 114 |
+
result = instantiate_translation_model(
|
| 115 |
+
model_name,
|
| 116 |
+
text,
|
| 117 |
+
lang_map[src_label],
|
| 118 |
+
lang_map[tgt_label]
|
| 119 |
+
)
|
| 120 |
st.success("Resultado:")
|
| 121 |
st.write(result)
|
| 122 |
except Exception as e:
|
| 123 |
st.error(f"Erro: {e}")
|
| 124 |
|
| 125 |
+
# ---------------- UI: DECODER ----------------
|
| 126 |
def build_decoder_page(model_name):
|
| 127 |
st.title(f"✍️ {model_name}: Geração de Texto")
|
| 128 |
max_length = st.sidebar.slider("Máximo de Tokens", 10, 200, 50)
|
| 129 |
+
num_seq = st.sidebar.number_input("Sequências", 1, 5, 1)
|
| 130 |
text = st.text_area("Prompt", "Katxór sta trás di pórta.")
|
| 131 |
|
| 132 |
if st.button("Gerar"):
|
|
|
|
| 134 |
try:
|
| 135 |
results = instantiate_gpt2(model_name, max_length, num_seq, text)
|
| 136 |
for res in results:
|
| 137 |
+
st.info(res["generated_text"])
|
| 138 |
except Exception as e:
|
| 139 |
st.error(f"Erro: {e}")
|
| 140 |
|
| 141 |
+
# ---------------- UI: ENCODER ----------------
|
| 142 |
def build_encoder_page(model_name):
|
| 143 |
st.title(f"🔍 {model_name}: Fill-Mask")
|
| 144 |
top_k = st.sidebar.slider("Top K sugestões", 1, 5, 3)
|
| 145 |
+
|
| 146 |
+
mask_token = "<mask>" if "RoBERTa" in model_name else "[MASK]"
|
| 147 |
st.write(f"Use o token **{mask_token}** para a palavra em falta.")
|
| 148 |
+
|
| 149 |
input_text = st.text_input("Frase", f"Katxór sta trás di {mask_token}.")
|
| 150 |
|
| 151 |
if st.button("Prever"):
|
| 152 |
try:
|
| 153 |
results = instantiate_encoder(model_name, top_k, input_text)
|
| 154 |
for res in results:
|
| 155 |
+
st.write(f"✅ **{res['token_str']}** ({res['score']:.2%})")
|
| 156 |
+
except Exception:
|
| 157 |
st.error(f"Certifique-se que usou o token {mask_token}")
|
| 158 |
|
| 159 |
+
# ---------------- MAIN ----------------
|
|
|
|
| 160 |
model_dict = {
|
| 161 |
+
"RoBERTa-Kriolu": "Encoder",
|
| 162 |
+
"GPT2_v1.18": "Decoder",
|
| 163 |
"LLM-kea-v1.0": "Decoder",
|
| 164 |
"Modelo-Traducao-kea-ptpt-v1.0": "Encoder-Decoder",
|
| 165 |
"nllb-v1.0": "Encoder-Decoder",
|
|
|
|
| 175 |
elif arch == "Encoder-Decoder":
|
| 176 |
build_translation_page(selected_model)
|
| 177 |
else:
|
| 178 |
+
build_decoder_page(selected_model)
|