Spaces:
Runtime error
Runtime error
Update app.py
Browse files20 unmodified lines21222324252627282930317 unmodified lines3940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213320 unmodified linesdef clean_text(s: str) -> str:"""Normalize text by:1) Removing NON-ASCII characters (common preprocessing meaning).2) Lowercasing.NOTE: The prompt says "remove ascii characters and lower case".In typical NLP pipelines this is interpreted as "remove NON-ASCII characters and lowercase".That's what's implemented here. Adjust as needed."""if not s:return ""7 unmodified linescleaned = clean_text(text)if not cleaned.strip():return (cleaned,"No content after cleaning.",[],"—","—",)# Tokenizewith torch.no_grad():encoded = tokenizer(cleaned,return_tensors="pt",add_special_tokens=True,padding=False,truncation=True,max_length=512,)outputs = model(**encoded)# [batch=1, seq_len, hidden_size]last_hidden = outputs.last_hidden_state # (1, L, 768) for base BERTembeddings = last_hidden.squeeze(0).cpu().numpy() # (L, 768)# Convert IDs to tokensinput_ids = encoded["input_ids"].squeeze(0).tolist()tokens = tokenizer.convert_ids_to_tokens(input_ids)# Build a simple table: token, first 8 dims (for readability), full vector lengthtable = []for tok, vec in zip(tokens, embeddings):table.append([tok,vec.shape[0],vec[:8].round(6).tolist(), # preview first 8 dimsvec.tolist(), # full embedding vector])seq_len = embeddings.shape[0]dim = embeddings.shape[1]summary = f"Sequence length: {seq_len} tokens | Embedding dimension: {dim} | Model: {MODEL_NAME}"# Gradio expects a list-of-lists for Dataframe; provide headers tooheaders = ["token", "embedding_dim", "embedding_preview_first_8", "embedding_full_vector"]return cleaned, summary, [headers] + table, str(seq_len), str(dim)# Gradio UIwith gr.Blocks(title="BERT Tokenizer & Embeddings") as demo:gr.Markdown("""# BERT Tokenizer & Embeddings (Gradio)Paste text, we'll **remove non-ASCII characters**, **lowercase**, tokenize with **BERT** (`bert-base-uncased`),and show both tokens and their embeddings.- **embedding_preview_first_8** shows the first 8 dimensions (for readability).- **embedding_full_vector** contains the complete embedding for each token (length 768).""")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",interactive=False,wrap=True,height=400)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],)if __name__ == "__main__":# For local dev: http://127.0.0.1:7860demo.launch()20 unmodified lines21222324252627287 unmodified lines3637383920 unmodified linesdef clean_text(s: str) -> str:"""Normalize text by:1) Removing NON-ASCII characters.2) Lowercasing."""if not s:return ""7 unmodified linescleaned = clean_text(text)if not cleaned.strip():retu
app.py+2-96