""" ML in Elixir — Bumblebee + Hugging Face (Gradio/Python companion) This Gradio app mirrors the Livebook template's Bumblebee sections. Deploy to HF Spaces with sdk: gradio. ## Skills - `hf_cli.md` – Hugging Face CLI usage - `hf_jobs.md` – Running workloads on HF Jobs - `training_trl.md` – TRL model training - `hf_dataset_viewer.md` – Dataset Viewer API - `gradio.md` – Gradio UI integration - *(Full catalog at https://skills.sh/huggingface/skills)* """ import gradio as gr import torch import torch.nn.functional as F from transformers import ( pipeline, AutoTokenizer, AutoModel, AutoModelForCausalLM, ) import numpy as np # ─── Load pipelines ────────────────────────────────────────────── sentiment = pipeline( "sentiment-analysis", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english", ) fill_mask = pipeline("fill-mask", model="google-bert/bert-base-uncased") ner = pipeline("ner", model="dslim/bert-base-NER", aggregation_strategy="simple") zero_shot = pipeline("zero-shot-classification", model="facebook/bart-large-mnli") text_gen = pipeline("text-generation", model="openai-community/gpt2") # Image classification img_cls = pipeline("image-classification", model="google/vit-base-patch16-224") # Speech-to-text asr = pipeline("automatic-speech-recognition", model="openai/whisper-tiny") # Embeddings emb_tok = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2") emb_model = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2") def embed(texts): inputs = emb_tok(texts, padding=True, truncation=True, return_tensors="pt") with torch.no_grad(): out = emb_model(**inputs) mask = inputs["attention_mask"].unsqueeze(-1) embs = (out.last_hidden_state * mask).sum(1) / mask.sum(1) return F.normalize(embs, p=2, dim=1) # ─── Gradio functions ──────────────────────────────────────────── def classify_sentiment(text): if not text.strip(): return {} results = sentiment(text) return {r["label"]: float(r["score"]) for r in results} def run_fill_mask(text): if "[MASK]" not in text: return "Please include [MASK] in your text." results = fill_mask(text) lines = [ f"**{r['score']:.4f}** `{r['token_str']}` — {r['sequence']}" for r in results ] return "\n\n".join(lines) def run_ner(text): if not text.strip(): return "Enter text with entities." entities = ner(text) lines = [ f"- **{e['entity_group']}** `{e['word']}` (score: {e['score']:.4f})" for e in entities ] return "\n".join(lines) if lines else "No entities found." def run_zero_shot(text, labels_str): if not text.strip() or not labels_str.strip(): return {} labels = [l.strip() for l in labels_str.split(",") if l.strip()] result = zero_shot(text, labels) return {l: float(s) for l, s in zip(result["labels"], result["scores"])} def run_text_gen(prompt, max_tokens, temperature): if not prompt.strip(): return "" output = text_gen( prompt, max_new_tokens=int(max_tokens), temperature=float(temperature), do_sample=True, ) return output[0]["generated_text"] def run_similarity(text1, text2): if not text1.strip() or not text2.strip(): return 0.0 embs = embed([text1, text2]) score = F.cosine_similarity(embs[0:1], embs[1:2]).item() return float(score) def classify_image(image): if image is None: return {} results = img_cls(image) return {r["label"]: float(r["score"]) for r in results} def transcribe_audio(audio): if audio is None: return "Upload an audio file." result = asr(audio) return result["text"] def run_hf_jobs_demo(): """Run a tiny sentiment‑analysis demo using a fixed phrase. Uses the pre‑loaded ``sentiment`` pipeline defined earlier. Returns a human‑readable label + score string. """ result = sentiment("Hugging Face Jobs are awesome!")[0] return f"{result['label']}: {result['score']:.4f}" # ─── Build Gradio UI ───────────────────────────────────────────── with gr.Blocks( title="🐝 ML in Elixir — Bumblebee Companion", theme=gr.themes.Soft(), ) as demo: gr.Markdown( """ # 🐝 ML in Elixir — Bumblebee + Hugging Face Python/Gradio companion to the [Elixir Livebook template](https://github.com). Each tab mirrors a Bumblebee section from the Livebook. """ ) with gr.Tab("😊 Sentiment Analysis"): gr.Markdown("*Mirrors `Bumblebee.Text.Classification` in Elixir*") with gr.Row(): sa_input = gr.Textbox( label="Text", value="Elixir is the best language for building scalable ML systems!", lines=2, ) sa_output = gr.Label(label="Sentiment") sa_input.change(classify_sentiment, inputs=sa_input, outputs=sa_output) with gr.Tab("🔍 Fill-Mask (BERT)"): gr.Markdown("*Mirrors `Bumblebee.Text.fill_mask` in Elixir*") with gr.Row(): fm_input = gr.Textbox( label="Text with [MASK]", value="Elixir is a [MASK] language." ) fm_output = gr.Markdown(label="Predictions") fm_input.change(run_fill_mask, inputs=fm_input, outputs=fm_output) with gr.Tab("🏷️ Named Entity Recognition"): gr.Markdown("*Mirrors `Bumblebee.Text.TokenClassification` in Elixir*") with gr.Row(): ner_input = gr.Textbox( label="Text", value="Sean Moriarity wrote Machine Learning in Elixir for Pragmatic Bookshelf.", lines=2, ) ner_output = gr.Markdown(label="Entities") ner_input.change(run_ner, inputs=ner_input, outputs=ner_output) with gr.Tab("🎯 Zero-Shot Classification"): gr.Markdown("*Mirrors `Bumblebee.Text.ZeroShotClassification` in Elixir*") with gr.Row(): with gr.Column(): zs_text = gr.Textbox( label="Text", value="Nx brings numerical computing to the BEAM for ML pipelines.", lines=3, ) zs_labels = gr.Textbox( label="Labels (comma-separated)", value="technology, sports, politics, science, finance", ) zs_output = gr.Label(label="Classification") zs_text.change(run_zero_shot, inputs=[zs_text, zs_labels], outputs=zs_output) with gr.Tab("✍️ Text Generation (GPT-2)"): gr.Markdown("*Mirrors `Bumblebee.Text.generation` in Elixir*") with gr.Row(): with gr.Column(): tg_prompt = gr.Textbox( label="Prompt", value="Machine learning in Elixir is" ) tg_tokens = gr.Slider(10, 100, value=50, step=1, label="Max tokens") tg_temp = gr.Slider(0.1, 2.0, value=0.7, step=0.1, label="Temperature") tg_output = gr.Textbox(label="Generated Text", lines=5) tg_prompt.change( run_text_gen, inputs=[tg_prompt, tg_tokens, tg_temp], outputs=tg_output, ) with gr.Tab("📐 Embedding Similarity"): gr.Markdown("*Mirrors `Bumblebee.Text.TextEmbedding` in Elixir*") with gr.Row(): emb1 = gr.Textbox( label="Text A", value="Nx provides numerical computing for Elixir" ) emb2 = gr.Textbox( label="Text B", value="Axon is a neural network library built on Nx" ) sim_output = gr.Number(label="Cosine Similarity") for inp in [emb1, emb2]: inp.change(run_similarity, inputs=[emb1, emb2], outputs=sim_output) with gr.Tab("🖼️ Image Classification"): gr.Markdown("*Mirrors `Bumblebee.Vision.ImageClassification` in Elixir*") with gr.Row(): img_input = gr.Image(label="Upload image", type="pil") img_output = gr.Label(label="Classification") img_input.change(classify_image, inputs=img_input, outputs=img_output) with gr.Tab("🎙️ Speech-to-Text (Whisper)"): gr.Markdown("*Mirrors `Bumblebee.Audio.speech_to_text` in Elixir*") with gr.Row(): audio_input = gr.Audio(label="Upload audio", type="filepath") audio_output = gr.Textbox(label="Transcription", lines=5) audio_input.change(transcribe_audio, inputs=audio_input, outputs=audio_output) # ----------- Free‑tier HF Jobs demo (runs locally, no credit needed) ----------- with gr.Tab("🚀 HF Jobs Demo"): gr.Markdown("*Free‑tier demo: runs a sentiment analysis on a fixed string*") demo_btn = gr.Button("Run Demo") demo_output = gr.Label(label="Result") demo_btn.click(run_hf_jobs_demo, inputs=None, outputs=demo_output) if __name__ == "__main__": demo.launch()