¡Ojo! Cuidado en Firebase con el forEach de los Snapshots de la Realtime Database

Firebase es un PaaS de Google con un nivel de abstracción muy alto que te permite tener un completo backend serverless. Hacía años que no lo usaba y estoy encantado con él, pero hay que andarse con ojo porque ningún entorno ni tecnología llega a ser perfecto.

La semana pasada estaba programando una cosa en Javascript usando la librería de Firebase, para un proyecto en el que he usado su Realtime Database para montar un sistema de presencia que me diga en todo momento quién está on y quién está off.

En un momento dado, detecté un problema que no entendía de dónde podía venir:

Hacía una query a la base de datos, que me devolvía unos resultados que yo procesaba. Sin embargo, el resultado era un único dato cuando en la BBDD tenía que haber más. Tras unos cuantos tests, me di cuenta de que si lo mismo lo programaba de distintos modos (que deberían comportarse igual) ¡el resultado era distinto!

snapshot.forEach(s=> array.push(s.val()));
//vs
snapshot.forEach(s=>{array.push(s.val())});

Esas dos estructuras, daban resultados distintos ¿cómo podía ser?

Tras darle unas cuantas vueltas con cara de absoluta incredulidad llegué a la clave del asunto en el último sitio que me quedaba por mirar de la documentación de Firebase:

Último ejemplo de la documentación de Firebase
https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#for-each

Se habían alineado Roma con Santiago:

  • Un desarrollador/diseñador había elegido usar un nombre habitual, dándole un comportamiento no habitual.
  • En Javascript todo lo que no sea falso/0/undefined se evalua como true.
  • La información referente a como funcionaba estaba en el último rincón de la documentación.

Todo habría sido distinto si el método se hubiese llamado cancellableForEach; o si al menos hubiesen comprobado que el valor recibido era verdadero comparándolo con el operador de igualdad estricta («=== true»); o si, ya cogiéndolo por los pelos, la ejecución del método cuando reciba algo que no sea booleano arrojase un warning…

En cualquier caso, tras un rato de frustración el problema quedó solucionado.

Valga este post tanto para recordar que hay que tener cuidado en Firebase con el forEach de los Snapshots de la Realtime Database, como para recordar la importancia de los nombres que ponemos a las cosas.

El nivel de acceso Archive en Azure

En las cuentas de Storage en Azure, disponemos de varios elementos de configuración que influyen directamente en la disponibilidad de la información que vamos a almacenar, el precio de tenerlo guardado, el de acceder a los datos y la latencia que tendremos hasta poder leer el primer byte de información. Entre esos elementos está el propio tipo de cuenta y el nivel de rendimiento, así como el tipo de replicación. Para simplificar todo y no desviarnos del objetivo de este artículo, nos centraremos en las cuentas de tipo propósito general V2 (StorageV2) con nivel de rendimiento estándar y replicación LRS (Locally-redundant storage). De este modo nos podremos centrar en el elemento que nos interesa explicar hoy: el nivel de acceso.

Nivel de acceso Azure

Seguir leyendo en CompartiMOSS.

Montar blobs de Azure en Windows

Tal y como hicimos hace unas semanas con Linux, vamos a montar blobs de Azure en Windows para poder usar un container como una unidad de almacenamiento barato.

La verdad es que con Azure CLI y usando el comando subst sería muy fácil montar algo. Sin embargo, todo buen programador ha de revisar si alguien antes que él ya se ha enfrentado al mismo problema. En este caso, así es.

La empresa Gladinet mantiene (o mantenía, ya que no parece muy actualizado y algunos conectores han dejado de funcionar) un software que te permite montar como una unidad virtual casi cualquier repositorio online que se os podáis imaginar.

La página de descargas es una locura, y sólo uno de los enlaces parece llevar a su última versión (la 4) que es la que incluye un conector a los blobs de Azure que funciona.

Una vez instalado y conectado con vuestro container, ya podréis acceder a su contenido y subir archivos como si de cualquier otra carpata de vuestro sistema se tratase.

Montar blobs de Azure en Linux

Si necesitas más espacio en un sistema, por ejemplo, para almacenar copias de seguridad, puedes montar un almacenamiento en la nube como los blobs de Azure en Linux para dotar a tu sistema de almacenamiento «infinito» a un precio muy competitivo aprovechando el Storage.

Se puede hacer con cualquiera, yo lo voy a hacer con Azure porque es con el que suelo trabajar por defecto, aunque haya trabajado con muchos otros.

Esto lo he hecho en Ubuntu 18.04 aunque debería de poderse hacer con más o menos complicaciones en cualquier versión de Linux.

  1. Actualizar repositorios
    wget https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb
    dpkg -i packages-microsoft-prod.deb
    apt-get update
    
  2. Instalar paquetes
    apt-get install blobfuse fuse -y
    
  3. Crear directorio temporal
    mkdir /mnt/resource/blobfusetmp -p
    
  4. Crear archivo de configuración
    vi ~/fuse_connection.cfg
    #Hay que poner las siguientes líneas sin comentarios y con los valores de tu cuenta, tu key y tu container
    #accountName myaccount
    #accountKey storageaccesskey
    #containerName mycontainer
    chmod 600 fuse_connection.cfg
    
    
  5. Montar en un directorio
    mkdir ~/disks
    blobfuse /root/disks --tmp-path=/mnt/resource/blobfusetmp  --config-file=/root/fuse_connection.cfg -o attr_timeout=240 -o entry_timeout=240 -o negative_timeout=120
    

Si esta última llamada la metes en un script que se llame, por ejemplo, desde rc.local te asegurarás de que la «unidad cloud» que has creado en Azure se monte con cada arranque del sistema.

Con esto habrás conseguido tener una nueva unidad montada aprovechando los blobs de Azure en Linux que, aunque sí tendrá más latencia que las unidades físicas de las que dispongas, su precio será mucho menor.

Best papers awards in Computer Science of 2018

2018 has finished with a lot of innovations. It brought a lot of awards for papers about several disciplines of Computer Science at different conferences this year. Here we have the abstract of some of them:

  • Memory-Augmented Monte Carlo Tree Search

    This paper proposes and evaluates Memory-Augmented Monte Carlo Tree Search (M-MCTS), which provides a new approach to exploit generalization in online realtime search. The key idea of M-MCTS is to incorporate MCTS with a memory structure, where each entry contains information of a particular state. This memory is used to generate an approximate value estimation by combining the estimations of similar states. We show that the memory based value approximation is better than the vanilla Monte Carlo estimation with high probability under mild conditions. We evaluate M-MCTS in the game of Go. Experimental results show that MMCTS outperforms the original MCTS with the same number of simulations.

  • Finding Syntax in Human Encephalography with Beam Search

    Recurrent neural network grammars (RNNGs) are generative models of (tree,string) pairs that rely on neural networks to evaluate derivational choices. Parsing with them using beam search yields a variety of incremental complexity metrics such as word surprisal and parser action count. When used as regressors against human electrophysiological responses to naturalistic text, they derive two amplitude effects: an early peak and a P600-like later peak. By contrast, a non-syntactic neural language model yields no reliable effects. Model comparisons attribute the early peak to syntactic composition within the RNNG. This pattern of results recommends the RNNG+beam search combination as a mechanistic model of the syntactic processing that occurs during normal human language comprehension.

  • Voice Interfaces in Everyday Life

    Voice User Interfaces (VUIs) are becoming ubiquitously available, being embedded both into everyday mobility via smartphones, and into the life of the home via ‘assistant’ devices. Yet, exactly how users of such devices practically thread that use into their everyday social interactions remains underexplored. By collecting and studying audio data from month-long deployments of the Amazon Echo in participants’ homes-informed by ethnomethodology and conversation analysis-our study documents the methodical practices of VUI users, and how that use is accomplished in the complex social life of the home. Data we present shows how the device is made accountable to and embedded into conversational settings like family dinners where various simultaneous activities are being achieved. We discuss how the VUI is finely coordinated with the sequential organisation of talk. Finally, we locate implications for the accountability of VUI interaction, request and response design, and raise conceptual challenges to the notion of designing ‘conversational’ interfaces.

  • Relevance Estimation with Multiple Information Sources on Search Engine Result Pages

    Relevance estimation is among the most important tasks in the ranking of search results because most search engines follow the Probability Ranking Principle. Current relevance estimation methodologies mainly concentrate on text matching between the query and Web documents, link analysis and user behavior models. However, users judge the relevance of search results directly from Search Engine Result Pages (SERPs), which provide valuable signals for reranking. Morden search engines aggregate heterogeneous information items (such as images, news, and hyperlinks) to a single ranking list on SERPs. The aggregated search results have different visual patterns, textual semantics and presentation structures, and a better strategy should rely on all these information sources to improve ranking performance. In this paper, we propose a novel framework named Joint Relevance Estimation model (JRE), which learns the visual patterns from screenshots of search results, explores the presentation structures from HTML source codes and also adopts the semantic information of textual contents. To evaluate the performance of the proposed model, we construct a large scale practical Search Result Relevance (SRR) dataset which consists of multiple information sources and 4-grade relevance scores of over 60,000 search results. Experimental results show that the proposed JRE model achieves better performance than state-of-the-art ranking solutions as well as the original ranking of commercial search engines.

  • An empirical study on crash recovery bugs in large-scale distributed systems

    In large-scale distributed systems, node crashes are inevitable, and can happen at any time. As such, distributed systems are usually designed to be resilient to these node crashes via various crash recovery mechanisms, such as write-ahead logging in HBase and hinted handoffs in Cassandra. However, faults in crash recovery mechanisms and their implementations can introduce intricate crash recovery bugs, and lead to severe consequences.In this paper, we present CREB, the most comprehensive study on 103 Crash REcovery Bugs from four popular open-source distributed systems, including ZooKeeper, Hadoop MapReduce, Cassandra and HBase. For all the studied bugs, we analyze their root causes, triggering conditions, bug impacts and fixing. Through this study, we obtain many interesting findings that can open up new research directions for combating crash recovery bugs.

  • Delayed Impact of Fair Machine Learning

    Fairness in machine learning has predominantly been studied in static classification settings without concern for how decisions change the underlying population over time. Conventional wisdom suggests that fairness criteria promote the long-term well-being of those groups they aim to protect.
    We study how static fairness criteria interact with temporal indicators of well-being, such as long-term improvement, stagnation, and decline in a variable of interest. We demonstrate that even in a one-step feedback model, common fairness criteria in general do not promote improvement over time, and may in fact cause harm in cases where an unconstrained objective would not.
    We completely characterize the delayed impact of three standard criteria, contrasting the regimes in which these exhibit qualitatively different behavior. In addition, we find that a natural form of measurement error broadens the regime in which fairness criteria perform favorably.
    Our results highlight the importance of measurement and temporal modeling in the evaluation of fairness criteria, suggesting a range of new challenges and trade-offs.

  • Large-Scale Analysis of Framework-Specific Exceptions in Android Apps

    Mobile apps have become ubiquitous. For app developers, it is a key priority to ensure their apps’ correctness and reliability. However, many apps still suffer from occasional to frequent crashes, weakening their competitive edge. Large-scale, deep analyses of the characteristics of real-world app crashes can provide useful insights to guide developers, or help improve testing and analysis tools. However, such studies do not exist — this paper fills this gap. Over a four-month long effort, we have collected 16,245 unique exception traces from 2,486 open-source Android apps, and observed that framework-specific exceptions account for the majority of these crashes. We then extensively investigated the 8,243 framework-specific exceptions (which took six person-months): (1) identifying their characteristics (e.g., manifestation locations, common fault categories), (2) evaluating their manifestation via state-of-the-art bug detection techniques, and (3) reviewing their fixes. Besides the insights they provide, these findings motivate and enable follow-up research on mobile apps, such as bug detection, fault localization and patch generation. In addition, to demonstrate the utility of our findings, we have optimized Stoat, a dynamic testing tool, and implemented ExLocator, an exception localization tool, for Android apps. Stoat is able to quickly uncover three previously-unknown, confirmed/fixed crashes in Gmail and Google+; ExLocator is capable of precisely locating the root causes of identified exceptions in real-world apps. Our substantial dataset is made publicly available to share with and benefit the community.

  • SentiGAN: Generating Sentimental Texts via Mixture Adversarial Networks

    Generating texts of different sentiment labels is getting more and more attention in the area of natural language generation. Recently, Generative Adversarial Net (GAN) has shown promising results in text generation. However, the texts generated by GAN usually suffer from the problems of poor quality, lack of diversity and mode collapse. In this paper, we propose a novel framework – SentiGAN, which has multiple generators and one multi-class discriminator, to address the above problems. In our framework, multiple generators are trained simultaneously, aiming at generating texts of different sentiment labels without supervision. We propose a penalty based objective in the generators to force each of them to generate diversified examples of a specific sentiment label. Moreover, the use of multiple generators and one multi-class discriminator can make each generator focus on generating its own examples of a specific sentiment label accurately. Experimental results on four datasets demonstrate that our model consistently outperforms several state-of-the-art text generation methods in the sentiment accuracy and quality of generated texts.

  • Understanding Ethereum via Graph Analysis

    Being the largest blockchain with the capability of running smart contracts, Ethereum has attracted wide attention and its market capitalization has reached 20 billion USD. Ethereum not only supports its cryptocurrency named Ether but also provides a decentralized platform to execute smart contracts in the Ethereum virtual machine. Although Ether’s price is approaching 200 USD and nearly 600K smart contracts have been deployed to Ethereum, little is known about the characteristics of its users, smart contracts, and the relationships among them. To fill in the gap, in this paper, we conduct the first systematic study on Ethereum by leveraging graph analysis to characterize three major activities on Ethereum, namely money transfer, smart contract creation, and smart contract invocation. We design a new approach to collect all transaction data, construct three graphs from the data to characterize major activities, and discover new observations and insights from these graphs. Moreover, we propose new approaches based on cross-graph analysis to address two security issues in Ethereum. The evaluation through real cases demonstrates the effectiveness of our new approaches.

  • LegoOS: A Disseminated, Distributed OS for Hardware Resource Disaggregation

    The monolithic server model where a server is the unit of deployment, operation, and failure is meeting its limits in the face of several recent hardware and application trends. To improve heterogeneity, elasticity, resource utilization, and failure handling in datacenters, we believe that datacenters should break monolithic servers into disaggregated, network-attached hardware components. Despite the promising benefits of hardware resource disaggregation, no existing OSes or software systems can properly manage it. We propose a new OS model called the splitkernel to manage disaggregated systems. Splitkernel disseminates traditional OS functionalities into loosely-coupled monitors, each of which runs on and manages a hardware component. Using the splitkernel model, we built LegoOS, a new OS designed for hardware resource disaggregation. LegoOS appears to users as a set of distributed servers. Internally, LegoOS cleanly separates processor, memory, and storage devices both at the hardware level and the OS level. We implemented LegoOS from scratch and evaluated it by emulating hardware components using commodity servers. Our evaluation results show that LegoOS’s performance is comparable to monolithic Linux servers, while largely improving resource packing and failure rate over monolithic clusters.

  • Should I Follow the Crowd? A Probabilistic Analysis of the Effectiveness of Popularity in Recommender Systems

    The use of IR methodology in the evaluation of recommender systems has become common practice in recent years. IR metrics have been found however to be strongly biased towards rewarding algorithms that recommend popular items –the same bias that state of the art recommendation algorithms display. Recent research has confirmed and measured such biases, and proposed methods to avoid them. The fundamental question remains open though whether popularity is really a bias we should avoid or not; whether it could be a useful and reliable signal in recommendation, or it may be unfairly rewarded by the experimental biases. We address this question at a formal level by identifying and modeling the conditions that can determine the answer, in terms of dependencies between key random variables, involving item rating, discovery and relevance. We find conditions that guarantee popularity to be effective or quite the opposite, and for the measured metric values to reflect a true effectiveness, or qualitatively deviate from it. We exemplify and confirm the theoretical findings with empirical results. We build a crowdsourced dataset devoid of the usual biases displayed by common publicly available data, in which we illustrate contradictions between the accuracy that would be measured in a common biased offline experimental setting, and the actual accuracy that can be measured with unbiased observations.

  • SuRF: Practical Range Query Filtering with Fast Succinct Tries

    We present the Succinct Range Filter (SuRF), a fast and compact data structure for approximate membership tests. Unlike traditional Bloom filters, SuRF supports both single-key lookups and common range queries: open-range queries, closed-range queries, and range counts. SuRF is based on a new data structure called the Fast Succinct Trie (FST) that matches the point and range query performance of state-of-the-art order-preserving indexes, while consuming only 10 bits per trie node. The false positive rates in SuRF for both point and range queries are tunable to satisfy different application needs. We evaluate SuRF in RocksDB as a replacement for its Bloom filters to reduce I/O by filtering requests before they access on-disk data structures. Our experiments on a 100 GB dataset show that replacing RocksDB’s Bloom filters with SuRFs speeds up open-seek (without upper-bound) and closed-seek (with upper-bound) queries by up to 1.5× and 5× with a modest cost on the worst-case (all-missing) point query throughput due to slightly higher false positive rate.

  • A Constant-Factor Approximation Algorithm for the Asymmetric Traveling Salesman Problem

    We give a constant-factor approximation algorithm for the asymmetric traveling salesman problem. Our approximation guarantee is analyzed with respect to the standard LP relaxation, and thus our result confirms the conjectured constant integrality gap of that relaxation.
    Our techniques build upon the constant-factor approximation algorithm for the special case of node-weighted metrics. Specifically, we give a generic reduction to structured instances that resemble but are more general than those arising from node-weighted metrics. For those instances, we then solve Local-Connectivity ATSP, a problem known to be equivalent (in terms of constant-factor approximation) to the asymmetric traveling salesman problem.

  • Authoring and Verifying Human-Robot Interactions

    As social agents, robots designed for human interaction must adhere to human social norms. How can we enable designers, engineers, and roboticists to design robot behaviors that adhere to human social norms and do not result in interaction breakdowns? In this paper, we use automated formal-verification methods to facilitate the encoding of appropriate social norms into the interaction design of social robots and the detection of breakdowns and norm violations in order to prevent them. We have developed an authoring environment that utilizes these methods to provide developers of social-robot applications with feedback at design time and evaluated the benefits of their use in reducing such breakdowns and violations in human-robot interactions. Our evaluation with application developers (N=9) shows that the use of formal-verification methods increases designers’ ability to identify and contextualize social-norm violations. We discuss the implications of our approach for the future development of tools for effective design of social-robot applications.

  • HighLife: Higher-arity Fact Harvesting

    Text-based knowledge extraction methods for populating knowledge bases have focused on binary facts: relationships between two entities. However, in advanced domains such as health, it is often crucial to consider ternary and higher-arity relations. An example is to capture which drug is used for which disease at which dosage (e.g. 2.5 mg/day) for which kinds of patients (e.g., children vs. adults). In this work, we present an approach to harvest higher-arity facts from textual sources. Our method is distantly supervised by seed facts, and uses the fact-pattern duality principle to gather fact candidates with high recall. For high precision, we devise a constraint-based reasoning method to eliminate false candidates. A major novelty is in coping with the difficulty that higher-arity facts are often expressed only partially in texts and strewn across multiple sources. For example, one sentence may refer to a drug, a disease and a group of patients, whereas another sentence talks about the drug, its dosage and the target group without mentioning the disease. Our methods cope well with such partially observed facts, at both pattern-learning and constraint-reasoning stages. Experiments with health-related documents and with news articles demonstrate the viability of our method.

If you want more, you can visit the Jeff Huang’s list.

Tecnología útil que incluya a todos

A veces, cuando nos paramos a ver el mundo, nos damos cuenta de que hay problemas que hoy en día son fáciles de resolver pero que paradógicamente siguen sin estar resueltos. Normalmente, la raiz de que esto sea así es que nadie con los conocimientos adecuados se ha enfrentado al problema. La tecnología es útil cuando resuelve problemas, pero para resolver problemas hay que saber que existen.

Top4ELA

Hace un par de semanas fui invitado por la Fundación Luzón a una especie de hackathon. En él se pretendía conseguir soluciones tecnológicas a los problemas que tienen en su día a día un colectivo con muchas dificultades. Ellos se encargaron de poner a gente con conocimientos de tecnologías dispares enfrente de los problemas que rodean a la ELA (Esclerosis Lateral Amiotrófica).

El evento fue organizado conjuntamente con Samsung España, quienes pusieron todo de su parte para que estuviésemos cómodos y centrados en el trabajo que teníamos por delante. Además nos prestaron sus últimos juguetes para que pudiésemos validar todo lo que planteásemos . Fueron de mucha utilidad todos, desde las cámaras 360, hasta su nuevo asistente virtual Bixby o sus teles con el nuevo sistema operativo Tizen.

La fundación trabaja para que la vida de los pacientes de ELA pueda ser mejor mientras se encuentra el origen de la enfermedad y esperemos que una cura.

La ELA es una enfermedad muy dura porque va destruyendo la capacidad motora de los pacientes mientras su cabeza sigue funcionando a la perfección. ¿Alguna vez habéis tenido la sensación de que vuestro cuerpo se ha dormido pero vuestro cerebro no? ¿De que os enteráis de todo lo que pasa a vuestro alrededor pero no tenéis modo de reaccionar? Imaginad que fuese así constantemente.

En las fases avanzadas de la enfermedad, los pacientes sólo pueden mover los ojos. Nada más.

La realidad de la ELA

Así, lo primero de lo que se encargó la fundación fue de ponernos en contacto con la realidad de la enfermedad. Pero esta no es sólo la de los pacientes, es también la de sus médicos, sus familias o sus cuidadores. Ejemplos de esto fueron Carlos Espada (Socio de Everis y enfermo de ELA a quien podéis ver en una charla a continuación), María Bestue (neuróloga que trabaja con pacientes de ELA), los hijos y la mujer de Francisco Luzón (el fundador de la fundación) o Angélica y Alexandra (dos de las cuidadoras de Carlos).

Los problemas de la ELA

La siguiente parte del trabajo, que gracias a la coordinación de Mario fue muy efectiva, se centro en identificar los problemas de cualquiera de estos actores que creyesemos que podríamos solucionar de un modo sencillo.

Uno de los problemas más graves de esta enfermedad es que convierte a los pacientes en grandes dependientes que necesitan hacer una inversión muy grande para vivir. Además, en la mayoría de los casos, estos dejan de poder realizar los trabajos que realizaban antes. Este es un problema muy grande debido a que dificulta el acceso a soluciones que podrían mitigar otros problemas más «pequeños». Siempre he creído que las necesidades de todos deben de cubrirse desde las administraciones públicas, aunque mientras esto se consigue es de agradecer el trabajo de fundaciones como esta.

En algunos sitios se está intentando resolver ese gran problema, como en Japón dónde han creado un bar en el que los camareros son robots controlados por gente que sufre algún tipo de parálisis.

En nuestro caso nos quedamos con 4 problemas que creíamos que podrían tener alguna solución en el corto plazo:

  1. El desconocimiento que hay de la enfermedad.
  2. La perdida de identidad de los pacientes.
  3. La dificultad de comunicación de los pacientes (haciendo sólo uso de sus ojos).
  4. La fragmentación de los datos clínicos de los pacientes.
Soluciones

Cada uno de estos problemas, y sus posibles soluciones dan para largo y tendido.

Yo trabajé en el cuarto de estos, de la mano de dos cracks de los datos que ya han hecho público su resumen y análisis: Ana y Josep; y con María Bestue que nos ayudó tremendamente a entender las implicaciones de este problema básico.

En mi caso, voy a dejar para más adelante la creación de un «proyecto tipo» con un análisis más completo del problema y la solución que planteamos, que no sólamente afecta a los pacientes de ELA sino que a cualquiera nos podría resultar de utilidad en un momento dado, como cuando me estuve pegando con Sanitas por conseguir todos mis datos.

Para acabar, como punto y seguido, os dejo con un vídeo de César de La Hora Maker, que creo que resume muy bien el fin de semana además de lograr otros objetivos.

¿Cómo conseguir que una Inteligencia Artificial coloree las fotos del abuelo?

Cuando hablamos  de Inteligencia Artificial, es fácil pensar en sistemas muy complejos y caros. Sin embargo, lo más complejo es crear un modelo para resolver una clase de problemas. Ese modelo, una vez creado, es fácil de aplicar para solucionar un problema concreto usando un poco de imaginación. Hoy veremos como usar un modelo creado por otra persona, para nuestro objetivo: colorear las fotos que tengamos en blanco y negro de nuestros abuelos.

Imagen en blanco y negro coloreada por una Inteligencia Artificial
De una postal antigua, republicada en eldiariomontanes.es

Para la creación de un modelo, hay que saber mucho del ámbito de aplicación, hay que tener una buena base de matemáticas estadísticas y hay que conocer los diferentes algoritmos e invertir un buen tiempo probando cosas distintas. Mucha gente está creando distintos modelos, ya sea para practicar, para investigar o con otros objetivos.

Algunos de estos modelos son liberados por sus creadores, como el que nos ocupa hoy:

DeOldify es un proyecto basado en Deep Learning para colorear y restaurar imágenes antiguas. Su creador (Jason Antic) lo liberó bajo licencia MIT, lo cual nos permitirá hacer casi cualquier cosa con él.

Por tanto, para conseguir nuestro objetivo de hoy, que no es ni más ni menos que colorear las fotos antiguas de nuestros abuelos que tengamos por casa, podremos hacer uso de este proyecto.

Pero ¡ojo! También podríamos usarlo para montar un servicio online de coloreado automático de imágenes antiguas a razón de euro cada una, o para colorear las imágenes captadas por una cámara de visión nocturna (de las baratas que se ven en verde y negro).

¿Qué podemos esperar de esta Inteligencia Artificial?

En mis pruebas, que podéis ver en la foto de cabecera o en el mini-hilo que parte del siguiente twit, podéis ver los resultados con algunas fotos muy distintas. Probablemente, trabajando un poco sobre el modelo para afinar algunos puntos o incluso reentrenándolo (siguiendo los pasos de Jason) con imágenes similares a sobre las cuales queremos aplicar el modelo, podríamos obtener resultados mejores aún.

¿Cómo podemos usar esta Inteligencia Artificial?

Cuando estuve haciendo mis pruebas (hace un mes aprox.), y dado que quería jugar mucho, opté por instalar todo lo necesario en mi máquina. En ese momento no es algo que habría aconsejado porque no era trivial, pero ahora parece que con unas pocas instrucciones lo puedes tener funcionando en cualquier lado. ¡Ojo! No las he probado, pero Jason dice que en su ordenador funciona ;).

git clone https://github.com/jantic/DeOldify.git DeOldify
cd DeOldify
conda env create -f environment.yml

#Then run it with this:

source activate deoldify
jupyter lab

Sin embargo hay un modo mucho más sencillo y es ejecutarlo online partiendo del notebook subido a la plataforma de Google Colab.  Ten en cuenta que es una plataforma que no está pulida del todo y que no siempre funciona bien, por lo que si no te funciona a la primera: no te desesperes.

Los pasos serían:
  1. Visita la url.
  2. Abajo, donde ves las fotos de Lincoln y demás, cambia los links de los wget por links a las fotos que quieras (tienen que estar en internet en una url accesible a cualquiera, por ejemplo puedes compartirlas mediante un enlace de Google Drive). Si lo necesitases podrías copiar más bloques para procesar más fotos: un wget y un vis.plot_transformed_image por imagen.
  3. Ejecuta la opción de menú Runtime>Run all.
  4. Cuando el script llegue a la mitad (al bloque de auth.authenticate_user…) te pedirá que sigas un link y copies un código para autenticarte con una cuenta de Google. Esto es porque necesita descargarse los pesos que se han obtenido en los entrenamientos del modelo para que la red neuronal pueda usarlos con las nuevas fotos, cuando te lo instalas en tu equipo es un paso que se puede saltar, pero con este script de Colab es necesario.
  5. Espera a que procese las imágenes.
  6. Comparte conmigo tus resultados ya sea con un comentario, un twit o lo que veas.

Con estos pasos tan sencillos, obtendrás unas imágenes antiguas que antes sólo tenías en blanco y negro, coloreadas por una Inteligencia Artificial. Cuando tu familia te pregunte como lo has hecho, puedes hablarles de Inteligencia Artificial, Deep Learning, etc. o bien puedes usar el comodín de «magia de informático».