Alexandre-Numind commited on
Commit
3b9a7b5
Β·
verified Β·
1 Parent(s): 183dac2

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +324 -0
app.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json, torch, gradio as gr
2
+ from transformers import AutoProcessor, AutoModelForVision2Seq
3
+ from utils import process_all_vision_info
4
+
5
+ model_name = "numind/NuExtract-2.0-4B"
6
+
7
+ model = AutoModelForVision2Seq.from_pretrained(
8
+ model_name,
9
+ trust_remote_code=True,
10
+ torch_dtype=torch.bfloat16,
11
+ attn_implementation="flash_attention_2",
12
+ device_map="auto",
13
+ )
14
+ processor = AutoProcessor.from_pretrained(
15
+ model_name,
16
+ trust_remote_code=True,
17
+ padding_side="left",
18
+ use_fast=True,
19
+ )
20
+
21
+ def run_model(image, text, template):
22
+ """Return (extracted_json, template_update, warning_update)."""
23
+ try:
24
+ json.loads(template)
25
+ template_valid = True
26
+ except Exception:
27
+ template_valid = False
28
+
29
+ messages = (
30
+ [{"role": "user", "content": text}]
31
+ if text
32
+ else [{"role": "user", "content": [{"type": "image", "image": image}]}]
33
+ )
34
+
35
+ template_arg = template if template_valid else None
36
+ if not template_valid:
37
+ messages = [{"role": "user", "content": template}]
38
+
39
+ chat_txt = processor.tokenizer.apply_chat_template(
40
+ messages, template=template_arg, tokenize=False, add_generation_prompt=True
41
+ )
42
+
43
+ img_inputs = process_all_vision_info(messages)
44
+ inputs = processor(
45
+ text=[chat_txt],
46
+ images=img_inputs,
47
+ padding=True,
48
+ return_tensors="pt"
49
+ ).to("cuda")
50
+
51
+ seq_len = inputs.input_ids.shape[1]
52
+ if seq_len > 10_000:
53
+ return (
54
+ "",
55
+ gr.update(),
56
+ gr.update(
57
+ value=(
58
+ f"❌ **Input too long**: {seq_len} tokens "
59
+ f"(limit = 10 000). Please shorten the text or image context."
60
+ ),
61
+ visible=True,
62
+ ),
63
+ )
64
+
65
+ ids = model.generate(**inputs, do_sample=False, num_beams=1, max_new_tokens=4000)
66
+ ids2 = [o[len(i):] for i, o in zip(inputs.input_ids, ids)]
67
+ out = processor.batch_decode(
68
+ ids2, skip_special_tokens=True, clean_up_tokenization_spaces=False
69
+ )[0]
70
+
71
+ if template_valid:
72
+ extract_out = json.dumps(json.loads(out), indent=4,ensure_ascii = False)
73
+ templ_upd = gr.update()
74
+ warn_upd = gr.update(visible=False)
75
+ else:
76
+ extract_out = ""
77
+ templ_upd = gr.update(value=out)
78
+ warn_upd = gr.update(
79
+ value="⚠️ Template wasn’t valid JSON. "
80
+ "I generated one for you β€” check it, then press **Run** again.",
81
+ visible=True,
82
+ )
83
+
84
+ return extract_out, templ_upd, warn_upd
85
+
86
+
87
+ with gr.Blocks(title="NuExtract – zero-shot structured extraction") as demo:
88
+ # πŸš€ Banner
89
+ gr.HTML("""<!DOCTYPE html>
90
+ <html lang="en">
91
+ <head>
92
+ <meta charset="UTF-8" />
93
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
94
+ <title>NuExtract-2 Overview</title>
95
+ <style>
96
+ img { display:block; margin-bottom:1rem; }
97
+ ul { margin:1rem 0; padding-left:1.5rem; }
98
+ a { color:#4187f6; text-decoration:none; }
99
+ a:hover { text-decoration:underline; }
100
+ h1,h2 { margin:0 0 .5rem 0; font-weight:600; }
101
+ pre { overflow-x:auto; border-radius:6px; padding:1rem; }
102
+ code { border-radius:4px; padding:.2em .4em; font-family:monospace; }
103
+ html[data-theme="dark"],
104
+ @media (prefers-color-scheme: dark) {
105
+ body { background-color:#1e1e1e;}
106
+ code { background-color: #2d2d2d;}
107
+ pre { background-color:#2a2a2a;}
108
+ }
109
+ html[data-theme="light"],
110
+ @media (prefers-color-scheme: light) {
111
+ body { background-color#ffffff;}
112
+ code { background-color#f5f5f5;}
113
+ pre { background-color#f5f5f5;}
114
+ }
115
+ </style>
116
+ </head>
117
+ <body>
118
+ <p align="center">
119
+ <a href="https://nuextract.ai/">
120
+ <img src="https://cdn.prod.website-files.com/638364a4e52e440048a9529c/64188f405afcf42d0b85b926_logo_numind_final.png"
121
+ alt="NuMind Logo" style="width: 200px; height: 50px;" />
122
+ </a>
123
+ </p>
124
+ <p align="center">
125
+ πŸ–₯️ <a href="https://nuextract.ai/">API / Platform</a>&nbsp&nbsp | &nbsp&nbspπŸ“‘ <a href="https://numind.ai/blog">Blog</a>&nbsp&nbsp | &nbsp&nbspπŸ—£οΈ <a href="https://discord.gg/3tsEtJNCDe">Discord</a> &nbsp&nbsp | &nbsp&nbspπŸ› οΈ <a href="https://github.com/numindai/nuextract">Github</a>
126
+ </p>
127
+
128
+ <section>
129
+ <h3> This space is a demo for <a href="https://huggingface.co/numind/NuExtract-2.0-4B" target="_blank">NuExtract-2.0-4B</a> </h3>
130
+ <h3> You can also check: <a href="https://huggingface.co/numind/NuExtract-2.0-2B" target="_blank">NuExtract-2.0-2B</a> and <a href="https://huggingface.co/numind/NuExtract-2.0-8B" target="_blank">NuExtract-2.0-8B</a> and our top performing model via the <a href="https://nuextract.ai/">API / Platform</a> </h3>
131
+
132
+ <h1>NuExtreact-2.0</h1>
133
+ <p>NuExtract 2.0 is a family of models trained specifically for structured information extraction tasks. It supports both multimodal inputs and is multilingual.</p>
134
+ <p> To use the model, provide an input text/image and a JSON template describing the information you need to extract. The template should be a JSON object, specifying field names and their expected type. </p>
135
+ <article>
136
+ <h3>Supported Template Types</h3>
137
+ <ul>
138
+ <li><code>verbatim-string</code> β€” extract text exactly as it appears.</li>
139
+ <li><code>string</code> β€” generic text, with possible paraphrasing.</li>
140
+ <li><code>integer</code> β€” whole number.</li>
141
+ <li><code>number</code> β€” decimal or whole number.</li>
142
+ <li><code>date-time</code> β€” ISO 8601 date format.</li>
143
+ <li><code>boolean</code> β€” True or False.</li>
144
+ <li>Array of any type above (e.g. <code>["string"]</code>).</li>
145
+ <li><code>enum</code> β€” one value from a predefined list (e.g. <code>["yes", "no", "maybe"]</code>).</li>
146
+ <li><code>multi-label</code> β€” multiple values from a list (e.g. <code>[["A", "B", "C"]]</code>).</li>
147
+ </ul>
148
+ <p> You can specify any nested strucure, such as object inside object or list of object </p>
149
+ <p>If no relevant information is found, the model returns <code>null</code> or <code>[]</code>.</p>
150
+ </article>
151
+
152
+ <article>
153
+ <h3>Example Template</h3>
154
+ <pre><code>{
155
+ "first_name": "verbatim-string",
156
+ "last_name": "verbatim-string",
157
+ "description": "string",
158
+ "age": "integer",
159
+ "classes": [
160
+ {
161
+ "name" : "verbatim-string",
162
+ "professors" : ["verbatim-string"],
163
+ "gpa": number",
164
+ }
165
+ ],
166
+ "average_gpa": "number",
167
+ "birth_date": "date-time",
168
+ "nationality": ["France", "England", "Japan", "USA", "China"],
169
+ "languages_spoken": [["English", "French", "Japanese", "Mandarin", "Spanish"]]
170
+ }</code></pre>
171
+ </article>
172
+ <strong>You can also provide a description of what you want to extract, use a non-JSON format (e.g. YAML, Pydantic) or even an example of input text. The model will automatically update the template field and generate a compatible JSON template based on our typing system.</strong>
173
+ </section>
174
+ <br>
175
+ <section>
176
+ <ul><h4><strong>Model used in this demo:</strong> <a href="https://huggingface.co/numind/NuExtract-2.0-4B" target="_blank">NuExtract-2.0-4B</a></h4></ul>
177
+ <i>⚠️ This demo restricts inputs to 10,000 tokens</i>
178
+ </section>
179
+ </body>
180
+ </html>
181
+ """)
182
+
183
+ templ = gr.Textbox(
184
+ lines=10,
185
+ label="Template (JSON or prompt)",
186
+ placeholder="JSON template or instruction/other format to generate a template",
187
+ )
188
+
189
+ with gr.Row(equal_height=False):
190
+ img = gr.Image(type="filepath", label="Input image (PNG)", scale=1)
191
+ txt = gr.Textbox(lines=10, label="Text", scale=1)
192
+
193
+ example_data = [
194
+ [
195
+ "examples/affiche.jpg", # image file
196
+ "", # no text
197
+ """{
198
+ "movie_name": "verbatim-string",
199
+ "tagline": "verbatim-string",
200
+ "language": "string",
201
+ "motion_picture_association_rating": [
202
+ "G - General Audiences",
203
+ "PG - Parental Guidance Suggested",
204
+ "PG-13 – Parents Strongly Cautioned",
205
+ "R – Restricted",
206
+ "NC-17 – Adults Only",
207
+ "not provided"
208
+ ],
209
+ "movie_distribution_company": "verbatim-string",
210
+ "movie_production_company": ["verbatim-string"],
211
+ "theatre_release_date": "date-time",
212
+ "movie_director_name": "verbatim-string",
213
+ "actors_names": [
214
+ "verbatim-string"
215
+ ],
216
+ "award" : "verbatim-string",
217
+ "reviews": [
218
+ {
219
+ "critic_name": "verbatim-string",
220
+ "review_comment": "verbatim-string"
221
+ }
222
+ ],
223
+ "technologies": [
224
+ [
225
+ "Dolby Stereo",
226
+ "Dolby Digital",
227
+ "Dolby Stereo Digital",
228
+ "Dolby Atmos",
229
+ "Dolby Vision",
230
+ "Dolby Cinema",
231
+ "DTS",
232
+ "SDDS",
233
+ "IMAX",
234
+ "4DX"
235
+ ]
236
+ ]
237
+ }"""
238
+ ],
239
+ [
240
+ None, # no image
241
+ """Provectus is a Silicon Valley-based Artificial Intelligence consultancy and solutions provider.
242
+
243
+ At Provectus, we are obsessed with leveraging cloud, data, and AI to reimagine the way businesses operate, compete, and deliver customer value. With the wide range of AI solutions for various use cases and industry verticals, Provectus is recognized by technology analysts and top cloud vendors as a leading AI consultancy and solutions provider. We are transformational leaders for our clients and employees.
244
+
245
+ Currently, we are looking for a highly motivated and self-driven Front End Developer.
246
+ Join us!
247
+
248
+ Briefly about your first project in our company:
249
+ The customer is an online distributor of menswear and a leader in the US market that works with Dolce & Gabbana, Calvin Klein, Ralph Lauren. We are developing a system for automating the processes of renting, buying, selling, and ordering suits online.
250
+
251
+ Team:
252
+ Frontend, Backend, and Mobile Engineers.
253
+ Team Lead and PM are on the customer side in the United States.
254
+
255
+ Requirements
256
+ Software Engineering or related field with 3+ years of professional software development experience in Frontend technology such as ReactJs, AngularJs
257
+ Deep understanding of front end development fundamentals including JavaScript, CSS, HTML and strong skills in React.js and its core principles, React.js workflows (such as Flux or Redux), Typescript, webpack, Babel, npm.
258
+ Strong skills working with REST-based APIs and JSON data structures
259
+ Hands-on experience working experience with source control system Git
260
+ Experience working with micro-frontend using web components
261
+ Strong analytical and debugging skills
262
+ At least an Intermediate level of English.
263
+
264
+ Responsibilities
265
+ Implementing best practices and technical solutions in process of migration from Angular to React
266
+ Working on new functionality
267
+ Taking ownership of business requirements and design, implement, test solutions
268
+ Write a professional, performant, high-quality code that will support a scaling business
269
+ Ask the right questions and think deeply about building solutions that support both - short-term and long-term goals
270
+ Proactively participate in the agile development process sprints, providing effort estimates, commitments, and feedback to tasks.""", # text
271
+ """{
272
+ "company": "verbatim-string",
273
+ "industry": "string",
274
+ "position": "string",
275
+ "contract_type": "string",
276
+ "location": "string",
277
+ "remote": [
278
+ "yes",
279
+ "no",
280
+ "hybrid"
281
+ ],
282
+ "education": "string",
283
+ "years_of_experience": "string",
284
+ "required_skills": [
285
+ "string"
286
+ ],
287
+ "responsibilities": [
288
+ "string"
289
+ ],
290
+ "salary": "string",
291
+ "benefits": [
292
+ "string"
293
+ ],
294
+ "language_skills": [
295
+ {
296
+ "language": "verbatim-string",
297
+ "level": "string"
298
+ }
299
+ ]
300
+ }"""
301
+ ],
302
+ ]
303
+
304
+ warn = gr.Markdown(visible=False)
305
+ run_btn = gr.Button("Run", variant="primary")
306
+ out_json = gr.Textbox(
307
+ lines=14,
308
+ label="Extraction Output (JSON)",
309
+ show_copy_button=True,
310
+ )
311
+ run_btn.click(
312
+ fn=run_model,
313
+ inputs=[img, txt, templ],
314
+ outputs=[out_json, templ, warn],
315
+ )
316
+ gr.Examples(
317
+ examples=example_data,
318
+ inputs=[img, txt, templ],
319
+ label="πŸ” Click an example to pre-fill the inputs",
320
+ cache_examples=False,
321
+ )
322
+
323
+
324
+ demo.launch(debug=True, share=True)