File size: 11,164 Bytes
009d93e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import random
import json
import gradio as gr

from pipeline import Pipeline
from models import *


examples = [
    {
        "task": "NER",
        "use_file": False,
        "text": "Finally, every other year , ELRA organizes a major conference LREC , the International Language Resources and Evaluation Conference .",
        "instruction": "",
        "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"]""",
        "file_path": None,
    },
    {
        "task": "RE",
        "use_file": False,
        "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 .",
        "instruction": "",
        "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"]""",
        "file_path": None,
    },
        {
        "task": "EE",
        "use_file": False,
        "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 .",
        "instruction": "",
        "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"]}""",
        "file_path": None,
    },
    # {
    #     "task": "Base",
    #     "use_file": True,
    #     "file_path": "data/Harry_Potter_Chapter_1.pdf",
    #     "instruction": "Extract main characters and the background setting from this chapter.",
    #     "constraint": "",
    #     "text": "",
    # },
    # {
    #     "task": "Base",
    #     "use_file": True,
    #     "file_path": "data/Tulsi_Gabbard_News.html",
    #     "instruction": "Extract key information from the given text.",
    #     "constraint": "",
    #     "text": "",
    # },
]


def create_interface():
    with gr.Blocks(title="OneKE Demo") as demo:
        gr.HTML("""
            <div style="text-align:center;">
                <p align="center">
                    <a href="https://github.com/zjunlp/DeepKE/blob/main/example/llm/assets/oneke_logo.png">
                        <img src="https://raw.githubusercontent.com/zjunlp/DeepKE/refs/heads/main/example/llm/assets/oneke_logo.png" width="240"/>
                    </a>
                </p>
                <h1>OneKE: A Dockerized Schema-Guided LLM Agent-based Knowledge Extraction System</h1>
                <p>
                ๐ŸŒ[<a href="https://oneke.openkg.cn/" target="_blank">Web</a>]
                โŒจ๏ธ[<a href="https://github.com/zjunlp/OneKE" target="_blank">Code</a>]
                ๐Ÿ“น[<a href="http://oneke.openkg.cn/demo.mp4" target="_blank">Video</a>]
                </p>
            </div>
        """)

        example_button_gr = gr.Button("๐ŸŽฒ Quick Start with an Example ๐ŸŽฒ")


        with gr.Row():
            with gr.Column():
                model_gr = gr.Dropdown(choices=["gpt-3.5-turbo", "gpt-4o", "gpt-4o-mini"], label="๐Ÿค– Select your Model")
                api_key_gr = gr.Textbox(label="๐Ÿ”‘ Enter your API-Key")
            with gr.Column():
                task_gr = gr.Dropdown(choices=["Base", "NER", "RE", "EE"], label="๐ŸŽฏ Select your Task")
                use_file_gr = gr.Checkbox(label="๐Ÿ“‚ Use File", value=True)

        file_path_gr = gr.File(label="๐Ÿ“– Upload a File", visible=True)
        text_gr = gr.Textbox(label="๐Ÿ“– Text", placeholder="Enter your Text", visible=False)
        instruction_gr = gr.Textbox(label="๐Ÿ•น๏ธ Instruction", visible=True)
        constraint_gr = gr.Textbox(label="๐Ÿ•น๏ธ Constraint", visible=False)

        def update_fields(task):
            if task == "Base":
                return gr.update(visible=True, label="๐Ÿ•น๏ธ Instruction", placeholder="Enter your Instruction"), gr.update(visible=False)
            elif task == "NER":
                return gr.update(visible=False), gr.update(visible=True, label="๐Ÿ•น๏ธ Constraint", placeholder="Enter your NER Constraint")
            elif task == "RE":
                return gr.update(visible=False), gr.update(visible=True, label="๐Ÿ•น๏ธ Constraint", placeholder="Enter your RE Constraint")
            elif task == "EE":
                return gr.update(visible=False), gr.update(visible=True, label="๐Ÿ•น๏ธ Constraint", placeholder="Enter your EE Constraint")

        def update_input_fields(use_file):
            if use_file:
                return gr.update(visible=False), gr.update(visible=True)
            else:
                return gr.update(visible=True), gr.update(visible=False)

        def start_with_example():
            example_index = random.randint(0, len(examples) - 1)
            example = examples[example_index]
            return (
                gr.update(value=example["task"]),
                gr.update(value=example["use_file"]),
                gr.update(value=example["file_path"], visible=example["use_file"]),
                gr.update(value=example["text"], visible=not example["use_file"]),
                gr.update(value=example["instruction"], visible=example["task"] == "Base"),
                gr.update(value=example["constraint"], visible=example["task"] in ["NER", "RE", "EE"]),
            )

        def submit(model, api_key, task, instruction, constraint, text, use_file, file_path):
            try:
                # ๅˆ›ๅปบ Pipeline ๅฎžไพ‹
                pipeline = Pipeline(ChatGPT(model_name_or_path=model, api_key=api_key))
                if task == "Base":
                    instruction = instruction
                    constraint = ""
                else:
                    instruction = ""
                    constraint = constraint
                if use_file:
                    text = ""
                    file_path = file_path
                else:
                    text = text
                    file_path = None

                # ่ฐƒ็”จ Pipeline
                _, _, ger_frontend_schema, ger_frontend_res = pipeline.get_extract_result(
                    task=task,
                    instruction=instruction,
                    constraint=constraint,
                    use_file=use_file,
                    file_path=file_path,
                    text=text,
                )

                ger_frontend_schema = str(ger_frontend_schema)
                ger_frontend_res = json.dumps(ger_frontend_res, ensure_ascii=False, indent=4) if isinstance(ger_frontend_res, dict) else str(ger_frontend_res)
                return ger_frontend_schema, ger_frontend_res, gr.update(value="", visible=False)

            except Exception as e:
                error_message = f"โš ๏ธ Error:\n {str(e)}"
                return "", "", gr.update(value=error_message, visible=True)

        def clear_all():
            return (
                gr.update(value=""),  # model
                gr.update(value=""),  # API Key
                gr.update(value=""),  # task
                gr.update(value="", visible=False),  # instruction
                gr.update(value="", visible=False),  # constraint
                gr.update(value=True),  # use_file
                gr.update(value="", visible=False),  # text
                gr.update(value=None, visible=True),  # file_path
                gr.update(value=""),
                gr.update(value=""),
                gr.update(value="", visible=False),  # error_output
            )

        with gr.Row():
            submit_button_gr = gr.Button("Submit", variant="primary", scale=8)
            clear_button = gr.Button("Clear", scale=5)
        gr.HTML("""
		    <div style="width: 100%; text-align: center; font-size: 16px; font-weight: bold; position: relative; margin: 20px 0;">
    			<span style="position: absolute; left: 0; top: 50%; transform: translateY(-50%); width: 45%; border-top: 1px solid #ccc;"></span>
	    		<span style="position: relative; z-index: 1; background-color: white; padding: 0 10px;">Output:</span>
			    <span style="position: absolute; right: 0; top: 50%; transform: translateY(-50%); width: 45%; border-top: 1px solid #ccc;"></span>
		    </div>
        """)
        error_output_gr = gr.Textbox(label="๐Ÿ˜ตโ€๐Ÿ’ซ Ops, an Error Occurred", visible=False)
        with gr.Row():
            with gr.Column(scale=1):
                py_output_gr = gr.Code(label="๐Ÿค” Generated Schema", language="python", lines=10, interactive=False)
            with gr.Column(scale=1):
                json_output_gr = gr.Code(label="๐Ÿ˜‰ Final Answer", language="json", lines=10, interactive=False)

        task_gr.change(fn=update_fields, inputs=task_gr, outputs=[instruction_gr, constraint_gr])
        use_file_gr.change(fn=update_input_fields, inputs=use_file_gr, outputs=[text_gr, file_path_gr])

        example_button_gr.click(
            fn=start_with_example,
            inputs=[],
            outputs=[
                task_gr,
                use_file_gr,
                file_path_gr,
                text_gr,
                instruction_gr,
                constraint_gr,
            ],
        )
        submit_button_gr.click(
            fn=submit,
            inputs=[
                model_gr,
                api_key_gr,
                task_gr,
                instruction_gr,
                constraint_gr,
                text_gr,
                use_file_gr,
                file_path_gr,
            ],
            outputs=[py_output_gr, json_output_gr, error_output_gr],
            show_progress=True,
        )
        clear_button.click(
            fn=clear_all,
            outputs=[
                model_gr,
                api_key_gr,
                task_gr,
                instruction_gr,
                constraint_gr,
                use_file_gr,
                text_gr,
                file_path_gr,
                py_output_gr,
                json_output_gr,
                error_output_gr,
            ],
        )

    return demo


interface = create_interface()
interface.launch()