Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Sunday, 24 May 2026

Capture The Flag (CTF)

Last month I participated in a CTF event organised by the RR team in Indy through this platform, CyLab Security Academy. The challenges covered several categories and were organised in 6 levels, each level only made available if you solve at least 50% of the challenges in the previous level. While some challenges I could solve in a few minutes, others took much much longer. In fact I got stuck for days in a reverse engineering one. I ended up learning a fair bit about assembly and radare2 through The Official Radare2 Book and eventually cracked the challenge. However I ran out of time and could only complete one more challenge before the deadline. All in all, great experience. I decided to go solo instead of teaming up with someone else and managed to finish in the top 10th percentile of participants (~13th percentile of people who at least solved one challenge). Nothing like jumping into a new topic to see how many things you don't know...



Friday, 7 February 2025

Bluesky posts and followers

Now that I am posting a random photo each day, I find myself looking forward to see which one will be posted. A few days ago an old photo got almost 300 likes and yesterday another old photo got also ~300 likes and over 30 reposts. 

I have also been looking at my followers in Bluesky, most of which follow me because of one list I am in.




~1.2k followers. Number of posts of each account is shown both as color map and size of the bubble (also log scale dealing with accounts with 0 & 1 posts as if they have 1.5 posts to avoid minus infinite or zero size).

Insights
~300 accounts have not posted at all yet. They may be new accounts, or they may be lurkers.
About half of the followers have less than ten posts
~80 accounts have more than 1000 posts
1 account has over 25k posts (!) and as far as I can see, it is not a bot.

PS Feb 8th: I will run this as a cron job each week. Let´s see what it looks like in one year time. 

Monday, 3 February 2025

Even more flet adventures

The automated posts of random photos started well, however I wanted to have customized messages for each photo. That means writing a short message for each one. Not difficult, but tedious. Enter Gemini and flet.

I used this prompt to create a skeleton script of what I wanted. Of course the script did not work out of the box even after a few attempts. Still, good enough to start the debugging and make something useful.

I would like to create a flet app which allows the following:

-select folder with images (jpg and png file formats). Do not use filedialog for this. Use filepicker

-for each photo, the user can create image captions which are saved in separate text files (same name as photo, just with .txt extension)


I ended up with less than 80 lines of code to create this mini tool, which made the whole task a lot easier. At some point I may give a try to one of the image captioning ai models in Huggingface. Just not sure I want my photos captioned without supervision and the posted.

PS: I downloaded the Salesforce/blip-image-captioning-base model from Huggingface and gave it a try. Considering the low effort the hit rate is not bad. Still, not something I would trust being posted without supervision. The automated text generated for the five photos above was:

a photography of a rose
a photography of a road in paris
a photography of a clay sculpture of a man with a boxing glove
a photography of a jet engine
a photography of the tokyo tower

PPS: For comparison, I got myself an API key for Google Gemini and used "Describe this photo. The resulting text must have at most 250 characters." Wow. This is not even the latest model, as I used Gemini 1.5 Flash

A single, red rose, partially open, is shown against a blurred green background.  The rose's petals are a blend of deep red and lighter pink, showcasing delicate texture.  The stem and leaves are visible.

A high-angle, long shot reveals a wide, tree-lined avenue cutting through a lush green park.  Vehicles travel along the road, leading toward a distant cityscape under a cloudy sky.  A television tower is visible on the horizon.

A small ceramic figurine, resembling a gnome, sits on a white surface. It has a large red nose, brown body, and a dark green hat.  The background is plain white.

Black and white photo of a large turbofan engine.  The engine's fan blades are prominent, filling most of the frame.  It's displayed indoors, in what appears to be an airport terminal.

Tokyo Tower, a red and white lattice tower, rises above lush green trees under a partly sunny sky.  The tower is partially obscured by the foliage.

P³S 5th Feb: Posts will now have the AI generated description as Alt text

Friday, 31 January 2025

Hello automated posting of photos in Bluesky

I posted a daily photo in IG for a long long time. This time round, I will be posting a photo each day in Bluesky using a script. Plus it is a random photo from a folder containing a few hundred of them, so it is also a surprise for me which one ges published each day. I would love to add Alt text, but that would require to run them all through some sort of AI (aka learning how to automate it). Not quite sure about that from the ethical point of view (plus who says the descriptions will be any good). On the other hand, creating descriptions for hundreds of photos is quite some work. Need to think about it.

Sunday, 19 January 2025

More flet adventures

After getting the photo collage desktop app to a reasonable state, I am looking now at using it as a web app, which turns out to be reasonably straight forward, although a few tweaks are required here and there. I got myself a small server in the cloud to do some trials and so far I managed to set up nginx as a reverse proxy, set up certificates with certbot, and set up two separate apps side by side which are launched as services.

Lots of learning. Also plenty of issues to fix so it shows well on mobiles and tablets and to manage upload and download of files. Still, plenty of fun.

Saturday, 18 January 2025

Good bye, CalendarPuzzle bot in twitter

 After a bit more than three years, today the CalendarPuzzle posted its last post in Twitter. Sorry for the followers there, I do hope that they will make their way to Bluesky and follow the bot posting there.

Saturday, 28 December 2024

Photo Collage app - progress update

Scope creep was unavoidable since basic functionality took me less than expected :-)

Very enjoyable side project!


7 minutes ago : add filter capability to layouts
2 hours ago : collage items resizing and show values to user to make alignment easier
2 hours ago : delete collage items in layouts with right click
3 hours ago : grid spacing added
2 days ago : clean up
2 days ago : clean up save_collage
2 days ago : adjust crop area saved
2 days ago : basic save capability (ImageGrab)
2 days ago : added filename text field with default time stamp, extension dropdown and save button
2 days ago : Added selection of background color
6 days ago : clean up unused code
6 days ago : interactive viewer in collage area :-)
6 days ago : interactiveviewer in separate screen area
8 days ago : Merge branch 'working_app'
8 days ago : fixed clash between src and src_base64
8 days ago : clean up, remove png thumbnails, only use base64
8 days ago : fixed base64 image thumbnails
8 days ago : clean up
8 days ago : saving layouts now works
8 days ago : remove commented out code
8 days ago : load layouts from files
8 days ago : list layouts and show them
8 days ago : able to save and load new layouts
8 days ago : able to create collage areas
9 days ago : add comments to each secion of the code to group statements related to each area
9 days ago : reorder rail, start new layout section
10 days ago : ImageFit.CONTAIN
11 days ago : set layout as start of rail
11 days ago : initial layout definition accepting photos
13 days ago : placeholder moved to assets folder
13 days ago : files can be dragged to destination
2 weeks ago : draggable photo thumbs
2 weeks ago : create photos.py for first rail action
2 weeks ago : initial page and working areas without any functionality

Saturday, 14 December 2024

Photo Collage app

One tool I would like to have is a mini app which allows me to make a photo collage. I already have a notebook which allows me to do matrix-type of collages but I don´t get to select the order of the photos or manipulate photos (zooming and moving). Instead of doing Advent of Code, this year I will (try to) build this app by myself. I am going to give flet a try and see how far I get. Wish me luck


So, a few requirements:

I want to be able to select photos from a local folder. Stretch: select photos from several folders.

I want to be able to use different layouts for the collage. Stretch: I can define new layouts within the app

I want to be able to drag and drop photos into each area of the collage

I want to be able to zoom in and out and pan the photo within each area of the collage



Update 15th Dec


I can already select Photos from several folders (just click the button several times and they will be appended to the list)
I can already drag and drop photos into certain areas


Update 20th Dec
I can select fotos from local folders. If I select photos from different folders, they are added to the list of available photos
I can define (manually in the code) different layouts and then select one and drop it to be used
I can allocate photos to each collage area dragging and dropping photos into the desired area
I can create new layouts (not yet save them though) creating separate areas of desired sizes and moving them as I wish in the collage area (thanks to Flet Tutorial - Create Image Photo Crop App)



Update 22nd Dec
Almost there, much faster than I thought.
I can pan and zoom in/out each photo separately. Just need to save the resulting photo and a few finishing touches. All in all, great experience. Plus it would work with little effort as a web app. Nice!






Sunday, 26 May 2024

Comparing LLM´s

 

Comparing LLM´s. Amazing what you can do with open source models locally.

Prompt:

I have received two photobooks by post. The package was damaged in two corners and as a result the books themselves are also slightly damaged. I have photos that can be attached. I need you to write a polite short message to customer service. It must be in German. Thanks.


Online version (https://gemini.google.com/): Output in seconds

Sehr geehrte Damen und Herren,

mit dieser Nachricht möchte ich Ihnen den Erhalt von zwei Fotobüchern mitteilen, die ich kürzlich bestellt habe. Leider war das Paket bei der Ankunft in zwei Ecken beschädigt. Infolgedessen weisen auch die Bücher selbst leichte Beschädigungen auf.

Ich habe Fotos vom beschädigten Paket und den Büchern beigefügt. Könnten Sie sich bitte mit mir in Verbindung setzen, um das weitere Vorgehen zu besprechen?

Vielen Dank im Voraus für Ihre Mühe.

Mit freundlichen Grüßen,

[Ihr Name]

Local version (vicuna-13b-v1.5-16k.Q4_K_M.gguf): Four minutes (load, sample, prompt eval and eval, ~200 tokens, no GPU, fairly old i5 with just 2 cores and 16GB of memory)

Sehr geehrte Damen und Herren,

ich habe heute zwei Fotobücher erhalten, die jedoch leider stark beschädigt sind. Der Verpackung war an zwei Ecken aufgebrochen und die Bücher selbst haben ebenfalls einige Schäden davor. Ich habe Fotos, die ich gerne anheften kann.

Ich hoffe, dass Sie in der Lage sind, mir eine Entschuldigung zukommen zu lassen und eine Lösung für das Problem zu finden.

Mit freundlichen Grüßen,

[Your Name]


Sunday, 19 May 2024

LLM´s

A few days ago I read one of the latest blog entries from Miguel Grinberg about how LLMs work and I was wondering if you can run an LLM in your own computer, even if it doesn´t have a GPU. The answer is yes (as long as you have some patience with the output) and there are some tutorials out there on how to do it. I finally followed this one from Ryan Stewart, which works straight out of the box.

I don´t have a use case in mind, other than being curious about how things work. So many new tools out there lately!

Edit 2024-05-26

for future reference https://yc.prosetech.com/running-your-very-own-local-llm-6d4db99c0611


Monday, 1 May 2023

AI Tools - coding and photos

As it was to be expected, it did not take long before my attention drifted towards a coding topic. I sometimes post here a collection of photos and I usually prepare them manually.

With this in mind, I had a short conversation with ChatGPT as per below:

Q: I know a bit of python. I would like to make a jupyter notebook that allows me to select images in my computer and make a collage with them. Can you help with this and explain your choice of libraries?

A: ... [some python code]

Q: the notebook should handle rows and columns and images in the collage should have a white margin as separation. Can you rewrite the notebook?

A: ... [some python code]

Q: images should be accepted as jpg or png

A: ... [some python code]

Q: I am writing python code. I have an image of size (x,y) and would like to resize to size (a,b) so that image is centered in new dimension. How would you do this?

A: ... [some python code]

Q: Thanks

A: You're welcome! Let me know if you have any further questions.

I still had to change the code quite a bit to make it work but it definitely helped. Strangely enough, I never say thanks to my car for taking me from one place to another but it seemed reasonable to say Thanks to ChatGPT.

So some examples generated quickly. I like it that photos are now perfectly aligned and centered and I can play a bit with the margin width.


PS: If you follow me in IG you may have noticed that a couple of pictures have not been posted yet.

Friday, 18 November 2022

Por si las moscas

Aprovechando que puedo usar la API de twitter para el bot del calendario, he creado un programita para descargarme las listas de seguidos y seguidores en twitter (muy modestas). Nunca se sabe. 

def write_file(tweepy_function, screen_name, file_name):
    #https://stackoverflow.com/questions/52450621/get-list-of-followers-and-following-for-group-of-users-tweepy
    csvFile = open(file_name+'.csv', 'w')
    csvWriter = csv.writer(csvFile)
    c = 1
    for page in tweepy.Cursor(tweepy_function, screen_name=screen_name, count=200).pages(50):
        for user in page:
            csvWriter.writerow([user.screen_name, user.id, user.url, user.location, user.followers_count, user.friends_count, user.description.encode('utf-8')])
            print(c, ',', user.name, ', @'+user.screen_name, user.url)
            c+=1
    csvFile.close()
    return None

def main():
    api = get_tweepy_api() #tweepy.API(auth)
    screen_name = "your_handle_without_@"
    write_file(api.get_followers, screen_name, 'followers')
    write_file(api.get_friends, screen_name, 'following')

Saturday, 12 November 2022

Progress report

Writing a book takes time and while it has taken me a bit longer than expected, I am making progress. So much so that I am already thinking of printing it. However this post is not about content and rather about technical issues.

I found a print on demand service, very aptly called Book on Demand which seems reasonable. Truth be told, I did not spend a lot of time doing research comparing features and prices. For what I want (printing about five books for the family) any book service will do. This one offers what I assume is the usual selection of soft cover and hardcover, paper weights, color vs B&W and a long list of other options. You can pay for many things, or do it all yourself (my case). Not quite unexpectedly, my book has a ton of photos (more on that later), and it would be nice to print them in color, except that obviously not every page has a photo, only about one third of them. I am currently at over 300 pages (A5), and that´s a lot of pages to print black text in "color", which would be too expensive. Luckily, there is an option to enter the list of pages which should be printed in color, which reduces the price significantly.

The way I saw it there were two main options:

Option A: Finish the pdf and make a note manually of which pages have photos. This would take about ten minutes, maybe fifteen minutes?

Option B: Write some code that inspects the pdf and spits out the list of pages with photos. Who knows how long this takes, for sure more than 15 minutes as there are likely many unknown unknowns, plus I have no idea about structure of pdf files.

It goes without saying that I went for Option B. Adn even writing this post took more than 15 minutes.

On to the tech details. I ended up installing PyPDF2 and following this. But for some reason my pdf has many images in all pages (I generate it from LibreOffice, no idea if that makes a difference).

Since the easy way did not work, I did it the hard one, aka the fun way, opening the pdf file as a text file (ignoring utf-8 errors and not even bothering to uncompress the pdf file first) and peeking into it until I figured out the following.

There is an object which gives some information about pages in the pdf (my pdf currently has 317 pages). I just had to figure out what those numbers followed by '0 R' were about.

1487 0 obj
<</Type/Pages
/Resources 1524 0 R
/MediaBox[ 0 0 419 595 ]
/Kids[ 1 0 R 4 0 R 7 0 R 10 0 R 13 0 R 16 0 R...
56 0 R 60 0 R 64 0 R 69 0 R 74 0 R 78 0 R 81 0 R...
122 0 R 125 0 R 128 0 R 131 0 R 135 0 R 138 0 R...
...
1045 0 R 1048 0 R 1051 0 R 1054 0 R 1057 0 R 1060 0 R...
...1120 0 R 1123 0 R 1126 0 R 1129 0 R ]
/Count 317>>
endobj
990 0 R 993 0 R 996 0 R 999 0 R 1002 0 R 1008 0 R...

Turns out that searching for "images" I found the list of my inserted images. Something like 

34 0 obj
<</Type/XObject/Subtype/Image/Width 881 /Height 644 ... /Length 122470>>
stream
JFIF
O]NV
...

And putting two and two together I figured out that the first list has the first object that goes in that page, so first page has objects 1 to 3, second page objects 4 to 6, etc. I know that the first page with an image is the 11th one (at least in this iteration of the book), which would include objects 31 to 34 and, bingo, the first image is object 34. To do another I checked the last page with a photo in my pdf (288th page), and the object range also includes the object listed for the last image. So that seems to be it, actually a lot easier than expected.

This takes less than 30 lines of code, and this remind me of the Automate the Boring Stuff with Python book, by Al Sweigart. And yes, it took me more than 15 minutes, but I am sure I will make changes to the output pdf, and if nothing else, this has been way more satisfying than doing it manually. I don´t get to code any more at work and sometimes I miss it.


Sunday, 19 December 2021

Calendar puzzle (ii)

In the end I went for the brute force approach, ie the not so elegant approach. It took me a while to write and debug the code but eventually I got there and found thousands and thousands of solutions (in fact I assume I found them all). Once I somewhat tidy the code up I will post it in github. Today I spent some time figuring out how to plot the calendar, learning about colour maps, grids, etc. As usual, python has you covered! People who have created and contributed to libraries such as numpy and matplotlib definitely deserve a lot of credit.

Since it makes no sense to publish here a daily puzzle I have created a twitter account for the Calendar, so that I can create a bot which tweets a solution every day (or if I feel even more adventurous and I have time, maybe posting a hint and then a few hours later the solution?). I read this great post from Miguel García and so far so good as I already managed to post something from a script after fumbling my way through Twitter´s Development Portal.

Not quite sure yet where to run the bot. One option would be to set up a raspberry pi, another one would be to explore pythonanywhere which I already used to host the tute app. We´ll see.

PS1: It will be in pythonanywhere, whose free tier allows to run one scheduled task per day (!), which is enough for this. It should run each day at 8am. Let´s see.

PS2: It works! :-) Code in a semi tidy state available in GitHub 

PS3 (October 2024): Bot now also available for Bluesky 





Solutions for today, who would have thought that there are so many ways to solve this puzzle?







Monday, 13 December 2021

Calendar puzzle

This year I am participating again on Advent of Code. So far, so good, let´s see how many stars I manage to get in the end. However this post is not about AoC, but about another puzzle I came across.

It´s a calendar with eight pieces that can hide months and days on table below, so the remaining cells show the date. Apparently you can find a combination for each day of the year (rotating and flipping pieces is allowed). However brute forcing won´t work. I calculated the amount of different positions and it´s a lot of combinations. Looking at the pieces below, there are 96 different ways in which you can place piece A, 98 for B, 82 for C, 154 for D, 151 for E, 80 for F, 196 for G and 154 for H (pieces with simmetries have less possible locations).

So brute forcing this problem would require to loop through each of the 98 positions possible for A, for each one then loop over whatever positions are still possible from the original 82 for B, etc, etc. 

I will give it a try but I wonder if there is a more elegant approach. Hints are welcome.








Monday, 8 November 2021

Timelines

A couple of weeks ago I uploaded to my github account a script I have been using lately to create timelines. It´s not super polished but it is good enough. I also noticed over the Fall holidays that I miss coding. I cannot wait until December starts, ie Advent of Code is around the corner...





Sunday, 26 September 2021

How it started

Nine years ago I received the message below, which would spark a spiral of learning in the coming years and eventually change my career, although I didn't know that at the time.



6.00x Course Team noreply@edx.org via mail50.us1.rsgsv.net 

Sep 26, 2012, 7:47 PM

to me

 

Dear Juan Carlos Cabrejas,

Welcome to 6.00x: Introduction to Computer Science and Programming! When the course begins on Monday (10/1), you will be joining tens of thousands of other students from around the world in MIT's newest online course. In addition to learning the basics of computer programming in Python, and the fundamentals of computation, you will get hands-on experience implementing a variety of Python programs and using powerful Python libraries.

The course website is available starting today! We invite you to visit

https://www.edx.org/courses/MITx/6.00x/2012_Fall/about

Click on the "View Courseware" link to gain access to the course syllabus, calendar and other materials. Starting on October 1, there will be new lecture videos and homework assignments posted every Monday at 10:00 AM EST. There will be two midterm exams and one final exam; you can find more information about these by visiting the course website.

Our primary communication channel will be the website’s interactive forum, where students and staff will get to contribute to an ongoing discussion of the material. The forum will go live next Monday at 10:00 AM EST. Meanwhile, you can familiarize yourself with the guidelines for the discussion forum by visiting the course webpage.


We look forward to a great semester with you!

Eric, John, Chris and the 6.00x Course Team


Is this email not displaying correctly? View it in your browser.

Unsubscribe | Privacy Policy

Copyright © 2012 edX. Some rights reserved.

edX, 11 Cambridge Center, Suite 101, Cambridge, MA 02142


Sunday, 23 May 2021

Academia Hacker


El Instituto Nacional de Ciberseguridad ha organizado la Academia Hacker, una iniciativa para fomentar el aprendizaje en ciberseguridad. Es una actividad en la que durante ocho semanas los equipos se enfrentan a cinco retos cada semana en diferentes temas, tales como criptografía, ingeniería inversa, esteganografía, programación, etc.

Después de tres semanas, la verdad es que el balance es muy positivo, porque nos ha forzado a mirar temas y herramientas que de otra manera no habríamos tocado. Aunque solo sea arañar la superficie, es divertido sentirte hacker por un rato (by the way, white hat). Algunas herramientas que hemos usado por ahora son VirtualBox, Kali Linux, Cyberchef, Wireshark, John the Ripper, radare2, gdb, IDA y una verdadera gema, el Z3 Theorem solver. Algunas ya las conocía, pero otras no.

Por ahora hemos conseguido resolver casi todos los retos, aunque supongo que cuando empiecen a subir de dificultad la cosa cambiará. Lo bueno es que al final de cada semana publican un vídeo con la forma de resolverlo. Más oportunidades para aprender (!)

----

Al final quedamos en el puesto ~75. Había 1000 equipos inscritos, y aunque luego no todos participaron, no está nada mal para un par de novatillos pasando el rato ;-)

Saturday, 8 May 2021

Mapa de españoles en Alemania (2020)

 


If you have some time, it is relatively straight forward to combine data sources and create the map above, which combines geometry and population information at the county level (Kreise) from open sources. Total population iaw Destatis is just above 180k.

Geometry: This dataset from Bundesamt für Kartographie und Geodäsie with Data licence Germany – attribution – Version 2.0

Population; Destatis - Statistisches Bundesamt with Data licence Germany – attribution – Version 2.0

Code adapted from this example with postal code areas from Dr. Juan Camilo Orduz.



As reference, same map in 2001 (note the huge difference in scale!) with total population just below 130k.





Wednesday, 7 April 2021

Online "tute"





Did it ever happen to you that you bought a book with the best of intentions and then you never find time to read it? Well, that was me with this book, which you can also read for free in Miguel Grinberg´s famous flask mega tutorial. At some point I went through several chapters but never really put together my own app, or deployed it somewhere.

For me the problem with tutorials is how to get really engaged. In terms of learning experience, there is a big difference between just following steps and actually trying to create something else by yourself (even if still mostly based on the tutorial steps). Because once it is your own persoanl project, you are automatically engaged. My CoderDojo is still paused because of COVID, but something I used to recommend to children (and parents) was to find something that really interests you and then work your way through the problems. A lot of the learning happens when trying to solve a problem.

A few weeks ago, someone at work mentioned pythonanywhere, which gives you the opportunity to deploy an app easily. I just needed an idea. And I had it over Easter. My father and my son often play tute when we are in Spain. However last time we were there was Christmas of previous year, so I had the idea to make an app to play tute. Oh, I hear you say, but there are plenty of web pages which already allow you to play and are way better than anything you can hack in a few days. Yes, but you don´t learn a lot playing with other people´s apps!

So after my very own (and short) Easter of Code, version 0.1 is up and running. We already played a game with my father this morning and it was a good laugh. Hope we do it now from time to time.

Things I have learned:

  • I didn´t really know all the rules of tute. Thanks to wikipedians!
  • I set up VS Code to debug flask apps.
  • SQLite is not great a choice when model changes, as dropping columns seems a bit of a pain when the model changes. I ended up restarting the database a couple of times.
  • Page reloads are good enough for us. Ajax or websockets would be better though, even more learning opportunities.
  • Know when to take a break. Impossible problems one day are magically solved in five minutes in the morning with a fresh head.
  • Styling matters. Thanks to my brother for advice.
Updated April 17th: Code available in GitHub