File size: 9,315 Bytes
d8bc695
4cd256c
d8bc695
b82696e
822c7af
f284c6a
b1962b7
e29bac8
259780b
 
d8bc695
62d3b1e
41aed23
8579f09
b82696e
 
 
8579f09
d8bc695
41aed23
 
d8bc695
41aed23
80d41f4
 
ab24356
 
 
80d41f4
d8bc695
b82696e
 
d8bc695
41aed23
b82696e
d8bc695
b82696e
 
 
 
41aed23
 
 
4cd256c
41aed23
 
259780b
 
41aed23
259780b
41aed23
 
 
 
 
 
4cd256c
259780b
 
41aed23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cd256c
41aed23
 
8579f09
b82696e
 
 
 
 
d8bc695
b82696e
 
 
 
 
41aed23
b82696e
 
 
 
 
 
 
 
 
f2bf1fd
b82696e
 
41aed23
269266b
 
 
e29bac8
269266b
259780b
269266b
 
 
 
4cd256c
 
269266b
4cd256c
269266b
 
2a387d1
3495fb1
259780b
 
 
4cd256c
 
 
259780b
 
 
4cd256c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259780b
4cd256c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import streamlit as st
from transformers import pipeline, AutoModelForSequenceClassification, AutoTokenizer, AutoModelForTokenClassification, AutoModelForCausalLM
import pandas as pd
import spacy
import io
import torch
import torchaudio
import librosa
from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor

st.set_page_config(layout="wide")

# Örnek metin listesi
example_list = [
    "Mustafa Kemal Atatürk 1919 yılında Samsun'a çıktı.", 
    """Mustafa Kemal Atatürk, Türk asker, devlet adamı ve Türkiye Cumhuriyeti'nin kurucusudur.
Birinci Dünya Savaşı sırasında Osmanlı ordusunda görev yapan Atatürk, Çanakkale Cephesi'nde miralaylığa, Sina ve Filistin Cephesi'nde ise Yıldırım Orduları komutanlığına atandı. Savaşın sonunda, Osmanlı Imparatorluğu'nun yenilgisini takiben Kurtuluş Savaşı ile simgelenen Türk Ulusal Hareketi'ne öncülük ve önderlik etti. Türk Kurtuluş Savaşı sürecinde Ankara Hükümeti'ni kurdu, Türk Orduları Başkomutanı olarak Sakarya Meydan Muharebesi'ndeki başarısından dolayı 19 Eylül 1921 tarihinde "Gazi" unvanını aldı ve mareşallik rütbesine yükseldi. Askeri ve siyasi eylemleriyle İtilaf Devletleri ve destekçilerine karşı zafer kazandı. Savaşın ardından Cumhuriyet Halk Partisi'ni Halk Fırkası adıyla kurdu ve ilk genel başkanı oldu. 29 Ekim 1923'te Cumhuriyetin ilanı akabinde Cumhurbaşkanı seçildi. 1938'deki ölümüne dek dört dönem bu görevi yürüterek Türkiye'de en uzun süre cumhurbaşkanlığı yapmış kişi oldu."""
]

# Uygulama başlığı
st.title("NLP Toolkit")

# Model seçim
model_list = {
    'Metin Sınıflandırma': 'dbmdz/bert-base-turkish-cased',
    'Metin Analizi': 'savasy/bert-base-turkish-ner-cased',
    'Duygu Analizi': 'akdeniz27/xlm-roberta-base-turkish-ner',
    'Metin Oluşturma': 'dbmdz/bert-base-turkish-cased'
}

st.sidebar.header("Select NER Model")
model_checkpoint = st.sidebar.radio("", model_list)

st.sidebar.write("For details of models: 'https://huggingface.co/WhiteAngelss/")
st.sidebar.write("")

if model_checkpoint == "akdeniz27/xlm-roberta-base-turkish-ner":
    aggregation = "simple"
else:
    aggregation = "first"

# Metin giriş yöntemi
st.subheader("Metin Giriş Yöntemi Seç")
input_method = st.radio("", ('Örneklerden Seç', 'Metin Yaz veya Yapıştır', 'Dosya Yükle', 'Ses Dosyası Yükle'))

if input_method == 'Örneklerden Seç':
    selected_text = st.selectbox('Metin Seç', example_list, index=0, key="example_selectbox")
    input_text = st.text_area("Metin", selected_text, height=128, key="text_area")
elif input_method == "Metin Yaz veya Yapıştır":
    input_text = st.text_area('Metin Yaz veya Yapıştır', value="", height=128, key="text_area")
elif input_method == "Dosya Yükle":
    uploaded_file = st.file_uploader("Dosya Seç", type="txt")
    if uploaded_file is not None:
        input_text = str(uploaded_file.read(), "utf-8")
    else:
        input_text = ""
elif input_method == "Ses Dosyası Yükle":
    uploaded_audio = st.file_uploader("Ses Dosyasını Seç", type=["wav"], key="audio_file_uploader")
    audio_bytes = uploaded_audio.read() if uploaded_audio is not None else None

@st.cache_resource
def load_pipeline(model_name, task_type):
    if task_type == "Metin Sınıflandırma":
        model = AutoModelForSequenceClassification.from_pretrained(model_name)
        tokenizer = AutoTokenizer.from_pretrained(model_name)
        return pipeline('text-classification', model=model, tokenizer=tokenizer)
    elif task_type == "Metin Analizi":
        model = AutoModelForTokenClassification.from_pretrained(model_name)
        tokenizer = AutoTokenizer.from_pretrained(model_name)
        return pipeline('ner', model=model, tokenizer=tokenizer)
    elif task_type == "Duygu Analizi":
        model = AutoModelForSequenceClassification.from_pretrained(model_name)
        tokenizer = AutoTokenizer.from_pretrained(model_name)
        return pipeline('sentiment-analysis', model=model, tokenizer=tokenizer)
    elif task_type == "Metin Oluşturma":
        model = AutoModelForCausalLM.from_pretrained(model_name)
        tokenizer = AutoTokenizer.from_pretrained(model_name)
        return pipeline('text-generation', model=model, tokenizer=tokenizer)

@st.cache_resource
def setModel(model_checkpoint, aggregation):
    model = AutoModelForTokenClassification.from_pretrained(model_checkpoint)
    tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
    return pipeline('ner', model=model, tokenizer=tokenizer, aggregation_strategy=aggregation)

@st.cache_resource
def get_html(html: str):
    WRAPPER = """<div style="overflow-x: auto; border: 1px solid #e6e9ef; border-radius: 0.25rem; padding: 1rem; margin-bottom: 2.5rem">{}</div>"""
    html = html.replace("\n", " ")
    return WRAPPER.format(html)

@st.cache_resource
def entity_comb(output):
    output_comb = []
    for ind, entity in enumerate(output):
        if ind == 0:
            output_comb.append(entity)
        elif output[ind]["start"] == output[ind-1]["end"] and output[ind]["entity_group"] == output[ind-1]["entity_group"]:
            output_comb[-1]["word"] = output_comb[-1]["word"] + output[ind]["word"]
            output_comb[-1]["end"] = output[ind]["end"]
        else:
            output_comb.append(entity)
    return output_comb

# Ses dosyasını metne çevirme fonksiyonu
def transcribe_audio(audio_file):
    processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-large-xlsr-53")
    model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-large-xlsr-53")
    
    audio_input = io.BytesIO(audio_file)
    waveform, sample_rate = torchaudio.load(audio_input, normalize=True)
    
    inputs = processor(waveform.squeeze().numpy(), sampling_rate=sample_rate, return_tensors="pt", padding="longest")
    
    with torch.no_grad():
        logits = model(inputs.input_values).logits
    
    predicted_ids = torch.argmax(logits, dim=-1)
    transcription = processor.batch_decode(predicted_ids)[0]
    
    return transcription

# Çalıştır butonu
if st.button("Çalıştır"):
    if input_method == "Ses Dosyası Yükle" and uploaded_audio is not None:
        transcription = transcribe_audio(uploaded_audio)
        st.subheader("Ses Transkripsiyonu")
        st.write(transcription)
    elif input_method in ["Metin Yaz veya Yapıştır", "Örneklerden Seç", "Dosya Yükle"] and input_text:
        task = st.sidebar.radio("Görev Seçin", ['Metin Sınıflandırma', 'Metin Analizi', 'Duygu Analizi', 'Metin Oluşturma'])
        
        if task == "Metin Sınıflandırma":
            pipeline_model = load_pipeline(model_checkpoint, task)
            output = pipeline_model(input_text)
            df = pd.DataFrame(output)
            st.subheader(f"{task} Sonuçları")
            st.dataframe(df)

        elif task == "Duygu Analizi":
            pipeline_model = load_pipeline(model_checkpoint, task)
            output = pipeline_model(input_text)
            df = pd.DataFrame(output)
            st.subheader(f"{task} Sonuçları")
            st.dataframe(df)

        elif task == "Metin Analizi":
            ner_pipeline = setModel(model_checkpoint, aggregation)
            output = ner_pipeline(input_text)
            output_comb = entity_comb(output)
            df = pd.DataFrame.from_dict(output_comb)
            cols_to_keep = ['word', 'entity_group', 'score', 'start', 'end']
            df_final = df[cols_to_keep]
            st.subheader("Tanımlanan Varlıklar")
            st.dataframe(df_final)

            st.subheader("Spacy Tarzı Görselleştirme")
            spacy_display = {"ents": [], "text": input_text, "title": None}

            for entity in output_comb:
                spacy_display["ents"].append({"start": entity["start"], "end": entity["end"], "label": entity["entity_group"]})

            tner_entity_list = ["person", "group", "facility", "organization", "geopolitical area", "location", "product", "event", "work of art", "law", "language", "date", "time", "percent", "money", "quantity", "ordinal number", "cardinal number"]
            spacy_entity_list = ["PERSON", "NORP", "FAC", "ORG", "GPE", "LOC", "PRODUCT", "EVENT", "WORK_OF_ART", "LAW", "LANGUAGE", "DATE", "TIME", "PERCENT", "MONEY", "QUANTITY", "ORDINAL", "CARDINAL", "MISC"]

            for ent in spacy_display["ents"]:
                if model_checkpoint == "asahi417/tner-xlm-roberta-base-ontonotes5":
                    ent["label"] = spacy_entity_list[tner_entity_list.index(ent["label"])]
                else:
                    if ent["label"] == "PER":
                        ent["label"] = "PERSON"

            html = spacy.displacy.render(spacy_display, style="ent", minify=True, manual=True, options={"ents": spacy_entity_list})
            style = "<style>mark.entity { display: inline-block }</style>"
            st.write(f"{style}{get_html(html)}", unsafe_allow_html=True)

        elif task == "Metin Oluşturma":
            pipeline_model = load_pipeline(model_checkpoint, task)
            output = pipeline_model(input_text, max_length=50, num_return_sequences=1)
            st.subheader(f"{task} Sonuçları")
            for idx, item in enumerate(output):
                st.write(f"Öneri {idx+1}: {item['generated_text']}")