Spaces:
Sleeping
Sleeping
File size: 7,777 Bytes
7a1582c 71f491e 7a1582c 71f491e 7a1582c 5c82ebc 71f491e 7a1582c 71f491e 7a1582c 71f491e 7a1582c 71f491e 7a1582c 5c82ebc 701a95c 5c82ebc 71f491e 5c82ebc 71f491e 5c82ebc 701a95c 5c82ebc 71f491e 5c82ebc 7a1582c 9f9b485 7a1582c 9f9b485 7a1582c d76edf1 7a1582c | 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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | import gradio as gr
from transformers import pipeline
# ---------------------------------------------------
# Models
# ---------------------------------------------------
MODEL_NAMES = [
"c-ho/2026-04-24-crf-classweights-clean",
"c-ho/2026-04-23-crf-classweights-clean",
]
EXAMPLE_TEXT = (
"As a result, Indo-European developed a minimal vowel system "
"combined with a very large consonant inventory including "
"glottalized stops, also grammatical gender and adjectival agreement."
)
# ---------------------------------------------------
# Lazy model cache
# ---------------------------------------------------
model_cache = {}
def get_model(model_name):
if model_name not in model_cache:
model_cache[model_name] = pipeline(
"ner",
model=model_name,
aggregation_strategy="simple"
)
return model_cache[model_name]
# ---------------------------------------------------
# Model info
# ---------------------------------------------------
model_info = {
m: {
"link": f"https://huggingface.co/{m}",
"usage": f'''from transformers import pipeline
ner = pipeline(
"ner",
model="{m}",
aggregation_strategy="simple"
)
result = ner("Hello world")
print(result)
'''
}
for m in MODEL_NAMES
}
# ---------------------------------------------------
# UI helper
# ---------------------------------------------------
def display_model_info(model_name):
info = model_info[model_name]
return (
info["usage"],
f"[Open model page]({info['link']})"
)
# ---------------------------------------------------
# Merge subwords into full spans
# ---------------------------------------------------
def merge_subwords(results):
merged = []
current = None
for token in results:
word = token.get("word", "")
label = token.get(
"entity_group",
token.get("entity", "UNK")
)
score = token.get("score", 0.0)
start = token.get("start", 0)
end = token.get("end", 0)
# Continuation token
if word.startswith("##") and current is not None:
current["word"] += word[2:]
current["end"] = end
current["score"] = max(current["score"], score)
else:
# flush previous
if current is not None:
merged.append(current)
current = {
"word": word,
"start": start,
"end": end,
"entity_group": label,
"score": score
}
if current is not None:
merged.append(current)
return merged
# ---------------------------------------------------
# Main inference function
# ---------------------------------------------------
def analyze_text(text, model_name):
ner = get_model(model_name)
results = ner(text)
# merge subwords first
results = merge_subwords(results)
highlighted_text = []
last_idx = 0
table_rows = []
for ent in results:
start = ent["start"]
end = ent["end"]
label = ent["entity_group"]
# Add normal text before entity
if start > last_idx:
highlighted_text.append(
(text[last_idx:start], None)
)
# Add highlighted entity
highlighted_text.append(
(text[start:end], label)
)
last_idx = end
table_rows.append([
ent["word"],
label,
round(ent["score"], 3)
])
# Add remaining text
if last_idx < len(text):
highlighted_text.append(
(text[last_idx:], None)
)
return highlighted_text, table_rows
# ---------------------------------------------------
# Entity colors
# ---------------------------------------------------
COLOR_MAP = {
# -----------------------------------
# Academic / theoretical
# -----------------------------------
"AcademicDiscipline": "#5339a8", # intense purple
"AmbiguouslyDefinedConcept": "#ab8fbd", # muted purple
"UnclassifiedLinguisticConcept": "#d4a1c7", # soft gray-pink
# -----------------------------------
# Language / general linguistic
# -----------------------------------
"LanguageRelatedTerm": "#E9C46A", # warm sand yellow
"OtherLinguisticTerm": "#A8DADC", # pale cyan
"LanguageResourceInformation": "#457B9D", # medium blue
# -----------------------------------
# Phonology / graphemics
# -----------------------------------
"PhonologicalPhenomenon": "#E76F51", # coral red
"GraphemicPhenomenon": "#F4A261", # orange
# -----------------------------------
# Morphology / syntax
# -----------------------------------
"MorphologicalPhenomenon": "#37bdac", # turquoise green
"MorphosyntacticPhenomenon": "#43916d", # medium green
"SyntacticPhenomenon": "#53703a", # darker moss
# -----------------------------------
# Lexicon / semantics / discourse
# -----------------------------------
"LexicalPhenomenon": "#577590", # slate blue
"SemanticPhenomenon": "#4361EE", # vivid blue
"DiscoursePhenomenon": "#B5179E", # magenta-purple
# -----------------------------------
# Special / misc
# -----------------------------------
"NEW_TAG": "#FF006E", # neon pink
"TOPNODE_DUMMY": "#BDBDBD", # neutral gray
# Outside tag
"O": "#FFFFFF"
}
# ---------------------------------------------------
# UI
# ---------------------------------------------------
with gr.Blocks(title="Linguistic Annotation Demo") as demo:
gr.Markdown(
"""
# Linguistic Annotation Demo
This Space demonstrates custom linguistic sequence tagging models
for detecting linguistic terminology and phenomena with concepts from an ontology based on the Bibliography of Linguistic Literature (BLL).
"""
)
with gr.Row():
with gr.Column(scale=1):
model_selector = gr.Dropdown(
choices=MODEL_NAMES,
value=MODEL_NAMES[0],
label="Select Model"
)
text_input = gr.Textbox(
label="Input Text",
lines=8,
value=EXAMPLE_TEXT
)
run_button = gr.Button("Run Annotation")
with gr.Column(scale=1):
code_output = gr.Code(
label="Transformers Usage"
)
link_output = gr.Markdown()
highlighted_output = gr.HighlightedText(
label="Annotated Text",
combine_adjacent=True,
color_map=COLOR_MAP,
show_legend=True,
elem_id="ner-highlight"
)
entity_table = gr.Dataframe(
headers=["Text", "Label", "Confidence"],
datatype=["str", "str", "number"],
interactive=False,
label="Detected Entities"
)
# -------------------------
# Events
# -------------------------
run_button.click(
analyze_text,
inputs=[text_input, model_selector],
outputs=[highlighted_output, entity_table]
)
model_selector.change(
display_model_info,
inputs=model_selector,
outputs=[code_output, link_output]
)
demo.load(
display_model_info,
inputs=model_selector,
outputs=[code_output, link_output]
)
# ---------------------------------------------------
# Launch
# ---------------------------------------------------
demo.launch(
server_name="0.0.0.0",
server_port=7860
) |