Spaces:
Sleeping
Sleeping
File size: 6,286 Bytes
fc01824 05cb2a4 fc01824 05cb2a4 fc01824 05cb2a4 fc01824 05cb2a4 fc01824 05cb2a4 fc01824 05cb2a4 fc01824 05cb2a4 |
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 |
import time
from typing import Dict, List
import gradio as gr
import pandas as pd
from transformers import pipeline
class NERDemo:
def __init__(self):
self.ner_pipeline = pipeline(
"ner",
model="enesmanan/multilingual-xlm-roberta-ner",
aggregation_strategy="simple",
)
self.supported_languages = {
"en": "English",
"de": "German",
"tr": "Turkish",
"es": "Spanish",
"fr": "French",
}
def process_ner(self, text: str, language: str) -> Dict:
"""Process text through NER pipeline and return entities with metadata"""
if not text:
return {"text": "", "entities": []}
start_time = time.time()
entities = self.ner_pipeline(text)
processing_time = round((time.time() - start_time) * 1000, 2) # ms
# Create DataFrame for entity statistics
if entities:
df = pd.DataFrame(entities)
entity_stats = df["entity_group"].value_counts().to_dict()
else:
entity_stats = {}
return {
"text": text,
"entities": entities,
"stats": entity_stats,
"processing_time": processing_time,
}
def create_demo(self) -> gr.Interface:
"""Create and configure the Gradio interface"""
theme = gr.themes.Base(
primary_hue="blue",
secondary_hue="slate",
font=gr.themes.GoogleFont("Source Sans Pro"),
neutral_hue="slate",
).set(
body_text_color="*neutral_950",
block_background_fill="*neutral_50",
block_border_width="0px",
button_primary_background_fill="*primary_500",
button_primary_background_fill_hover="*primary_600",
button_primary_text_color="white",
input_background_fill="white",
block_radius="lg",
)
with gr.Blocks(theme=theme) as demo:
with gr.Row():
gr.HTML(
"""
<div style="text-align: center; max-width: 800px; margin: 0 auto; padding: 1rem; font-family: 'Source Sans Pro', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Arial', sans-serif;">
<h1 style="color: #374151; font-size: 2.5rem; font-weight: 600; margin-bottom: 0.5rem;">
Multilingual Named Entity Recognition
</h1>
<p style="color: #6B7280; font-size: 1.1rem; line-height: 1.5; margin-top: 0.5rem;">
This demo uses XLM-RoBERTa model fine-tuned for NER tasks in multiple languages.
Automatically detects and highlights named entities such as persons, organizations, locations, and more.
</p>
</div>
"""
)
with gr.Row():
with gr.Column(scale=3):
text_input = gr.Textbox(
label="Input Text",
placeholder="Enter text in any supported language...",
lines=3,
)
language = gr.Dropdown(
choices=list(self.supported_languages.values()),
label="Language (Optional)",
value="English",
)
with gr.Row():
submit_btn = gr.Button("Analyze", variant="primary")
clear_btn = gr.Button("Clear")
with gr.Column(scale=2):
with gr.Group():
gr.HTML(
"""
<div style="margin-bottom: 1rem;">
<h3 style="color: #374151; font-size: 1.25rem; font-weight: 600; margin-bottom: 0.5rem;">
Entity Statistics
</h3>
</div>
"""
)
stats_output = gr.Json(label="Detected Entities")
time_output = gr.Markdown(elem_classes="text-sm text-gray-600")
highlighted_output = gr.HighlightedText(
label="Detected Entities", show_legend=True
)
# Example inputs
examples = [
[
"Emma Watson starred in Harry Potter and studied at Oxford University while working with United Nations.",
"English",
],
[
"Die Deutsche Bank hat ihren Hauptsitz in Frankfurt, während BMW in München produziert.",
"German",
],
[
"Enes Fehmi Manan, İzmir'de yaşıyor ve Fibababanka'da çalışıyor.",
"Turkish",
],
[
"Le Louvre à Paris expose la Joconde de Leonardo da Vinci depuis le XIXe siècle.",
"French",
],
[
"El Real Madrid jugará contra el Barcelona en el Santiago Bernabéu el próximo mes.",
"Spanish",
],
]
gr.Examples(examples, inputs=[text_input, language])
# Event handlers
def process_and_format(text: str, lang: str) -> tuple:
result = self.process_ner(text, lang)
stats = result["stats"]
time_msg = f"Processing time: {result['processing_time']} ms"
return (result, stats, time_msg)
submit_btn.click(
process_and_format,
inputs=[text_input, language],
outputs=[highlighted_output, stats_output, time_output],
)
clear_btn.click(
lambda: (None, None, ""),
outputs=[highlighted_output, stats_output, time_output],
)
return demo
if __name__ == "__main__":
ner_demo = NERDemo()
demo = ner_demo.create_demo()
demo.launch(share=True)
|