Spaces:
Runtime error
Runtime error
Download app.py from alantv/bertsample: direct link, hf CLI and curl.
- Browser
- Download file 3.9 kB
-
https://huggingface.co/spaces/alantv/bertsample/resolve/main/app.py
- Command line
-
hf download hf://spaces/alantv/bertsample/app.py
-
curl -L -o app.py https://huggingface.co/spaces/alantv/bertsample/resolve/main/app.py
3.9 kB
| # 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 | |
| ) | |