File size: 10,390 Bytes
e67043b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
from .utils import *
import pandas as pd
import requests
import json
from ...tool import Tool


def build_tool(config) -> Tool:
    tool = Tool(
        "Search in Wikidata",
        "answering factual questions in wikidata.",
        description_for_model="Plugin for answering factual questions in wikidata.",
        logo_url="https://your-app-url.com/.well-known/logo.png",
        contact_email="[email protected]",
        legal_info_url="[email protected]",
    )
    sparql = Slot2Sparql()

    @tool.get("/find_entity")
    def find_entity(input):
        """Find all <r, t> that has the relation <input, r, t>. It looks like viewing the main page of the input entity. The result is a table."""
        try:
            sparqlIdx = -1

            if input[0] == "#":
                input = {"id": int(input[1:]), "attr": "tmp"}
            elif input[0] == "Q":
                input = {"id": input, "attr": "wd"}
            elif input[0] == "P":
                input = {"id": input, "attr": "wdt"}
            elif input[0] == "@":
                input = {"id": input[1:], "attr": "wds"}
            else:
                input = {"id": input, "attr": "val"}
            sparql.find_entity(input)
            sparqlIdx = len(sparql.select_lst) - 1

            query, ids = sparql.give_str(sparqlIdx)

            query += "\nLIMIT 2000"

            ids = ["#" + str(id["id"]) for id in ids]

            result = getResult(query)

            variable_name = [
                enc(sparql.select_lst[sparqlIdx].state[-1][1])[1:],
                enc(sparql.select_lst[sparqlIdx].state[-1][2])[1:],
                enc(sparql.select_lst[sparqlIdx].state[-1][3])[1:],
            ]

            response = [{} for i in range(0, len(result))]

            print("RESULT:", result)

            for idx, re in enumerate(result):
                response[idx].update(
                    get_property_details(re[variable_name[0]]["value"])
                    if re[variable_name[0]]["type"] == "uri"
                    else {
                        "relation": "",
                        "relationLabel": re[variable_name[0]]["value"],
                        "relationDescription": "",
                        # 'propuri': ''
                    }
                )

                response[idx].update(
                    {
                        "tail": re[variable_name[1]]["value"].split("/")[-1]
                        if re[variable_name[1]]["type"] == "uri"
                        else "",
                        "tailLabel": re.get(variable_name[1] + "Label", {"value": ""})[
                            "value"
                        ]
                        if re[variable_name[1]]["type"] == "uri"
                        else re[variable_name[1]]["value"],
                        "tailDescription": re.get(
                            variable_name[1] + "Description", {"value": ""}
                        )["value"],
                        # 'tailuri': re[variable_name[1]]['value'] if re[variable_name[1]]['type'] == 'uri' else '',
                        # 'tailtype': 'uri' if re[variable_name[1]]['type'] == 'uri' else re[variable_name[1]].get('datatype', '')
                    }
                )
                if variable_name[2] in re:
                    response[idx].update(
                        {
                            "time": re.get(variable_name[2] + "Label", {"value": ""})[
                                "value"
                            ]
                            if re[variable_name[2]]["type"] == "uri"
                            else re[variable_name[2]]["value"],
                        }
                    )
                else:
                    response[idx].update({"time": "ALWAYS"})

            df = pd.DataFrame.from_dict(response)
            return df.to_markdown()
        except Exception:
            print("Invalid option!\n", Exception)
            return df.to_markdown()

    @tool.get("/find_entity_by_tail")
    def find_entity_by_tail(input: str):
        """Find all <h, r> that has the relation <h, r, input>. It looks like viewing the reverse main page of the input entity. The result is a table."""
        try:
            sparqlIdx = -1

            if input[0] == "#":
                input = {"id": int(input[1:]), "attr": "tmp"}
            elif input[0] == "Q":
                input = {"id": input, "attr": "wd"}
            elif input[0] == "P":
                input = {"id": input, "attr": "wdt"}
            elif input[0] == "@":
                input = {"id": input[1:], "attr": "wds"}
            else:
                input = {"id": input, "attr": "val"}
            sparql.find_entity_by_tail(input)
            sparqlIdx = len(sparql.select_lst) - 1

            query, ids = sparql.give_str(sparqlIdx)

            query += "\nLIMIT 2000"

            ids = ["#" + str(id["id"]) for id in ids]

            result = getResult(query)

            variable_name = [
                enc(sparql.select_lst[sparqlIdx].state[-1][0])[1:],
                enc(sparql.select_lst[sparqlIdx].state[-1][1])[1:],
            ]

            response = [{} for i in range(0, len(result))]

            for idx, re in enumerate(result):
                response[idx].update(
                    get_property_details(re[variable_name[1]]["value"])
                    if re[variable_name[1]]["type"] == "uri"
                    else {
                        "relation": "",
                        "relationLabel": re[variable_name[1]]["value"],
                        "relationDescription": "",
                        # 'labelUri': ''
                    }
                )

                response[idx].update(
                    {
                        "head": re[variable_name[0]]["value"].split("/")[-1]
                        if re[variable_name[0]]["type"] == "uri"
                        else "",
                        "headLabel": re.get(variable_name[0] + "Label", {"value": ""})[
                            "value"
                        ]
                        if re[variable_name[0]]["type"] == "uri"
                        else re[variable_name[0]]["value"],
                        "headDescription": re.get(
                            variable_name[0] + "Description", {"value": ""}
                        )["value"],
                        # 'headUri': re[variable_name[0]]['value'] if re[variable_name[0]]['type'] == 'uri' else '',
                        # 'headType': 'uri' if re[variable_name[0]]['type'] == 'uri' else re[variable_name[0]].get('datatype', '')
                    }
                )

            df = pd.DataFrame.from_dict(response)
            return df.to_markdown()

        except Exception:
            print("Invalid option!\n", Exception)
            return pd.DataFrame().to_markdown()

    @tool.get("/get_entity_id")
    def get_entity_id(input: str):
        """Search for all the entities that has the surface form as the input. For example, all the entities that are named ``Obama'', including either person, book, anything else."""
        try:
            result = requests.get(
                "https://www.wikidata.org/w/api.php",
                params={
                    "type": "item",
                    "action": "wbsearchentities",
                    "language": "en",
                    "search": input,
                    "origin": "*",
                    "format": "json",
                },
            ).text

            result = json.loads(result)["search"]
            # print(result)

            df = pd.DataFrame.from_dict(result)
            for row in df.axes[1]:
                if row != "id" and row != "label" and row != "description":
                    df.pop(row)
            return df.to_markdown()

        except Exception:
            print("Invalid option!\n", Exception)
            return pd.DataFrame().to_markdown()

    @tool.get("/get_relation_id")
    def get_relation_id(input: str):
        """Search for all the relations that has the surface form as the input. For example, all the relations that are named ``tax''."""
        try:
            result = requests.get(
                "https://www.wikidata.org/w/api.php",
                params={
                    "type": "property",
                    "action": "wbsearchentities",
                    "language": "en",
                    "search": input,
                    "origin": "*",
                    "format": "json",
                },
            ).text

            result = json.loads(result)["search"]

            df = pd.DataFrame.from_dict(result)
            for row in df.axes[1]:
                if row != "id" and row != "label" and row != "description":
                    df.pop(row)
            return df.to_markdown()

        except Exception:
            print("Invalid option!\n", Exception)
            return pd.DataFrame().to_markdown()

    @tool.get("/search_by_code")
    def search_by_code(query: str):
        """After knowing the unique id of entity or relation, perform a sparql query. E.g.,
        Select ?music\nWhere {{\nwd:Q00 wdt:P00 ?music.\n}} The entity label will be automatically retrieved.
        """
        try:
            query, basic_sel = convert_sparql_to_backend(query)

            result = getResult(query)

            for i in range(0, len(result)):
                for sel in basic_sel:
                    if sel not in result[i]:
                        continue
                    if (
                        len(result[i][sel]["value"]) < 4
                        or result[i][sel]["value"][0:4] != "http"
                    ):
                        continue
                    id = result[i][sel]["value"].split("/")[-1]

                    if type(id) == str and len(id) > 0 and id[0] == "P":
                        result[i].update(
                            convert(
                                get_property_details_with_name(
                                    result[i][sel]["value"], sel
                                )
                            )
                        )

            df = pd.DataFrame.from_dict(result)
            return df.to_markdown()
        except Exception:
            print("Invalid option!\n", Exception)
            return pd.DataFrame().to_markdown()

    return tool