aboutsummaryrefslogtreecommitdiff
path: root/gn3/db/rdf/wiki.py
blob: 88bf2e1126bc67afaafddb495fc529040839a6cf (plain)
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
270
"""Sparql queries to get metadata about WIKI and RIF metadata.

NOTE: In the CONSTRUCT queries below, we manually sort the arrays from
 the result of a CONSTRUCT.  This is because the SPARQL engine does
 not provide a guarantee that it will support an ORDER BY clause in a
 CONSTRUCT. Using ORDER BY on a solution sequence for a CONSTRUCT or
 DESCRIBE query has no direct effect because only SELECT returns a
 sequence of results.  See:
   <https://stackoverflow.com/questions/78186393>
   <https://www.w3.org/TR/rdf-sparql-query/#modOrderBy>
"""
from string import Template
from gn3.db.rdf import (
    BASE_CONTEXT,
    RDF_PREFIXES,
    query_frame_and_compact,
    update_rdf,
)


WIKI_CONTEXT = BASE_CONTEXT | {
    "foaf": "http://xmlns.com/foaf/0.1/",
    "dct": "http://purl.org/dc/terms/",
    "categories": "gnt:belongsToCategory",
    "web_url": "foaf:homepage",
    "version": "gnt:hasVersion",
    "symbol": "rdfs:label",
    "reason": "gnt:reason",
    "species": "gnt:species",
    "pubmed_ids": "dct:references",
    "email": "foaf:mbox",
    "initial": "gnt:initial",
    "comment": "rdfs:comment",
    "created": "dct:created",
    "id": "dct:identifier",
}


def __sanitize_result(result: dict) -> dict:
    """Make sure `categories` and `pubmed_ids` are always arrays"""
    if not result:
        return {}
    categories = result.get("categories")
    if isinstance(categories, str):
        result["categories"] = [categories] if categories else []
    result["categories"] = sorted(result["categories"])
    pmids = result.get("pubmed_ids")
    if isinstance(pmids, str):
        result["pubmed_ids"] = [pmids] if pmids else []
    if isinstance(pmids, int):
        result["pubmed_ids"] = [pmids]
    result["pubmed_ids"] = [
        int(pmid.split("/")[-1]) if isinstance(pmid, str) else pmid
        for pmid in result["pubmed_ids"]
    ]
    result["pubmed_ids"] = sorted(result["pubmed_ids"])
    return result


def get_wiki_entries_by_symbol(
    symbol: str, sparql_uri: str, graph: str = "<http://genenetwork.org>"
) -> dict:
    """Fetch all the Wiki entries using the symbol"""
    # This query uses a sub-query to fetch the latest comment by the
    # version id.
    query = Template(
        """
$prefix

CONSTRUCT {
    ?comment rdfs:label ?symbol;
             gnt:reason ?reason ;
             gnt:species ?species ;
             dct:references ?pmid ;
             foaf:homepage ?weburl ;
             rdfs:comment ?text ;
             foaf:mbox ?email ;
             gnt:initial ?usercode ;
             gnt:belongsToCategory ?category ;
             gnt:hasVersion ?max ;
             dct:created ?created ;
             dct:identifier ?id_ .
} FROM $graph WHERE {
    ?comment rdfs:label ?text_ ;
             gnt:symbol ?symbol ;
             rdf:type gnc:GNWikiEntry ;
             dct:identifier ?id_ ;
             dct:created ?createTime .
    FILTER ( LCASE(?symbol) = LCASE('$symbol') ) .
    {
        SELECT (MAX(?vers) AS ?max) ?id_ WHERE {
            ?comment dct:identifier ?id_ ;
                     dct:hasVersion ?vers .
        }
    }
    ?comment dct:hasVersion ?max .
    OPTIONAL { ?comment gnt:reason ?reason_ } .
    OPTIONAL {
        ?comment gnt:belongsToSpecies ?speciesId .
        ?speciesId gnt:shortName ?species .
    } .
    OPTIONAL { ?comment dct:references ?pmid_ } .
    OPTIONAL { ?comment foaf:homepage ?weburl_ } .
    OPTIONAL { ?comment gnt:initial ?usercode_ } .
    OPTIONAL { ?comment foaf:mbox ?email_ } .
    OPTIONAL { ?comment gnt:belongsToCategory ?category_ } .
    BIND (str(?createTime) AS ?created) .
    BIND (str(?text_) AS ?text) .
    BIND (STR(COALESCE(?pmid_, "")) AS ?pmid) .
    BIND (COALESCE(?reason_, "") AS ?reason) .
    BIND (STR(COALESCE(?weburl_, "")) AS ?weburl) .
    BIND (COALESCE(?usercode_, "") AS ?usercode) .
    BIND (STR(COALESCE(?email_, "")) AS ?email) .
    BIND (COALESCE(?species_, "") AS ?species) .
    BIND (COALESCE(?category_, "") AS ?category) .
}
"""
    ).substitute(
        prefix=RDF_PREFIXES,
        graph=graph,
        symbol=symbol,
    )
    results = query_frame_and_compact(query, WIKI_CONTEXT, sparql_uri)
    data = [__sanitize_result(result) for result in results.get("data", {})]
    # See note above in the doc-string
    results["data"] = sorted(data, key=lambda d: d["created"])
    if not data:
        return results
    return results


def get_comment_history(
    comment_id: int, sparql_uri: str, graph: str = "<http://genenetwork.org>"
) -> dict:
    """Get all the historical data for a given id"""
    query = Template(
        """
$prefix

CONSTRUCT {
    ?comment rdfs:label ?symbolName ;
             gnt:reason ?reason ;
             gnt:species ?species ;
             dct:references ?pmid ;
             foaf:homepage ?weburl ;
             rdfs:comment ?text ;
             foaf:mbox ?email ;
             gnt:initial ?usercode ;
             gnt:belongsToCategory ?category ;
             gnt:hasVersion ?version ;
             dct:created ?created .
} FROM $graph WHERE {
    ?comment rdf:type gnc:GNWikiEntry ;
             rdfs:label ?text_ ;
             gnt:symbol ?symbol ;
             dct:created ?createTime ;
             dct:hasVersion ?version ;
             dct:identifier $comment_id .
    OPTIONAL { ?comment gnt:reason ?reason_ } .
    OPTIONAL {
        ?comment gnt:belongsToSpecies ?speciesId .
        ?speciesId gnt:shortName ?species_ .
    } .
    OPTIONAL { ?comment dct:references ?pmid_ . } .
    OPTIONAL { ?comment foaf:homepage ?weburl_ . } .
    OPTIONAL { ?comment gnt:initial ?usercode_ . } .
    OPTIONAL { ?comment foaf:mbox ?email_ . } .
    OPTIONAL { ?comment gnt:belongsToCategory ?category_ . } .
    BIND (str(?text_) AS ?text) .
    BIND (str(?createTime) AS ?created) .
    BIND (STR(COALESCE(?pmid_, "")) AS ?pmid) .
    BIND (COALESCE(?reason_, "") AS ?reason) .
    BIND (STR(COALESCE(?weburl_, "")) AS ?weburl) .
    BIND (COALESCE(?usercode_, "") AS ?usercode) .
    BIND (STR(COALESCE(?email_, "")) AS ?email) .
    BIND (COALESCE(?species_, "") AS ?species) .
    BIND (COALESCE(?category_, "") AS ?category) .
}
"""
    ).substitute(prefix=RDF_PREFIXES, graph=graph, comment_id=comment_id)
    results = query_frame_and_compact(query, WIKI_CONTEXT, sparql_uri)
    data = [__sanitize_result(result) for result in results.get("data", {})]
    # See note above in the doc-string
    results["data"] = sorted(data, key=lambda d: d["version"], reverse=True)
    return results


def update_wiki_comment(
        insert_dict: dict,
        sparql_user: str,
        sparql_password: str,
        sparql_auth_uri: str,
        graph: str = "<http://genenetwork.org>",
) -> str:
    """Update a wiki comment by inserting a comment with the same
identifier but an updated version id.  The End form of this query
looks like:

    INSERT {
            GRAPH <http://genenetwork.org> {
            [ rdfs:label '''XXXX'''@en] rdf:type gnc:GNWikiEntry ;
                    gnt:symbol "XXXX" ;
                    foaf:mbox <XXXX> ;
                    gnt:initial "XXXX" ;
                    gnt:belongsToSpecies ?speciesId ;
                    gnt:reason "XXXX" ;
                    foaf:homepage <XXXX> ;
                    dct:references pmid:XXXX ;
                    dct:references pmid:XXXX ;
                    gnt:belongsToCategory "XXXX";
                    gnt:belongsToCategory "XXXX";
                    dct:hasVersion "123"^^xsd:integer ;
                    dct:identifier "1"^^xsd:integer ;
                    dct:created "2024-09-11 11:00"^^xsd:datetime .

            } USING <http://genenetwork.org> WHERE {
                    ?speciesId gnt:shortName "{species}" .

            }
    }
    """
    name = f"gn:wiki-{insert_dict['Id']}-{insert_dict['versionId']}"
    comment_triple = Template("""$name rdf:label '''$comment'''@en ;
rdf:type gnc:GNWikiEntry ;
gnt:symbol "$symbol" ;
dct:identifier "$comment_id"^^xsd:integer ;
dct:hasVersion "$next_version"^^xsd:integer ;
dct:created "$created"^^xsd:datetime .
""").substitute(
        comment=insert_dict["comment"],
        name=name, symbol=insert_dict['symbol'],
        comment_id=insert_dict["Id"], next_version=insert_dict["versionId"],
        created=insert_dict["createtime"])
    using = ""
    if insert_dict["email"]:
        comment_triple += f"{name} foaf:mbox <{insert_dict['email']}> .\n"
    if insert_dict["initial"]:
        comment_triple += f"{name} gnt:initial \"{insert_dict['initial']}\" .\n"
    if insert_dict["species"]:
        comment_triple += f"{name} gnt:belongsToSpecies ?speciesId .\n"
        using = Template(
            """ USING $graph WHERE { ?speciesId gnt:shortName "$species" . } """).substitute(
                graph=graph, species=insert_dict["species"]
        )
    if insert_dict["reason"]:
        comment_triple += f"{name} gnt:reason \"{insert_dict['reason']}\" .\n"
    if insert_dict["weburl"]:
        comment_triple += f"{name} foaf:homepage <{insert_dict['weburl']}> .\n"
    for pmid in insert_dict["PubMed_ID"].split():
        comment_triple += f"{name} dct:references pubmed:{pmid} .\n"
    for category in insert_dict["categories"]:
        comment_triple += f'{name} gnt:belongsToCategory "{category}".\n'

    return update_rdf(
        query=Template(
            """
$prefix

INSERT {
GRAPH $graph {
$comment_triple}
} $using
""").substitute(prefix=RDF_PREFIXES,
                graph=graph,
                comment_triple=comment_triple,
                using=using),
        sparql_user=sparql_user,
        sparql_password=sparql_password,
        sparql_auth_uri=sparql_auth_uri,
    )