Spaces:
Running on Zero
Running on Zero
Download app.py from hugging-apps/gliformer-2b: direct link, hf CLI and curl.
- Browser
- Download file 46.9 kB
-
https://huggingface.co/spaces/hugging-apps/gliformer-2b/resolve/main/app.py
- Command line
-
hf download hf://spaces/hugging-apps/gliformer-2b/app.py
-
curl -L -o app.py https://huggingface.co/spaces/hugging-apps/gliformer-2b/resolve/main/app.py
46.9 kB
import spaces # MUST come before torch / any CUDA-touching import
import json
import torch
import gradio as gr
from gliformer import GLiFormer
MODEL_ID = "knowledgator/gliformer-2b-v1.5"
# Explicit bf16. With no dtype kwarg the loader builds a mixed-precision
# model (bf16 backbone from the config, fp32 heads), and on this
# gliner/transformers combo the sequence-editing head then fails with
# "mat1 and mat2 must have the same dtype, but got BFloat16 and Float".
# Passing dtype explicitly casts the whole model uniformly; bf16 halves
# the VRAM (~5.3 GB packed) versus fp32 (~10.6 GB) with measurably identical
# quality on every task head (NER/classification/relation/structuring/
# embeddings all score 0.95โ1.0 either way).
model = GLiFormer.from_pretrained(MODEL_ID, load_tokenizer=True, dtype=torch.bfloat16)
model = model.to("cuda").eval()
CSS = """
#col-container { max-width: 1200px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""
# โโ Helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _parse_labels(labels_text: str) -> list:
"""Split a comma-separated label string into a clean list."""
return [part.strip() for part in (labels_text or "").split(",") if part.strip()]
def _dump(obj) -> str:
"""Pretty-print a prediction payload as JSON."""
return json.dumps(obj, indent=2, ensure_ascii=False, default=str)
def _highlights(text: str, entities) -> list:
"""Turn GLiFormer entity spans into gr.HighlightedText (substring, label) pairs."""
spans = []
for ent in entities or []:
start, end = ent.get("start"), ent.get("end")
if start is None or end is None:
continue
spans.append((int(start), int(end), ent.get("label") or ent.get("type") or "entity"))
spans.sort(key=lambda s: (s[0], -(s[1] - s[0])))
out, cursor = [], 0
for start, end, label in spans:
if start < cursor: # skip overlaps that HighlightedText cannot render
continue
if start > cursor:
out.append((text[cursor:start], None))
out.append((text[start:end], label))
cursor = end
if cursor < len(text):
out.append((text[cursor:], None))
return out or [(text, None)]
# โโ Task 1: named entity recognition โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@spaces.GPU(duration=10)
def extract_entities(
text: str,
entity_labels: str,
threshold: float = 0.5,
flat_ner: bool = True,
multi_label: bool = False,
):
"""Extract named entities from text with entity types chosen at inference time.
Args:
text: Input text to analyse.
entity_labels: Comma-separated entity types, e.g. "person, organization, location".
threshold: Confidence threshold for keeping a span.
flat_ner: Enforce non-overlapping spans.
multi_label: Allow a span to carry more than one entity type.
Returns:
The text as (substring, entity_label) pairs, plus the raw prediction JSON.
"""
labels = _parse_labels(entity_labels)
if not (text or "").strip():
return [("Please enter some text.", None)], "[]"
if not labels:
return [(text, None)], '"Please enter at least one entity label."'
try:
entities = model.predict_entities(
text,
labels,
threshold=float(threshold),
flat_ner=bool(flat_ner),
multi_label=bool(multi_label),
)
except Exception as exc: # surface model errors in the UI instead of 500ing
return [(text, None)], _dump({"error": str(exc)})
return _highlights(text, entities), _dump(entities)
# โโ Task 2: text classification โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@spaces.GPU(duration=10)
def classify_text(
text: str,
class_labels: str,
threshold: float = 0.5,
multi_label: bool = False,
):
"""Classify text against candidate classes supplied at inference time.
Args:
text: Input text to classify.
class_labels: Comma-separated candidate classes, e.g. "positive, negative, neutral".
threshold: Confidence threshold for keeping a class.
multi_label: Return every class above the threshold instead of only the best one.
Returns:
A label/confidence mapping and the raw prediction JSON.
"""
labels = _parse_labels(class_labels)
if not (text or "").strip():
return {"Please enter some text.": 0.0}, "[]"
if not labels:
return {"Please enter at least one class label.": 0.0}, "[]"
try:
predictions = model.classify(
text,
labels,
threshold=float(threshold),
multi_label=bool(multi_label),
)
except Exception as exc:
return {"error": 0.0}, _dump({"error": str(exc)})
scores = {}
for item in predictions or []:
if isinstance(item, dict) and "class_name" in item:
scores[str(item["class_name"])] = float(item.get("score") or 0.0)
if not scores:
scores = {"no class above threshold": 0.0}
return scores, _dump(predictions)
# โโ Task 3: joint entity + relation extraction โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@spaces.GPU(duration=10)
def extract_relations(
text: str,
entity_labels: str,
relation_labels: str,
threshold: float = 0.5,
flat_ner: bool = True,
):
"""Extract entities and the relations between them in a single joint pass.
Args:
text: Input text to analyse.
entity_labels: Comma-separated entity types the relation endpoints may take.
relation_labels: Comma-separated relation types, e.g. "CEO of, succeeded".
threshold: Confidence threshold for spans and triples.
flat_ner: Enforce non-overlapping entity spans.
Returns:
Highlighted entities, a head/relation/tail table, and the raw prediction JSON.
"""
entities_in = _parse_labels(entity_labels)
relations_in = _parse_labels(relation_labels)
if not (text or "").strip():
return [("Please enter some text.", None)], [["โ", "โ", "โ", "โ"]], "{}"
if not entities_in or not relations_in:
return (
[(text, None)],
[["โ", "โ", "โ", "โ"]],
'"Please provide both entity labels and relation labels."',
)
try:
results = model.inference(
text,
joint_relations={
"relations": {"entities": entities_in, "relations": relations_in}
},
threshold=float(threshold),
flat_ner=bool(flat_ner),
)
except Exception as exc:
return [(text, None)], [["โ", "โ", "โ", "โ"]], _dump({"error": str(exc)})
entities = (results.get("ner") or [[]])[0]
triples = (results.get("joint_relex") or [[]])[0]
rows = []
for triple in triples or []:
head = (triple.get("head") or {}).get("text", "")
tail = (triple.get("tail") or {}).get("text", "")
score = triple.get("score")
rows.append(
[
str(head),
str(triple.get("relation", "")),
str(tail),
f"{float(score):.3f}" if score is not None else "",
]
)
if not rows:
rows = [["โ", "no relation above threshold", "โ", "โ"]]
payload = {"ner": entities, "joint_relex": triples}
return _highlights(text, entities), rows, _dump(payload)
# โโ Task 4: structured / typed / multi-level extraction โโโโโโโโโโโโโโโโโโโโโโ
@spaces.GPU(duration=10)
def extract_structured(text: str, schema_json: str, threshold: float = 0.5) -> str:
"""Extract structured records from text following a JSON schema.
The schema maps a record name to its fields. Scalar fields map to a type
name (``"str"``, ``"int"``); a repeated child is a one-element list holding
its own template for multi-level records. v1.5 typed fields are also
supported: ``{"$type": "class", "$options": [...]}`` picks from fixed
options, ``{"$type": "date"}`` and ``{"$type": "number"}`` return parsed
values, and ``{"$type": "text"}`` copies a span from the input.
Args:
text: Input text to extract records from.
schema_json: The extraction schema as a JSON object.
threshold: Confidence threshold for field and record decoding.
Returns:
The extracted records as a JSON string.
"""
if not (text or "").strip():
return '"Please enter some text."'
try:
schema = json.loads(schema_json or "")
except json.JSONDecodeError as exc:
return _dump({"error": f"Schema is not valid JSON: {exc}"})
if not isinstance(schema, dict) or not schema:
return _dump({"error": "Schema must be a non-empty JSON object."})
try:
records = model.structure(text, schema, threshold=float(threshold))
except Exception as exc:
return _dump({"error": str(exc)})
return _dump(records)
# โโ Task 5: text editing (v1.5) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@spaces.GPU(duration=10)
def edit_text(text: str, instruction: str = "fix grammar"):
"""Edit text following a natural-language instruction.
Args:
text: Input text to edit.
instruction: What to change, e.g. "fix grammar" or "make it formal".
Returns:
The edited text, a table of character-level edits, and the raw JSON.
"""
if not (text or "").strip():
return "Please enter some text.", [["โ", "โ", "โ", "โ"]], "[]"
try:
result = model.edit_text(text, instruction=(instruction or "").strip() or None)
except Exception as exc:
return text, [["error", str(exc), "โ", "โ"]], _dump({"error": str(exc)})
rows = []
for edit in result.get("edits") or []:
score = edit.get("score")
rows.append(
[
str(edit.get("op", "")),
str(edit.get("source", "")),
str(edit.get("replacement", "")),
f"{float(score):.3f}" if score is not None else "",
]
)
if not rows:
rows = [["โ", "no edits made", "โ", "โ"]]
return str(result.get("text", text)), rows, _dump(result)
# โโ Task 6: multiple tasks in one pass (v1.5) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@spaces.GPU(duration=10)
def run_multi_task(
text: str,
entity_labels: str,
class_labels: str,
schema_json: str,
prompt: str = "",
threshold: float = 0.5,
) -> str:
"""Run several extraction tasks in a single pass over the text.
Fill in whichever groups you want: entity types, candidate classes, and/or
a structuring schema. Only the filled groups are extracted. A field marked
``"$calculate": true`` in the schema is computed from numbers read in the
text; give its question in the prompt box.
Args:
text: Input text to analyse.
entity_labels: Comma-separated entity types, or empty to skip NER.
class_labels: Comma-separated candidate classes, or empty to skip classification.
schema_json: Structuring schema as a JSON object, or "{}" to skip structuring.
prompt: Optional instruction placed in front of the labels and schema.
threshold: Confidence threshold shared by every task.
Returns:
A JSON object with one section per requested task.
"""
if not (text or "").strip():
return '"Please enter some text."'
entities = _parse_labels(entity_labels) or None
classes = _parse_labels(class_labels) or None
try:
schema = json.loads(schema_json or "") if (schema_json or "").strip() else None
except json.JSONDecodeError as exc:
return _dump({"error": f"Schema is not valid JSON: {exc}"})
if schema is not None and (not isinstance(schema, dict) or not schema):
schema = None
if entities is None and classes is None and schema is None:
return '"Provide entity types, classes, or a schema โ at least one group."'
kwargs = {}
if (prompt or "").strip():
kwargs["prompt"] = prompt.strip()
if schema is not None and '"$calculate"' in (schema_json or ""):
kwargs["decoder_kwargs"] = {"value_spans": True}
try:
results = model.inference(
text,
entities=entities,
classes=classes,
structures=schema,
threshold=float(threshold),
**kwargs,
)
except Exception as exc:
return _dump({"error": str(exc)})
payload = {}
for key in ("ner", "classification", "structuring", "calculation"):
if key in results:
payload[key] = results[key][0] if results.get(key) else []
return _dump(payload)
# โโ Task 7: embeddings / semantic ranking โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@spaces.GPU(duration=10)
def rank_by_similarity(query: str, candidates: str):
"""Rank candidate texts against a query using the model's embedding head.
Args:
query: The query text.
candidates: Candidate texts, one per line.
Returns:
A ranked candidate/cosine-similarity table and the raw ranking JSON.
"""
if not (query or "").strip():
return [["Please enter a query text.", "โ"]], "[]"
lines = [line.strip() for line in (candidates or "").split("\n") if line.strip()]
if not lines:
return [["Please enter at least one candidate text.", "โ"]], "[]"
try:
embeddings = model.embed_text([query] + lines)
embeddings = embeddings.detach().float().cpu()
query_emb, cand_emb = embeddings[0:1], embeddings[1:]
query_emb = query_emb / query_emb.norm(dim=-1, keepdim=True).clamp(min=1e-9)
cand_emb = cand_emb / cand_emb.norm(dim=-1, keepdim=True).clamp(min=1e-9)
sims = (query_emb @ cand_emb.T).squeeze(0).tolist()
except Exception as exc:
return [["error", str(exc)]], _dump({"error": str(exc)})
ranked = sorted(zip(lines, sims), key=lambda pair: -pair[1])
rows = [[text, f"{sim:.4f}"] for text, sim in ranked]
payload = [{"text": text, "similarity": round(float(sim), 4)} for text, sim in ranked]
return rows, _dump(payload)
# โโ UI โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
TICKET_SCHEMA = json.dumps(
{
"ticket": {
"customer": {"$type": "text"},
"category": {
"$type": "class",
"$options": ["hardware", "software", "billing", "account"],
"$multi": False,
},
"priority": {"$type": "class", "$options": ["low", "medium", "high"], "$multi": False},
"opened": {"$type": "date"},
}
},
indent=2,
)
CALC_SCHEMA = json.dumps(
{
"$root": {
"growth": {
"$type": "text",
"$format": "number",
"$description": "Revenue change from 2022 to 2023",
"$calculate": True,
}
}
},
indent=2,
)
FLIGHT_SCHEMA = json.dumps(
{
"flight": {
"flight_number": "str",
"origin": "str",
"departure_time": "str",
"destination": "str",
"arrival_time": "str",
}
},
indent=2,
)
with gr.Blocks(
title="GLiFormer 2B v1.5",
theme=gr.themes.Citrus(),
css=CSS,
) as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown(
"""
# ๐งฉ GLiFormer 2B v1.5 โ one encoder, every extraction task
[knowledgator/gliformer-2b-v1.5](https://huggingface.co/knowledgator/gliformer-2b-v1.5)
(2.65B params, bidirectional Qwen3.5-2B encoder) turns text into labeled spans,
classes, relations, nested and typed records, text edits, and embeddings โ with
the labels, schemas and instructions you supply at inference time, no retraining.
Built with the [GLiFormer](https://github.com/Knowledgator/GLiFormer) framework.
"""
)
with gr.Tabs():
# โโ Entities โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Tab("๐ท๏ธ Entities"):
with gr.Row():
with gr.Column():
ner_text = gr.Textbox(
label="Text",
lines=5,
placeholder="Paste the text you want to extract entities fromโฆ",
value=(
"Satya Nadella, chief executive of Microsoft, said in Redmond "
"on March 3, 2024 that the company would acquire Nuance "
"Communications for $19.7 billion."
),
)
ner_labels = gr.Textbox(
label="Entity types (comma-separated)",
value="person, organization, location, date, money",
placeholder="person, organization, locationโฆ",
)
with gr.Accordion("Advanced settings", open=False):
ner_threshold = gr.Slider(
0.05, 0.95, value=0.5, step=0.05, label="Threshold"
)
ner_flat = gr.Checkbox(
value=True, label="Flat NER (non-overlapping spans)"
)
ner_multi = gr.Checkbox(
value=False, label="Allow multiple types per span"
)
ner_btn = gr.Button("Extract entities", variant="primary")
with gr.Column():
ner_out = gr.HighlightedText(
label="Entities", combine_adjacent=True, show_legend=True
)
with gr.Accordion("Raw predictions (JSON)", open=False):
ner_json = gr.Code(label="", language="json", lines=14)
gr.Examples(
examples=[
[
"Satya Nadella, chief executive of Microsoft, said in Redmond on March 3, 2024 that the company would acquire Nuance Communications for $19.7 billion.",
"person, organization, location, date, money",
],
[
"Alice works at Acme in London.",
"person, organization, location",
],
[
"Patients treated with metformin showed a marked reduction in HbA1c levels, while those receiving insulin glargine reported more frequent hypoglycemia.",
"drug, biomarker, adverse event",
],
[
"The Supreme Court of California ruled on June 12, 1998 in Smith v. Nakamura that the arbitration clause in the employment contract was unenforceable.",
"court, date, case, legal provision",
],
[
"Preheat the oven to 180ยฐC, whisk two eggs with 200 g of caster sugar, then fold in the sifted flour and bake for 25 minutes.",
"ingredient, quantity, temperature, duration, equipment",
],
],
inputs=[ner_text, ner_labels],
outputs=[ner_out, ner_json],
fn=extract_entities,
cache_examples=True,
cache_mode="lazy",
)
# โโ Classification โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Tab("๐ Classification"):
with gr.Row():
with gr.Column():
cls_text = gr.Textbox(
label="Text",
lines=5,
placeholder="Paste the text you want to classifyโฆ",
value="The new search feature is fast and easy to use.",
)
cls_labels = gr.Textbox(
label="Candidate classes (comma-separated)",
value="positive, negative, neutral",
placeholder="positive, negative, neutralโฆ",
)
with gr.Accordion("Advanced settings", open=False):
cls_threshold = gr.Slider(
0.05, 0.95, value=0.5, step=0.05, label="Threshold"
)
cls_multi = gr.Checkbox(
value=False,
label="Multi-label (keep every class above threshold)",
)
cls_btn = gr.Button("Classify", variant="primary")
with gr.Column():
cls_out = gr.Label(label="Predicted classes", num_top_classes=8)
with gr.Accordion("Raw predictions (JSON)", open=False):
cls_json = gr.Code(label="", language="json", lines=10)
gr.Examples(
examples=[
[
"The new search feature is fast and easy to use.",
"positive, negative, neutral",
],
[
"The battery lasts barely three hours and the screen flickers constantly โ I regret this purchase.",
"positive, negative, neutral",
],
[
"The central bank raised interest rates by 25 basis points in an effort to curb persistent inflation.",
"economics, sports, health, entertainment",
],
[
"CONGRATULATIONS! You have been selected to receive a free iPhone. Click here now to claim your prize!!!",
"spam, legitimate",
],
[
"Patient reports crushing chest pain radiating to the left arm together with shortness of breath.",
"emergency, routine, follow-up",
],
],
inputs=[cls_text, cls_labels],
outputs=[cls_out, cls_json],
fn=classify_text,
cache_examples=True,
cache_mode="lazy",
)
# โโ Relations โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Tab("๐ Relations"):
gr.Markdown(
"Joint extraction: entities and their relations are decoded together, "
"so every triple is grounded in a predicted span."
)
with gr.Row():
with gr.Column():
rel_text = gr.Textbox(
label="Text",
lines=5,
placeholder="Paste the text you want to extract relations fromโฆ",
value=(
"Tim Cook has led Apple since 2011, when he took over from "
"Steve Jobs in Cupertino."
),
)
rel_entities = gr.Textbox(
label="Entity types (comma-separated)",
value="person, organization, location",
)
rel_relations = gr.Textbox(
label="Relation types (comma-separated)",
value="CEO of, succeeded",
)
with gr.Accordion("Advanced settings", open=False):
rel_threshold = gr.Slider(
0.05, 0.95, value=0.5, step=0.05, label="Threshold"
)
rel_flat = gr.Checkbox(
value=True, label="Flat NER (non-overlapping spans)"
)
rel_btn = gr.Button("Extract relations", variant="primary")
with gr.Column():
rel_ents_out = gr.HighlightedText(
label="Entities", combine_adjacent=True, show_legend=True
)
rel_table = gr.Dataframe(
label="Relation triples",
headers=["head", "relation", "tail", "score"],
datatype=["str", "str", "str", "str"],
column_count=(4, "fixed"),
wrap=True,
)
with gr.Accordion("Raw predictions (JSON)", open=False):
rel_json = gr.Code(label="", language="json", lines=14)
gr.Examples(
examples=[
[
"Tim Cook has led Apple since 2011, when he took over from Steve Jobs in Cupertino.",
"person, organization, location",
"CEO of, succeeded",
],
[
"Alice works at Acme.",
"person, organization",
"works_at",
],
[
"Angela Merkel served as Chancellor of Germany and studied physics in Leipzig.",
"person, country, city",
"leader of, studied in",
],
[
"Pfizer developed Comirnaty in partnership with BioNTech, which is based in Mainz.",
"company, product, city",
"developed, partnered with, based in",
],
[
"Serena Williams won Wimbledon in 2016, defeating Angelique Kerber in the final.",
"player, tournament, year",
"won, defeated",
],
],
inputs=[rel_text, rel_entities, rel_relations],
outputs=[rel_ents_out, rel_table, rel_json],
fn=extract_relations,
cache_examples=True,
cache_mode="lazy",
)
# โโ Structured extraction โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Tab("๐ฆ Structured records"):
gr.Markdown(
"Describe the records you want as a JSON schema. Scalar fields map to a "
"type name (`\"str\"`, `\"int\"`); a repeated child is a one-element list "
"holding its own template for nested records. v1.5 typed fields pick "
"categories (`\"$type\": \"class\"` + `\"$options\"`), parse dates and "
"numbers, or copy spans (`\"$type\": \"text\"`)."
)
with gr.Row():
with gr.Column():
struct_text = gr.Textbox(
label="Text",
lines=7,
placeholder="Paste the text you want to turn into recordsโฆ",
value=(
"Flight LH441 departs Frankfurt at 10:15 and lands in Houston "
"at 14:50. Flight LH442 leaves Houston at 17:20 and reaches "
"Frankfurt at 09:35. Flight LH610 departs Munich at 07:05 and "
"arrives in Cairo at 11:40."
),
)
struct_schema = gr.Code(
label="Schema (JSON)",
language="json",
lines=10,
value=FLIGHT_SCHEMA,
)
with gr.Accordion("Advanced settings", open=False):
struct_threshold = gr.Slider(
0.05, 0.95, value=0.5, step=0.05, label="Threshold"
)
struct_btn = gr.Button("Extract records", variant="primary")
with gr.Column():
struct_json = gr.Code(
label="Extracted records (JSON)", language="json", lines=26
)
gr.Examples(
examples=[
[
"Flight LH441 departs Frankfurt at 10:15 and lands in Houston at 14:50. Flight LH442 leaves Houston at 17:20 and reaches Frankfurt at 09:35. Flight LH610 departs Munich at 07:05 and arrives in Cairo at 11:40.",
FLIGHT_SCHEMA,
],
[
"Ticket #4821: Maria Lopez reports that her laptop will not boot after the update. She needs it for a client demo tomorrow. Opened on March 3, 2025.",
TICKET_SCHEMA,
],
[
"Maria Gonzalez, 34, is a cardiologist in Madrid. Her colleague Ahmed Farouk, 41, works as a radiologist in Cairo. Jonas Weber, 29, is a paediatrician in Bern, and Sofia Rossi, 52, practises as a neurologist in Bologna.",
json.dumps(
{
"person": {
"name": "str",
"age": "int",
"occupation": "str",
"city": "str",
}
},
indent=2,
),
],
[
"Northwind Logistics operates two depots. Depot Rotterdam is managed by Iris Bakker and handles route R-12 to Lyon and route R-19 to Milan. Depot Hamburg is managed by Lars Petersen and handles route R-04 to Prague.",
json.dumps(
{
"company": {
"name": "str",
"depots": [
{
"depot": "str",
"manager": "str",
"routes": [
{
"route_id": "str",
"destination": "str",
}
],
}
],
}
},
indent=2,
),
],
[
"Order 44-B contains 3 keyboards at 45 euros each, 2 monitors at 210 euros each, 5 USB hubs at 19 euros each, 1 docking station at 175 euros, and 4 webcams at 62 euros each.",
json.dumps(
{
"line_item": {
"item": "str",
"quantity": "int",
"unit_price": "str",
}
},
indent=2,
),
],
],
inputs=[struct_text, struct_schema],
outputs=struct_json,
fn=extract_structured,
cache_examples=True,
cache_mode="lazy",
)
# โโ Text editing โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Tab("โ๏ธ Text editing"):
gr.Markdown(
"New in v1.5: a sequence-editing head rewrites the text following a "
"natural-language instruction, returning character-level edits."
)
with gr.Row():
with gr.Column():
edit_text_in = gr.Textbox(
label="Text",
lines=4,
placeholder="Paste the text you want to editโฆ",
value="The team have finished they're report and its ready for review.",
)
edit_instruction = gr.Textbox(
label="Instruction",
value="fix grammar",
placeholder="fix grammar, make it formal, โฆ",
)
edit_btn = gr.Button("Edit text", variant="primary")
with gr.Column():
edit_out = gr.Textbox(label="Edited text", lines=4)
edit_table = gr.Dataframe(
label="Edits (against the input text)",
headers=["op", "source", "replacement", "score"],
datatype=["str", "str", "str", "str"],
column_count=(4, "fixed"),
wrap=True,
)
with gr.Accordion("Raw predictions (JSON)", open=False):
edit_json = gr.Code(label="", language="json", lines=12)
gr.Examples(
examples=[
["The team have finished they're report and its ready for review.", "fix grammar"],
[
"The team have finished they're report and its ready for review.",
"fix grammar",
],
["hey can u send me the file asap thx", "make it formal"],
],
inputs=[edit_text_in, edit_instruction],
outputs=[edit_out, edit_table, edit_json],
fn=edit_text,
cache_examples=True,
cache_mode="lazy",
)
# โโ Multi-task โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Tab("๐ง Multi-task (one pass)"):
gr.Markdown(
"The v1.5 headline: entities, classes and structured records are "
"extracted in a **single pass** over the text. Fill in whichever "
"groups you want; a `\"$calculate\": true` field is computed from "
"numbers in the text when you give its question as the prompt."
)
with gr.Row():
with gr.Column():
mt_text = gr.Textbox(
label="Text",
lines=4,
placeholder="Paste the text to analyseโฆ",
value="Alice joined Acme as a software engineer.",
)
mt_entities = gr.Textbox(
label="Entity types (comma-separated, optional)",
value="person, organization",
)
mt_classes = gr.Textbox(
label="Candidate classes (comma-separated, optional)",
value="business, sports, technology",
)
mt_schema = gr.Code(
label="Structuring schema (JSON, optional)",
language="json",
lines=6,
value=json.dumps({"employee": ["name", "company"]}, indent=2),
)
mt_prompt = gr.Textbox(
label="Prompt (optional, e.g. the question for a $calculate field)",
value="",
placeholder="By how much did revenue growโฆ",
)
with gr.Accordion("Advanced settings", open=False):
mt_threshold = gr.Slider(
0.05, 0.95, value=0.5, step=0.05, label="Threshold"
)
mt_btn = gr.Button("Run all tasks", variant="primary")
with gr.Column():
mt_json = gr.Code(
label="Results (JSON, one section per task)", language="json", lines=24
)
gr.Examples(
examples=[
[
"Alice joined Acme as a software engineer.",
"person, organization",
"business, sports, technology",
json.dumps({"employee": ["name", "company"]}, indent=2),
"",
],
[
"Revenue was $1,200 million in 2023 and $1,000 million in 2022.",
"",
"",
CALC_SCHEMA,
"By how much did revenue grow from 2022 to 2023?",
],
[
"Maria Gonzalez, 34, is a cardiologist in Madrid.",
"person",
"medicine, finance, sports",
json.dumps(
{
"person": {
"name": "str",
"age": "int",
"occupation": "str",
"city": "str",
}
},
indent=2,
),
"",
],
],
inputs=[mt_text, mt_entities, mt_classes, mt_schema, mt_prompt],
outputs=mt_json,
fn=run_multi_task,
cache_examples=True,
cache_mode="lazy",
)
# โโ Embeddings โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Tab("๐งฎ Embeddings"):
gr.Markdown(
"The same encoder also exposes an embedding head. Candidates are ranked "
"by cosine similarity against the query."
)
with gr.Row():
with gr.Column():
emb_query = gr.Textbox(
label="Query",
lines=2,
placeholder="What are you looking for?",
value="Tesla is investing in a new factory in Texas.",
)
emb_candidates = gr.Textbox(
label="Candidates (one per line)",
lines=7,
value=(
"A new automotive plant is being built in Austin.\n"
"SpaceX launched a rocket to the International Space Station.\n"
"The stock market saw significant gains today.\n"
"Electric vehicle production is expanding in the US.\n"
"The weather in New York is sunny and warm."
),
)
emb_btn = gr.Button("Rank candidates", variant="primary")
with gr.Column():
emb_table = gr.Dataframe(
label="Ranked candidates",
headers=["candidate", "cosine similarity"],
datatype=["str", "str"],
column_count=(2, "fixed"),
wrap=True,
)
with gr.Accordion("Raw ranking (JSON)", open=False):
emb_json = gr.Code(label="", language="json", lines=12)
gr.Examples(
examples=[
[
"Tesla is investing in a new factory in Texas.",
"A new automotive plant is being built in Austin.\nSpaceX launched a rocket to the International Space Station.\nThe stock market saw significant gains today.\nElectric vehicle production is expanding in the US.\nThe weather in New York is sunny and warm.",
],
[
"How do I reset my password?",
"Click 'Forgot password' to receive a reset link by email.\nOur office hours are 9am to 5pm on weekdays.\nSteps to recover access to your account credentials.\nThe new pricing plan includes additional storage.\nWe accept Visa and Mastercard for all subscriptions.",
],
[
"symptoms of vitamin D deficiency",
"Low vitamin D can cause bone pain and muscle weakness.\nFatigue and frequent illness may signal insufficient vitamin D.\nVitamin C is abundant in citrus fruit.\nRegular strength training builds lean muscle mass.\nThe recommended daily intake of sodium is under 2 grams.",
],
[
"best practices for unit testing in Python",
"Use pytest fixtures to isolate test dependencies.\nKeep each test focused on a single behaviour.\nDjango templates render HTML on the server.\nNumPy arrays support vectorised arithmetic.\nDocker images should be kept small for faster pulls.",
],
],
inputs=[emb_query, emb_candidates],
outputs=[emb_table, emb_json],
fn=rank_by_similarity,
cache_examples=True,
cache_mode="lazy",
)
# โโ Wiring โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
ner_btn.click(
extract_entities,
inputs=[ner_text, ner_labels, ner_threshold, ner_flat, ner_multi],
outputs=[ner_out, ner_json],
api_name="extract_entities",
)
cls_btn.click(
classify_text,
inputs=[cls_text, cls_labels, cls_threshold, cls_multi],
outputs=[cls_out, cls_json],
api_name="classify_text",
)
rel_btn.click(
extract_relations,
inputs=[rel_text, rel_entities, rel_relations, rel_threshold, rel_flat],
outputs=[rel_ents_out, rel_table, rel_json],
api_name="extract_relations",
)
struct_btn.click(
extract_structured,
inputs=[struct_text, struct_schema, struct_threshold],
outputs=struct_json,
api_name="extract_structured",
)
edit_btn.click(
edit_text,
inputs=[edit_text_in, edit_instruction],
outputs=[edit_out, edit_table, edit_json],
api_name="edit_text",
)
mt_btn.click(
run_multi_task,
inputs=[mt_text, mt_entities, mt_classes, mt_schema, mt_prompt, mt_threshold],
outputs=mt_json,
api_name="run_multi_task",
)
emb_btn.click(
rank_by_similarity,
inputs=[emb_query, emb_candidates],
outputs=[emb_table, emb_json],
api_name="rank_by_similarity",
)
demo.launch(mcp_server=True)
import spaces # MUST come before torch / any CUDA-touching import
import json
import torch
import gradio as gr
from gliformer import GLiFormer
MODEL_ID = "knowledgator/gliformer-2b-v1.5"
# Explicit bf16. With no dtype kwarg the loader builds a mixed-precision
# model (bf16 backbone from the config, fp32 heads), and on this
# gliner/transformers combo the sequence-editing head then fails with
# "mat1 and mat2 must have the same dtype, but got BFloat16 and Float".
# Passing dtype explicitly casts the whole model uniformly; bf16 halves
# the VRAM (~5.3 GB packed) versus fp32 (~10.6 GB) with measurably identical
# quality on every task head (NER/classification/relation/structuring/
# embeddings all score 0.95โ1.0 either way).
model = GLiFormer.from_pretrained(MODEL_ID, load_tokenizer=True, dtype=torch.bfloat16)
model = model.to("cuda").eval()
CSS = """
#col-container { max-width: 1200px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""
# โโ Helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _parse_labels(labels_text: str) -> list:
"""Split a comma-separated label string into a clean list."""
return [part.strip() for part in (labels_text or "").split(",") if part.strip()]
def _dump(obj) -> str:
"""Pretty-print a prediction payload as JSON."""
return json.dumps(obj, indent=2, ensure_ascii=False, default=str)
def _highlights(text: str, entities) -> list:
"""Turn GLiFormer entity spans into gr.HighlightedText (substring, label) pairs."""
spans = []
for ent in entities or []:
start, end = ent.get("start"), ent.get("end")
if start is None or end is None:
continue
spans.append((int(start), int(end), ent.get("label") or ent.get("type") or "entity"))
spans.sort(key=lambda s: (s[0], -(s[1] - s[0])))
out, cursor = [], 0
for start, end, label in spans:
if start < cursor: # skip overlaps that HighlightedText cannot render
continue
if start > cursor:
out.append((text[cursor:start], None))
out.append((text[start:end], label))
cursor = end
if cursor < len(text):
out.append((text[cursor:], None))
return out or [(text, None)]
# โโ Task 1: named entity recognition โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def extract_entities(
text: str,
entity_labels: str,
threshold: float = 0.5,
flat_ner: bool = True,
multi_label: bool = False,
):
"""Extract named entities from text with entity types chosen at inference time.
Args:
text: Input text to analyse.
entity_labels: Comma-separated entity types, e.g. "person, organization, location".
threshold: Confidence threshold for keeping a span.
flat_ner: Enforce non-overlapping spans.
multi_label: Allow a span to carry more than one entity type.
Returns:
The text as (substring, entity_label) pairs, plus the raw prediction JSON.
"""
labels = _parse_labels(entity_labels)
if not (text or "").strip():
return [("Please enter some text.", None)], "[]"
if not labels:
return [(text, None)], '"Please enter at least one entity label."'
try:
entities = model.predict_entities(
text,
labels,
threshold=float(threshold),
flat_ner=bool(flat_ner),
multi_label=bool(multi_label),
)
except Exception as exc: # surface model errors in the UI instead of 500ing
return [(text, None)], _dump({"error": str(exc)})