File size: 2,004 Bytes
e369cb0
 
 
 
 
 
 
 
 
 
 
05a2e2d
 
 
 
e369cb0
 
05a2e2d
 
 
e369cb0
05a2e2d
e369cb0
05a2e2d
 
 
e369cb0
05a2e2d
 
e369cb0
05a2e2d
 
 
e369cb0
05a2e2d
 
e369cb0
05a2e2d
 
 
e369cb0
05a2e2d
 
e369cb0
05a2e2d
 
e369cb0
05a2e2d
 
e369cb0
 
 
 
 
 
05a2e2d
 
 
 
e369cb0
 
05a2e2d
 
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
import gradio as gr
import spacy
import math
from datasets import load_dataset
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer, AutoModel
import torch
import torch.nn.functional as F


#Mean Pooling - Take attention mask into account for correct averaging
def mean_pooling(model_output, attention_mask):
    token_embeddings = model_output[0] #First element of model_output contains all token embeddings
    input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
    return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)


def training():
    dataset = load_dataset("glue", "cola")
    dataset = dataset["train"]

    sentences = ["This is an example sentence", "Each sentence is converted"]

    model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
    embeddings = model.encode(sentences)
    print(embeddings)
    
    # Sentences we want sentence embeddings for
    sentences = ['This is an example sentence', 'Each sentence is converted']

    # Load model from HuggingFace Hub
    tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
    model = AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')

    # Tokenize sentences
    encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')

    # Compute token embeddings
    with torch.no_grad():
        model_output = model(**encoded_input)

    # Perform pooling
    sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])

    # Normalize embeddings
    sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)

    print("Sentence embeddings:")
    print(sentence_embeddings)
    

def greet(name):
    return "Hello " + name + "!!"


def main():
    iface = gr.Interface(fn=greet, inputs="text", outputs="text")
    iface.launch()


    
if __name__ == "__main__":
    main()