thealper2 commited on
Commit
68db425
1 Parent(s): ead407c

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +28 -0
  2. app.py +96 -0
  3. requirements.txt +4 -0
Dockerfile ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use the official Python 3.9 image
2
+ FROM python:3.9
3
+
4
+ # Set the working directory to /code
5
+ WORKDIR /code
6
+
7
+ # Copy the current directory contents into the container at /code
8
+ COPY ./requirements.txt /code/requirements.txt
9
+
10
+ # Install requirements.txt
11
+ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
12
+
13
+ # Set up a new user named "user" with user ID 1000
14
+ RUN useradd -m -u 1000 user
15
+ # Switch to the "user" user
16
+ USER user
17
+ # Set home to the user's home directory
18
+ ENV HOME=/home/user \\
19
+ PATH=/home/user/.local/bin:$PATH
20
+
21
+ # Set the working directory to the user's home directory
22
+ WORKDIR $HOME/app
23
+
24
+ # Copy the current directory contents into the container at $HOME/app setting the owner to the user
25
+ COPY --chown=user . $HOME/app
26
+
27
+ # Start the FastAPI app on port 7860, the default port expected by Spaces
28
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import torch
4
+ import os
5
+ from transformers import BertTokenizer, BertModel
6
+
7
+ class BertClassifier(torch.nn.Module):
8
+ def __init__(self, dropout=0.5):
9
+ super(BertClassifier, self).__init__()
10
+
11
+ self.bert = BertModel.from_pretrained("dbmdz/bert-base-turkish-uncased")
12
+ self.dropout = torch.nn.Dropout(dropout)
13
+ # Kullandığımız önceden eğilmiş model "base" sınıfına ait bir BERT modelidir. Yani;
14
+ # 12 layers of Transformer encoder, 12 attention heads, 768 hidden size, 110M parameters.
15
+ # 768, BERT-base modelindeki hidden size'yi, 5 ise veri setimizdeki toplam kategori sayısını temsil ediyor.
16
+ self.linear = torch.nn.Linear(768, 5)
17
+ self.relu = torch.nn.ReLU()
18
+
19
+ def forward(self, input_id, mask):
20
+ # _ değişkeni dizideki tüm belirteçlerin gömme vektörlerini içerir.
21
+ # pooled_output değişkeni [CLS] belirtecinin gömme vektörünü içerir.
22
+ # Metin sınıflandırma için polled_output değişkenini girdi olarak kullanmak yeterlidir.
23
+
24
+ # Attention mask, bir belirtecin gercek bir kelimemi yoksa dolgu mu olduğunu tanımlar.
25
+ # Eğer gerçek bir kelime ise attention_mask=1, eğer dolgu ise attention_mask=0 olacaktır.
26
+ # return_dict, değeri "True ise" bir BERT modeli tahmin, eğitim veya değerlendirme sırasında ortaya çıkan
27
+ # loss, logits, hidden_states ve attentions dan oluşan bir tuple oluşturacaktır.
28
+ _, pooled_output = self.bert(input_ids=input_id, attention_mask=mask, return_dict=False)
29
+ dropout_output = self.dropout(pooled_output)
30
+ linear_output = self.linear(dropout_output)
31
+ final_layer = self.relu(linear_output)
32
+
33
+ return final_layer
34
+
35
+ model = BertClassifier()
36
+ tokenizer = BertTokenizer.from_pretrained("dbmdz/bert-base-turkish-uncased")
37
+ model.load_state_dict(torch.load('tubitak2.pt', map_location=torch.device('cpu')))
38
+
39
+ def predict_text(model, sentence):
40
+ device = torch.device("cpu")
41
+ #model = model.cuda()
42
+ # Prediction işlemi sırasında model ağırlıklarını değiştirmeyeceğimiz modelin gradyanlara ihtiyacı yoktur
43
+ # "no_grad" fonksiyonu ile gradyan hesaplarını devre dışı bırakıyoruz.
44
+ with torch.no_grad():
45
+ # text = Modeli eğitmek için kullanılacak veri setindeki "clean_text" sütunundaki her bir satır.
46
+ # padding = Her bir diziyi belirttiğimiz maksimum uzunluga kadar doldurmak için.
47
+ # max_length = Her bir dizinin maksimum uzunluğu
48
+ # truncation = Eğer değeri "True" ise dizimiz maksimum uzunluğu aşar ise onu keser.
49
+ # return_tensors = Döndürelecek tensörlerin türü. Pytorch kullandığımız için "pt" yazıyoruz. Tensorflow kullansaydık "tf" yazmamız gerekirdi.
50
+ input_id = tokenizer(sentence, padding='max_length', max_length = 512, truncation=True, return_tensors="pt")
51
+
52
+ # Attention mask, bir belirtecin gercek bir kelimemi yoksa dolgu mu olduğunu tanımlar.
53
+ # Eğer gerçek bir kelime ise attention_mask=1, eğer dolgu ise attention_mask=0 olacaktır.
54
+ mask = input_id['attention_mask'].to(device)
55
+
56
+ # squeeze() fonksiyonu ile "input_ids" özelliğindeki tensörlerin boyutu 1 olan boyutları
57
+ # kaldırarak, tensörün boyutunu azaltıyoruz.
58
+ input_id = input_id['input_ids'].squeeze(1).to(device)
59
+
60
+ # Modelin eğitim verileri üzerindeki tahminlerinin sonuçları saklanır.
61
+ output = model(input_id, mask)
62
+
63
+ categories = {
64
+ 0: 'HAM',
65
+ 1: 'SPAM',
66
+ }
67
+
68
+ # Kategorik sınıfı döndür.
69
+ return categories.get(output.argmax(dim=1).item())
70
+
71
+ def predict(df):
72
+ # TODO:
73
+ df['text'] = df['text'].apply(preprocess_text)
74
+
75
+ for i in range(len(df)):
76
+ df.loc[i, 'label'] = predict_text(model, df['text'][i])
77
+
78
+ return df
79
+
80
+ def get_file(file):
81
+ output_file = "output_GAT0R.csv"
82
+
83
+ # For windows users, replace path seperator
84
+ file_name = file.name.replace("\\", "/")
85
+ df = pd.read_csv(file_name, sep="|")
86
+ predict(df)
87
+
88
+ df.to_csv(output_file, index=False, sep="|")
89
+
90
+ return output_file
91
+
92
+ # Launch the interface with user password
93
+ iface = gr.Interface(get_file, "file", "file")
94
+
95
+ if __name__ == "__main__":
96
+ iface.launch(debug=True)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio==3.28.3
2
+ pandas==1.5.3
3
+ torch==2.0.0
4
+ transformers==4.27.2