Spaces:
Build error
Build error
Upload 3 files
Browse files- app.py +141 -0
- requirements.txt +6 -0
- tubitak2.pt +3 -0
app.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import torch
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
import string
|
| 7 |
+
import nltk
|
| 8 |
+
import emoji
|
| 9 |
+
from nltk.corpus import stopwords
|
| 10 |
+
from transformers import BertTokenizer, BertModel
|
| 11 |
+
|
| 12 |
+
nltk.download('stopwords')
|
| 13 |
+
stop_words_list = stopwords.words('turkish')
|
| 14 |
+
|
| 15 |
+
# Ön işleme adımlarını yapmak için fonksiyonumuzu tanımlıyoruz.
|
| 16 |
+
def preprocess_text(text):
|
| 17 |
+
# Küçük harflere çevirme
|
| 18 |
+
text = text.lower()
|
| 19 |
+
# Satır sonu karakterlerini kaldırma
|
| 20 |
+
text = re.sub(r'\n', ' ', text)
|
| 21 |
+
# Rakamları kaldırma
|
| 22 |
+
text = re.sub(r'\d', '', text)
|
| 23 |
+
# Noktalama işaretlerini kaldırma
|
| 24 |
+
text = text.translate(str.maketrans("", "", string.punctuation))
|
| 25 |
+
# Stop-words'leri kaldırma
|
| 26 |
+
words = text.split()
|
| 27 |
+
words = [word for word in words if not word in stop_words_list]
|
| 28 |
+
# Tekrarlanan karakterlerin kaldırılması
|
| 29 |
+
words = [re.sub(r'(.)\1{1,}', r'\1\1', word) for word in words]
|
| 30 |
+
# Tekrarlanan boşlukların kaldırılması
|
| 31 |
+
words = [word.strip() for word in words if len(word.strip()) > 1]
|
| 32 |
+
|
| 33 |
+
text = " ".join(words)
|
| 34 |
+
return text
|
| 35 |
+
|
| 36 |
+
class BertClassifier(torch.nn.Module):
|
| 37 |
+
def __init__(self, dropout=0.5):
|
| 38 |
+
super(BertClassifier, self).__init__()
|
| 39 |
+
|
| 40 |
+
self.bert = BertModel.from_pretrained("dbmdz/bert-base-turkish-uncased")
|
| 41 |
+
self.dropout = torch.nn.Dropout(dropout)
|
| 42 |
+
# Kullandığımız önceden eğilmiş model "base" sınıfına ait bir BERT modelidir. Yani;
|
| 43 |
+
# 12 layers of Transformer encoder, 12 attention heads, 768 hidden size, 110M parameters.
|
| 44 |
+
# 768, BERT-base modelindeki hidden size'yi, 5 ise veri setimizdeki toplam kategori sayısını temsil ediyor.
|
| 45 |
+
self.linear = torch.nn.Linear(768, 5)
|
| 46 |
+
self.relu = torch.nn.ReLU()
|
| 47 |
+
|
| 48 |
+
def forward(self, input_id, mask):
|
| 49 |
+
# _ değişkeni dizideki tüm belirteçlerin gömme vektörlerini içerir.
|
| 50 |
+
# pooled_output değişkeni [CLS] belirtecinin gömme vektörünü içerir.
|
| 51 |
+
# Metin sınıflandırma için polled_output değişkenini girdi olarak kullanmak yeterlidir.
|
| 52 |
+
|
| 53 |
+
# Attention mask, bir belirtecin gercek bir kelimemi yoksa dolgu mu olduğunu tanımlar.
|
| 54 |
+
# Eğer gerçek bir kelime ise attention_mask=1, eğer dolgu ise attention_mask=0 olacaktır.
|
| 55 |
+
# return_dict, değeri "True ise" bir BERT modeli tahmin, eğitim veya değerlendirme sırasında ortaya çıkan
|
| 56 |
+
# loss, logits, hidden_states ve attentions dan oluşan bir tuple oluşturacaktır.
|
| 57 |
+
_, pooled_output = self.bert(input_ids=input_id, attention_mask=mask, return_dict=False)
|
| 58 |
+
dropout_output = self.dropout(pooled_output)
|
| 59 |
+
linear_output = self.linear(dropout_output)
|
| 60 |
+
final_layer = self.relu(linear_output)
|
| 61 |
+
|
| 62 |
+
return final_layer
|
| 63 |
+
|
| 64 |
+
model = BertClassifier()
|
| 65 |
+
tokenizer = BertTokenizer.from_pretrained("dbmdz/bert-base-turkish-uncased")
|
| 66 |
+
model.load_state_dict(torch.load('tubitak2.pt', map_location=torch.device('cpu')))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def predict_text(model, sentence):
|
| 71 |
+
device = torch.device("cpu")
|
| 72 |
+
#model = model.cuda()
|
| 73 |
+
# Prediction işlemi sırasında model ağırlıklarını değiştirmeyeceğimiz modelin gradyanlara ihtiyacı yoktur
|
| 74 |
+
# "no_grad" fonksiyonu ile gradyan hesaplarını devre dışı bırakıyoruz.
|
| 75 |
+
with torch.no_grad():
|
| 76 |
+
# text = Modeli eğitmek için kullanılacak veri setindeki "clean_text" sütunundaki her bir satır.
|
| 77 |
+
# padding = Her bir diziyi belirttiğimiz maksimum uzunluga kadar doldurmak için.
|
| 78 |
+
# max_length = Her bir dizinin maksimum uzunluğu
|
| 79 |
+
# truncation = Eğer değeri "True" ise dizimiz maksimum uzunluğu aşar ise onu keser.
|
| 80 |
+
# 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.
|
| 81 |
+
input_id = tokenizer(sentence, padding='max_length', max_length = 512, truncation=True, return_tensors="pt")
|
| 82 |
+
|
| 83 |
+
# Attention mask, bir belirtecin gercek bir kelimemi yoksa dolgu mu olduğunu tanımlar.
|
| 84 |
+
# Eğer gerçek bir kelime ise attention_mask=1, eğer dolgu ise attention_mask=0 olacaktır.
|
| 85 |
+
mask = input_id['attention_mask'].to(device)
|
| 86 |
+
|
| 87 |
+
# squeeze() fonksiyonu ile "input_ids" özelliğindeki tensörlerin boyutu 1 olan boyutları
|
| 88 |
+
# kaldırarak, tensörün boyutunu azaltıyoruz.
|
| 89 |
+
input_id = input_id['input_ids'].squeeze(1).to(device)
|
| 90 |
+
|
| 91 |
+
# Modelin eğitim verileri üzerindeki tahminlerinin sonuçları saklanır.
|
| 92 |
+
output = model(input_id, mask)
|
| 93 |
+
|
| 94 |
+
categories = {
|
| 95 |
+
0: 'HAM',
|
| 96 |
+
1: 'SPAM',
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
# Kategorik sınıfı döndür.
|
| 100 |
+
if categories.get(output.argmax(dim=1)) == 0:
|
| 101 |
+
return st.success("Sonuç: " + categories.get(output.argmax(dim=1).item()))
|
| 102 |
+
else:
|
| 103 |
+
return st.warning("Sonuç: " + categories.get(output.argmax(dim=1).item()))
|
| 104 |
+
|
| 105 |
+
import re
|
| 106 |
+
|
| 107 |
+
# Ön işleme adımlarını yapmak için fonksiyonumuzu tanımlıyoruz.
|
| 108 |
+
def preprocess_text(text):
|
| 109 |
+
# Küçük harflere çevirme
|
| 110 |
+
text = text.lower()
|
| 111 |
+
# Satır sonu karakterlerini kaldırma
|
| 112 |
+
text = re.sub(r'\n', ' ', text)
|
| 113 |
+
# Rakamları kaldırma
|
| 114 |
+
text = re.sub(r'\d', '', text)
|
| 115 |
+
# Noktalama işaretlerini kaldırma
|
| 116 |
+
import string
|
| 117 |
+
text = text.translate(str.maketrans("", "", string.punctuation))
|
| 118 |
+
# Stop-words'leri kaldırma
|
| 119 |
+
words = text.split()
|
| 120 |
+
words = [word for word in words if not word in stop_words_list]
|
| 121 |
+
# Tekrarlanan karakterlerin kaldırılması
|
| 122 |
+
words = [re.sub(r'(.)\1{1,}', r'\1\1', word) for word in words]
|
| 123 |
+
# Tekrarlanan boşlukların kaldırılması
|
| 124 |
+
words = [word.strip() for word in words if len(word.strip()) > 1]
|
| 125 |
+
|
| 126 |
+
text = " ".join(words)
|
| 127 |
+
return text
|
| 128 |
+
|
| 129 |
+
def predict(text):
|
| 130 |
+
# TODO:
|
| 131 |
+
regex = r'@\w+\s?'
|
| 132 |
+
text = re.sub(regex, '', text)
|
| 133 |
+
text = preprocess_text(text)
|
| 134 |
+
predict_text(text)
|
| 135 |
+
|
| 136 |
+
st.title("Türkçe Zararlı Metin Sınıflandırma")
|
| 137 |
+
text = st.text_input("Bir metin giriniz...")
|
| 138 |
+
res = st.button("Sınıflandır")
|
| 139 |
+
|
| 140 |
+
if res:
|
| 141 |
+
predict(model, text)
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
emoji==2.2.0
|
| 2 |
+
nltk==3.8
|
| 3 |
+
pandas==1.5.3
|
| 4 |
+
streamlit==1.22.0
|
| 5 |
+
torch==2.0.0
|
| 6 |
+
transformers==4.27.2
|
tubitak2.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e89cef3c4e1c7d075a46815edded245f9e790abf07d6a3fd4d91e0b66a6abf02
|
| 3 |
+
size 442570553
|