-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtfhubutils2.py
44 lines (29 loc) · 1.15 KB
/
tfhubutils2.py
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# coding=utf-8
import tensorflow.compat.v2 as tf
import tensorflow_hub as hub
from tensorflow_text import SentencepieceTokenizer
import tensorflow as tf
from functools import lru_cache
if tf.test.gpu_device_name():
print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
else:
print("Please install GPU version of TF")
class TFHubContext2:
def __init__(self, url="https://tfhub.dev/google/universal-sentence-encoder-multilingual-large/3") -> None:
super().__init__()
print("initialize model.")
self.model = hub.load(url)
def get_embedding(self, texts):
# Reduce logging output.
# tf.logging.set_verbosity(tf.logging.ERROR)
return self.model(texts)
def close(self):
print('TFHubContext closed')
from functools import lru_cache
@lru_cache(maxsize=10)
# def get_sentence_encoder(name='universal-sentence-encoder-multilingual-large/3'):
def get_sentence_encoder(name='universal-sentence-encoder-large/5'):
# 'https://tfhub.dev/google/universal-sentence-encoder-multilingual-large/3'
return TFHubContext2(url=f'https://tfhub.dev/google/{name}')