umarigan commited on
Commit
ae36be9
1 Parent(s): 5188ba6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -30
app.py CHANGED
@@ -1,29 +1,46 @@
1
- # Turkish NER Demo for Various Models
2
-
3
- from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer, DebertaV2Tokenizer, DebertaV2Model
4
- import sentencepiece
5
  import streamlit as st
6
  import pandas as pd
7
  import spacy
 
 
 
 
8
 
9
  st.set_page_config(layout="wide")
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  example_list = [
12
- "Mustafa Kemal Atatürk 1919 yılında Samsun'a çıktı.",
13
  """Mustafa Kemal Atatürk, Türk asker, devlet adamı ve Türkiye Cumhuriyeti'nin kurucusudur.
14
- 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."""
 
15
  ]
16
 
17
  st.title("Demo for Turkish NER Models")
18
 
19
- model_list = ['akdeniz27/bert-base-turkish-cased-ner',
20
- 'akdeniz27/convbert-base-turkish-cased-ner',
21
- # 'akdeniz27/xlm-roberta-base-turkish-ner',
22
- 'girayyagmur/bert-base-turkish-ner-cased',
23
- 'FacebookAI/xlm-roberta-large',
24
- 'savasy/bert-base-turkish-ner-cased',
25
- 'xlm-roberta-large-finetuned-conll03-english',
26
- 'asahi417/tner-xlm-roberta-base-ontonotes5']
 
27
 
28
  st.sidebar.header("Select NER Model")
29
  model_checkpoint = st.sidebar.radio("", model_list)
@@ -31,24 +48,31 @@ model_checkpoint = st.sidebar.radio("", model_list)
31
  st.sidebar.write("For details of models: 'https://huggingface.co/akdeniz27/")
32
  st.sidebar.write("")
33
 
34
- if model_checkpoint == "akdeniz27/xlm-roberta-base-turkish-ner":
35
- aggregation = "simple"
36
- elif model_checkpoint == "xlm-roberta-large-finetuned-conll03-english" or model_checkpoint == "asahi417/tner-xlm-roberta-base-ontonotes5":
37
  aggregation = "simple"
38
- st.sidebar.write("")
39
- st.sidebar.write("The selected NER model is included just to show the zero-shot transfer learning capability of XLM-Roberta pretrained language model.")
40
  else:
41
  aggregation = "first"
42
-
43
  st.subheader("Select Text Input Method")
44
- input_method = st.radio("", ('Select from Examples', 'Write or Paste New Text'))
 
45
  if input_method == 'Select from Examples':
46
  selected_text = st.selectbox('Select Text from List', example_list, index=0, key=1)
47
- st.subheader("Text to Run")
48
  input_text = st.text_area("Selected Text", selected_text, height=128, max_chars=None, key=2)
49
  elif input_method == "Write or Paste New Text":
50
- st.subheader("Text to Run")
51
  input_text = st.text_area('Write or Paste Text Below', value="", height=128, max_chars=None, key=2)
 
 
 
 
 
 
 
 
 
 
52
 
53
  @st.cache_resource
54
  def setModel(model_checkpoint, aggregation):
@@ -61,7 +85,7 @@ def get_html(html: str):
61
  WRAPPER = """<div style="overflow-x: auto; border: 1px solid #e6e9ef; border-radius: 0.25rem; padding: 1rem; margin-bottom: 2.5rem">{}</div>"""
62
  html = html.replace("\n", " ")
63
  return WRAPPER.format(html)
64
-
65
  @st.cache_resource
66
  def entity_comb(output):
67
  output_comb = []
@@ -74,11 +98,11 @@ def entity_comb(output):
74
  else:
75
  output_comb.append(entity)
76
  return output_comb
77
-
78
  Run_Button = st.button("Run", key=None)
79
 
80
  if Run_Button and input_text != "":
81
-
82
  ner_pipeline = setModel(model_checkpoint, aggregation)
83
  output = ner_pipeline(input_text)
84
 
@@ -109,8 +133,6 @@ if Run_Button and input_text != "":
109
  else:
110
  if ent["label"] == "PER": ent["label"] = "PERSON"
111
 
112
- # colors = {'PER': '#85DCDF', 'LOC': '#DF85DC', 'ORG': '#DCDF85', 'MISC': '#85ABDF',}
113
- html = spacy.displacy.render(spacy_display, style="ent", minify=True, manual=True, options={"ents": spacy_entity_list}) # , "colors": colors})
114
  style = "<style>mark.entity { display: inline-block }</style>"
115
- st.write(f"{style}{get_html(html)}", unsafe_allow_html=True)
116
-
 
 
 
 
 
1
  import streamlit as st
2
  import pandas as pd
3
  import spacy
4
+ from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer
5
+ import PyPDF2
6
+ import docx
7
+ import io
8
 
9
  st.set_page_config(layout="wide")
10
 
11
+ # Function to read text from uploaded file
12
+ def read_file(file):
13
+ if file.type == "text/plain":
14
+ return file.getvalue().decode("utf-8")
15
+ elif file.type == "application/pdf":
16
+ pdf_reader = PyPDF2.PdfReader(io.BytesIO(file.getvalue()))
17
+ return " ".join(page.extract_text() for page in pdf_reader.pages)
18
+ elif file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
19
+ doc = docx.Document(io.BytesIO(file.getvalue()))
20
+ return " ".join(paragraph.text for paragraph in doc.paragraphs)
21
+ else:
22
+ st.error("Unsupported file type")
23
+ return None
24
+
25
+ # Rest of your code remains the same
26
  example_list = [
27
+ "Mustafa Kemal Atatürk 1919 yılında Samsun'a çıktı.",
28
  """Mustafa Kemal Atatürk, Türk asker, devlet adamı ve Türkiye Cumhuriyeti'nin kurucusudur.
29
+ # ... (rest of the example text)
30
+ """
31
  ]
32
 
33
  st.title("Demo for Turkish NER Models")
34
 
35
+ model_list = [
36
+ 'akdeniz27/bert-base-turkish-cased-ner',
37
+ 'akdeniz27/convbert-base-turkish-cased-ner',
38
+ 'girayyagmur/bert-base-turkish-ner-cased',
39
+ 'FacebookAI/xlm-roberta-large',
40
+ 'savasy/bert-base-turkish-ner-cased',
41
+ 'xlm-roberta-large-finetuned-conll03-english',
42
+ 'asahi417/tner-xlm-roberta-base-ontonotes5'
43
+ ]
44
 
45
  st.sidebar.header("Select NER Model")
46
  model_checkpoint = st.sidebar.radio("", model_list)
 
48
  st.sidebar.write("For details of models: 'https://huggingface.co/akdeniz27/")
49
  st.sidebar.write("")
50
 
51
+ if model_checkpoint in ["akdeniz27/xlm-roberta-base-turkish-ner", "xlm-roberta-large-finetuned-conll03-english", "asahi417/tner-xlm-roberta-base-ontonotes5"]:
 
 
52
  aggregation = "simple"
53
+ if model_checkpoint != "akdeniz27/xlm-roberta-base-turkish-ner":
54
+ st.sidebar.write("The selected NER model is included just to show the zero-shot transfer learning capability of XLM-Roberta pretrained language model.")
55
  else:
56
  aggregation = "first"
57
+
58
  st.subheader("Select Text Input Method")
59
+ input_method = st.radio("", ('Select from Examples', 'Write or Paste New Text', 'Upload File'))
60
+
61
  if input_method == 'Select from Examples':
62
  selected_text = st.selectbox('Select Text from List', example_list, index=0, key=1)
 
63
  input_text = st.text_area("Selected Text", selected_text, height=128, max_chars=None, key=2)
64
  elif input_method == "Write or Paste New Text":
 
65
  input_text = st.text_area('Write or Paste Text Below', value="", height=128, max_chars=None, key=2)
66
+ else:
67
+ uploaded_file = st.file_uploader("Choose a file", type=["txt", "pdf", "docx"])
68
+ if uploaded_file is not None:
69
+ input_text = read_file(uploaded_file)
70
+ if input_text:
71
+ st.text_area("Extracted Text", input_text, height=128, max_chars=None, key=2)
72
+ else:
73
+ input_text = ""
74
+
75
+ # Rest of your functions (setModel, get_html, entity_comb) remain the same
76
 
77
  @st.cache_resource
78
  def setModel(model_checkpoint, aggregation):
 
85
  WRAPPER = """<div style="overflow-x: auto; border: 1px solid #e6e9ef; border-radius: 0.25rem; padding: 1rem; margin-bottom: 2.5rem">{}</div>"""
86
  html = html.replace("\n", " ")
87
  return WRAPPER.format(html)
88
+
89
  @st.cache_resource
90
  def entity_comb(output):
91
  output_comb = []
 
98
  else:
99
  output_comb.append(entity)
100
  return output_comb
101
+
102
  Run_Button = st.button("Run", key=None)
103
 
104
  if Run_Button and input_text != "":
105
+ # Your existing processing code remains the same
106
  ner_pipeline = setModel(model_checkpoint, aggregation)
107
  output = ner_pipeline(input_text)
108
 
 
133
  else:
134
  if ent["label"] == "PER": ent["label"] = "PERSON"
135
 
136
+ html = spacy.displacy.render(spacy_display, style="ent", minify=True, manual=True, options={"ents": spacy_entity_list})
 
137
  style = "<style>mark.entity { display: inline-block }</style>"
138
+ st.write(f"{style}{get_html(html)}", unsafe_allow_html=True)