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
| 3 |
+
import fasttext, torch, clip
|
| 4 |
+
from sentence_transformers import SentenceTransformer, util
|
| 5 |
+
|
| 6 |
+
model_en, preprocess_en = clip.load(model_tag="ViT-B/32")
|
| 7 |
+
model_multi = SentenceTransformer(model_tag="sentence-transformers/clip-ViT-B-32-multilingual-v1")
|
| 8 |
+
|
| 9 |
+
def prep_examples():
|
| 10 |
+
example_text1 = "Coronavirus disease (COVID-19) is an infectious disease caused by the SARS-CoV-2 virus. Most \
|
| 11 |
+
people who fall sick with COVID-19 will experience mild to moderate symptoms and recover without special treatment. \
|
| 12 |
+
However, some will become seriously ill and require medical attention."
|
| 13 |
+
example_labels1 = "business;;health related;;politics;;climate change"
|
| 14 |
+
|
| 15 |
+
example_text2 = "Elephants are"
|
| 16 |
+
example_labels2 = "big;;small;;strong;;fast;;carnivorous"
|
| 17 |
+
|
| 18 |
+
example_text3 = "Elephants"
|
| 19 |
+
example_labels3 = "are big;;can be very small;;generally not strong enough;;are faster than you think"
|
| 20 |
+
|
| 21 |
+
example_text4 = "Dogs are man's best friend"
|
| 22 |
+
example_labels4 = "positive;;negative;;neutral"
|
| 23 |
+
|
| 24 |
+
example_text5 = "Şampiyonlar Ligi’nde 5. hafta oynanan karşılaşmaların ardından sona erdi. Real Madrid, \
|
| 25 |
+
Inter ve Sporting oynadıkları mücadeleler sonrasında Son 16 turuna yükselmeyi başardı. \
|
| 26 |
+
Gecenin dev mücadelesinde ise Manchester City, PSG’yi yenerek liderliği garantiledi."
|
| 27 |
+
example_labels5 = "dünya;;ekonomi;;kültür;;siyaset;;spor;;teknoloji"
|
| 28 |
+
|
| 29 |
+
example_text6 = "Letzte Woche gab es einen Selbstmord in einer nahe gelegenen kolonie"
|
| 30 |
+
example_labels6 = "verbrechen;;tragödie;;stehlen"
|
| 31 |
+
|
| 32 |
+
example_text7 = "El autor se perfila, a los 50 años de su muerte, como uno de los grandes de su siglo"
|
| 33 |
+
example_labels7 = "cultura;;sociedad;;economia;;salud;;deportes"
|
| 34 |
+
|
| 35 |
+
example_text8 = "Россия в среду заявила, что военные учения в аннексированном Москвой Крыму закончились \
|
| 36 |
+
и что солдаты возвращаются в свои гарнизоны, на следующий день после того, как она объявила о первом выводе \
|
| 37 |
+
войск от границ Украины."
|
| 38 |
+
example_labels8 = "новости;;комедия"
|
| 39 |
+
|
| 40 |
+
example_text9 = "I quattro registi - Federico Fellini, Pier Paolo Pasolini, Bernardo Bertolucci e Vittorio De Sica - \
|
| 41 |
+
hanno utilizzato stili di ripresa diversi, ma hanno fortemente influenzato le giovani generazioni di registi."
|
| 42 |
+
example_labels9 = "cinema;;politica;;cibo"
|
| 43 |
+
|
| 44 |
+
example_text10 = "Ja, vi elsker dette landet,\
|
| 45 |
+
som det stiger frem,\
|
| 46 |
+
furet, værbitt over vannet,\
|
| 47 |
+
med de tusen hjem.\
|
| 48 |
+
Og som fedres kamp har hevet\
|
| 49 |
+
det av nød til seir"
|
| 50 |
+
example_labels10 = "helse;;sport;;religion;;mat;;patriotisme og nasjonalisme"
|
| 51 |
+
|
| 52 |
+
example_text11 = "Amar sonar bangla ami tomay bhalobasi"
|
| 53 |
+
example_labels11 = "bhalo;;kharap"
|
| 54 |
+
|
| 55 |
+
examples = [
|
| 56 |
+
[example_text1, example_labels1],
|
| 57 |
+
[example_text2, example_labels2],
|
| 58 |
+
[example_text3, example_labels3],
|
| 59 |
+
[example_text4, example_labels4],
|
| 60 |
+
[example_text5, example_labels5],
|
| 61 |
+
[example_text6, example_labels6],
|
| 62 |
+
[example_text7, example_labels7],
|
| 63 |
+
[example_text8, example_labels8],
|
| 64 |
+
[example_text9, example_labels9],
|
| 65 |
+
[example_text10, example_labels10],
|
| 66 |
+
[example_text11, example_labels11]]
|
| 67 |
+
|
| 68 |
+
return examples
|
| 69 |
+
|
| 70 |
+
def detect_lang(sequence):
|
| 71 |
+
seq_lang = 'en'
|
| 72 |
+
|
| 73 |
+
sequence = sequence.replace('\n', ' ')
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
seq_lang = fasttext_model.predict(sequence, k=1)[0][0].split("__label__")[1]
|
| 77 |
+
except:
|
| 78 |
+
print("Language detection failed!",
|
| 79 |
+
"Date:{}, Sequence:{}".format(
|
| 80 |
+
str(datetime.datetime.now())))
|
| 81 |
+
|
| 82 |
+
return seq_lang
|
| 83 |
+
|
| 84 |
+
def sequence_to_classify(text, labels):
|
| 85 |
+
lang = detect_lang(text)
|
| 86 |
+
if lang == 'en':
|
| 87 |
+
model = model_en
|
| 88 |
+
preprocess = preprocess_en
|
| 89 |
+
hypothesis_template = "This example is {}."
|
| 90 |
+
else:
|
| 91 |
+
model = model_multi
|
| 92 |
+
hypothesis_template = "{}."
|
| 93 |
+
|
| 94 |
+
labels = [hypothesis_template.format(label) for label in labels.split(";;")]
|
| 95 |
+
|
| 96 |
+
if str(type(model)) == "<class 'clip.model.CLIP'>":
|
| 97 |
+
text_tokens = clip.tokenize(text)
|
| 98 |
+
text_features = model.encode_text(text_tokens)
|
| 99 |
+
|
| 100 |
+
label_tokens = clip.tokenize(labels)
|
| 101 |
+
labels_features = model.encode_text(label_tokens)
|
| 102 |
+
else:
|
| 103 |
+
text_features = torch.tensor(model.encode(text))
|
| 104 |
+
labels_features = torch.tensor(self.model.encode(labels))
|
| 105 |
+
|
| 106 |
+
sim_scores = util.cos_sim(text_features, labels_features)
|
| 107 |
+
preds = []
|
| 108 |
+
|
| 109 |
+
for textlet, sim_score in zip([text], sim_scores):
|
| 110 |
+
out = []
|
| 111 |
+
pred = {}
|
| 112 |
+
for raw_score in sim_score:
|
| 113 |
+
out.append(raw_score.item() * 100)
|
| 114 |
+
probs = torch.tensor([out])
|
| 115 |
+
probs = probs.softmax(dim=-1).cpu().numpy()
|
| 116 |
+
scores = list(probs.flatten())
|
| 117 |
+
|
| 118 |
+
sorted_sl = sorted(zip(scores, candidate_labels), key=lambda t:t[0], reverse=True)
|
| 119 |
+
|
| 120 |
+
pred["labels"] = textlet
|
| 121 |
+
pred["scores"], pred["labels"] = zip(*sorted_sl)
|
| 122 |
+
preds.append(pred)
|
| 123 |
+
|
| 124 |
+
predicted_labels = preds['labels']
|
| 125 |
+
predicted_scores = preds['scores']
|
| 126 |
+
clean_output = {idx: float(predicted_scores.pop(0)) for idx in predicted_labels}
|
| 127 |
+
print("Date:{}, Sequence:{}, Labels: {}".format(
|
| 128 |
+
str(datetime.datetime.now()),
|
| 129 |
+
text,
|
| 130 |
+
predicted_labels))
|
| 131 |
+
|
| 132 |
+
return clean_output
|
| 133 |
+
|
| 134 |
+
iface = gr.Interface(
|
| 135 |
+
title="Alternate Zero-shot Multi-label Multilingual NLP Classifier",
|
| 136 |
+
description="Work in progress.",
|
| 137 |
+
fn=sequence_to_classify,
|
| 138 |
+
inputs=[gr.inputs.Textbox(lines=10,
|
| 139 |
+
label="Please enter the text you would like to classify...",
|
| 140 |
+
placeholder="Text here..."),
|
| 141 |
+
gr.inputs.Textbox(lines=2,
|
| 142 |
+
label="Please enter the candidate labels (separated by 2 consecutive semicolons)...",
|
| 143 |
+
placeholder="Labels here separated by ;;")],
|
| 144 |
+
outputs=gr.outputs.Label(num_top_classes=5),
|
| 145 |
+
#interpretation="default",
|
| 146 |
+
examples=prep_examples())
|
| 147 |
+
|
| 148 |
+
iface.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
sentence-transformers
|
| 3 |
+
git+https://github.com/openai/CLIP.git
|
| 4 |
+
fasttext
|