Streamlit App
Browse files- .gitattributes +1 -0
- app.py +99 -0
- media/3bears.ico +0 -0
- media/background.jpg +3 -0
- model.pth +3 -0
- model.py +146 -0
- requirements.txt +3 -0
- style/style.css +26 -0
- tokenizer.json +0 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
media/background.jpg filter=lfs diff=lfs merge=lfs -text
|
app.py
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from tokenizers import Tokenizer
|
3 |
+
from torch.utils.data import DataLoader
|
4 |
+
|
5 |
+
import streamlit as st
|
6 |
+
import base64
|
7 |
+
from model import CustomDataset, TransformerEncoder
|
8 |
+
|
9 |
+
st.set_page_config(layout="wide",page_title="TeknoFest We Bears NLP Competition", page_icon="./media/3bears.ico")
|
10 |
+
|
11 |
+
tag2id = {"O": 0, "olumsuz": 1, "nötr": 2, "olumlu": 3, "org": 4}
|
12 |
+
id2tag = {value: key for key, value in tag2id.items()}
|
13 |
+
device = torch.device('cpu')
|
14 |
+
|
15 |
+
@st.cache_resource
|
16 |
+
def load_model_to_cpu(_model, path="model.pth"):
|
17 |
+
checkpoint = torch.load(path, map_location=torch.device('cpu'))
|
18 |
+
_model.load_state_dict(checkpoint)
|
19 |
+
return _model
|
20 |
+
|
21 |
+
def get_base64(bin_file):
|
22 |
+
with open(bin_file, 'rb') as f:
|
23 |
+
data = f.read()
|
24 |
+
return base64.b64encode(data).decode()
|
25 |
+
|
26 |
+
def predict_fonk(model, device, example, tokenizer):
|
27 |
+
model.to(device)
|
28 |
+
model.eval()
|
29 |
+
predictions = []
|
30 |
+
|
31 |
+
encodings_prdict = tokenizer.encode(example)
|
32 |
+
|
33 |
+
predict_texts = [encodings_prdict.tokens]
|
34 |
+
predict_input_ids = [encodings_prdict.ids]
|
35 |
+
predict_attention_masks = [encodings_prdict.attention_mask]
|
36 |
+
predict_token_type_ids = [encodings_prdict.type_ids]
|
37 |
+
prediction_labels = [encodings_prdict.type_ids]
|
38 |
+
|
39 |
+
predict_data = CustomDataset(predict_texts, predict_input_ids, predict_attention_masks, predict_token_type_ids,
|
40 |
+
prediction_labels)
|
41 |
+
|
42 |
+
predict_loader = DataLoader(predict_data, batch_size=1, shuffle=False)
|
43 |
+
|
44 |
+
with torch.no_grad():
|
45 |
+
for dataset in predict_loader:
|
46 |
+
batch_input_ids = dataset['input_ids'].to(device)
|
47 |
+
batch_att_mask = dataset['attention_mask'].to(device)
|
48 |
+
|
49 |
+
|
50 |
+
|
51 |
+
outputs = model(batch_input_ids, batch_att_mask)
|
52 |
+
logits = outputs.view(-1, outputs.size(-1)) # Flatten the outputs
|
53 |
+
_, predicted = torch.max(logits, 1)
|
54 |
+
|
55 |
+
# Ignore padding tokens for predictions
|
56 |
+
predictions.append(predicted)
|
57 |
+
|
58 |
+
results_list = []
|
59 |
+
entity_list = []
|
60 |
+
results_dict = {}
|
61 |
+
trio = zip(predict_loader.dataset[0]["text"], predictions[0].tolist(), predict_attention_masks[0])
|
62 |
+
|
63 |
+
for i, (token, label, attention) in enumerate(trio):
|
64 |
+
if attention != 0 and label != 0 and label !=4:
|
65 |
+
for next_ones in predictions[0].tolist()[i+1:]:
|
66 |
+
i+=1
|
67 |
+
if next_ones == 4:
|
68 |
+
token = token +" "+ predict_loader.dataset[0]["text"][i]
|
69 |
+
else:break
|
70 |
+
if token not in entity_list:
|
71 |
+
entity_list.append(token)
|
72 |
+
results_list.append({"entity":token,"sentiment":id2tag.get(label)})
|
73 |
+
|
74 |
+
|
75 |
+
results_dict["entity_list"] = entity_list
|
76 |
+
results_dict["results"] = results_list
|
77 |
+
|
78 |
+
|
79 |
+
return results_dict
|
80 |
+
|
81 |
+
model = TransformerEncoder()
|
82 |
+
model = load_model_to_cpu(model, "model.pth")
|
83 |
+
tokenizer = Tokenizer.from_file("tokenizer.json")
|
84 |
+
|
85 |
+
background = get_base64("./media/background.jpg")
|
86 |
+
|
87 |
+
with open("./style/style.css", "r") as style:
|
88 |
+
css=f"""<style>{style.read().format(background=background)}</style>"""
|
89 |
+
st.markdown(css, unsafe_allow_html=True)
|
90 |
+
|
91 |
+
left, middle, right = st.columns([1,1.5,1])
|
92 |
+
main, comps , result = middle.tabs([" ", " ", " "])
|
93 |
+
with main:
|
94 |
+
example = st.text_area(label='Metin Kutusu: ', placeholder="Lütfen Şikayet veya Yorum Metnini Buraya Yazın, daha sonra Predicte tıklayın")
|
95 |
+
|
96 |
+
if st.button("Predict"):
|
97 |
+
predict_list = predict_fonk(model=model, device=device, example=example, tokenizer=tokenizer)
|
98 |
+
|
99 |
+
st.write(predict_list)
|
media/3bears.ico
ADDED
|
media/background.jpg
ADDED
![]() |
Git LFS Details
|
model.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:320bc3db757e8b07b86ae43a0a3ff8adca691db7e25359b1e31d999ef4906d65
|
3 |
+
size 280754978
|
model.py
ADDED
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from torch.utils.data import Dataset
|
5 |
+
import math
|
6 |
+
|
7 |
+
class CustomDataset(Dataset):
|
8 |
+
def __init__(self, texts, input_ids, attention_masks, token_type_ids, labels):
|
9 |
+
self.texts = texts
|
10 |
+
self.input_ids = input_ids
|
11 |
+
self.token_type_ids = token_type_ids
|
12 |
+
self.attention_masks = attention_masks
|
13 |
+
self.labels = labels
|
14 |
+
|
15 |
+
|
16 |
+
def __len__(self):
|
17 |
+
return len(self.texts)
|
18 |
+
|
19 |
+
def __getitem__(self, item ):
|
20 |
+
text = self.texts[item]
|
21 |
+
input_id = torch.LongTensor(self.input_ids[item])
|
22 |
+
token_type_id = torch.LongTensor(self.token_type_ids[item])
|
23 |
+
attention_mask = torch.LongTensor(self.attention_masks[item])
|
24 |
+
label = torch.LongTensor(self.labels[item])
|
25 |
+
|
26 |
+
|
27 |
+
return {
|
28 |
+
'text': text,
|
29 |
+
'input_ids': input_id,
|
30 |
+
'token_type_ids': token_type_id,
|
31 |
+
'attention_mask': attention_mask,
|
32 |
+
'labels': label,
|
33 |
+
}
|
34 |
+
class FeedForwardSubLayer(nn.Module):
|
35 |
+
# Specify the two linear layers' input and output sizes
|
36 |
+
def __init__(self, d_model, d_ff):
|
37 |
+
super(FeedForwardSubLayer, self).__init__()
|
38 |
+
self.fc1 = nn.Linear(d_model, d_ff)
|
39 |
+
self.fc2 = nn.Linear(d_ff, d_model)
|
40 |
+
self.relu = nn.ReLU()
|
41 |
+
|
42 |
+
# Apply a forward pass
|
43 |
+
def forward(self, x):
|
44 |
+
return self.fc2(self.relu(self.fc1(x)))
|
45 |
+
|
46 |
+
# Complete the initialization of elements in the encoder layer
|
47 |
+
class EncoderLayer(nn.Module):
|
48 |
+
def __init__(self, d_model, num_heads, d_ff, dropout):
|
49 |
+
super(EncoderLayer, self).__init__()
|
50 |
+
self.self_attn = MultiHeadAttention(d_model, num_heads)
|
51 |
+
self.feed_forward = FeedForwardSubLayer(d_model, d_ff)
|
52 |
+
self.norm1 = nn.LayerNorm(d_model)
|
53 |
+
self.norm2 = nn.LayerNorm(d_model)
|
54 |
+
self.dropout = nn.Dropout(dropout)
|
55 |
+
|
56 |
+
def forward(self, x, mask):
|
57 |
+
attn_output = self.self_attn(x, x, x, mask)
|
58 |
+
x = self.norm1(x + self.dropout(attn_output))
|
59 |
+
ff_output = self.feed_forward(x)
|
60 |
+
return self.norm2(x + self.dropout(ff_output))
|
61 |
+
|
62 |
+
class MultiHeadAttention(nn.Module):
|
63 |
+
def __init__(self, d_model, num_heads):
|
64 |
+
super(MultiHeadAttention, self).__init__()
|
65 |
+
# Set the number of attention heads
|
66 |
+
self.num_heads = num_heads
|
67 |
+
self.d_model = d_model
|
68 |
+
assert d_model % num_heads == 0 #dimension, headlere tam bölünüyormu kontrol et.
|
69 |
+
self.head_dim = d_model // num_heads
|
70 |
+
# Set up the linear transformations
|
71 |
+
self.query_linear = nn.Linear(d_model, d_model)
|
72 |
+
self.key_linear = nn.Linear(d_model, d_model)
|
73 |
+
self.value_linear = nn.Linear(d_model, d_model)
|
74 |
+
self.output_linear = nn.Linear(d_model, d_model)
|
75 |
+
|
76 |
+
def split_heads(self, x, batch_size):
|
77 |
+
# Split the sequence embeddings in x across the attention heads
|
78 |
+
x = x.view(batch_size, -1, self.num_heads, self.head_dim)
|
79 |
+
return x.permute(0, 2, 1, 3) #.contiguous().view(batch_size * self.num_heads, -1, self.head_dim)
|
80 |
+
|
81 |
+
def compute_attention(self, query, key, mask=None):
|
82 |
+
# Compute dot-product attention scores
|
83 |
+
scores = torch.matmul(query, key.permute(0,1,3,2))
|
84 |
+
mask = mask.unsqueeze(1).unsqueeze(1)
|
85 |
+
|
86 |
+
|
87 |
+
if mask is not None:
|
88 |
+
scores = scores.masked_fill(mask == 0, float("-1e20"))
|
89 |
+
# Normalize attention scores into attention weights
|
90 |
+
attention_weights = F.softmax(scores, dim=-1)
|
91 |
+
return attention_weights
|
92 |
+
|
93 |
+
def forward(self, query, key, value, mask=None):
|
94 |
+
batch_size = query.size(0)
|
95 |
+
|
96 |
+
query = self.split_heads(self.query_linear(query), batch_size)
|
97 |
+
key = self.split_heads(self.key_linear(key), batch_size)
|
98 |
+
value = self.split_heads(self.value_linear(value), batch_size)
|
99 |
+
|
100 |
+
attention_weights = self.compute_attention(query, key, mask)
|
101 |
+
|
102 |
+
# Multiply attention weights by values, concatenate and linearly project outputs
|
103 |
+
output = torch.matmul(attention_weights, value)
|
104 |
+
output = output.view(batch_size, self.num_heads, -1, self.head_dim).permute(0, 2, 1, 3).contiguous().view(
|
105 |
+
batch_size, -1, self.d_model)
|
106 |
+
return self.output_linear(output)
|
107 |
+
|
108 |
+
class PositionalEncoder(nn.Module):
|
109 |
+
def __init__(self, d_model, max_length):
|
110 |
+
super(PositionalEncoder, self).__init__()
|
111 |
+
self.d_model = d_model
|
112 |
+
self.max_length = max_length
|
113 |
+
|
114 |
+
# Initialize the positional encoding matrix
|
115 |
+
pe = torch.zeros(max_length, d_model)
|
116 |
+
position = torch.arange(0, max_length, dtype=torch.float).unsqueeze(1)
|
117 |
+
div_term = torch.exp(torch.arange(0, d_model, 2, dtype=torch.float) * -(math.log(10000.0) / d_model))
|
118 |
+
|
119 |
+
# Calculate and assign position encodings to the matrix
|
120 |
+
pe[:, 0::2] = torch.sin(position * div_term)
|
121 |
+
pe[:, 1::2] = torch.cos(position * div_term)
|
122 |
+
pe = pe.unsqueeze(0)
|
123 |
+
self.register_buffer('pe', pe)
|
124 |
+
|
125 |
+
# Update the embeddings tensor adding the positional encodings
|
126 |
+
def forward(self, x):
|
127 |
+
x = x + self.pe[:, :x.size(1)]
|
128 |
+
return x
|
129 |
+
|
130 |
+
class TransformerEncoder(nn.Module):
|
131 |
+
def __init__(self):
|
132 |
+
super(TransformerEncoder, self).__init__()
|
133 |
+
self.embedding = nn.Embedding(100000, 512)
|
134 |
+
self.positional_encoding = PositionalEncoder(512, 128)
|
135 |
+
# Define a stack of multiple encoder layers
|
136 |
+
self.layers = nn.ModuleList([EncoderLayer(512, 8, 2048, 0.1) for _ in range(6)])
|
137 |
+
|
138 |
+
# Complete the forward pass method
|
139 |
+
def forward(self, x, mask):
|
140 |
+
x = self.embedding(x)
|
141 |
+
x = self.positional_encoding(x)
|
142 |
+
for layer in self.layers:
|
143 |
+
x = layer(x, mask)
|
144 |
+
return x
|
145 |
+
|
146 |
+
|
requirements.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
torch==2.3.0
|
2 |
+
tokenizers==0.13.3
|
3 |
+
streamlit
|
style/style.css
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
body {{
|
2 |
+
background-image: url("data:image/png;base64,{background}");
|
3 |
+
background-size: cover;
|
4 |
+
background-repeat: no-repeat;
|
5 |
+
background-attachment: fixed;
|
6 |
+
background-position: center;
|
7 |
+
margin: 0;
|
8 |
+
padding: 0;
|
9 |
+
height: 100vh;
|
10 |
+
}}
|
11 |
+
|
12 |
+
p {{
|
13 |
+
color: black;
|
14 |
+
font-family: "Google Sans",Roboto,Arial,sans-serif;
|
15 |
+
font-size: 20px;
|
16 |
+
|
17 |
+
}}
|
18 |
+
|
19 |
+
header[data-testid = "stHeader"]{{background: rgba(255,255,255,0);}}
|
20 |
+
button[data-testid = "baseButton-secondary"]{{width: 100%;}}
|
21 |
+
div[data-testid = "stButton"] > button > div > p {{color: white; font-size: 15px;}}
|
22 |
+
div[data-testid = "stApp"]{{background: None; color: black;}}
|
23 |
+
div[id^=tabs-bui][id$=-tabpanel-0]{{padding: 20px; border-radius: 2rem; background: rgba(255,255,255,0.7);}}
|
24 |
+
div[class = "react-json-view"]{{padding: 20px; border-radius: 2rem; background: rgba(255,255,255,0.7);}}
|
25 |
+
div[data-testid = "stMarkdownContainer"] > p {{color: black; font-size: 15px; font-weight: bold;}}
|
26 |
+
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|