Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,22 +1,57 @@
|
|
| 1 |
-
from transformers import pipeline
|
| 2 |
-
import gradio as gr
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import pipeline
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import pandas as pd
|
| 4 |
+
|
| 5 |
+
# Load NER model
|
| 6 |
+
ner_model = pipeline(
|
| 7 |
+
"ner",
|
| 8 |
+
model="dslim/bert-base-NER",
|
| 9 |
+
aggregation_strategy="simple"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
def create_df():
|
| 13 |
+
return pd.DataFrame(
|
| 14 |
+
columns=["Entity", "Confidence (%)"]
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
def ner_inference(text):
|
| 18 |
+
entities = ner_model(text)
|
| 19 |
+
|
| 20 |
+
per_rows, org_rows, loc_rows = [], [], []
|
| 21 |
+
|
| 22 |
+
for ent in entities:
|
| 23 |
+
row = [ent["word"], round(ent["score"] * 100, 2)]
|
| 24 |
+
|
| 25 |
+
if ent["entity_group"] == "PER":
|
| 26 |
+
per_rows.append(row)
|
| 27 |
+
elif ent["entity_group"] == "ORG":
|
| 28 |
+
org_rows.append(row)
|
| 29 |
+
elif ent["entity_group"] == "LOC":
|
| 30 |
+
loc_rows.append(row)
|
| 31 |
+
|
| 32 |
+
df_per = pd.DataFrame(per_rows, columns=["Person", "Confidence (%)"]) if per_rows else create_df()
|
| 33 |
+
df_org = pd.DataFrame(org_rows, columns=["Organization", "Confidence (%)"]) if org_rows else create_df()
|
| 34 |
+
df_loc = pd.DataFrame(loc_rows, columns=["Location", "Confidence (%)"]) if loc_rows else create_df()
|
| 35 |
+
|
| 36 |
+
return df_per, df_org, df_loc
|
| 37 |
+
|
| 38 |
+
# Gradio UI
|
| 39 |
+
interface = gr.Interface(
|
| 40 |
+
fn=ner_inference,
|
| 41 |
+
inputs=gr.Textbox(
|
| 42 |
+
lines=5,
|
| 43 |
+
placeholder="Enter text here...",
|
| 44 |
+
label="Input Text"
|
| 45 |
+
),
|
| 46 |
+
outputs=[
|
| 47 |
+
gr.Dataframe(label="👤 Persons", interactive=False),
|
| 48 |
+
gr.Dataframe(label="🏢 Organizations", interactive=False),
|
| 49 |
+
gr.Dataframe(label="📍 Locations", interactive=False),
|
| 50 |
+
],
|
| 51 |
+
title="Named Entity Recognition (NER)",
|
| 52 |
+
description="NER results grouped by entity type for better readability and usability.",
|
| 53 |
+
theme="dark"
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
if __name__ == "__main__":
|
| 57 |
+
interface.launch()
|