NLP_project / pages /gpt_v1.py
vvv-knyazeva's picture
Update pages/gpt_v1.py
22d9875
raw
history blame
3.19 kB
from transformers import GPT2LMHeadModel, GPT2Tokenizer
import streamlit as st
import torch
import textwrap
import plotly.express as px
df = px.data.iris()
@st.cache_data
def get_img_as_base64(file):
with open(file, "rb") as f:
data = f.read()
return base64.b64encode(data).decode()
#img = get_img_as_base64("https://catherineasquithgallery.com/uploads/posts/2021-02/1612739741_65-p-goluboi-fon-tsifri-110.jpg")
page_bg_img = f"""
<style>
[data-testid="stAppViewContainer"] > .main {{
background-image: url("https://i.pinimg.com/originals/9f/57/bd/9f57bd45d33eb906fdb3d7ffe22e2058.png");
background-size: 70%;
background-position: top left;
background-repeat: no-repeat;
background-attachment: local;
}}
# [data-testid="stSidebar"] > div:first-child {{
# background-image: url("https://catherineasquithgallery.com/uploads/posts/2021-02/1614542041_37-p-fon-belii-tekstura-43.jpg");
# background-size: 100%;
# background-position: center;
# background-repeat: no-repeat;
# background-attachment: fixed;
# }}
[data-testid="stHeader"] {{
background: rgba(0,0,0,0);
}}
[data-testid="stToolbar"] {{
right: 2rem;
}}
div.css-1n76uvr.esravye0 {{
background-color: rgba(238, 238, 238, 0.5);
border: 10px solid #EEEEEE;
padding: 5% 5% 5% 10%;
border-radius: 5px;
}}
</style>
"""
st.markdown(page_bg_img, unsafe_allow_html=True)
st.markdown('## Генерация текста GPT-моделью')
tokenizer = GPT2Tokenizer.from_pretrained('sberbank-ai/rugpt3small_based_on_gpt2')
model = GPT2LMHeadModel.from_pretrained(
'sberbank-ai/rugpt3small_based_on_gpt2',
output_attentions = False,
output_hidden_states = False,
)
# Вешаем сохраненные веса на нашу модель
model.load_state_dict(torch.load('model.pt', map_location=torch.device('cpu')))
col1, col2, col3 = st.columns([5, 2, 12])
with col1:
length = st.slider('Длина генерируемой последовательности:', 8, 256, 16)
num_samples = st.slider('Число генераций:', 1, 10, 1)
temperature = st.slider('Температура:', 1.0, 10.0, 2.0)
top_k = st.slider('Количество наиболее вероятных слов генерации:', 10, 200, 50)
top_p = st.slider('Минимальная суммарная вероятность топовых слов:', 0.4, 1.0, 0.9)
with col2:
pass
with col3:
prompt = st.text_input('Введите текст:')
if st.button('Сгенерировать текст'):
with torch.inference_mode():
prompt = tokenizer.encode(prompt, return_tensors='pt')
out = model.generate(
input_ids=prompt,
max_length=length,
num_beams=5,
do_sample=True,
temperature=temperature,
top_k=top_k,
top_p=top_p,
no_repeat_ngram_size=3,
num_return_sequences=num_samples,
).cpu().numpy()
for i, out_ in enumerate(out):
st.write(f'Текст {i+1}:')
st.write(textwrap.fill(tokenizer.decode(out_), 100))