Spaces:
Sleeping
Sleeping
init
Browse files- app.py +21 -0
- models/kdnv_model.pt +3 -0
- models/kdnv_preprocess.py +96 -0
- pages/kdnv_model.py +58 -0
app.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
|
| 3 |
+
st.title('Супер классные нейросетки')
|
| 4 |
+
st.caption('От Димы, Наташи и Серёжи')
|
| 5 |
+
st.divider()
|
| 6 |
+
|
| 7 |
+
col1, col2, col3 = st.columns(3)
|
| 8 |
+
|
| 9 |
+
# with col1:
|
| 10 |
+
# st.page_link('pages/chernyshov_model.py', label='Модель Серёжи Ч.', icon='🍆')
|
| 11 |
+
# st.page_link('pages/chernyshov_learning.py', label='Обучение', icon='💀')
|
| 12 |
+
|
| 13 |
+
# with col2:
|
| 14 |
+
# st.page_link('pages/bond_model.py', label='Модель Любы.', icon='🧠')
|
| 15 |
+
# st.page_link('pages/bond_learning.py', label='Обучение', icon='ℹ️')
|
| 16 |
+
|
| 17 |
+
with col3:
|
| 18 |
+
st.page_link('pages/kdnv_model.py', label='Модель Серёжи К.', icon='🌲')
|
| 19 |
+
# st.page_link('pages/kdnv_history.py', label='Инфа по модели', icon='👀')
|
| 20 |
+
|
| 21 |
+
st.divider()
|
models/kdnv_model.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:57a165966b26b1498022b6307b2dd219585e4dede223f52aaeb819f15b1cae34
|
| 3 |
+
size 500982354
|
models/kdnv_preprocess.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
|
| 3 |
+
# Патч для pymorphy2, чтобы использовать getfullargspec вместо getargspec
|
| 4 |
+
if not hasattr(inspect, 'getargspec'):
|
| 5 |
+
def getargspec(func):
|
| 6 |
+
specs = inspect.getfullargspec(func)
|
| 7 |
+
return specs.args, specs.varargs, specs.varkw, specs.defaults
|
| 8 |
+
inspect.getargspec = getargspec
|
| 9 |
+
|
| 10 |
+
import re
|
| 11 |
+
import string
|
| 12 |
+
import numpy as np
|
| 13 |
+
import torch
|
| 14 |
+
from torch import Tensor
|
| 15 |
+
import spacy
|
| 16 |
+
import pymorphy2
|
| 17 |
+
from nltk.corpus import stopwords
|
| 18 |
+
|
| 19 |
+
# Загрузка стоп-слов для русского языка
|
| 20 |
+
stop_words = set(stopwords.words('russian'))
|
| 21 |
+
# Загрузка модели spacy для русского языка
|
| 22 |
+
nlp = spacy.load("ru_core_news_sm", disable=["parser", "ner"])
|
| 23 |
+
# Инициализация pymorphy2
|
| 24 |
+
morph = pymorphy2.MorphAnalyzer()
|
| 25 |
+
|
| 26 |
+
def data_preprocessing(text: str) -> str:
|
| 27 |
+
# Приведение к нижнему регистру
|
| 28 |
+
text = text.lower()
|
| 29 |
+
|
| 30 |
+
# Удаление HTML-тегов
|
| 31 |
+
text = re.sub(r'<.*?>', '', text)
|
| 32 |
+
|
| 33 |
+
# Удаление символов переноса строки и неразрывного пробела
|
| 34 |
+
text = text.replace('\n', ' ').replace('\xa0', ' ')
|
| 35 |
+
|
| 36 |
+
# Удаление пунктуации и цифр в одном шаге
|
| 37 |
+
text = ''.join([c for c in text if c not in string.punctuation and not c.isdigit()])
|
| 38 |
+
|
| 39 |
+
# Удаление стоп-слов и лемматизация
|
| 40 |
+
doc = nlp(text)
|
| 41 |
+
text = ' '.join([morph.parse(token.text)[0].normal_form for token in doc if token.text not in stop_words and not token.is_digit])
|
| 42 |
+
|
| 43 |
+
return text
|
| 44 |
+
|
| 45 |
+
def get_words_by_freq(sorted_words: list[tuple[str, int]], n: int = 10) -> list:
|
| 46 |
+
return list(filter(lambda x: x[1] > n, sorted_words))
|
| 47 |
+
|
| 48 |
+
def padding(review_int: list, seq_len: int) -> np.array:
|
| 49 |
+
"""Make left-sided padding for input list of tokens
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
review_int (list): input list of tokens
|
| 53 |
+
seq_len (int): max length of sequence, it len(review_int[i]) > seq_len it will be trimmed, else it will be padded by zeros
|
| 54 |
+
|
| 55 |
+
Returns:
|
| 56 |
+
np.array: padded sequences
|
| 57 |
+
"""
|
| 58 |
+
features = np.zeros((len(review_int), seq_len), dtype=int)
|
| 59 |
+
for i, review in enumerate(review_int):
|
| 60 |
+
if len(review) <= seq_len:
|
| 61 |
+
zeros = list(np.zeros(seq_len - len(review)))
|
| 62 |
+
new = zeros + review
|
| 63 |
+
else:
|
| 64 |
+
new = review[: seq_len]
|
| 65 |
+
features[i, :] = np.array(new)
|
| 66 |
+
|
| 67 |
+
return features
|
| 68 |
+
|
| 69 |
+
def preprocess_single_string(
|
| 70 |
+
input_string: str,
|
| 71 |
+
seq_len: int,
|
| 72 |
+
vocab_to_int: dict,
|
| 73 |
+
verbose: bool = False
|
| 74 |
+
) -> Tensor:
|
| 75 |
+
"""Function for all preprocessing steps on a single string
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
input_string (str): input single string for preprocessing
|
| 79 |
+
seq_len (int): max length of sequence, it len(review_int[i]) > seq_len it will be trimmed, else it will be padded by zeros
|
| 80 |
+
vocab_to_int (dict, optional): word corpus {'word' : int index}. Defaults to vocab_to_int.
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
list: preprocessed string
|
| 84 |
+
"""
|
| 85 |
+
preprocessed_string = data_preprocessing(input_string)
|
| 86 |
+
result_list = []
|
| 87 |
+
for word in preprocessed_string.split():
|
| 88 |
+
try:
|
| 89 |
+
result_list.append(vocab_to_int[word])
|
| 90 |
+
except KeyError as e:
|
| 91 |
+
if verbose:
|
| 92 |
+
print(f'{e}: not in dictionary!')
|
| 93 |
+
pass
|
| 94 |
+
result_padded = padding([result_list], seq_len)[0]
|
| 95 |
+
|
| 96 |
+
return Tensor(result_padded)
|
pages/kdnv_model.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import streamlit as st
|
| 3 |
+
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
| 4 |
+
import textwrap
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@st.cache_resource()
|
| 8 |
+
def load_model():
|
| 9 |
+
model = GPT2LMHeadModel.from_pretrained('sberbank-ai/rugpt3small_based_on_gpt2')
|
| 10 |
+
model.load_state_dict(torch.load('models/kdnv_model.pt', map_location=torch.device('cpu')))
|
| 11 |
+
return model
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
model = load_model()
|
| 15 |
+
tokenizer = GPT2Tokenizer.from_pretrained('sberbank-ai/rugpt3small_based_on_gpt2')
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def predict(text, max_len=100, num_beams=10, temperature=1.5, top_p=0.7):
|
| 19 |
+
with torch.inference_mode():
|
| 20 |
+
prompt = text
|
| 21 |
+
prompt = tokenizer.encode(prompt, return_tensors='pt')
|
| 22 |
+
out = model.generate(
|
| 23 |
+
input_ids=prompt,
|
| 24 |
+
max_length=max_len,
|
| 25 |
+
num_beams=num_beams,
|
| 26 |
+
do_sample=True,
|
| 27 |
+
temperature=temperature,
|
| 28 |
+
top_p=top_p,
|
| 29 |
+
no_repeat_ngram_size=1,
|
| 30 |
+
num_return_sequences=1,
|
| 31 |
+
).cpu().numpy()
|
| 32 |
+
|
| 33 |
+
return textwrap.fill(tokenizer.decode(out[0]))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
st.title('Ночной собутыльник')
|
| 38 |
+
st.caption('От Серёжи')
|
| 39 |
+
st.divider()
|
| 40 |
+
|
| 41 |
+
with st.form(key='Промт'):
|
| 42 |
+
prompt = st.text_input("Твоя фраза")
|
| 43 |
+
col = st.columns(4)
|
| 44 |
+
with col[0]:
|
| 45 |
+
max_len = st.slider("Длина ответа", 20, 200, 100)
|
| 46 |
+
with col[1]:
|
| 47 |
+
num_beams = st.slider("Глубина мысли", 0.1, 1., 0.5)
|
| 48 |
+
with col[2]:
|
| 49 |
+
temperature = st.slider("Связность речи", 0.1, 1., 0.35)
|
| 50 |
+
with col[3]:
|
| 51 |
+
top_p = st.slider("Уровень опьянения", 0.1, 1.0, 0.7)
|
| 52 |
+
|
| 53 |
+
submit = st.form_submit_button('Отвечай!')
|
| 54 |
+
|
| 55 |
+
if submit:
|
| 56 |
+
if prompt:
|
| 57 |
+
pred = predict(prompt, max_len=max_len, num_beams=int(num_beams * 20), temperature=(1-temperature) * 5, top_p=top_p)
|
| 58 |
+
st.write(pred)
|