ShawnRu commited on
Commit
2c95708
Β·
verified Β·
1 Parent(s): 3e19f2b

Update src/webui.py

Browse files
Files changed (1) hide show
  1. src/webui.py +401 -401
src/webui.py CHANGED
@@ -1,401 +1,401 @@
1
- """
2
- For HuggingFace Space.
3
- """
4
-
5
- import gradio as gr
6
- import json
7
- import random
8
- import re
9
-
10
- from models import *
11
- from pipeline import Pipeline
12
-
13
-
14
- examples = [
15
- {
16
- "task": "NER",
17
- "mode": "quick",
18
- "use_file": False,
19
- "text": "Finally, every other year , ELRA organizes a major conference LREC , the International Language Resources and Evaluation Conference .",
20
- "instruction": "",
21
- "constraint": """["algorithm", "conference", "else", "product", "task", "field", "metrics", "organization", "researcher", "program language", "country", "location", "person", "university"]""",
22
- "file_path": None,
23
- "update_case": False,
24
- "truth": "",
25
- },
26
- {
27
- "task": "Base",
28
- "mode": "quick",
29
- "use_file": True,
30
- "file_path": "data/input_files/Tulsi_Gabbard_News.html",
31
- "instruction": "Extract key information from the given text.",
32
- "constraint": "",
33
- "text": "",
34
- "update_case": False,
35
- "truth": "",
36
- },
37
- {
38
- "task": "RE",
39
- "mode": "quick",
40
- "use_file": False,
41
- "text": "The aid group Doctors Without Borders said that since Saturday , more than 275 wounded people had been admitted and treated at Donka Hospital in the capital of Guinea , Conakry .",
42
- "instruction": "",
43
- "constraint": """["nationality", "country capital", "place of death", "children", "location contains", "place of birth", "place lived", "administrative division of country", "country of administrative divisions", "company", "neighborhood of", "company founders"]""",
44
- "file_path": None,
45
- "update_case": True,
46
- "truth": """{"relation_list": [{"head": "Guinea", "tail": "Conakry", "relation": "country capital"}]}""",
47
- },
48
- {
49
- "task": "EE",
50
- "mode": "standard",
51
- "use_file": False,
52
- "text": "The file suggested to the user contains no software related to video streaming and simply carries the malicious payload that later compromises victim \u2019s account and sends out the deceptive messages to all victim \u2019s contacts .",
53
- "instruction": "",
54
- "constraint": """{"phishing": ["damage amount", "attack pattern", "tool", "victim", "place", "attacker", "purpose", "trusted entity", "time"], "data breach": ["damage amount", "attack pattern", "number of data", "number of victim", "tool", "compromised data", "victim", "place", "attacker", "purpose", "time"], "ransom": ["damage amount", "attack pattern", "payment method", "tool", "victim", "place", "attacker", "price", "time"], "discover vulnerability": ["vulnerable system", "vulnerability", "vulnerable system owner", "vulnerable system version", "supported platform", "common vulnerabilities and exposures", "capabilities", "time", "discoverer"], "patch vulnerability": ["vulnerable system", "vulnerability", "issues addressed", "vulnerable system version", "releaser", "supported platform", "common vulnerabilities and exposures", "patch number", "time", "patch"]}""",
55
- "file_path": None,
56
- "update_case": False,
57
- "truth": "",
58
- },
59
- {
60
- "task": "Triple",
61
- "mode": "quick",
62
- "use_file": True,
63
- "file_path": "data/input_files/Artificial_Intelligence_Wikipedia.txt",
64
- "instruction": "",
65
- "constraint": """[["Person", "Place", "Event", "property"], ["Interpersonal", "Located", "Ownership", "Action"]]""",
66
- "text": "",
67
- "update_case": False,
68
- "truth": "",
69
- },
70
- {
71
- "task": "Base",
72
- "mode": "quick",
73
- "use_file": True,
74
- "file_path": "data/input_files/Harry_Potter_Chapter1.pdf",
75
- "instruction": "Extract main characters and the background setting from this chapter.",
76
- "constraint": "",
77
- "text": "",
78
- "update_case": False,
79
- "truth": "",
80
- },
81
- ]
82
- example_start_index = 0
83
-
84
-
85
- def create_interface():
86
- with gr.Blocks(title="OneKE Demo", theme=gr.themes.Glass(text_size="lg")) as demo:
87
- gr.HTML("""
88
- <div style="text-align:center;">
89
- <p align="center">
90
- <a>
91
- <img src="https://raw.githubusercontent.com/zjunlp/OneKE/refs/heads/main/figs/logo.png" width="240"/>
92
- </a>
93
- </p>
94
- <h1>OneKE: A Dockerized Schema-Guided LLM Agent-based Knowledge Extraction System</h1>
95
- <p>
96
- 🌐[<a href="https://oneke.openkg.cn/" target="_blank">Home</a>]
97
- πŸ“Ή[<a href="http://oneke.openkg.cn/demo.mp4" target="_blank">Video</a>]
98
- πŸ“[<a href="https://arxiv.org/abs/2412.20005v2" target="_blank">Paper</a>]
99
- πŸ’»[<a href="https://github.com/zjunlp/OneKE" target="_blank">Code</a>]
100
- </p>
101
- </div>
102
- """)
103
-
104
- example_button_gr = gr.Button("🎲 Quick Start with an Example 🎲")
105
-
106
- with gr.Row():
107
- with gr.Column():
108
- model_gr = gr.Dropdown(
109
- label="πŸͺ„ Select your Model",
110
- choices=["deepseek-chat", "deepseek-reasoner",
111
- "gpt-3.5-turbo", "gpt-4o-mini", "gpt-4o",
112
- ],
113
- value="deepseek-chat",
114
- )
115
- api_key_gr = gr.Textbox(
116
- label="πŸ”‘ Enter your API-Key",
117
- placeholder="Please enter your API-Key from ChatGPT or DeepSeek.",
118
- type="password",
119
- )
120
- base_url_gr = gr.Textbox(
121
- label="πŸ”— Enter your Base-URL",
122
- placeholder="Please leave this field empty if using the default Base-URL.",
123
- )
124
- with gr.Column():
125
- task_gr = gr.Dropdown(
126
- label="🎯 Select your Task",
127
- choices=["Base", "NER", "RE", "EE", "Triple"],
128
- value="Base",
129
- )
130
- mode_gr = gr.Dropdown(
131
- label="🧭 Select your Mode",
132
- choices=["quick", "standard", "customized"],
133
- value="quick",
134
- )
135
- schema_agent_gr = gr.Dropdown(choices=["Not Required", "get_default_schema", "get_deduced_schema"], value="Not Required", label="πŸ€– Select your Schema-Agent", visible=False)
136
- extraction_Agent_gr = gr.Dropdown(choices=["Not Required", "extract_information_direct", "extract_information_with_case"], value="Not Required", label="πŸ€– Select your Extraction-Agent", visible=False)
137
- reflection_agent_gr = gr.Dropdown(choices=["Not Required", "reflect_with_case"], value="Not Required", label="πŸ€– Select your Reflection-Agent", visible=False)
138
-
139
- use_file_gr = gr.Checkbox(label="πŸ“‚ Use File", value=True)
140
- file_path_gr = gr.File(label="πŸ“– Upload a File", visible=True)
141
- text_gr = gr.Textbox(label="πŸ“– Text", lines=5, placeholder="Please enter the text to be processed.", visible=False)
142
- instruction_gr = gr.Textbox(label="πŸ•ΉοΈ Instruction", lines=3, placeholder="Please enter any type of information you want to extract here, for example: Help me extract all the place names.", visible=True)
143
- constraint_gr = gr.Textbox(label="πŸ•ΉοΈ Constraint", lines=3, placeholder="Please specify the types of entities, relations, events, or other relevant attributes in list format as per the task requirements.", visible=False)
144
-
145
- update_case_gr = gr.Checkbox(label="πŸ’° Update Case", value=False)
146
- # update_schema_gr = gr.Checkbox(label="πŸ“Ÿ Update Schema", value=False)
147
- truth_gr = gr.Textbox(label="πŸͺ™ Truth", lines=2, placeholder="""Please enter the truth you want LLM know, for example: {"relation_list": [{"head": "Guinea", "tail": "Conakry", "relation": "country capital"}]}""", visible=False)
148
- # selfschema_gr = gr.Textbox(label="πŸ“Ÿ Schema", lines=5, placeholder="Enter your New Schema", visible=False, interactive=True)
149
-
150
- def get_model_category(model_name_or_path):
151
- if model_name_or_path in ["gpt-3.5-turbo", "gpt-4o-mini", "gpt-4o", "o3-mini"]:
152
- return ChatGPT
153
- elif model_name_or_path in ["deepseek-chat", "deepseek-reasoner"]:
154
- return DeepSeek
155
- elif re.search(r'(?i)llama', model_name_or_path):
156
- return LLaMA
157
- elif re.search(r'(?i)qwen', model_name_or_path):
158
- return Qwen
159
- elif re.search(r'(?i)minicpm', model_name_or_path):
160
- return MiniCPM
161
- elif re.search(r'(?i)chatglm', model_name_or_path):
162
- return ChatGLM
163
- else:
164
- return BaseEngine
165
-
166
- def customized_mode(mode):
167
- if mode == "customized":
168
- return gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
169
- else:
170
- return gr.update(visible=False, value="Not Required"), gr.update(visible=False, value="Not Required"), gr.update(visible=False, value="Not Required")
171
-
172
- def update_fields(task):
173
- if task == "Base" or task == "":
174
- return gr.update(visible=True, label="πŸ•ΉοΈ Instruction", lines=3,
175
- placeholder="Please enter any type of information you want to extract here, for example: Help me extract all the place names."), gr.update(visible=False)
176
- elif task == "NER":
177
- return gr.update(visible=False), gr.update(visible=True, label="πŸ•ΉοΈ Constraint", lines=3,
178
- placeholder="Please specify the entity types to extract in list format, and all types will be extracted by default if not specified.")
179
- elif task == "RE":
180
- return gr.update(visible=False), gr.update(visible=True, label="πŸ•ΉοΈ Constraint", lines=3,
181
- placeholder="Please specify the relation types to extract in list format, and all types will be extracted by default if not specified.")
182
- elif task == "EE":
183
- return gr.update(visible=False), gr.update(visible=True, label="πŸ•ΉοΈ Constraint", lines=3,
184
- placeholder="Please specify the event types and their corresponding extraction attributes in dictionary format, and all types and attributes will be extracted by default if not specified.")
185
- elif task == "Triple":
186
- return gr.update(visible=False), gr.update(visible=True, label="πŸ•ΉοΈ Constraint", lines=3,
187
- placeholder="Please read the documentation and specify the types of triples in list format.")
188
-
189
- def update_input_fields(use_file):
190
- if use_file:
191
- return gr.update(visible=False), gr.update(visible=True)
192
- else:
193
- return gr.update(visible=True), gr.update(visible=False)
194
-
195
- def update_case(update_case):
196
- if update_case:
197
- return gr.update(visible=True)
198
- else:
199
- return gr.update(visible=False)
200
-
201
- # def update_schema(update_schema):
202
- # if update_schema:
203
- # return gr.update(visible=True)
204
- # else:
205
- # return gr.update(visible=False)
206
-
207
- def start_with_example():
208
- global example_start_index
209
- example = examples[example_start_index]
210
- example_start_index += 1
211
- if example_start_index >= len(examples):
212
- example_start_index = 0
213
-
214
- return (
215
- gr.update(value=example["task"]),
216
- gr.update(value=example["mode"]),
217
- gr.update(value=example["use_file"]),
218
- gr.update(value=example["file_path"], visible=example["use_file"]),
219
- gr.update(value=example["text"], visible=not example["use_file"]),
220
- gr.update(value=example["instruction"], visible=example["task"] == "Base"),
221
- gr.update(value=example["constraint"], visible=example["task"] in ["NER", "RE", "EE", "Triple"]),
222
- gr.update(value=example["update_case"]),
223
- gr.update(value=example["truth"]), # gr.update(value=example["update_schema"]), gr.update(value=example["selfschema"]),
224
- gr.update(value="Not Required", visible=False),
225
- gr.update(value="Not Required", visible=False),
226
- gr.update(value="Not Required", visible=False),
227
- )
228
-
229
- def submit(model, api_key, base_url, task, mode, instruction, constraint, text, use_file, file_path, update_case, truth, schema_agent, extraction_Agent, reflection_agent):
230
- try:
231
- ModelClass = get_model_category(model)
232
- if base_url == "Default" or base_url == "":
233
- if api_key == "":
234
- pipeline = Pipeline(ModelClass(model_name_or_path=model))
235
- else:
236
- pipeline = Pipeline(ModelClass(model_name_or_path=model, api_key=api_key))
237
- else:
238
- if api_key == "":
239
- pipeline = Pipeline(ModelClass(model_name_or_path=model, base_url=base_url))
240
- else:
241
- pipeline = Pipeline(ModelClass(model_name_or_path=model, api_key=api_key, base_url=base_url))
242
-
243
- if task == "Base":
244
- instruction = instruction
245
- constraint = ""
246
- else:
247
- instruction = ""
248
- constraint = constraint
249
- if use_file:
250
- text = ""
251
- file_path = file_path
252
- else:
253
- text = text
254
- file_path = None
255
- if not update_case:
256
- truth = ""
257
-
258
- agent3 = {}
259
- if mode == "customized":
260
- if schema_agent not in ["", "Not Required"]:
261
- agent3["schema_agent"] = schema_agent
262
- if extraction_Agent not in ["", "Not Required"]:
263
- agent3["extraction_agent"] = extraction_Agent
264
- if reflection_agent not in ["", "Not Required"]:
265
- agent3["reflection_agent"] = reflection_agent
266
-
267
- # use 'Pipeline'
268
- _, _, ger_frontend_schema, ger_frontend_res = pipeline.get_extract_result(
269
- task=task,
270
- text=text,
271
- use_file=use_file,
272
- file_path=file_path,
273
- instruction=instruction,
274
- constraint=constraint,
275
- mode=mode,
276
- three_agents=agent3,
277
- isgui=True,
278
- update_case=update_case,
279
- truth=truth,
280
- output_schema="",
281
- show_trajectory=False,
282
- )
283
-
284
- ger_frontend_schema = str(ger_frontend_schema)
285
- ger_frontend_res = json.dumps(ger_frontend_res, ensure_ascii=False, indent=4) if isinstance(ger_frontend_res, dict) else str(ger_frontend_res)
286
- return ger_frontend_schema, ger_frontend_res, gr.update(value="", visible=False)
287
-
288
- except Exception as e:
289
- error_message = f"⚠️ Error:\n {str(e)}"
290
- return "", "", gr.update(value=error_message, visible=True)
291
-
292
- def clear_all():
293
- return (
294
- gr.update(value="Not Required", visible=False), # sechema_agent
295
- gr.update(value="Not Required", visible=False), # extraction_Agent
296
- gr.update(value="Not Required", visible=False), # reflection_agent
297
- gr.update(value="Base"), # task
298
- gr.update(value="quick"), # mode
299
- gr.update(value="", visible=False), # instruction
300
- gr.update(value="", visible=False), # constraint
301
- gr.update(value=True), # use_file
302
- gr.update(value="", visible=False), # text
303
- gr.update(value=None, visible=True), # file_path
304
- gr.update(value=False), # update_case
305
- gr.update(value="", visible=False), # truth # gr.update(value=False), # update_schema gr.update(value="", visible=False), # selfschema
306
- gr.update(value=""), # py_output_gr
307
- gr.update(value=""), # json_output_gr
308
- gr.update(value="", visible=False), # error_output
309
- )
310
-
311
- with gr.Row():
312
- submit_button_gr = gr.Button("Submit", variant="primary", scale=8)
313
- clear_button = gr.Button("Clear", scale=5)
314
- gr.HTML("""
315
- <div style="width: 100%; text-align: center; font-size: 16px; font-weight: bold; position: relative; margin: 20px 0;">
316
- <span style="position: absolute; left: 0; top: 50%; transform: translateY(-50%); width: 45%; border-top: 1px solid #ccc;"></span>
317
- <span style="position: relative; z-index: 1; background-color: white; padding: 0 10px;">Output:</span>
318
- <span style="position: absolute; right: 0; top: 50%; transform: translateY(-50%); width: 45%; border-top: 1px solid #ccc;"></span>
319
- </div>
320
- """)
321
- error_output_gr = gr.Textbox(label="πŸ˜΅β€πŸ’« Ops, an Error Occurred", visible=False, interactive=False)
322
- with gr.Row():
323
- with gr.Column(scale=1):
324
- py_output_gr = gr.Code(label="πŸ€” Generated Schema", language="python", lines=10, interactive=False)
325
- with gr.Column(scale=1):
326
- json_output_gr = gr.Code(label="πŸ˜‰ Final Answer", language="json", lines=10, interactive=False)
327
-
328
- task_gr.change(fn=update_fields, inputs=task_gr, outputs=[instruction_gr, constraint_gr])
329
- mode_gr.change(fn=customized_mode, inputs=mode_gr, outputs=[schema_agent_gr, extraction_Agent_gr, reflection_agent_gr])
330
- use_file_gr.change(fn=update_input_fields, inputs=use_file_gr, outputs=[text_gr, file_path_gr])
331
- update_case_gr.change(fn=update_case, inputs=update_case_gr, outputs=[truth_gr])
332
- # update_schema_gr.change(fn=update_schema, inputs=update_schema_gr, outputs=[selfschema_gr])
333
-
334
- example_button_gr.click(
335
- fn=start_with_example,
336
- inputs=[],
337
- outputs=[
338
- task_gr,
339
- mode_gr,
340
- use_file_gr,
341
- file_path_gr,
342
- text_gr,
343
- instruction_gr,
344
- constraint_gr,
345
- update_case_gr,
346
- truth_gr, # update_schema_gr, selfschema_gr,
347
- schema_agent_gr,
348
- extraction_Agent_gr,
349
- reflection_agent_gr,
350
- ],
351
- )
352
- submit_button_gr.click(
353
- fn=submit,
354
- inputs=[
355
- model_gr,
356
- api_key_gr,
357
- base_url_gr,
358
- task_gr,
359
- mode_gr,
360
- instruction_gr,
361
- constraint_gr,
362
- text_gr,
363
- use_file_gr,
364
- file_path_gr,
365
- update_case_gr,
366
- truth_gr, # update_schema_gr, selfschema_gr,
367
- schema_agent_gr,
368
- extraction_Agent_gr,
369
- reflection_agent_gr,
370
- ],
371
- outputs=[py_output_gr, json_output_gr, error_output_gr],
372
- show_progress=True,
373
- )
374
- clear_button.click(
375
- fn=clear_all,
376
- outputs=[
377
- schema_agent_gr,
378
- extraction_Agent_gr,
379
- reflection_agent_gr,
380
- task_gr,
381
- mode_gr,
382
- instruction_gr,
383
- constraint_gr,
384
- use_file_gr,
385
- text_gr,
386
- file_path_gr,
387
- update_case_gr,
388
- truth_gr, # update_schema_gr, selfschema_gr,
389
- py_output_gr,
390
- json_output_gr,
391
- error_output_gr,
392
- ],
393
- )
394
-
395
- return demo
396
-
397
-
398
- # Launch the front-end interface
399
- if __name__ == "__main__":
400
- interface = create_interface()
401
- interface.launch()
 
1
+ """
2
+ For HuggingFace Space.
3
+ """
4
+
5
+ import gradio as gr
6
+ import json
7
+ import random
8
+ import re
9
+
10
+ from models import *
11
+ from pipeline import Pipeline
12
+
13
+
14
+ examples = [
15
+ {
16
+ "task": "NER",
17
+ "mode": "quick",
18
+ "use_file": False,
19
+ "text": "Finally, every other year , ELRA organizes a major conference LREC , the International Language Resources and Evaluation Conference .",
20
+ "instruction": "",
21
+ "constraint": """["algorithm", "conference", "else", "product", "task", "field", "metrics", "organization", "researcher", "program language", "country", "location", "person", "university"]""",
22
+ "file_path": None,
23
+ "update_case": False,
24
+ "truth": "",
25
+ },
26
+ {
27
+ "task": "Base",
28
+ "mode": "quick",
29
+ "use_file": True,
30
+ "file_path": "data/input_files/Tulsi_Gabbard_News.html",
31
+ "instruction": "Extract key information from the given text.",
32
+ "constraint": "",
33
+ "text": "",
34
+ "update_case": False,
35
+ "truth": "",
36
+ },
37
+ {
38
+ "task": "RE",
39
+ "mode": "quick",
40
+ "use_file": False,
41
+ "text": "The aid group Doctors Without Borders said that since Saturday , more than 275 wounded people had been admitted and treated at Donka Hospital in the capital of Guinea , Conakry .",
42
+ "instruction": "",
43
+ "constraint": """["nationality", "country capital", "place of death", "children", "location contains", "place of birth", "place lived", "administrative division of country", "country of administrative divisions", "company", "neighborhood of", "company founders"]""",
44
+ "file_path": None,
45
+ "update_case": True,
46
+ "truth": """{"relation_list": [{"head": "Guinea", "tail": "Conakry", "relation": "country capital"}]}""",
47
+ },
48
+ {
49
+ "task": "EE",
50
+ "mode": "standard",
51
+ "use_file": False,
52
+ "text": "The file suggested to the user contains no software related to video streaming and simply carries the malicious payload that later compromises victim \u2019s account and sends out the deceptive messages to all victim \u2019s contacts .",
53
+ "instruction": "",
54
+ "constraint": """{"phishing": ["damage amount", "attack pattern", "tool", "victim", "place", "attacker", "purpose", "trusted entity", "time"], "data breach": ["damage amount", "attack pattern", "number of data", "number of victim", "tool", "compromised data", "victim", "place", "attacker", "purpose", "time"], "ransom": ["damage amount", "attack pattern", "payment method", "tool", "victim", "place", "attacker", "price", "time"], "discover vulnerability": ["vulnerable system", "vulnerability", "vulnerable system owner", "vulnerable system version", "supported platform", "common vulnerabilities and exposures", "capabilities", "time", "discoverer"], "patch vulnerability": ["vulnerable system", "vulnerability", "issues addressed", "vulnerable system version", "releaser", "supported platform", "common vulnerabilities and exposures", "patch number", "time", "patch"]}""",
55
+ "file_path": None,
56
+ "update_case": False,
57
+ "truth": "",
58
+ },
59
+ {
60
+ "task": "Triple",
61
+ "mode": "quick",
62
+ "use_file": True,
63
+ "file_path": "data/input_files/Artificial_Intelligence_Wikipedia.txt",
64
+ "instruction": "",
65
+ "constraint": """[["Person", "Place", "Event", "property"], ["Interpersonal", "Located", "Ownership", "Action"]]""",
66
+ "text": "",
67
+ "update_case": False,
68
+ "truth": "",
69
+ },
70
+ {
71
+ "task": "Base",
72
+ "mode": "quick",
73
+ "use_file": True,
74
+ "file_path": "data/input_files/Harry_Potter_Chapter1.pdf",
75
+ "instruction": "Extract main characters and the background setting from this chapter.",
76
+ "constraint": "",
77
+ "text": "",
78
+ "update_case": False,
79
+ "truth": "",
80
+ },
81
+ ]
82
+ example_start_index = 0
83
+
84
+
85
+ def create_interface():
86
+ with gr.Blocks(title="OneKE Demo", theme=gr.themes.Glass(text_size="lg")) as demo:
87
+ gr.HTML("""
88
+ <div style="text-align:center;">
89
+ <p align="center">
90
+ <a>
91
+ <img src="https://raw.githubusercontent.com/zjunlp/OneKE/refs/heads/main/figs/logo.png" width="240"/>
92
+ </a>
93
+ </p>
94
+ <h1>OneKE: A Dockerized Schema-Guided LLM Agent-based Knowledge Extraction System</h1>
95
+ <p>
96
+ 🌐[<a href="http://oneke.openkg.cn/" target="_blank">Home</a>]
97
+ πŸ“Ή[<a href="http://oneke.openkg.cn/demo.mp4" target="_blank">Video</a>]
98
+ πŸ“[<a href="https://arxiv.org/abs/2412.20005v2" target="_blank">Paper</a>]
99
+ πŸ’»[<a href="https://github.com/zjunlp/OneKE" target="_blank">Code</a>]
100
+ </p>
101
+ </div>
102
+ """)
103
+
104
+ example_button_gr = gr.Button("🎲 Quick Start with an Example 🎲")
105
+
106
+ with gr.Row():
107
+ with gr.Column():
108
+ model_gr = gr.Dropdown(
109
+ label="πŸͺ„ Select your Model",
110
+ choices=["deepseek-chat", "deepseek-reasoner",
111
+ "gpt-3.5-turbo", "gpt-4o-mini", "gpt-4o",
112
+ ],
113
+ value="deepseek-chat",
114
+ )
115
+ api_key_gr = gr.Textbox(
116
+ label="πŸ”‘ Enter your API-Key",
117
+ placeholder="Please enter your API-Key from ChatGPT or DeepSeek.",
118
+ type="password",
119
+ )
120
+ base_url_gr = gr.Textbox(
121
+ label="πŸ”— Enter your Base-URL",
122
+ placeholder="Please leave this field empty if using the default Base-URL.",
123
+ )
124
+ with gr.Column():
125
+ task_gr = gr.Dropdown(
126
+ label="🎯 Select your Task",
127
+ choices=["Base", "NER", "RE", "EE", "Triple"],
128
+ value="Base",
129
+ )
130
+ mode_gr = gr.Dropdown(
131
+ label="🧭 Select your Mode",
132
+ choices=["quick", "standard", "customized"],
133
+ value="quick",
134
+ )
135
+ schema_agent_gr = gr.Dropdown(choices=["Not Required", "get_default_schema", "get_deduced_schema"], value="Not Required", label="πŸ€– Select your Schema-Agent", visible=False)
136
+ extraction_Agent_gr = gr.Dropdown(choices=["Not Required", "extract_information_direct", "extract_information_with_case"], value="Not Required", label="πŸ€– Select your Extraction-Agent", visible=False)
137
+ reflection_agent_gr = gr.Dropdown(choices=["Not Required", "reflect_with_case"], value="Not Required", label="πŸ€– Select your Reflection-Agent", visible=False)
138
+
139
+ use_file_gr = gr.Checkbox(label="πŸ“‚ Use File", value=True)
140
+ file_path_gr = gr.File(label="πŸ“– Upload a File", visible=True)
141
+ text_gr = gr.Textbox(label="πŸ“– Text", lines=5, placeholder="Please enter the text to be processed.", visible=False)
142
+ instruction_gr = gr.Textbox(label="πŸ•ΉοΈ Instruction", lines=3, placeholder="Please enter any type of information you want to extract here, for example: Help me extract all the place names.", visible=True)
143
+ constraint_gr = gr.Textbox(label="πŸ•ΉοΈ Constraint", lines=3, placeholder="Please specify the types of entities, relations, events, or other relevant attributes in list format as per the task requirements.", visible=False)
144
+
145
+ update_case_gr = gr.Checkbox(label="πŸ’° Update Case", value=False)
146
+ # update_schema_gr = gr.Checkbox(label="πŸ“Ÿ Update Schema", value=False)
147
+ truth_gr = gr.Textbox(label="πŸͺ™ Truth", lines=2, placeholder="""Please enter the truth you want LLM know, for example: {"relation_list": [{"head": "Guinea", "tail": "Conakry", "relation": "country capital"}]}""", visible=False)
148
+ # selfschema_gr = gr.Textbox(label="πŸ“Ÿ Schema", lines=5, placeholder="Enter your New Schema", visible=False, interactive=True)
149
+
150
+ def get_model_category(model_name_or_path):
151
+ if model_name_or_path in ["gpt-3.5-turbo", "gpt-4o-mini", "gpt-4o", "o3-mini"]:
152
+ return ChatGPT
153
+ elif model_name_or_path in ["deepseek-chat", "deepseek-reasoner"]:
154
+ return DeepSeek
155
+ elif re.search(r'(?i)llama', model_name_or_path):
156
+ return LLaMA
157
+ elif re.search(r'(?i)qwen', model_name_or_path):
158
+ return Qwen
159
+ elif re.search(r'(?i)minicpm', model_name_or_path):
160
+ return MiniCPM
161
+ elif re.search(r'(?i)chatglm', model_name_or_path):
162
+ return ChatGLM
163
+ else:
164
+ return BaseEngine
165
+
166
+ def customized_mode(mode):
167
+ if mode == "customized":
168
+ return gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
169
+ else:
170
+ return gr.update(visible=False, value="Not Required"), gr.update(visible=False, value="Not Required"), gr.update(visible=False, value="Not Required")
171
+
172
+ def update_fields(task):
173
+ if task == "Base" or task == "":
174
+ return gr.update(visible=True, label="πŸ•ΉοΈ Instruction", lines=3,
175
+ placeholder="Please enter any type of information you want to extract here, for example: Help me extract all the place names."), gr.update(visible=False)
176
+ elif task == "NER":
177
+ return gr.update(visible=False), gr.update(visible=True, label="πŸ•ΉοΈ Constraint", lines=3,
178
+ placeholder="Please specify the entity types to extract in list format, and all types will be extracted by default if not specified.")
179
+ elif task == "RE":
180
+ return gr.update(visible=False), gr.update(visible=True, label="πŸ•ΉοΈ Constraint", lines=3,
181
+ placeholder="Please specify the relation types to extract in list format, and all types will be extracted by default if not specified.")
182
+ elif task == "EE":
183
+ return gr.update(visible=False), gr.update(visible=True, label="πŸ•ΉοΈ Constraint", lines=3,
184
+ placeholder="Please specify the event types and their corresponding extraction attributes in dictionary format, and all types and attributes will be extracted by default if not specified.")
185
+ elif task == "Triple":
186
+ return gr.update(visible=False), gr.update(visible=True, label="πŸ•ΉοΈ Constraint", lines=3,
187
+ placeholder="Please read the documentation and specify the types of triples in list format.")
188
+
189
+ def update_input_fields(use_file):
190
+ if use_file:
191
+ return gr.update(visible=False), gr.update(visible=True)
192
+ else:
193
+ return gr.update(visible=True), gr.update(visible=False)
194
+
195
+ def update_case(update_case):
196
+ if update_case:
197
+ return gr.update(visible=True)
198
+ else:
199
+ return gr.update(visible=False)
200
+
201
+ # def update_schema(update_schema):
202
+ # if update_schema:
203
+ # return gr.update(visible=True)
204
+ # else:
205
+ # return gr.update(visible=False)
206
+
207
+ def start_with_example():
208
+ global example_start_index
209
+ example = examples[example_start_index]
210
+ example_start_index += 1
211
+ if example_start_index >= len(examples):
212
+ example_start_index = 0
213
+
214
+ return (
215
+ gr.update(value=example["task"]),
216
+ gr.update(value=example["mode"]),
217
+ gr.update(value=example["use_file"]),
218
+ gr.update(value=example["file_path"], visible=example["use_file"]),
219
+ gr.update(value=example["text"], visible=not example["use_file"]),
220
+ gr.update(value=example["instruction"], visible=example["task"] == "Base"),
221
+ gr.update(value=example["constraint"], visible=example["task"] in ["NER", "RE", "EE", "Triple"]),
222
+ gr.update(value=example["update_case"]),
223
+ gr.update(value=example["truth"]), # gr.update(value=example["update_schema"]), gr.update(value=example["selfschema"]),
224
+ gr.update(value="Not Required", visible=False),
225
+ gr.update(value="Not Required", visible=False),
226
+ gr.update(value="Not Required", visible=False),
227
+ )
228
+
229
+ def submit(model, api_key, base_url, task, mode, instruction, constraint, text, use_file, file_path, update_case, truth, schema_agent, extraction_Agent, reflection_agent):
230
+ try:
231
+ ModelClass = get_model_category(model)
232
+ if base_url == "Default" or base_url == "":
233
+ if api_key == "":
234
+ pipeline = Pipeline(ModelClass(model_name_or_path=model))
235
+ else:
236
+ pipeline = Pipeline(ModelClass(model_name_or_path=model, api_key=api_key))
237
+ else:
238
+ if api_key == "":
239
+ pipeline = Pipeline(ModelClass(model_name_or_path=model, base_url=base_url))
240
+ else:
241
+ pipeline = Pipeline(ModelClass(model_name_or_path=model, api_key=api_key, base_url=base_url))
242
+
243
+ if task == "Base":
244
+ instruction = instruction
245
+ constraint = ""
246
+ else:
247
+ instruction = ""
248
+ constraint = constraint
249
+ if use_file:
250
+ text = ""
251
+ file_path = file_path
252
+ else:
253
+ text = text
254
+ file_path = None
255
+ if not update_case:
256
+ truth = ""
257
+
258
+ agent3 = {}
259
+ if mode == "customized":
260
+ if schema_agent not in ["", "Not Required"]:
261
+ agent3["schema_agent"] = schema_agent
262
+ if extraction_Agent not in ["", "Not Required"]:
263
+ agent3["extraction_agent"] = extraction_Agent
264
+ if reflection_agent not in ["", "Not Required"]:
265
+ agent3["reflection_agent"] = reflection_agent
266
+
267
+ # use 'Pipeline'
268
+ _, _, ger_frontend_schema, ger_frontend_res = pipeline.get_extract_result(
269
+ task=task,
270
+ text=text,
271
+ use_file=use_file,
272
+ file_path=file_path,
273
+ instruction=instruction,
274
+ constraint=constraint,
275
+ mode=mode,
276
+ three_agents=agent3,
277
+ isgui=True,
278
+ update_case=update_case,
279
+ truth=truth,
280
+ output_schema="",
281
+ show_trajectory=False,
282
+ )
283
+
284
+ ger_frontend_schema = str(ger_frontend_schema)
285
+ ger_frontend_res = json.dumps(ger_frontend_res, ensure_ascii=False, indent=4) if isinstance(ger_frontend_res, dict) else str(ger_frontend_res)
286
+ return ger_frontend_schema, ger_frontend_res, gr.update(value="", visible=False)
287
+
288
+ except Exception as e:
289
+ error_message = f"⚠️ Error:\n {str(e)}"
290
+ return "", "", gr.update(value=error_message, visible=True)
291
+
292
+ def clear_all():
293
+ return (
294
+ gr.update(value="Not Required", visible=False), # sechema_agent
295
+ gr.update(value="Not Required", visible=False), # extraction_Agent
296
+ gr.update(value="Not Required", visible=False), # reflection_agent
297
+ gr.update(value="Base"), # task
298
+ gr.update(value="quick"), # mode
299
+ gr.update(value="", visible=False), # instruction
300
+ gr.update(value="", visible=False), # constraint
301
+ gr.update(value=True), # use_file
302
+ gr.update(value="", visible=False), # text
303
+ gr.update(value=None, visible=True), # file_path
304
+ gr.update(value=False), # update_case
305
+ gr.update(value="", visible=False), # truth # gr.update(value=False), # update_schema gr.update(value="", visible=False), # selfschema
306
+ gr.update(value=""), # py_output_gr
307
+ gr.update(value=""), # json_output_gr
308
+ gr.update(value="", visible=False), # error_output
309
+ )
310
+
311
+ with gr.Row():
312
+ submit_button_gr = gr.Button("Submit", variant="primary", scale=8)
313
+ clear_button = gr.Button("Clear", scale=5)
314
+ gr.HTML("""
315
+ <div style="width: 100%; text-align: center; font-size: 16px; font-weight: bold; position: relative; margin: 20px 0;">
316
+ <span style="position: absolute; left: 0; top: 50%; transform: translateY(-50%); width: 45%; border-top: 1px solid #ccc;"></span>
317
+ <span style="position: relative; z-index: 1; background-color: white; padding: 0 10px;">Output:</span>
318
+ <span style="position: absolute; right: 0; top: 50%; transform: translateY(-50%); width: 45%; border-top: 1px solid #ccc;"></span>
319
+ </div>
320
+ """)
321
+ error_output_gr = gr.Textbox(label="πŸ˜΅β€πŸ’« Ops, an Error Occurred", visible=False, interactive=False)
322
+ with gr.Row():
323
+ with gr.Column(scale=1):
324
+ py_output_gr = gr.Code(label="πŸ€” Generated Schema", language="python", lines=10, interactive=False)
325
+ with gr.Column(scale=1):
326
+ json_output_gr = gr.Code(label="πŸ˜‰ Final Answer", language="json", lines=10, interactive=False)
327
+
328
+ task_gr.change(fn=update_fields, inputs=task_gr, outputs=[instruction_gr, constraint_gr])
329
+ mode_gr.change(fn=customized_mode, inputs=mode_gr, outputs=[schema_agent_gr, extraction_Agent_gr, reflection_agent_gr])
330
+ use_file_gr.change(fn=update_input_fields, inputs=use_file_gr, outputs=[text_gr, file_path_gr])
331
+ update_case_gr.change(fn=update_case, inputs=update_case_gr, outputs=[truth_gr])
332
+ # update_schema_gr.change(fn=update_schema, inputs=update_schema_gr, outputs=[selfschema_gr])
333
+
334
+ example_button_gr.click(
335
+ fn=start_with_example,
336
+ inputs=[],
337
+ outputs=[
338
+ task_gr,
339
+ mode_gr,
340
+ use_file_gr,
341
+ file_path_gr,
342
+ text_gr,
343
+ instruction_gr,
344
+ constraint_gr,
345
+ update_case_gr,
346
+ truth_gr, # update_schema_gr, selfschema_gr,
347
+ schema_agent_gr,
348
+ extraction_Agent_gr,
349
+ reflection_agent_gr,
350
+ ],
351
+ )
352
+ submit_button_gr.click(
353
+ fn=submit,
354
+ inputs=[
355
+ model_gr,
356
+ api_key_gr,
357
+ base_url_gr,
358
+ task_gr,
359
+ mode_gr,
360
+ instruction_gr,
361
+ constraint_gr,
362
+ text_gr,
363
+ use_file_gr,
364
+ file_path_gr,
365
+ update_case_gr,
366
+ truth_gr, # update_schema_gr, selfschema_gr,
367
+ schema_agent_gr,
368
+ extraction_Agent_gr,
369
+ reflection_agent_gr,
370
+ ],
371
+ outputs=[py_output_gr, json_output_gr, error_output_gr],
372
+ show_progress=True,
373
+ )
374
+ clear_button.click(
375
+ fn=clear_all,
376
+ outputs=[
377
+ schema_agent_gr,
378
+ extraction_Agent_gr,
379
+ reflection_agent_gr,
380
+ task_gr,
381
+ mode_gr,
382
+ instruction_gr,
383
+ constraint_gr,
384
+ use_file_gr,
385
+ text_gr,
386
+ file_path_gr,
387
+ update_case_gr,
388
+ truth_gr, # update_schema_gr, selfschema_gr,
389
+ py_output_gr,
390
+ json_output_gr,
391
+ error_output_gr,
392
+ ],
393
+ )
394
+
395
+ return demo
396
+
397
+
398
+ # Launch the front-end interface
399
+ if __name__ == "__main__":
400
+ interface = create_interface()
401
+ interface.launch()