~markjtully/onehundredscopes/medicines-lens

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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
#    Copyright (C) 2011  Mark Tully <markjtully@gmail.com>

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import sys
import urllib2
import re
import lxml.html
import json
import subprocess
from urllib import FancyURLopener
import Image
import os

# Unity imports
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gio
from gi.repository import Unity

BUS_NAME = "net.launchpad.lens.medicines"

PIL = 1
SPC = 2


class MyOpener(FancyURLopener):
    version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'


class Daemon (object):
    """ Yelp Daemon sets up the lens & searches Ubuntu Help for results
    matching query
    """

    special_searches = ["me", "chat", "meta", "au", "help", "lens"]

    def __init__(self):
        """ Sets up the lens and default scope
        The lens has 2 categories: One for SPCs (technical documents about
        the properties of a medicine aimed at healthcare professionals)
        and one for PILs (Patient information leaflets enclosed with a
        medicine, which are aimed at the person taking the medicine)  There
        is also a filter for searching different websites
        """
        self.location = self.get_location()
        if not os.path.isdir('/tmp/unity-lens-medicines'):
            os.makedirs('/tmp/unity-lens-medicines')
        self.lens = Unity.Lens.new("/net/launchpad/lens/medicines", "medicines")
        self.scope = Unity.Scope.new("/net/launchpad/lens/medicines/scope/ie")

        self.lens.props.search_hint = "Search for medicines"
        self.lens.props.visible = True
        self.lens.props.search_in_global = False
        self.scope.props.search_in_global = False

        # Set up categories. Categories for all scopes must be set up here.
        # They can not be done from within the scopes themselves
        cats = []
        cats.append(Unity.Category.new("Messages",
                                        Gio.ThemedIcon.new("/usr/lib/unity-lens-medicines/icons/Rx.svg"),
                                        Unity.CategoryRenderer.HORIZONTAL_TILE))
        cats.append(Unity.Category.new("Patient Information Leaflets",
                                        Gio.ThemedIcon.new("/usr/lib/unity-lens-medicines/icons/Rx.svg"),
                                        Unity.CategoryRenderer.HORIZONTAL_TILE))
        cats.append(Unity.Category.new("Summary of Product Characteristics",
                                        Gio.ThemedIcon.new("/usr/lib/unity-lens-medicines/icons/Rx.svg"),
                                        Unity.CategoryRenderer.HORIZONTAL_TILE))
        self.lens.props.categories = cats

        filters = []
        f = Unity.CheckOptionFilter.new("sources",
                                        "Sources",
                                        Gio.ThemedIcon.new("input-keyboard-symbolic"),
                                        False)

        f.add_option("ie", "medicines.ie", None)
        f.add_option("uk", "emc.medicines.org.uk", None)
        filters.append(f)
        self.lens.props.filters = filters

        # Listen for changes and requests
        self.scope.connect("search-changed", self.on_search_changed)
        self.scope.connect("filters-changed", self.on_filters_or_preferences_changed)
        self.scope.connect("notify::active", self.on_lens_active)
        self.scope.connect("preview-uri", self.preview_uri)
        self.scope.connect("activate-uri", self.activate_uri)

        self.preferences = Unity.PreferencesManager.get_default()
        self.preferences.connect("notify::remote-content-search", self.on_filters_or_preferences_changed)

        self.lens.add_local_scope(self.scope)
        self.lens.export()

    def get_location(self):
        """ Determine the user's location using Ubuntu's GeoIP
        lookup service
        Returns:
            The country the user's IP address is in as a 2 letter code
        """
        try:
            f = urllib2.urlopen('http://geoip.ubuntu.com/lookup')
            content = f.read()
            content = content.decode("utf-8")
            country = re.findall('''\<CountryCode\>(.*)\</CountryCode\>''', content)[0].lower()
        except:
            country = "us"
        return country

    def on_filters_or_preferences_changed(self, *_):
        """ Called when a filter is clicked.  Queue's a new search
        """
        self.scope.queue_search_changed(Unity.SearchType.DEFAULT)

    def on_lens_active(self, *_):
        """ Called when the lens is activated.  Queue's a new search
        """
        if self.scope.props.active:
            self.scope.queue_search_changed(Unity.SearchType.DEFAULT)

    def on_search_changed(self, scope, search=None, search_type=0, cancellable=None):
        """ Called when the search is changed.  Gets the search string and search
        type and passes it to update_results_model()
        Args:
          scope: a scope object
          search: the search string
          search_type: the search type (global or local)
          cancellable: cancellable object
        """
        if hasattr(search, "props"):
            search_string = search.props.search_string
        else:
            search_string = ""

        if search_type == Unity.SearchType.DEFAULT:
            results = scope.props.results_model
        else:
            results = scope.props.global_results_model

        print("Search changed to: '%s'" % search_string)
        self.update_results_model(search_string, results)
        if hasattr(search, "finished"):
            search.finished()

    def update_results_model(self, search, model):
        """ Takes the search string and determines the active filters,
        then runs a search of the relevant sources
        Args:
          search: the search string
          model: the model object that results are added to
        """
        model.clear()
        active_filters = []
        filters = self.scope.get_filter("sources")
        if not filters.props.filtering:
            if self.location == "ie":
                active_filters.append("ie")
            else:
                active_filters.append("uk")
        for source in filters.options:
            if source.props.active:
                active_filters.append(source.props.id)

        if self.preferences.props.remote_content_search != Unity.PreferencesManagerRemoteContent.ALL:
            icon_hint = Gio.ThemedIcon.new("error").to_string()
            model.append("open-privacy-settings", 
                          icon_hint, 
                          0, 
                          "text/html", 
                          ("Online search results disabled"), 
                          ("Click here to change options"), 
                          "open-privacy-settings")
        else:
            if not search == "":
                if "ie" in active_filters:
                    url = "http://www.medicines.ie/searchresults.aspx?term=%s&searchtype=AdvancedSearch" % search
                    self.append_results(url, model)
    
                if "uk" in active_filters:
                    url = "http://www.medicines.org.uk/EMC/searchresults.aspx?term=%s&searchtype=QuickSearch" % search
                    self.append_results(url, model)
    
    def append_results(self, url, model):
        """ Parses the html of the page of the url and adds results to
        the model
        Args:
          url: the url of the website's results page
          model: the model object that results are added to
        """
        icon_hint = Gio.ThemedIcon.new("text-html").to_string()
        tree = lxml.html.parse(url)
        tree.getroot().make_links_absolute()
        array = [tree.xpath("//tr[@class='GridRow_Office2007']"), tree.xpath("//tr[@class='GridAltRow_Office2007']")]
        for items in array:
            for item in items:
                title = item.xpath("td/table/tr/td/a")[0]
                drug = item.xpath("td/span")[0]
                itemtype = item.xpath("td/table/tr/td/img/@alt")[0]
                uri = item.xpath("td/table/tr/td/a/@href")[0]
                company = item.xpath("td/a")[0]
                group = 2
                if itemtype == "PIL":
                    group = 1
                    icon_hint = Gio.ThemedIcon.new("application-pdf").to_string()
                model.append(str(uri), icon_hint, group, "text/html", title.text_content().strip(), drug.text_content().strip() + "\n" + company.text_content().strip(), str(uri))

    def activate_uri(self, scope, uri):
        if re.search("PIL", uri):
            if uri.startswith("http://www.medicines.ie"):
                number = uri[33:]
                end = re.search("PIL", number)
                number = (number[:end.start() - 1])
                url = "http://www.medicines.ie/pdfviewer.aspx?isAttachment=true&documentid=%s" % number
            else:
                number = uri[41:]
                if re.search("XPIL", number):
                    end = re.search("XPIL", number)
                else:
                    end = re.search("PIL", number)
                number = (number[:end.start() - 1])
                url = "http://www.medicines.org.uk/EMC/pdfviewer.aspx?isAttachment=true&documentid=%s" % number
            command = []
            command.append("evince")
            command.append(url)
            subprocess.Popen(command)
            return Unity.ActivationResponse(handled=Unity.HandledType.HIDE_DASH, goto_uri='')
        else:
            return Unity.ActivationResponse(handled=Unity.HandledType.NOT_HANDLED)

    def preview_uri(self, scope, uri):
        """Preview request handler"""
        albumtracks = []
        model = scope.props.results_model
        iteration = model.get_first_iter()
        end_iter = model.get_last_iter()
        self.preview = None
        while iteration != end_iter:
            if model.get_value(iteration, 0) == uri:
                title = model.get_value(iteration, 4)
                description = model.get_value(iteration, 5).title() + "\n"

                if model.get_value(iteration, 2) == 1:
                    document_type = "PIL"
                    url = "http://www.medicines.ie/pdfviewer.aspx?isAttachment=true&documentid=7703"
                else:
                    document_type = "SPC"
                    url = uri
                # Get the appropriate wikipedia page for the drug in the product
                word = description.split()[0]
                if word[-1] == ",":
                    word = word[0:len(word) - 1]

                wikipage = "http://en.wikipedia.org/wiki/%s" % word.title()
                tree = lxml.html.parse(wikipage)
                tree.getroot().make_links_absolute()

                try:
                    # Get details fro the infobox on the wiki page for the preview description
                    link = tree.xpath("//table[@class='infobox']")[0]
                    
                    print(wikipage)
                    tree1 = lxml.html.parse(wikipage)
                    print(lxml.html.tostring(tree1.xpath("//body")[0])[:5000])
                    
                    infobox = link.text_content()
                    infobox = infobox.replace("\n", "\t")

                    try:
                        match1 = re.search("Bioavailability", infobox)
                        match2 = re.search("Metabolism", infobox)
                        description = description + "\n<b>Bioavailability:</b>\t" + infobox[match1.end():match2.start()]
                    except:
                        print("Bioavailability unavailable")

                    try:
                        match1 = re.search("Metabolism", infobox)
                        match2 = re.search("Half-life", infobox)
                        description = description + "\n<b>Metabolism:</b>\t" + infobox[match1.end():match2.start()]
                    except:
                        print("Metabolism unavailable")

                    try:
                        match1 = re.search("Half-life", infobox)
                        match2 = re.search("Excretion", infobox)
                        description = description + "\n<b>Half-life:</b>\t\t" + infobox[match1.end():match2.start()]
                    except:
                        print("Half Life unavailable")

                    try:
                        match1 = re.search("Excretion", infobox)
                        match2 = re.search("Identifiers", infobox)
                        description = description + "\n<b>Excretion:</b>\t\t" + infobox[match1.end():match2.start()]
                    except:
                        print("Excretion unavailable")

                    try:
                        match1 = re.search("Formula", infobox)
                        match2 = re.search("Mol", infobox)
                        description = description + "\n<b>Formula:</b>\t\t" + infobox[match1.end():match2.start()]
                    except:
                        print("Formula unavailable")

                    try:
                        match1 = re.search("Mol", infobox)
                        match2 = re.search("g/mol", infobox)
                        description = description + "\n<b>Molecular Mass:</b>" + infobox[match1.end() + 6:match1.end()+ 14] + " g/mol"
                    except:
                        print("Molecular Mass unavailable")

                    try:
                        match1 = re.search("ATC code", infobox)
                        match2 = re.search("PubChem", infobox)
                        description = description + "\n<b>ATC Code:</b>\t\t" + infobox[match1.end():match2.start()]
                    except:
                        print("ATC Code unavailable")

                    try:
                        match1 = re.search("Pregnancy cat.", infobox)
                        match2 = re.search("Legal status", infobox)
                        description = description + "\n<b>Pregnancy Category:</b>" + infobox[match1.end():match2.start()]
                    except:
                        print("Pregnancy Category unavailable")

                    try:
                        match1 = re.search(" name", infobox)
                        match2 = re.search("Clinical data", infobox)
                        description = description + "\n\n<b>Systematic (IUPAC) name:</b>\n" + infobox[match1.end():match2.start()].replace("\t", "")
                    except:
                        print("Systematic (IUPAC) name unavailable")

                    description += "\n\n<small>Chemical entity information from Wikipedia</small>"
    
                    if not os.path.exists('/tmp/unity-lens-medicines/%s.png' % word.title()):
                        # Get the preview image from Wikipedia
                        link = tree.xpath("//a[@class='image']/img/@src")[0]
                        image = link
                        # Change the image size to something better for previews
                        match = re.search(r"px-", link)
                        if match:
                            size = link[match.start()-3:match.start()]
                            if not re.search("png/", link):
                                image = link.replace(size, "500")

                        myopener = MyOpener()
                        myopener.retrieve(image, "/tmp/unity-lens-medicines/image.png")

                        try:
                            img = Image.open('/tmp/unity-lens-medicines/image.png','r')
                            img_w,img_h=img.size
                            background = Image.new('RGBA', (img_w,img_h), (255, 255, 255, 255))
                            bg_w,bg_h=background.size
                            offset=((bg_w-img_w)/2,(bg_h-img_h)/2)
                            background.paste(img,offset, img)
                            background.save('/tmp/unity-lens-medicines/%s.png' % word.title())
                        except:
                            myopener.retrieve(image, '/tmp/unity-lens-medicines/%s.png' % word.title())
                            print("No image transformation performed")
                except IndexError as e:
                    print(wikipage)
                    tree = lxml.html.parse(wikipage)
                    print(lxml.html.tostring(tree.xpath("//body")[0])[:5000])
                    print(e)
                
                # Assemble the preview
                self.preview = Unity.GenericPreview.new(title, description, None)
                self.preview.props.image_source_uri = 'file:///tmp/unity-lens-medicines/%s.png' % word.title()
                
                # Add the "View" action
                view_action = Unity.PreviewAction.new("activate_uri", "View %s" % (document_type), None)
                view_action.connect("activated", self.activate_uri)
                self.preview.add_action(view_action)
                break

            iteration = model.next(iteration)
        if self.preview is None:
            print ("Couldn't find model row for requested preview uri: '%s'", uri)
        return self.preview

if __name__ == "__main__":
    session_bus_connection = Gio.bus_get_sync(Gio.BusType.SESSION, None)
    session_bus = Gio.DBusProxy.new_sync(session_bus_connection, 0, None,
        'org.freedesktop.DBus', '/org/freedesktop/DBus',
        'org.freedesktop.DBus', None)
    result = session_bus.call_sync('RequestName',
        GLib.Variant("(su)", (BUS_NAME, 0x4)), 0, -1, None)
    result = result.unpack()[0]
    # We could try to do some automated rescue when this happens:
    if result != 1:
        print("Failed to own name %s. Bailing out." % BUS_NAME)
        print("Do you have another instance running?")
        raise SystemExit(1)
    daemon = Daemon()
    print("entering the main loop")
    GObject.MainLoop().run()