multimodalart HF Staff commited on
Commit
cbd76fa
·
verified ·
1 Parent(s): 13059a1

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. README.md +21 -7
  2. app.py +312 -0
  3. requirements.txt +1 -0
README.md CHANGED
@@ -1,13 +1,27 @@
1
  ---
2
- title: Gliner2 5 Multi Extractor
3
- emoji:
4
- colorFrom: yellow
5
- colorTo: blue
6
  sdk: gradio
7
  sdk_version: 6.25.0
8
- python_version: '3.12'
9
  app_file: app.py
10
- pinned: false
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: GLiNER2.5 Multi — Zero-Shot Information Extraction
3
+ emoji: 🔍
4
+ colorFrom: green
5
+ colorTo: pink
6
  sdk: gradio
7
  sdk_version: 6.25.0
 
8
  app_file: app.py
9
+ short_description: Zero-shot entity, classification, relation extraction
10
+ python_version: "3.12"
11
+ startup_duration_timeout: 30m
12
  ---
13
 
14
+ Zero-shot multilingual information extraction with [fastino/gliner2.5-multi-v1](https://huggingface.co/fastino/gliner2.5-multi-v1).
15
+
16
+ Supports four tasks, all with user-defined labels — no retraining needed:
17
+
18
+ - **Entity Extraction** — detect named entities (person, organization, product, …)
19
+ - **Text Classification** — single or multi-label zero-shot classification
20
+ - **Relation Extraction** — identify relationships between entities
21
+ - **Structured Data Extraction** — parse unstructured text into typed JSON records
22
+
23
+ The model is a 287M-parameter boundary-architecture encoder (mDeBERTa-v3-base) supporting 4096-token context and multiple languages.
24
+
25
+ ## License
26
+
27
+ Apache-2.0
app.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces # MUST come before torch / any CUDA-touching import
2
+ import torch
3
+ import gradio as gr
4
+ import json
5
+ import re
6
+
7
+ from gliner2 import AutoExtractor
8
+
9
+ MODEL_ID = "fastino/gliner2.5-multi-v1"
10
+
11
+ model = AutoExtractor.from_pretrained(MODEL_ID, map_location="cuda")
12
+ model.eval()
13
+
14
+ CSS = """
15
+ #col-container { max-width: 1100px; margin: 0 auto; }
16
+ .dark .gradio-container { color: var(--body-text-color); }
17
+ """
18
+
19
+
20
+ def _parse_labels(labels_text):
21
+ """Parse comma-separated labels into a clean list."""
22
+ if not labels_text or not labels_text.strip():
23
+ return []
24
+ labels = [l.strip() for l in labels_text.split(",") if l.strip()]
25
+ return labels
26
+
27
+
28
+ def _parse_class_schema(schema_text):
29
+ """Parse classification schema from text like: sentiment: positive, negative, neutral"""
30
+ result = {}
31
+ if not schema_text or not schema_text.strip():
32
+ return result
33
+ for line in schema_text.strip().split("\n"):
34
+ if ":" in line:
35
+ task, labels_str = line.split(":", 1)
36
+ task = task.strip()
37
+ labels = [l.strip() for l in labels_str.split(",") if l.strip()]
38
+ if task and labels:
39
+ result[task] = labels
40
+ return result
41
+
42
+
43
+ def _format_json(obj):
44
+ """Pretty-print JSON for display."""
45
+ return json.dumps(obj, indent=2, ensure_ascii=False, default=str)
46
+
47
+
48
+ @spaces.GPU(duration=30)
49
+ def extract_entities(text, labels_text, include_confidence=True, include_spans=True):
50
+ """Extract named entities from text using zero-shot GLiNER2.5.
51
+
52
+ Args:
53
+ text: The input text to extract entities from.
54
+ labels_text: Comma-separated entity labels to detect (e.g. "person, organization, location").
55
+ include_confidence: Whether to include confidence scores in output.
56
+ include_spans: Whether to include character spans in output.
57
+ """
58
+ labels = _parse_labels(labels_text)
59
+ if not text.strip():
60
+ return "Please enter some text."
61
+ if not labels:
62
+ return "Please enter at least one entity label."
63
+ result = model.extract_entities(
64
+ text,
65
+ labels,
66
+ include_confidence=include_confidence,
67
+ include_spans=include_spans,
68
+ )
69
+ return _format_json(result)
70
+
71
+
72
+ @spaces.GPU(duration=30)
73
+ def classify_text(text, schema_text):
74
+ """Classify text into categories using zero-shot classification with GLiNER2.5.
75
+
76
+ Args:
77
+ text: The input text to classify.
78
+ schema_text: Classification schema, one task per line in format 'task: label1, label2, ...'.
79
+ """
80
+ schema = _parse_class_schema(schema_text)
81
+ if not text.strip():
82
+ return "Please enter some text."
83
+ if not schema:
84
+ return "Please enter a classification schema (e.g. 'sentiment: positive, negative, neutral')."
85
+ result = model.classify_text(text, schema)
86
+ return _format_json(result)
87
+
88
+
89
+ @spaces.GPU(duration=30)
90
+ def extract_relations(text, labels_text, include_confidence=True, include_spans=True):
91
+ """Extract relations between entities from text using GLiNER2.5.
92
+
93
+ Args:
94
+ text: The input text to extract relations from.
95
+ labels_text: Comma-separated relation labels to detect (e.g. "works_for, located_in").
96
+ include_confidence: Whether to include confidence scores.
97
+ include_spans: Whether to include character spans.
98
+ """
99
+ labels = _parse_labels(labels_text)
100
+ if not text.strip():
101
+ return "Please enter some text."
102
+ if not labels:
103
+ return "Please enter at least one relation label."
104
+ result = model.extract_relations(
105
+ text,
106
+ labels,
107
+ include_confidence=include_confidence,
108
+ include_spans=include_spans,
109
+ )
110
+ return _format_json(result)
111
+
112
+
113
+ @spaces.GPU(duration=30)
114
+ def extract_structured(text, schema_text):
115
+ """Extract structured JSON data from text using GLiNER2.5.
116
+
117
+ Args:
118
+ text: The input text to extract structured data from.
119
+ schema_text: JSON schema description, one field per line in format 'field: type::description'.
120
+ """
121
+ if not text.strip():
122
+ return "Please enter some text."
123
+ # Parse schema: field_name::type::description (one per line)
124
+ schema = {}
125
+ for line in schema_text.strip().split("\n"):
126
+ line = line.strip()
127
+ if not line:
128
+ continue
129
+ parts = line.split("::", 2)
130
+ if len(parts) >= 1:
131
+ field = parts[0].strip()
132
+ dtype = parts[1].strip() if len(parts) > 1 else "str"
133
+ desc = parts[2].strip() if len(parts) > 2 else ""
134
+ entry = f"{dtype}::{desc}" if desc else dtype
135
+ schema[field] = [entry] if dtype != "list" else [f"list::{desc}" if desc else "list"]
136
+ if not schema:
137
+ return "Please enter a schema (e.g. 'name::str::Product name')."
138
+ result = model.extract_json(text, schema)
139
+ return _format_json(result)
140
+
141
+
142
+ with gr.Blocks(theme=gr.themes.Citrus(), css=CSS, title="GLiNER2.5 Multi — Information Extraction") as demo:
143
+ gr.Markdown("""
144
+ # 🔍 GLiNER2.5 Multi — Zero-Shot Information Extraction
145
+
146
+ Multilingual, multi-task information extraction with [fastino/gliner2.5-multi-v1](https://huggingface.co/fastino/gliner2.5-multi-v1) (287M params, mDeBERTa-v3 encoder).
147
+
148
+ Define your own labels at inference time — no retraining needed. Supports entity recognition, text classification, relation extraction, and structured data extraction across multiple languages.
149
+ """)
150
+
151
+ with gr.Row():
152
+ with gr.Column():
153
+ gr.Markdown("## 🏷️ Entity Extraction")
154
+ gr.Markdown("Extract named entities with custom labels.")
155
+ ner_text = gr.Textbox(
156
+ label="Input Text",
157
+ placeholder="Enter text to analyze…",
158
+ lines=5,
159
+ value="Apple CEO Tim Cook announced iPhone 15 in Cupertino yesterday. The event was held at Apple Park.",
160
+ )
161
+ ner_labels = gr.Textbox(
162
+ label="Entity Labels (comma-separated)",
163
+ value="company, person, product, location",
164
+ placeholder="person, organization, location…",
165
+ )
166
+ with gr.Accordion("Options", open=False):
167
+ ner_conf = gr.Checkbox(label="Include confidence scores", value=True)
168
+ ner_spans = gr.Checkbox(label="Include character spans", value=True)
169
+ ner_btn = gr.Button("Extract Entities", variant="primary")
170
+ ner_output = gr.Code(label="Result (JSON)", language="json", lines=15)
171
+
172
+ gr.Examples(
173
+ examples=[
174
+ ["Apple CEO Tim Cook announced iPhone 15 in Cupertino yesterday. The event was held at Apple Park.", "company, person, product, location"],
175
+ ["Barcelona defeated Real Madrid 3-1 at Camp Nou. Lewandowski scored twice for Barça.", "team, player, city, stadium"],
176
+ ["Marie Curie was born in Warsaw and later moved to Paris to work at the Sorbonne.", "person, city, country, organization"],
177
+ ],
178
+ inputs=[ner_text, ner_labels],
179
+ outputs=ner_output,
180
+ fn=extract_entities,
181
+ cache_examples=True,
182
+ cache_mode="lazy",
183
+ )
184
+
185
+ gr.Markdown("---")
186
+
187
+ with gr.Row():
188
+ with gr.Column():
189
+ gr.Markdown("## 📋 Text Classification")
190
+ gr.Markdown("Classify text into custom categories (zero-shot).")
191
+ cls_text = gr.Textbox(
192
+ label="Input Text",
193
+ placeholder="Enter text to classify…",
194
+ lines=3,
195
+ value="This laptop has amazing performance but terrible battery life!",
196
+ )
197
+ cls_schema = gr.Textbox(
198
+ label="Classification Schema (one task per line: task: label1, label2, …)",
199
+ value="sentiment: positive, negative, neutral",
200
+ lines=3,
201
+ )
202
+ cls_btn = gr.Button("Classify Text", variant="primary")
203
+ cls_output = gr.Code(label="Result (JSON)", language="json", lines=8)
204
+
205
+ gr.Examples(
206
+ examples=[
207
+ ["This laptop has amazing performance but terrible battery life!", "sentiment: positive, negative, neutral"],
208
+ ["Breaking: Tech giant acquires AI startup for $2B in landmark deal.", "topic: technology, business, politics, sports"],
209
+ ["Le film était captivant du début à la fin, avec des acteurs brillants.", "sentiment: positif, négatif, neutre"],
210
+ ],
211
+ inputs=[cls_text, cls_schema],
212
+ outputs=cls_output,
213
+ fn=classify_text,
214
+ cache_examples=True,
215
+ cache_mode="lazy",
216
+ )
217
+
218
+ gr.Markdown("---")
219
+
220
+ with gr.Row():
221
+ with gr.Column():
222
+ gr.Markdown("## 🔗 Relation Extraction")
223
+ gr.Markdown("Detect relationships between entities in text.")
224
+ rel_text = gr.Textbox(
225
+ label="Input Text",
226
+ placeholder="Enter text to analyze…",
227
+ lines=4,
228
+ value="Alice works for Acme Corp in Paris. Bob joined Acme last year and lives in London.",
229
+ )
230
+ rel_labels = gr.Textbox(
231
+ label="Relation Labels (comma-separated)",
232
+ value="works_for, located_in",
233
+ placeholder="works_for, located_in, founded_by…",
234
+ )
235
+ with gr.Accordion("Options", open=False):
236
+ rel_conf = gr.Checkbox(label="Include confidence scores", value=True)
237
+ rel_spans = gr.Checkbox(label="Include character spans", value=True)
238
+ rel_btn = gr.Button("Extract Relations", variant="primary")
239
+ rel_output = gr.Code(label="Result (JSON)", language="json", lines=15)
240
+
241
+ gr.Examples(
242
+ examples=[
243
+ ["Alice works for Acme Corp in Paris. Bob joined Acme last year and lives in London.", "works_for, located_in"],
244
+ ["Google was founded by Larry Page and Sergey Brin in Mountain View.", "founded_by, located_in"],
245
+ ["John Smith married Jane Doe in 2015 in New York City.", "married_to, located_in"],
246
+ ],
247
+ inputs=[rel_text, rel_labels],
248
+ outputs=rel_output,
249
+ fn=extract_relations,
250
+ cache_examples=True,
251
+ cache_mode="lazy",
252
+ )
253
+
254
+ gr.Markdown("---")
255
+
256
+ with gr.Row():
257
+ with gr.Column():
258
+ gr.Markdown("## 📦 Structured Data Extraction")
259
+ gr.Markdown("Parse text into structured JSON records with typed fields.")
260
+ json_text = gr.Textbox(
261
+ label="Input Text",
262
+ placeholder="Enter text to extract structured data from…",
263
+ lines=4,
264
+ value="iPhone 15 Pro Max with 256GB storage, A17 Pro chip, priced at $1199. Available in titanium and black colors.",
265
+ )
266
+ json_schema = gr.Textbox(
267
+ label="Schema (one field per line: field::type::description)",
268
+ value="name::str::Full product name and model\nstorage::str::Storage capacity\nprocessor::str::Chip or processor\nprice::str::Product price with currency\ncolors::list::Available color options",
269
+ lines=5,
270
+ )
271
+ json_btn = gr.Button("Extract Structured Data", variant="primary")
272
+ json_output = gr.Code(label="Result (JSON)", language="json", lines=12)
273
+
274
+ gr.Examples(
275
+ examples=[
276
+ ["iPhone 15 Pro Max with 256GB storage, A17 Pro chip, priced at $1199. Available in titanium and black colors.", "name::str::Full product name and model\nstorage::str::Storage capacity\nprocessor::str::Chip or processor\nprice::str::Product price with currency\ncolors::list::Available color options"],
277
+ ["Alice bought apples for $3.50 at Whole Foods. Bob purchased oranges for $2.00 at Trader Joe's.", "buyer::str::Name of buyer\nitem::str::Item purchased\nprice::str::Price paid\nstore::str::Store name"],
278
+ ],
279
+ inputs=[json_text, json_schema],
280
+ outputs=json_output,
281
+ fn=extract_structured,
282
+ cache_examples=True,
283
+ cache_mode="lazy",
284
+ )
285
+
286
+ # Wire buttons
287
+ ner_btn.click(
288
+ extract_entities,
289
+ inputs=[ner_text, ner_labels, ner_conf, ner_spans],
290
+ outputs=ner_output,
291
+ api_name="extract_entities",
292
+ )
293
+ cls_btn.click(
294
+ classify_text,
295
+ inputs=[cls_text, cls_schema],
296
+ outputs=cls_output,
297
+ api_name="classify_text",
298
+ )
299
+ rel_btn.click(
300
+ extract_relations,
301
+ inputs=[rel_text, rel_labels, rel_conf, rel_spans],
302
+ outputs=rel_output,
303
+ api_name="extract_relations",
304
+ )
305
+ json_btn.click(
306
+ extract_structured,
307
+ inputs=[json_text, json_schema],
308
+ outputs=json_output,
309
+ api_name="extract_structured",
310
+ )
311
+
312
+ demo.launch(mcp_server=True)
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ gliner2[local]