File size: 1,479 Bytes
0a58748
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9101334
0a58748
9101334
0a58748
 
 
 
 
 
 
 
 
 
 
 
 
9101334
 
0a58748
 
 
2188ac0
0a58748
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
import gradio as gr
import os
from transformers import pipeline, set_seed
from transformers import AutoTokenizer, AutoModel
import torch
import torch.nn.functional as F


def mean_pooling(model_output, attention_mask):
    token_embeddings = model_output[0]
    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)


tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
model = AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')


def Bemenet(input_string):
    # Tokenize sentences
    encoded_input = tokenizer([input_string], 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
    return F.normalize(sentence_embeddings, p=2, dim=1)


interface = gr.Interface(fn=Bemenet,
                        title="Beágyazások",
                        description="Az itt megosztott példa mondatokhoz készít beágyazásokat (embedding). A bal oldali input mezőbe beírt mondat beágyazása a jobb oldali szöveges mezőben jelenik meg.",
                        inputs="text",
                        outputs="text")


interface.launch()