Skip to content

Monadical's implementation of python bindings for libzim using the "class blend" approach - #3

Closed
pirate wants to merge 36 commits into
masterfrom
cython-blend
Closed

pirate wants to merge 36 commits into
masterfrom
cython-blend

Conversation

@pirate

@pirate pirate commented Apr 7, 2020 •

Copy link
Copy Markdown
Contributor

Continuation of our work here #2 (comment)

This PR uses the new class blend approach as discussed between @mgautierfr and @jdcaballerov .

I separated them so that the new work is visible independently, however if you'd prefer we work in a single PR, let me know and I will delete this one and push the work to the other PR.

@kelson42
kelson42 requested review from rgaudin and removed request for kelson42 April 7, 2020 06:10
@kelson42

Copy link
Copy Markdown
Contributor

We have a brand new release of libzim to be used here http://download.openzim.org/release/libzim/libzim_linux-x86_64-6.1.0.tar.gz

@mgautierfr mgautierfr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure to understand the status of this PR.
What we discuss about is to have two different wrapper for the articles but I see only one.
In fact, it seems that there is nothing related to reading a zim File even if the examples.py use a pyzim.ZimReader.

If we assume that this branch contains only things related to writing a zim :

  • Please move all this code in a submodule (write/writer/writing/...).
  • Rename Article, ZimArticle and ZimArticleWrapper to something including the fact they are used to write zim file. (If may not be necessary if you move them in a specific submodule)

Let's be sure that we understand well on what is the separation between zim::* and zim::writer::* :
They are two different libraries. They are in the same repository and compiled in the same .so but they have almost nothing in common.
They could be separated in two different repositories without a lot of change (I think that they share the blob structure and one internal small header class only). This is not plan at all, but you should keep this in mind. Especially this is almost two different bindings to create.

Comment thread pyzim/pyzim.pyx Outdated
content.encode('UTF-8'))
self.__setup(c_zim_art)
def __init__(self, bytes content):
self.c_blob = new Blob(<char *> content, len(content))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You must keep a reference to content.
If not, you may have a ZimBlob pointing to the bytes while the byte has been deleted by python's gc.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure to understand the status of this PR.

This is a WIP using the cython blend approach. Currently I am addressing issues from the first version #2 . That will help me a lot defining the API and understanding the use cases. The idea es to keep the same API and other than using the article subclasses for each task.

What we discuss about is to have two different wrapper for the articles but I see only one.

Locally it's more advanced (unpushed) . I do have a read article as follows:

cdef class ZimReadArticle(ZimArticle):
    cdef Article* c_read_article

    def __init__(self):
        ZimArticle.__init__(self)

    cdef __setup(self, Article *art):
        """Assigns an internal pointer to the wrapped C++ article object.
        
        Parameters
        ----------
        *art : zim.ZimArticle
            Pointer to a C++ article object
        """

        if self.c_read_article != NULL:
            del self.c_read_article

        # Set new internal C zim.ZimArticle article
        self.c_read_article = art

    @staticmethod
    cdef from_read_article(Article art):
        """Creates a python ZimReadArticle from a C++ zim Article article.
        
        Parameters
        ----------
        art : Article
            A C++ zim Article read with File

        Return
        ------
        article: ZimReadArticle
            A initialiazed ZimReadArticle
        """
        cdef ZimReadArticle article = ZimReadArticle()
        article.__setup(<Article *> &art)
        return article

    def is_redirect(self):
       # call is_redirect
        pass


    @property
    def can_write(self):
        return True

    def get_url(self):
        pass

    def get_title(self):
        return self.c_read_article.getTitle().decode('UTF-8')
    
    def get_mime_type(self):
        return  self.c_read_article.getMimeType().decode('UTF-8')
    
    def get_filename(self):
        return ""
  

    def get_data(self):
        return self.c_read_article.getTitle()
        c_blob = self.c_read_article.getData()
        return  ZimBlob.from_c_blob(&c_blob)

In fact, it seems that there is nothing related to reading a zim File even if the examples.py use a pyzim.ZimReader.

Unpushed WIP. The goal is to be able to use the same API regardless of the article type.

If we assume that this branch contains only things related to writing a zim :

  • Please move all this code in a submodule (write/writer/writing/...).
  • Rename Article, ZimArticle and ZimArticleWrapper to something including the fact they are used to write zim file. (If may not be necessary if you move them in a specific submodule)

Let's be sure that we understand well on what is the separation between zim::* and zim::writer::* :
They are two different libraries. They are in the same repository and compiled in the same .so but they have almost nothing in common.
They could be separated in two different repositories without a lot of change (I think that they share the blob structure and one internal small header class only). This is not plan at all, but you should keep this in mind. Especially this is almost two different bindings to create.

This is understood, but the idea I had at first was a pythonic api that doesn't need to know internal libzim details. If you agree we can totally separate reading from writing.

This will however restrict the property uses, for example

python_content = "hola hola"
read_article.content = python_content

I will have to replace the content, currently obtained from the article, with a python constructed Blob. Any ideas on this?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure of what you call the "blend" approach.
If you means that there is only one python article to wrap the two cpp articles, I disagree with this approach.

The goal is to be able to use the same API regardless of the article type.

That is the main point. We need different API because it is a different use case.

If you agree we can totally separate reading from writing

I totally agree, this is what I want. This should be handled differently and separately.

python_content = "hola hola"
read_article.content = python_content

Either I don't understand your question or you don't understand the use case :)
A "read" article (zim::Article) is read only because it is a "view" of what is inside the zim file. You cannot change it's value. So you cannot change it's value using property (or anything else).
On the opposite side a "write" article is not a article but an interface the user code have to implement. So, no property neither.

@pirate pirate Apr 14, 2020 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curious to hear more about your reasoning for keeping the reader and writer separate in python @mgautierfr. I can understand the reasoning for keeping them separate in C++, but to me it seems like most python users would intuitively try to use the same interface, e.g. a typical housekeeping process might be rewriting a few broken image URLs in a ZIM collection:

from libzim import ZimArticle

...
def rewrite_img_urls(zim: ZimArticle):
    article_body = zim.content().decode('UTF-8')
    new_article_body = re.replace(article_body, ... some regex pattern ...)
    zim.content = new_article_body

for article in load_articles(...):
    rewrite_img_urls(article)

Another approach is to make it behave like a file, you can see how the analogous project to libzim for the WARC format does it here:

Comment thread pyzim/pyzim.pyx Resolved
Comment thread pyzim/pyzim.pyx Resolved
Comment thread pyzim/pyzim.pyx Resolved
Comment thread pyzim/pyzim.pyx Resolved
Comment thread pyzim/pyzim.pyx Resolved
Comment thread pyzim/pyzim.pyx Resolved
Comment thread pyzim/pyzim.pyx Resolved
@mgautierfr

Copy link
Copy Markdown
Contributor

(I move the discussion about the global architecture here, it is better than on a comment on a line).

I'm curious to hear more about your reasoning for keeping the reader and writer separate in python @mgautierfr. I can understand the reasoning for keeping them separate in C++,

For the same reasoning for keeping them separated in C++. They are two different things not related in anyway (except having almost the same name and method names.) One is a read only object mapping binaries data. The other one is a interface to implement.
You can implement the interface using the read only object but this is a non sense to make it in the wrappper (who is a library from the python user code point of view)
Please, yet again, think as if they were two different libraries in two different repositories.

but to me it seems like most python users would intuitively try to use the same interface, e.g. a typical housekeeping process might be rewriting a few broken image URLs in a ZIM collection

No, most of the user will read only a zim file (kiwix-desktop, kiwix-serve, kiwix-android, apple/ios application, zim-dump, ...) or write a zim file (zimwriterfs, mwoffline, sotoki,...) without using a existing zim file.
The only tools that use both are zimpatch, zimdiff and zimrecreate. I honestly not sure we should use zimdiff/zimpatch and zimrecreate is mostly a dev tool used to compare zim files created with two version of the libzim's creator.

typical housekeeping process might be rewriting a few broken image URLs in a ZIM collection:

This use case is not clear to me. Are you speaking about a tools that change/update zim files to change images url in the articles ?
If yes, this is wrong : You cannot change the content of a zim file. At best you can create a new zim file with different content than the original, but you can't change the zim file itself.

@jdcaballerov
jdcaballerov requested a review from mgautierfr April 14, 2020 15:04
@jdcaballerov

jdcaballerov commented Apr 14, 2020 •

Copy link
Copy Markdown
Contributor

(I move the discussion about the global architecture here, it is better than on a comment on a line).

I'm curious to hear more about your reasoning for keeping the reader and writer separate in python @mgautierfr. I can understand the reasoning for keeping them separate in C++,

For the same reasoning for keeping them separated in C++. They are two different things not related in anyway (except having almost the same name and method names.) One is a read only object mapping binaries data. The other one is a interface to implement.
You can implement the interface using the read only object but this is a non sense to make it in the wrappper (who is a library from the python user code point of view)
Please, yet again, think as if they were two different libraries in two different repositories.

So you will never have a case where a user reads content from a zimfile and wants to write it maybe modifying URL from the python wrapper ?

but to me it seems like most python users would intuitively try to use the same interface, e.g. a typical housekeeping process might be rewriting a few broken image URLs in a ZIM collection

No, most of the user will read only a zim file (kiwix-desktop, kiwix-serve, kiwix-android, apple/ios application, zim-dump, ...) or write a zim file (zimwriterfs, mwoffline, sotoki,...) without using a existing zim file.

If this is the case we can completely separate. OR only.

The only tools that use both are zimpatch, zimdiff and zimrecreate. I honestly not sure we should use zimdiff/zimpatch and zimrecreate is mostly a dev tool used to compare zim files created with two version of the libzim's creator.

typical housekeeping process might be rewriting a few broken image URLs in a ZIM collection:

This use case is not clear to me. Are you speaking about a tools that change/update zim files to change images url in the articles ?
If yes, this is wrong : You cannot change the content of a zim file. At best you can create a new zim file with different content than the original, but you can't change the zim file itself.

So only 2 use cases are required:

  1. Read an article form a zim file, pass it as it is to a zim creator. (no modifications, of any kind)
  2. Create an article pass it to a zim creator.

1 and 2 will not be mixed, concretely: read an article from a file, modify the url, and pass it to the creator is not needed.

@mgautierfr

Copy link
Copy Markdown
Contributor

So you will never have a case where a user reads content from a zimfile and wants to write it maybe modifying URL from the python wrapper ?

zim file are read only. So you will never have a case where a user reads content from a zimfile and write it modified. From python, c++, node or whatever.

One use case, and not the common one, is a user create a new zimfile using the content of another zimfile.
In this case, and only this one, the user code may implement the "writer article" (the interface) with a custom article that use a "read article" to get the data. But the "link" between the writer article and read article is entirely in the user code and never in the wrapper.
You can have a look on zimrecreate (https://github.com/openzim/zim-tools/blob/master/src/zimrecreate.cpp#L34). The article is a zim::writer::Article and contains a zim::Article. But the link is done in the user code. It is not done in the library (and must not be done there.)

If this is the case we can completely separate. OR only.

Yes, we must separate them.
It is a OR only for your point of view (library creator). If the user want to reuse a read article as source of writer article, this is it problem and you don't have to know about it.

Read an article form a zim file, pass it as it is to a zim creator. (no modifications, of any kind)

This is a usecase out of the scope of the wrapper. If a user want to do this (with or without modification) it is his problem, not your.


This is the same as if you where creating a http library. This library allow the user code to create a client (do requests and receive responses) and also a server (handle requests and create responses). A user may want to create a proxy (handling incoming request by doing outgoing request and using the response it receives to create a responses to send). In this case, the proxy create the outgoing request using the data from the incoming request and it creates the response to send using the data from the response it has received. But all this is made on user code side. The library doesn't know about this and doesn't have to do something specific for this usecase.

@jdcaballerov
jdcaballerov force-pushed the cython-blend branch 2 times, most recently from 8691887 to b2e4643 Compare April 17, 2020 17:38
@jdcaballerov
jdcaballerov changed the base branch from dev to master April 17, 2020 17:40

@mgautierfr mgautierfr left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey !! I like what I see :)

We agree on the global architecture.
Few small thinks to change and a more difficult point on keeping a reference on the blob's content but we are good on the main idea.

On a more general point. It would be nice to have all this code (about writing) in a submodule (writer). This way we will add the reading part without conflict. Also, we don't need to call the class ZimCreatorWrapper or ZimArticle. Just Creator and Article is enough.

Comment thread libzim/examples.py Resolved
Comment thread libzim/lib.cxx Resolved
Comment thread libzim/lib.cxx Resolved
Comment thread libzim/libzim.pyx Resolved
Comment thread libzim/libzim.pyx Outdated
Comment on lines +72 to +88
@property
def mimetype(self):
return self.c_article.getMimeType().decode('UTF-8')

@property
def content(self):
blob = self.c_article.getData()
content = blob.data()[:blob.size()]
try:
return content.decode('UTF-8')
except UnicodeDecodeError:
return content

# This changes with implementation
@property
def can_write(self):
raise NotImplementedError

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be deleted. Probably a relic of the previous implementation.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am using can_write to safeguard writing incomplete articles in the creator.

Each type of article has different demands as I understand. For instance, redirect can have empty content but needs a redirect url. If someone inherits from this and doesn't implement can_write it will blow before getting to add_article that can cause issues once inside libzim.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hum. Redirect articles must return true for isRedirect. If this is the case, libzim will only use the getRedirectUrl and not getData.

I'm not sure of what you want to protect with can_write. Is can_write is equivalent to isRedirect ? Or you want to protect of something else.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I want to safeguard ZimCreator.add_article. From my point of view it's not 100% equivalent.
For instance I was requiring a normal html article to have a Url and content. Redirect articles can required to have redirect url but can have empty content.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, but I don't understand when can_write would be false or true. The user code will always return true no ?
Having a can_write doesn't protect you from articles badly implemented.

Comment thread libzim/libzim.pyx Resolved
Comment thread libzim/libzim.pyx
else:
ref_content = content

self.c_blob = new Blob(<char *> ref_content, len(ref_content))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We must keep a reference to ref_content.
Else, it may be deleted by the gc and the blob will point to nothing.

@jdcaballerov jdcaballerov Apr 17, 2020 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As far as I know when I pass a parameter to a cython function it auto creates the reference
Please take a look here:
https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html#python-objects-as-parameters-and-return-values

that's the reason I don't type it.

I also assign to ref_content so that this protects

https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html#caveats-when-using-a-python-string-in-a-c-context

If maybe I'm missing something, let me know.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The "auto reference increment" of cython works well when your function only use the parameter:

  • increment ref to pyobject
  • "wrap" pyobject into a cobject
  • pass cobject to function
  • use cobject in function
  • quit function
  • decrement ref to pyobject.

But now we are not directly using it. We are storing the cobject to use it later:

  • increment ref to (ref_content) pyobject
  • "wrap" pyobject into a cobject
  • pass cobject to (c)Blob constructor
  • store cobject in (c)Blob
  • quit constructor
  • decrement ref to (ref_content) pyobject.
  • Store the (c)blob in (py)Blob
  • quit (py)Blob.init (and so left all reference to ref_content)
  • [Later] Use Blob. <--- But ref_content doesn't exist.

I think we have to keep the ref_content in (py)Blob should be enough (so ref_content exist as long as (py)Blob exist).
And we sure that we keep a reference to (py)Blob when we pass the (c)Blob to the c world.
The best is probably to use a intermediate method in Article (it takes the (py)Blob return by the get_data and keep a ref in the article before returning it (where the blob will be converted to c in blob_cy_call_fct).
It will be good as long as libzim doesn't try to read the blob after the (py)Article has been delete.
Libzim ensure that it will keep a reference to the std::shared_ptrzim::creator::Articleas long as it need it (and so use blob). So the wrapper should be sure that we keep a reference to the (py)Article as long as thezim::creator::article` is not deleted. (But I think we are good here because the Article wrapper increment the ref on the python article).

Comment thread libzim/libzim.pyx Resolved
Comment thread libzim/libzim.pyx Resolved
@pirate pirate changed the title [WIP] Monadical's second implementation of python bindings for libzim using the "class blend" approach Monadical's implementation of python bindings for libzim using the "class blend" approach Apr 17, 2020
@mgautierfr

Copy link
Copy Markdown
Contributor

This PR is too long and too big. Especially if you add the reading part at the end.
I have :

@mgautierfr mgautierfr closed this Apr 21, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants