ELHACHYMI commited on
Commit
dd7aec2
·
verified ·
1 Parent(s): 5239852

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -45
app.py CHANGED
@@ -1,13 +1,13 @@
1
  import gradio as gr
2
  from transformers import pipeline
3
 
4
- # -------------------------------
5
  # MODEL CONFIGURATION
6
- # -------------------------------
7
 
8
  model_name = "ELHACHYMI/bert-ner"
9
 
10
- example_sent = "Bill Gates founded Microsoft in the United States."
11
 
12
  example_list = [
13
  "Elon Musk is the CEO of SpaceX and Tesla.",
@@ -17,103 +17,166 @@ example_list = [
17
  "Apple Inc. was created by Steve Jobs in Cupertino.",
18
  ]
19
 
20
- # Model info for usage display
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  model_info = {
22
  model_name: {
23
  "link": f"https://huggingface.co/{model_name}",
24
  "usage": f"""from transformers import pipeline
25
 
26
  ner = pipeline("ner", model="{model_name}", aggregation_strategy="simple")
27
- text = "{example_sent}"
28
- print(ner(text))""",
29
  }
30
  }
31
 
32
- # Load model
33
  ner_pipeline = pipeline("ner", model=model_name, aggregation_strategy="simple")
34
 
35
 
36
- # -------------------------------
37
  # DISPLAY MODEL INFO
38
- # -------------------------------
39
 
40
  def display_model_info(model_name):
41
  info = model_info[model_name]
42
  usage_code = info["usage"]
43
- link_button = f'[ Open model page: {model_name}]({info["link"]})'
44
- return usage_code, link_button
45
-
46
 
47
- # -------------------------------
48
- # NER ANALYSIS FUNCTION
49
- # -------------------------------
50
 
51
- def analyze_text(text):
52
- ner_results = ner_pipeline(text)
 
53
 
54
- highlighted_text = []
 
 
55
  last_idx = 0
56
 
57
- for entity in ner_results:
58
- start = entity["start"]
59
- end = entity["end"]
60
- label = entity["entity_group"]
61
 
62
- # Text before entity
63
  if start > last_idx:
64
- highlighted_text.append((text[last_idx:start], None))
65
 
66
- # Entity text
67
- highlighted_text.append((text[start:end], label))
68
  last_idx = end
69
 
70
- # Remaining text
71
  if last_idx < len(text):
72
- highlighted_text.append((text[last_idx:], None))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
- return highlighted_text
 
75
 
 
 
 
 
 
 
76
 
77
- # -------------------------------
78
- # GRADIO INTERFACE
79
- # -------------------------------
 
 
 
 
 
 
 
 
80
 
81
  with gr.Blocks() as demo:
82
  gr.Markdown("# Named Entity Recognition Demo using BERT")
83
- gr.Markdown("### Model: **ELHACHYMI/bert-ner**")
84
 
85
- # Input text
86
  text_input = gr.Textbox(
87
  label="Enter Text",
88
  lines=5,
89
- value=example_sent,
90
- placeholder="Type a sentence to analyze...",
91
  )
92
 
93
- # List of examples buttons
94
  with gr.Row():
95
  for ex in example_list:
96
  gr.Button(ex).click(lambda x=ex: x, outputs=text_input)
97
 
 
 
 
 
 
 
98
  analyze_button = gr.Button("Run NER Analysis")
99
 
100
- # Highlighted output
101
- output = gr.HighlightedText(label="NER Result", combine_adjacent=True)
 
 
 
 
 
 
 
102
 
103
- # Code + link output
104
- code_output = gr.Code(label="How to use this model in Python", visible=True)
105
  link_output = gr.Markdown()
106
 
107
- # Initialize code + link
108
  demo.load(
109
  fn=display_model_info,
110
  inputs=[gr.Textbox(value=model_name, visible=False)],
111
- outputs=[code_output, link_output],
112
  )
113
 
114
- # Run analysis
 
 
 
 
 
115
  analyze_button.click(
116
- analyze_text, inputs=[text_input], outputs=output
 
 
117
  )
118
 
119
  demo.launch()
 
1
  import gradio as gr
2
  from transformers import pipeline
3
 
4
+ # --------------------------------------
5
  # MODEL CONFIGURATION
6
+ # --------------------------------------
7
 
8
  model_name = "ELHACHYMI/bert-ner"
9
 
10
+ default_example = "Bill Gates founded Microsoft in the United States."
11
 
12
  example_list = [
13
  "Elon Musk is the CEO of SpaceX and Tesla.",
 
17
  "Apple Inc. was created by Steve Jobs in Cupertino.",
18
  ]
19
 
20
+ # Correct mapping from LABEL_X to entity names
21
+ ENTITY_MAP = {
22
+ "LABEL_0": "O",
23
+ "LABEL_1": "PER",
24
+ "LABEL_2": "PER",
25
+ "LABEL_3": "ORG",
26
+ "LABEL_4": "ORG",
27
+ "LABEL_5": "LOC",
28
+ "LABEL_6": "LOC",
29
+ "LABEL_7": "MISC",
30
+ "LABEL_8": "MISC",
31
+ }
32
+
33
+ # Colors for HTML rendering
34
+ COLOR_MAP = {
35
+ "PER": "#ff6666", # Red
36
+ "ORG": "#66b3ff", # Blue
37
+ "LOC": "#99ff99", # Green
38
+ "MISC": "#ffcc66", # Orange
39
+ }
40
+
41
  model_info = {
42
  model_name: {
43
  "link": f"https://huggingface.co/{model_name}",
44
  "usage": f"""from transformers import pipeline
45
 
46
  ner = pipeline("ner", model="{model_name}", aggregation_strategy="simple")
47
+ text = "{default_example}"
48
+ print(ner(text))"""
49
  }
50
  }
51
 
 
52
  ner_pipeline = pipeline("ner", model=model_name, aggregation_strategy="simple")
53
 
54
 
55
+ # --------------------------------------
56
  # DISPLAY MODEL INFO
57
+ # --------------------------------------
58
 
59
  def display_model_info(model_name):
60
  info = model_info[model_name]
61
  usage_code = info["usage"]
62
+ model_link = f'[Open model page: {model_name}]({info["link"]})'
63
+ return usage_code, model_link
 
64
 
 
 
 
65
 
66
+ # --------------------------------------
67
+ # HIGHLIGHTED MODE FUNCTION
68
+ # --------------------------------------
69
 
70
+ def analyze_highlight(text):
71
+ results = ner_pipeline(text)
72
+ highlighted = []
73
  last_idx = 0
74
 
75
+ for ent in results:
76
+ start, end = ent["start"], ent["end"]
77
+ raw_label = ent["entity_group"]
78
+ label = ENTITY_MAP.get(raw_label, raw_label)
79
 
 
80
  if start > last_idx:
81
+ highlighted.append((text[last_idx:start], None))
82
 
83
+ highlighted.append((text[start:end], label))
 
84
  last_idx = end
85
 
 
86
  if last_idx < len(text):
87
+ highlighted.append((text[last_idx:], None))
88
+
89
+ return highlighted
90
+
91
+
92
+ # --------------------------------------
93
+ # HTML COLOR MODE FUNCTION
94
+ # --------------------------------------
95
+
96
+ def colorize_text(text):
97
+ results = ner_pipeline(text)
98
+ html = ""
99
+ last = 0
100
+
101
+ for ent in results:
102
+ start, end = ent["start"], ent["end"]
103
+ raw_label = ent["entity_group"]
104
+ label = ENTITY_MAP.get(raw_label, raw_label)
105
 
106
+ if start > last:
107
+ html += text[last:start]
108
 
109
+ color = COLOR_MAP.get(label, "#dddddd")
110
+ html += (
111
+ f"<span style='background-color:{color}; padding:2px; border-radius:3px;'>"
112
+ f"{text[start:end]} ({label})"
113
+ f"</span>"
114
+ )
115
 
116
+ last = end
117
+
118
+ if last < len(text):
119
+ html += text[last:]
120
+
121
+ return html
122
+
123
+
124
+ # --------------------------------------
125
+ # GRADIO UI
126
+ # --------------------------------------
127
 
128
  with gr.Blocks() as demo:
129
  gr.Markdown("# Named Entity Recognition Demo using BERT")
130
+ gr.Markdown("### Model: ELHACHYMI/bert-ner")
131
 
 
132
  text_input = gr.Textbox(
133
  label="Enter Text",
134
  lines=5,
135
+ value=default_example,
136
+ placeholder="Type a sentence to analyze."
137
  )
138
 
 
139
  with gr.Row():
140
  for ex in example_list:
141
  gr.Button(ex).click(lambda x=ex: x, outputs=text_input)
142
 
143
+ mode_selector = gr.Dropdown(
144
+ choices=["Highlighted Mode", "Colorized HTML Mode"],
145
+ value="Highlighted Mode",
146
+ label="Output Display Mode"
147
+ )
148
+
149
  analyze_button = gr.Button("Run NER Analysis")
150
 
151
+ output_highlight = gr.HighlightedText(
152
+ label="NER Result (Highlighted Mode)",
153
+ combine_adjacent=True,
154
+ visible=True
155
+ )
156
+ output_html = gr.HTML(
157
+ label="NER Result (Colorized HTML Mode)",
158
+ visible=False
159
+ )
160
 
161
+ code_output = gr.Code(label="How to use this model")
 
162
  link_output = gr.Markdown()
163
 
 
164
  demo.load(
165
  fn=display_model_info,
166
  inputs=[gr.Textbox(value=model_name, visible=False)],
167
+ outputs=[code_output, link_output]
168
  )
169
 
170
+ def run_analysis(text, mode):
171
+ if mode == "Highlighted Mode":
172
+ return analyze_highlight(text), gr.update(visible=True), gr.update(visible=False)
173
+ else:
174
+ return gr.update(), gr.update(visible=False), colorize_text(text)
175
+
176
  analyze_button.click(
177
+ run_analysis,
178
+ inputs=[text_input, mode_selector],
179
+ outputs=[output_highlight, output_highlight, output_html]
180
  )
181
 
182
  demo.launch()