File size: 2,396 Bytes
6b25170
 
 
 
b27f0b5
6b25170
 
ca73ba7
6b25170
 
 
 
 
 
 
 
 
fafd715
 
6b25170
 
 
 
 
 
 
 
 
 
b27f0b5
 
 
 
6b25170
 
 
 
 
 
 
 
 
62d782d
 
08cfbf0
9fdf61c
62d782d
 
6b25170
 
 
 
 
62d782d
 
 
6b25170
7bb3454
 
6b25170
9405c46
6b25170
3805905
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
# Necessary imports
import gradio as gr
from transformers import pipeline


# Load the zero-shot classification model
classifier = pipeline(
    "zero-shot-classification", model="MoritzLaurer/ModernBERT-large-zeroshot-v2.0"
)


# Function to perform zero-shot classification
def ZeroShotTextClassification(text_input, candidate_labels):
    """
    Performs zero-shot classification on the given text input using the provided candidate labels.

    Args:
        - text_input (str): The input text to classify.
        - candidate_labels (str): A comma-separated string of candidate labels.

    Returns:
      dict: A dictionary containing the predicted labels as keys and their corresponding scores as values.
    """
    # Split the candidate labels
    labels = [label.strip(" ") for label in candidate_labels.split(",")]

    # Perform zero-shot classification
    prediction = classifier(text_input, labels)

    return {
        prediction["labels"][i]: prediction["scores"][i]
        for i in range(len(prediction["labels"]))
    }


# Examples to display in the interface
examples = [
    ["I love to play the guitar", "music, artist, food, travel"],
    ["I am a software engineer at Google", "technology, engineering, art, science"],
    ["I am a professional basketball player", "sports, athlete, chef, politics"],
]

# Title and description and article for the interface
title = "Zero Shot Text Classification"
description = "Classify text using zero-shot classification with ModernBERT-large zeroshot model! Provide a text input and a list of candidate labels separated by commas. Read more at the links below."
article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2412.13663' target='_blank'>Smarter, Better, Faster, Longer: A Modern Bidirectional Encoder for Fast, Memory Efficient, and Long Context Finetuning and Inference</a> | <a href='https://huggingface.co/MoritzLaurer/ModernBERT-large-zeroshot-v2.0' target='_blank'>Model Page</a></p>"


# Launch the interface
demo = gr.Interface(
    fn=ZeroShotTextClassification,
    inputs=[gr.Textbox(label="Input"), gr.Textbox(label="Candidate Labels")],
    outputs=gr.Label(label="Classification"),
    title=title,
    description=description,
    article=article,
    examples=examples,
    cache_examples=True,
    cache_mode="lazy",
    theme="Soft",
    flagging_mode="never",
)
demo.launch(debug=False)