Mostrando postagens com marcador filetype. Mostrar todas as postagens
Mostrando postagens com marcador filetype. Mostrar todas as postagens

domingo, 28 de fevereiro de 2016

Detectando Encoding e Tipo de Arquivo com Python

Read this blog post in English.

O conteúdo desse artigo está disponível também em vídeo:

Alguns dos usuários da minha biblioteca rows me pediram funcionalidades de detecção de encoding e tipo de arquivo, então comecei a procurar alguma biblioteca Python simples e rápida que desse conta dessa tarefa. O problema: encontrei muitas bibliotecas e nenhuma delas me atraiu por alguns dos seguintes motivos:

  • Não tinha uma implementação pythônica;
  • Não estava disponível no Debian (se eu usasse o pacote rows no Debian iria quebrar);
  • Não estava sendo mantida atualmente;
  • Não funcionava corretamente.

Então percebi que não existe uma "solução de ouro" para esse problema em Python. Muitos pythonistas usam a biblioteca chardet, mas ela detecta muitas vezes com erros e é razoavelmente lenta (principalmente se você precisar fazer a detecção enquanto um usuário aguarda a resposta através de uma chamada de API via HTTP) -- veja mais detalhes sobre isso no vídeo.

But there should be one -- and preferably only one -- obvious way to do it.

Então, eu pensei: por que não usar o programa file, que já é bastante conhecido por hackers do mundo UNIX, é rápido e muito mais assertivo que todas as outras opções? Para minha surpresa não existia um bom binding de Python para a libmagic (algumas bibliotecas rodavam o comando file mas isso não era uma opção para mim pois dependia de mais um pacote do sistema e não era uma solução muito portável).

Depois de vasculhar o repositório de código do file eu encontrei um binding simples para Python, que na época não estava disponível no PyPI e não era tão pythônica como eu esperava.

A Solução

Como o código é software livre, eu criei uma issue no sistema de bugs do file para resolver o problema e o Christos Zoulas (atual mantenedor) me pediu um patch, que eu implementei, enviei e foi aceito. :-)

Fiquei muito feliz de poder colaborar com um software importante e que eu uso desde de meus primeiros passos no mundo GNU/Linux (2003? 2004?)! Durante minha busca eu descobri que o primeiro commit da versão livre do file é de 1987 (eu tinha menos de 4 meses de idade!) -- e o software ainda é mantido hoje.

Agora todos podemos usar binding oficial do file para Python: a nova biblioteca é chamada file-magic e pode ser instalada executando:

pip install file-magic

Ela disponibiliza várias funções e atributos, mas as mais importantes são bem simples e intuitivas: elas retornam uma namedtuple com os resultados da detecção. Vamos ao código!

>>> import magic

>>> # Você pode especificar diretamente um nome de arquivo
>>> filename_detected = magic.detect_from_filename('turicas.jpg')
>>> print(filename_detected)
FileMagic(mime_type='image/jpeg', encoding='binary',
          name='JPEG image data, JFIF standard 1.02, aspect ratio, density 1x1, segment length 16, progressive, precision 8, 842x842, frames 3')
>>> # E você pode acessar os atributos da `namedtuple`:
>>> print(filename_detected.mime_type)
image/jpeg

# E se você já tem o conteúdo do arquivo em memória:
>>> with open('data.html') as fobj:
...     data = fobj.read()
>>> content_detected = magic.detect_from_content(data)
>>> print(content_detected)
FileMagic(mime_type='text/html', encoding='utf-8',
          name='HTML document, UTF-8 Unicode text')
>>> print(content_detected.encoding)
utf-8

Algumas coisas ainda precisam ser melhoradas (como a documentação, rodar os testes em outras plataformas etc.), porém a biblioteca já pode ser instalada através do pip, é rápida e precisa. :-)

Espero que vocês tenham gostado! ;-)

terça-feira, 2 de fevereiro de 2016

Detecting File Type and Encoding In Python

Read this blog post in Brazilian Portuguese.

I was looking for a simple and fast Python library to implement proper file type detection and encoding detection into my rows library and found that there are many libraries available on Python Package Index which claim to do it. None of them attracted me because one of the following reasons:

  • Do not have a pythonic implementation,
  • Is not available on Debian to install as a package (it's important so people can install rows and its dependencies using pip or apt-get),
  • Is not maintained anymore, or
  • Have some missing feature.

None seemed to be the de-facto way to do it in Python (I think pythonistas do it in many ways). Many pythonistas use the chardet library but its results are wrong sometimes and it's pretty slow (specially if you need to detect during an API HTTP request, while the client is waiting).

But there should be one -- and preferably only one -- obvious way to do it.

So, I thought: why not use the file software, which is well known by all UNIX hackers, faster and most accurate than all the other solutions I know? To my surprise there was not such a good Python binding for file on PyPI (and calling it as a child process was not and option since it would add one more system-dependant package, not detectable during a pip install if missing and would also turn this solution less portable). Then, searching on its repository I found a simple Python wrapper, which was not available on PyPI at that time and was not that pythonic as I expected.

The Solution

Since it's free/libre software, I've created an issue on file bug tracker to solve the problem and Christos Zoulas (the current maintainer) asked for a patch, which I implemented, sent and was accepted. I'm pretty happy I can contribute to a software I've been using since my earlier times on GNU/Linux (2003? 2004?). During this process I found that the first commit on the free/libre file (which every GNU/Linux distribution and BSD flavor uses) implementation was done when I was less than 4 months old (!) -- and it's still maintained today.

Now you can use the official file Python binding: the new library is called file-magic and can be installed by running:

pip install file-magic

It provides some methods and attributes but the most important are pretty simple and intuitive to use: they return a namedtuple with the data you want! Let's take a tour through an example:

>>> import magic

>>> # You can pass the filename and it'll open the file for you:
>>> filename_detected = magic.detect_from_filename('turicas.jpg')
>>> print filename_detected
FileMagic(mime_type='image/jpeg', encoding='binary',
          name='JPEG image data, JFIF standard 1.02, aspect ratio, density 1x1, segment length 16, progressive, precision 8, 842x842, frames 3')
>>> # It's a `namedtuple` so you can access the attributes directly:
>>> print filename_detected.mime_type
image/jpeg

# If you have the file contents already, just use `detect_from_content`:
>>> with open('data.html') as fobj:
...     data = fobj.read()
>>> content_detected = magic.detect_from_content(data)
>>> print content_detected
FileMagic(mime_type='text/html', encoding='utf-8',
          name='HTML document, UTF-8 Unicode text')
>>> print content_detected.encoding
utf-8

There are still some things to be improved (like running tests in other platforms -- including Python 3) but it's pip-installable and usable now, so we can benefit from it. Feel free to contribute. :)

Hope you enjoy it!