Spaces:
Runtime error
Runtime error
File size: 3,904 Bytes
0a20b40 e2ba056 0a20b40 e2ba056 0a20b40 e2ba056 0a20b40 e2ba056 3bc20c4 e2ba056 | 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 | # app.py
import os
import gradio as gr
import torch
import numpy as np
from transformers import AutoTokenizer, AutoModel
# Use a tiny model by default to avoid Space startup timeouts.
# You can switch to "bert-base-uncased" from the Space Settings -> Secrets with MODEL_NAME.
MODEL_NAME = os.getenv("MODEL_NAME", "prajjwal1/bert-tiny")
_tokenizer = None
_model = None
def get_model_and_tokenizer():
global _tokenizer, _model
if _tokenizer is None or _model is None:
_tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
_model = AutoModel.from_pretrained(MODEL_NAME)
_model.eval()
return _tokenizer, _model
def clean_text(s: str) -> str:
"""
Normalize text by:
1) Removing NON-ASCII characters (keep only ASCII).
2) Lowercasing.
"""
if not s:
return ""
s_ascii = s.encode("ascii", "ignore").decode("ascii")
return s_ascii.lower()
def bert_embed(text: str):
tokenizer, model = get_model_and_tokenizer()
cleaned = clean_text(text)
if not cleaned.strip():
return cleaned, "No content after cleaning.", [], "0", "0"
with torch.no_grad():
encoded = tokenizer(
cleaned,
return_tensors="pt",
add_special_tokens=True,
padding=False,
truncation=True,
max_length=512,
)
outputs = model(**encoded)
last_hidden = outputs.last_hidden_state # (1, L, H)
embeddings = last_hidden.squeeze(0).cpu().numpy() # (L, H)
input_ids = encoded["input_ids"].squeeze(0).tolist()
tokens = tokenizer.convert_ids_to_tokens(input_ids)
table = []
for tok, vec in zip(tokens, embeddings):
table.append([
tok,
int(vec.shape[0]),
np.round(vec[:8], 6).tolist(), # preview first 8 dims
vec.tolist(), # full vector
])
seq_len, dim = embeddings.shape
summary = f"Sequence length: {seq_len} tokens | Embedding dimension: {dim} | Model: {MODEL_NAME}"
return cleaned, summary, table, str(seq_len), str(dim)
with gr.Blocks(title="BERT Tokenizer & Embeddings") as demo:
gr.Markdown(
"""
# BERT Tokenizer & Embeddings
This Space **removes non-ASCII**, **lowercases**, tokenizes with **BERT**, and shows tokens + embeddings.
- Default model: `prajjwal1/bert-tiny` for fast startup
(set `MODEL_NAME=bert-base-uncased` in Space settings if you want full BERT).
- **embedding_preview_first_8** shows the first 8 dimensions.
- **embedding_full_vector** contains the complete embedding vector for each token.
"""
)
with gr.Row():
inp = gr.Textbox(
label="Input text",
placeholder="Type or paste text here...",
lines=6,
)
with gr.Row():
btn = gr.Button("Transform with BERT", variant="primary")
with gr.Accordion("Cleaned Text", open=False):
cleaned_out = gr.Textbox(label="Cleaned text", lines=4)
summary_out = gr.Markdown()
df = gr.Dataframe(
label="Tokens & Embeddings",
headers=["token", "embedding_dim", "embedding_preview_first_8", "embedding_full_vector"],
interactive=False,
wrap=True,
)
with gr.Row():
seq_len_out = gr.Textbox(label="Sequence length", interactive=False)
dim_out = gr.Textbox(label="Embedding dimension", interactive=False)
btn.click(
fn=bert_embed,
inputs=[inp],
outputs=[cleaned_out, summary_out, df, seq_len_out, dim_out],
)
# On Hugging Face Spaces, just running this file is enough;
# still, explicitly launch with the provided PORT to be safe.
if __name__ == "__main__":
port = int(os.getenv("PORT", "7860"))
demo.queue().launch(
server_name="0.0.0.0",
server_port=port,
show_error=True
)
|