Building while flying

Learning to build the plane on the flight with Kiro

I finally testing Kiro after long time being courted by AWS to try it. I have to confess that I have a double life, my formal work in IT infrastructure and my side things developing software, last years for hobby, not for profit.

So I took an idea that was rounding my head like a year ago, about developing a new app to take advantage of Open Data already available in some cities, and give normal people the ability to read the information in a friendlier way in their phones.

Testing Kiro was starting in a serious way with Spec Driven Development as never before. I had some rudimentary concepts and slight practice from a couple of years ago, nothing formal since my daily job is not programming. I already had taken a Kiro workshop where all that was shown, but honestly I had no idea what they were actually doing.

So I started my Kiro journey configuring my environment and launching myself to the unknown.

My first surprise was the ease of use, I literally started with the description of the app I wanted to build, and the process to create specs was totally smooth.

After finishing the first version, that compilated, worked and tested automatically, I proceeded to push it to my public repo. I’m participating in Kiroween Hackathon 2026, so I know this kind of things require evidence that you are actually doing everything, I ended up learning it by matter subtraction. I created a new feature with the quick spec flow, after having the feature finished and committed I noticed that the in this case I had spec files, but they were not created for the initial app version, only trace was the chat with the agent. Therefore I had to gather the specs from the code already built and all the decision making in the process was lost, Kiro kindly reconstructed initial specs with some kind of reverse engineering from the built code. I took note for future features or fixes to keep track of my work.

Next step was trying some Kiro features, the first I wanted to test was adding a Hook to do a security check on coding before any commit. I’m not totally clear about how effective is it running, because traces show me when it’s omitted, not when it’s executed. Probably it’s running but found no issues to break to avoid the commit.

This app is being developed for iPhone, so Xcode is mandatory for actual testing. I was really impressed by the easy integration with Xcode and how Kiro wrote the code with Unit and UI tests. It’s surprising how it test the interface and it’s able to check coherence by itself. I started the project from an empty XCode one, where version was already set to 26, Kiro integrated iPhone Liquid Glass design elements by default in my app. also respected the palette I established and created it in a centralized way.

Workflow running detailed

The following feature of Kiro I wanted to apply was creating workflows, every feature follows the same pattern, create specs, create an issue in the repo from the specs, create a branch to work on specs, Kiro loops for design, plan, code, test, and then push the Pull Request. It worked charmly, however it created lots of temporary files in .kiro folder that left my branch unclean, first I forcefully committed them, but every workflow run deletes them to be recreated, so I ended up adding a step on the workflow to archive them. Kiro also reviewed those files to not include local users or paths. Since some answers come after PR is merged, I also added another step to the workflow to archive those too, so I have complete traceability of task deployed by the workflow or as consequence of it.

You can see the workflow in action here.

I integrated my repo with SonarQube, and found out that Kiro was aware of the SonarQube reviews and reacted to them after the Pull Request is pushed. Because of the detailed Unit and UI test, and general code Quality no changes were requested by SonarQube.

About MCP servers, I started adding the one from XCode, that allowed me to ask to run tests directly from Kiro, outside a workflow, later I added a Kiro Power called Cubic AI that mentioned being able to generate Wikis. Cubic AI had also an MCP server that allowed listing wikis.

Cubic AI is a very interesting AI tool (7 day trial) that allowed me to generate a Wiki and also was possible to integrate with my repo. I didn’t know its usage until I published the next Pull Request. Cubic AI did a comprehensive code review over code generated by Kiro and suggested changes. It was very interesting how Kiro became aware of that review, so I had two options: Accepting fixes recommended by Cubic or leave them as is and leaving Kiro with the task to answer them. When I say comprehensive I mean 18 issues found, it happened a day at 2:30 am, that basically I closed the issues with “It’s 2:30 am, I want to sleep” and took it per closed. In the real world and in another time, I would have reviewed them more carefully. Finally I disabled Cubic AI integration because time invested reviewing the reviews and suggested changes, however it probably be very valuable in production environments.

I had like a checklist from Hackathon documentation on features to test, next one was steering files. I had to google first what they were, and I considered how useful they could be with the project in about 80% of completion, so I asked Kiro and he told me that workflow could be slimmer, having the common rules in the steering files instead on every step, that convinced me and proceeded to generate them, updating the workflow in the process.

Then it was the time to give Kiro Web a try, I decided to give it a different task, create the onboarding screens from zero in an empty project. The first thing that I noticed was the limitation because no XCode access was possible, so Unit and UI testing was out of the question. I decided to proceed anyway to receive user interface suggestions based in my app pitch and palette. It was impressive how accurate it was to my intent. I tested it locally and added needed assets, included manually style files from my main project. Another disadvantage I found is that Liquid Glass features were not included and I had to request Kiro to change the interface to do so, I suppose it was because the project was empty and maybe Kiro is not default defined to use the last versions of languages or OS features.

When I considered it finished, I added manually the files created in the separate project to my main one and requested Kiro to integrate them in my main project UI flow. I used the specs agent and it executed the task, information was stored in spec files but no traces of Kiro actions since I didn’t use the workflow. When real Unit and UI testing did their job I have to highlight the care Kiro does over accessibility. It verifies contrast, VoiceOver possible interactions, readability of fonts. The code itself includes all the needed configuration for VoiceOver to work properly, and for my app that had a “Spooky” tone, also asked if I wanted VoiceOver to match that.

Another important review that Kiro does is about licensing, I included customized fonts and sounds in different features. Kiro not only reviewed the readability of fonts in accessibility perspective, also having proper licensing to use the fonts, reading file metadata and querying internet for author information. Kiro also asked me if sounds were recorded by me and left my answers in the specs file.

I manually updated things in the repo when using Kiro will take more time and I could save agent credits, for more complex tasks. About credit spending, I realized is related with the complexity and length of the code. When I was doing the separated project for onboarding screens, the credit consumption was lower than integrating features in the complete project. It could be a cost savings point when you are testing certain parts, that it could be convenient to do them separately and integrating once proved.

For the sake of the project I was developing, existent agents were sufficient, later I decided to create one to emulate a functionality that Cubic AI has: Creating and updating Wiki. Then I set instructions to the agent to keep the same items that Cubic considered, and using mermaid as necessary. Results are consistent, however more detail in the actual content could help to do a better evaluation. The generated new version contained a Mermaid error from Cubic previous one, but it was possible to solve it via agent prompt.

I didn’t test PBT in my project, probably it could be more effective in larger projects, mine covers very straightforward use cases, that Kiro can easily identify and configure as UI testing in XCode.

If someone is interested, this is the actual repo with code Spooky Markets.

Mine your own Facebook data using Python

Did you know that you can download a copy of all your generated data in Facebook? What if you take advantage of it an do some self research?

This series of videos recorded for PyData Global 2020 show how to request your data, put your location data in a Map, Make a word cloud with your timeline posts and create a basic sentiment analysis of your posts with training based on your emoticon use.

You can find the repo with the code mentioned in the videos HERE

Introduction

INTRODUCTION

How to get a copy of your Facebook data

REQUEST YOUR DATA FROM FACEBOOK

Put your location data in a Map

CREATE A GOOGLE MAP IN HTML WITH YOU LOCATION INFO

Create a Word Cloud with your posts data

POSTS WORD CLOUD

Sentiment analysis of your posts using emoticons as criteria to generate your training data.

SENTIMENT CLASSIFICATION OF YOUR POSTS

Datos Geo localizados con Python Folium

Visualización de Datos Geo-localizados con Python Folium, sobre Open Street Maps.  Puedes consultar el código empleado en GitHub

Este fue el último Webinar del año de Women Who Code Medellín. Para 2019 planeamos volver a los Meetup presenciales en Medellín y realizar algunas actividades en Bogotá.  Estén atentas a los eventos en Meetup, pueden seguirnos en Facebook e Instagram.

Código basado en An Introduction to Geo Data Science with Python con algunos cambios.

Análisis de Sentimientos sobre Twitter usando la librería TextBlob de Python

Por: Isabel Yepes

El análisis de sentimiento utiliza técnicas de procesamiento de lenguaje natural (NLP) para obtener conclusiones sobre textos producidos por personas y analizar en ellos rasgos de interés asociados a emociones positivas o negativas.  Se requiere un modelo que ya haya sido entrenado con textos que nos permita obtener valores cuantificables.

Hoy nos apoyaremos en la guía de Free Code Camp “Basic data analysis on Twitter with Python” para hacer Análisis de Sentimientos sobre Twitter usando la librería TextBlob de Python que dispone de modelos de NLP para diversos usos.

Puedes ver este ejemplo en GitHub

Primero debemos tener instalada la librería tweepy.

#pip3 install tweepy

Si estás usando Python 3.7 tendrás un error al tratar de usar la librería que todavía no ha sido corregido en la última versión disponible (hoy, eso puede variar en poco tiempo) para resolverlo usamos la siguiente recomendación de StackOverFlow para reemplazar una palabra reservada Async en el archivo streaming.py de la librería.

La ubicación del archivo varía según tu sistema operativo, en Mac estará ubicado en /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tweepy/streaming.py edítala con un editor de texto plano y reemplaza todas las ocurrencias de async por async_ grabas y listo. Versiones anteriores a 3.7 de Python no requieren este cambio.

Previamente debemos tener la librería NLTK instalada, las instrucciones para hacerlo puedes verlas AQUÍ, para actualizarla si ya la tienes instalada

#python3
>>>import nltk
>>>python3 nltk.download
>>>quit()

Procedemos a clonar la librería TextBlob, realizar su instalación y descargar el corpus asociado sobre nltk

#git clone https://github.com/sloria/textblob
#cd textblob
#python3 setup.py install
#python3 -m textblob.download_corpora

Si quieres saber más sobre la librería puede visitar su sitio en GitHub, tiene más herramientas de análisis para texto en Inglés, si deseamos análisis en español es necesario utilizar otra diferente https://github.com/sloria/textblob Dentro del script analizaremos los tweets cuya propiedad “lang” = “en” es decir aquellos cuyo lenguaje fue identificado como inglés. Para otras propiedades del tweet pueden consultar la documentación de Twitter.

Tendremos las claves de aplicación de Twitter en un archivo separado, de modo que no queden en el mismo código que estamos empleando y puedan reusarse en otros scripts, llamaremos a este script de claves twkeys.py

Recientemente Twitter cambió su forma de usar credenciales y ahora debe aplicarse por una cuenta de desarrollador, el proceso para aplicar puedes verlo en https://apps.twitter.com

#Credenciales del Twitter API
def consumer_key():
	#API Key
	return "Add Consumer Key here"

def consumer_secret():
	#API Secret
	return "Add Consumer Secret here"

def access_key():
	#Access Key
	return "Add Access Token here"

def access_secret():
	#Access Secret
	return "Add Access Token Secret here"

Este es el código que usamos para realizar el análisis, el resultado nos mostrará las gráficas de dispersión de dos cuentas, el promedio simple y promedio ponderado de sentimiento de ambas.

#Importar consumer API de Twitter https://github.com/tweepy/tweepy
import tweepy
#importar las credenciales de Twitter de un script
import twkeys
#Importar librería para Sentiment Analysis
from textblob import TextBlob
from time import sleep
from datetime import datetime
#Importar para graficar los Datos
#Para Jupyter notebooks quitar el comentario a la siguiente línea
#%matplotlib inline
import matplotlib.pyplot as plt
#Importar para calcular promedio ponderado
import numpy as np

#Credenciales del Twitter API que están el el script twkeys.py
consumer_key = twkeys.consumer_key()
consumer_secret = twkeys.consumer_secret()
access_key = twkeys.access_key()
access_secret = twkeys.access_secret()

def get_all_tweets(screen_name,graph_id):
    #Este método solo tiene permitido descargar máximo los ultimos 3240 tweets del usuario
    #Especificar aquí durante las pruebas un número entre 200 y 3240
    limit_number =  3240
    
    #autorizar twitter, inicializar tweepy
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth)
    
    #inicializar una list to para almacenar los Tweets descargados por tweepy
    alltweets = []    
    
    #Hacer una petición inicial por los 200 tweets más recientes (200 es el número máximo permitido)
    new_tweets = api.user_timeline(screen_name = screen_name,count=200)
    
    #guardar los tweets más recientes
    alltweets.extend(new_tweets)
    
    #guardar el ID del tweet más antiguo menos 1
    oldest = alltweets[-1].id - 1
    
    #recorrer todos los tweets en la cola hasta que no queden más
    while len(new_tweets) > 0 and len(alltweets) <= limit_number:
        print ("getting tweets before" + str(oldest))
        
        #en todas las peticiones siguientes usar el parámetro max_id para evitar duplicados
        new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)
        
        #guardar los tweets descargados
        alltweets.extend(new_tweets)
        
        #actualizar el ID del tweet más antiguo menos 1
        oldest = alltweets[-1].id - 1
        
        #informar en la consola como vamos
        print (str(len(alltweets)) + " tweets descargados hasta el momento")
    
    #Realizar el análisis de sentimiento de los tweets descargados

    #Crear las listas de polaridad polarity_list y frecuencia de polaridad numbers_list
    polarity_list = []
    numbers_list = []
    number = 1

    for tweet in alltweets:
        if tweet.lang == "en":
            try:
                analysis = TextBlob(tweet.text)
                analysis = analysis.sentiment
                #Guardar la polaridad
                polarity = analysis.polarity
                polarity_list.append(polarity)
                #Contar las veces que esa polaridad ha ocurrido
                numbers_list.append(number)
                number = number + 1
            except tweepy.TweepError as e:
                print(e.reason)
            except StopIteration:
                break

    #Crear eje cartesiano
    plt.figure(graph_id)
    axes = plt.gca()
    axes.set_ylim([-1, 3])
    plt.scatter(numbers_list, polarity_list)
    
    #Calcular el promedio de polaridad, NOTA: No es promedio ponderado
    averagePolarity = (sum(polarity_list))/(len(polarity_list))
    averagePolarity = "{0:.0f}%".format(averagePolarity * 100)
    time  = datetime.now().strftime("At: %H:%M\nOn: %m-%d-%y")

    #Calcular el promedio ponderado
    weighted_avgPolarity = np.average(polarity_list, weights=numbers_list)
    weighted_avgPolarity = "{0:.0f}%".format(weighted_avgPolarity * 100)

    #Agregar texto con el promedio de sentimiento
    plt.text(10, 1.5, "Average Sentiment:  " + str(averagePolarity) + "\n" + " Weighted Average Sentiment:  " + str(weighted_avgPolarity) + "\n" + time, fontsize=12, bbox = dict(facecolor='none', edgecolor='black', boxstyle='square, pad = 1'))

    #Título
    plt.title("Sentiment of " + screen_name + " on Twitter")
    plt.xlabel("Number of Tweets")
    plt.ylabel("Sentiment")       
    pass

if __name__ == '__main__':
    #especificar el nombre de usuario de la cuenta a la cual se descargarán los tweets
    get_all_tweets("Add_account_1",200)
    get_all_tweets("Add_account_2",300)
    #Mostrar las gráfica
    plt.show()

El siguiente video explica todo el proceso.

Women Who Code Medellín – Python, generación de datos aleatorios – Mayo 2018

Continuamos con la temática de Ciencia de Datos para los Meetups de Women Who Code Medellín, este mes tratamos generación de datos aleatorios usando la librería Numpy de Python.

Reglas del juego que se presenta como ejemplo para ser resuelto simulando datos aleatorios para resolver la pregunta ¿Cuál es la probabilidad de Ganar este juego?

REGLAS

  • Se usa un dado para jugar, por lo cual los valores son de 1 a 6
  • Si tiramos 3 o menos devolvemos 1 peso al juego
  • Si tiramos más de 3 y hasta 5 nos dan 1 peso
  • Si tiramos 6, entonces tiramos de nuevo el dado y nos dan tantos pesos como el dado lo indique.
  • Jugamos con monedas, de modo que no hay valores de pesos negativos
  • El turno del jugador consiste en tirar el dado 100 veces
  • Se gana el juego si se obtiene más de 50 pesos al final del turno

Aquí el código que usamos en la presentación.

import numpy as np
import matplotlib.pyplot as plt
#Iniciar la semilla para garantizar que los datos serán iguales cada que se corra el algoritmo
np.random.seed(204)
todos_turnos = []
#Definir cuántas veces se corre la simulación
muestras = 600
for x in range(muestras) :
     #Comenzar el turno sin monedas
     monedas = 0
     turno_aleatorio = [0]
     for x in range(100) :
         dado = np.random.randint(1,7)
         if dado <= 3 :
              monedas = max(0,monedas - 1)
         elif dado < 6 :
               monedas = monedas + 1
         else :
               monedas = monedas + np.random.randint(1,7)
         #Registrar cuantas monedas tengo al final de cada tirada
         turno_aleatorio.append(monedas)
      #Guardar los resultados del turno
      todos_turnos.append(turno_aleatorio)

#Formatear el arreglo como numpy array 
np_todos_turnos = np.array(todos_turnos) 

#Trasponer filas por columnas para adaptar a la gráfica 
np_todos_turnos_t = np.transpose(np_todos_turnos) 

#Sacar la última fila - resultado final de todos los turnos 
ultimos = np_todos_turnos_t[-1,:] 

#Calcular probabilidad de ganar contando los valores del vector
#mayores o iguales a 50 y dividiendo por el número de turnos 
print('La probabilidad de ganar el juego es de ' + str(round(100*(ultimos >= 50).sum()/muestras,2)) + '%')

#Preparar la Gráfica del desarrollo de todos los turnos
plt.figure(200)
plt.xlabel('Cantidad lanzamientos del dado')
plt.ylabel('Monedas')
plt.title('Desarrollo de '+ str(muestras)+ ' turnos')
plt.plot(np_todos_turnos_t)

#Preparar la Gráfica de distribución de los turnos
plt.figure(300)
plt.xlabel('Total de monedas al final del turno')
plt.ylabel('Cantidad de turnos en el rango del total')
plt.title('Histograma para '+ str(muestras)+ ' turnos')
plt.hist(ultimos)

#Mostrar las gráficas
plt.show()