File size: 9,335 Bytes
27acc7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
"""
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()