PyKDE4: Tag and annotate files using Nepomuk

Some time has passed since I last blogged… this was not only due to lack of time but also due to motivation (writing long texts can be discouraging at times). In any case, I’d like to rectify for that. In this post, I’ll talk about Nepomuk, and in particular how to use it to tag and annotate arbitrary files using its API in PyKDE4.

Before starting, let me say that creating this tutorial was only possible thanks to the help of Sebastian Trueg, who helped me by pointing out some mistakes I was doing.

The example here is not showing the extra methods to set up a KApplication, etc.: the full code for this tutorial is available in the kdeexamples module.

Let’s start with the basics.

import sys
from PyQt4 import QtCore
from PyKDE4 import kdecore
from PyKDE4 import kdeui
from PyKDE4.nepomuk import Nepomuk

This will import all the bits needed to test our experiment. As a second step, we’ll create a dummy empty file.

dummy_file = open("dummy.txt", "w")
dummy_file.write("Some text\n")
dummy_file.close()

Or, if we have Python 2.6+ (as pointed out in the comments):

with open("dummy.txt", "w") as handle:
    handle.write("Some text\n")

Now that we have our file, it’s time to do something productive with it. But first and foremost, we have to ensure that Nepomuk is running. To do so, we make a simple check (EDIT: fixed the syntax):

result = Nepomuk.ResourceManager.instance().init()
if result != 0:
     return

Neomuk.instance().init() must return 0 if Nepomuk is properly set up. Once this is taken care of, we can manipulate the semantic information of our file. Thus, Nepomuk needs to be made aware of it: this is done by creating a resource that points to the actual file:

file_info = QtCore.QFileInfo("dummy.txt")
absolute_path = file_info.absoluteFilePath()
resource = Nepomuk.Resource(kdecore.KUrl(absolute_path)

Notice that we must use an absolute file path, or the resource will be not created properly and although no errors will happen when tagging, changes will not be made. Let’s now create a tag, which is done by simply constructing a Nepomuk.Tag instance:

tag = Nepomuk.Tag("test_example")
tag.setLabel("test_example")

In the first line we create the tag, then we associate it with a label, so that it will be displayed in applications such as Dolphin. The nice thing is that if the Tag already exists, it will be recycled: no duplicates will occur. A simple call to addTag to the resource we created earlier will now tag it:

resource.addTag(tag)

We can also add comments that can show up in Dolphin as well by using the setDescription method:

resource.setDescription("This is an example comment.")

What if we want to remove tags and descriptions? To wipe them all, we can use the remove() method of the Resource, otherwise we can strip elements by using removeProperty along with the tagUri() or descriptionUri() methods of the resource:

resource.remove() # strip everything
resource.removeProperty(resource.descriptionUri()) # remove comment
resource.removeProperty(resource.tagUri()) # remove tags

That’s it. As you can see, adding semantic information from PyKDE4 isn’t that hard. Sooner or later I’ll try my hand at queries and report back my findings.

8 thoughts on “PyKDE4: Tag and annotate files using Nepomuk

  1. Hyperion

    I would like to suggest using “with”-construct in order to open files:

    with open(“dummy.txt”, “w”):
    dummy_file.write(“Some text\n”)

    This is the pythonic way since Python 2.5 :-)

    Besides that thank you for sharing this example :-)

    I have a question too:

    result = Nepomuk.instance().init()
    if result != 0:
    return

    Is there a reason, why init() returns “0″, if everything works fine? This smells a bit like C-Style… As a more pythonc way I would consider this function to return an object if everything worked and perhaps raise an Exception with some error code and description otherwise.

  2. derek

    Thanks for this. I was about to sit down to figure this out and here it shows up.

    Derek

  3. Einar

    @Hyperion
    I’m actually using “with” a lot in my code but I assumed not everyone ran Python 2.6+. In any case I edited the post adding this possibility. And about the Nepomuk.instance().init() return type: this is what the wrapped C++ class returns, and I’m not sure if SIP (the binding generator used to wrap C++ to Python) could be used to adjust the function the way you suggest.

  4. Hyperion

    Arg… I thought “with” was included in 2.5 – but there it was only available if you import it:

    from __future__ import with_statement

    Thanks for reviewing it and thanks for your explanation of the init()-Return value.

  5. stephan

    Any ideas, why this is not working?

    $ python
    Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
    [GCC 4.4.5] on linux2
    Type “help”, “copyright”, “credits” or “license” for more information.
    >>> import sys
    >>> from PyQt4 import QtCore
    >>> from PyKDE4 import kdecore
    >>> from PyKDE4 import kdeui
    >>> from PyKDE4.nepomuk import Nepomuk
    >>> result = Nepomuk.instance().init()
    Traceback (most recent call last):
    File “”, line 1, in
    AttributeError: type object ‘Nepomuk’ has no attribute ‘instance’

    And is there an example somewhere, how I can read tags which are already attached to a file?

  6. Einar

    I noticed the problem: it’s a mistake on my part, sorry. You need to do Nepomuk.ResourceManager.instance().init().
    But for the second question, you can use a query (which I don’t know how to properly use yet) or if you know already the file you can instantiate a Resource on it (like in this tutorial), then see the tags attached to it with the tags() method.

Comments are closed.