mesutdmn commited on
Commit
707d24a
·
1 Parent(s): 489ae9f

Uploading to HuggingFace

Browse files
Files changed (6) hide show
  1. Dockerfile +13 -0
  2. app.py +96 -0
  3. model.pth +3 -0
  4. model.py +149 -0
  5. requirements.txt +5 -0
  6. tokenizer.json +0 -0
Dockerfile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+
3
+ RUN useradd -m -u 1000 user
4
+ USER user
5
+ ENV PATH="/home/user/.local/bin:$PATH"
6
+
7
+ WORKDIR /app
8
+
9
+ COPY --chown=user ./requirements.txt requirements.txt
10
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
11
+
12
+ COPY --chown=user . /app
13
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from tokenizers import Tokenizer
3
+ from torch.utils.data import DataLoader
4
+ import uvicorn
5
+ from fastapi import FastAPI
6
+ from pydantic import BaseModel, Field
7
+ from fastapi.responses import RedirectResponse
8
+ from model import CustomDataset, TransformerEncoder, load_model_to_cpu
9
+
10
+ app = FastAPI()
11
+
12
+
13
+
14
+ tag2id = {"O": 0, "olumsuz": 1, "nötr": 2, "olumlu": 3, "org": 4}
15
+ id2tag = {value: key for key, value in tag2id.items()}
16
+
17
+ device = torch.device('cpu')
18
+ def predict_fonk(model, device, example, tokenizer):
19
+ model.to(device)
20
+ model.eval()
21
+ predictions = []
22
+
23
+ encodings_prdict = tokenizer.encode(example)
24
+
25
+ predict_texts = [encodings_prdict.tokens]
26
+ predict_input_ids = [encodings_prdict.ids]
27
+ predict_attention_masks = [encodings_prdict.attention_mask]
28
+ predict_token_type_ids = [encodings_prdict.type_ids]
29
+ prediction_labels = [encodings_prdict.type_ids]
30
+
31
+ predict_data = CustomDataset(predict_texts, predict_input_ids, predict_attention_masks, predict_token_type_ids,
32
+ prediction_labels)
33
+
34
+ predict_loader = DataLoader(predict_data, batch_size=1, shuffle=False)
35
+
36
+ with torch.no_grad():
37
+ for dataset in predict_loader:
38
+ batch_input_ids = dataset['input_ids'].to(device)
39
+ batch_att_mask = dataset['attention_mask'].to(device)
40
+
41
+
42
+
43
+ outputs = model(batch_input_ids, batch_att_mask)
44
+ logits = outputs.view(-1, outputs.size(-1)) # Flatten the outputs
45
+ _, predicted = torch.max(logits, 1)
46
+
47
+ # Ignore padding tokens for predictions
48
+ predictions.append(predicted)
49
+
50
+ results_list = []
51
+ entity_list = []
52
+ results_dict = {}
53
+ trio = zip(predict_loader.dataset[0]["text"], predictions[0].tolist(), predict_attention_masks[0])
54
+
55
+ for i, (token, label, attention) in enumerate(trio):
56
+ if attention != 0 and label != 0 and label !=4:
57
+ for next_ones in predictions[0].tolist()[i+1:]:
58
+ i+=1
59
+ if next_ones == 4:
60
+ token = token +" "+ predict_loader.dataset[0]["text"][i]
61
+ else:break
62
+ if token not in entity_list:
63
+ entity_list.append(token)
64
+ results_list.append({"entity":token,"sentiment":id2tag.get(label)})
65
+
66
+
67
+ results_dict["entity_list"] = entity_list
68
+ results_dict["results"] = results_list
69
+
70
+
71
+ return results_dict
72
+
73
+ model = TransformerEncoder()
74
+ model = load_model_to_cpu(model, "model.pth")
75
+ tokenizer = Tokenizer.from_file("tokenizer.json")
76
+
77
+ class Item(BaseModel):
78
+ text: str = Field(..., example="""Fiber 100mb SuperOnline kullanıcısıyım yaklaşık 2 haftadır @Twitch @Kick_Turkey gibi canlı yayın platformlarında 360p yayın izlerken donmalar yaşıyoruz. Başka hiç bir operatörler bu sorunu yaşamazken ben parasını verip alamadığım hizmeti neden ödeyeyim ? @Turkcell """)
79
+
80
+ @app.get("/")
81
+ async def root():
82
+ return RedirectResponse(url="/docs#/default/predict_predict__post")
83
+
84
+ @app.post("/predict/", response_model=dict)
85
+ async def predict(item: Item):
86
+
87
+
88
+ predict_list = predict_fonk(model=model, device=device, example=item.text, tokenizer=tokenizer)
89
+
90
+ #Buraya model'in çıktısı gelecek
91
+ #Çıktı formatı aşağıdaki örnek gibi olacak
92
+ return predict_list
93
+
94
+
95
+ if __name__=="__main__":
96
+ uvicorn.run(app,host="0.0.0.0",port=8000)
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,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def load_model_to_cpu(model, path="model.pth"):
147
+ checkpoint = torch.load(path, map_location=torch.device('cpu'))
148
+ model.load_state_dict(checkpoint)
149
+ return model
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch==2.3.0
2
+ tokenizers==0.13.3
3
+ uvicorn
4
+ fastapi
5
+ pydantic
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff