SheevaPlug

Le coût de l'intelligence artificielle

Sunday, 09 February 2025
|
Écrit par
Grégory Soutadé

L'intelligence artificielle est un sujet récurrent ces derniers temps. Entre la génération d'image réaliste, la (plus ou moins grande) pertinence de ChatGPT, le modèle soi-disant ultra performant et à bas coût de DeepSeek, le projet de méga centre de calcul Stargate, l'échec de la première version publique de Lucie, la concurrence dans le domaine est acharnée, avec des investissements qui vont de pair.

D'ailleurs, on ne devrait pas parler d'une intelligence artificielle, mais de plusieurs. Chacune avec son modèle et sa finalité propre. C'est exactement comme pour le cerveau qui est découpé en différentes zones avec des domaines spécialisés (langage, mémoire, vision ...). Mais dans le cas du cerveau, nous avons tous les domaines en même temps !

Pourtant, quel que soit le domaine, l'intelligence artificielle n'est pas juste un modèle informatique. Avant de pouvoir être efficace, il faut réaliser toute une phase d'apprentissage à partir de données existantes. Sur ce point, le web représente une véritable aubaine, une mine d'or de données de type divers et varié. Ce n'est pas pour rien que Microsoft a racheté Github en 2018 pour la modique somme de 7,5 milliards de dollars... Il peut ainsi accéder à, désormais, 500 millions de projets ! En ce qui concerne les données multimédia (particulièrement les images), l'apprentissage est plus complexe car il faut des personnes pour "annoter" ce que contient l'image, c'est à dire spécifier dans un carré la nature d'un élément (une personne, une voiture ...). Sur ce point, les premières annotations à grande échelle ont été réalisées via les CAPTCHA afin de "prouver" que l'utilisateur n'est pas un robot. Aujourd'hui, il existe dans des pays où la mains d'œuvre est peu chère (notamment en Asie du Sud Est) des centres professionnels où les personnes sont payées pour annoter des millions d'images.

Tout cela est relativement transparent pour les utilisateurs finaux, qui se contentent d'envoyer des requêtes via le "prompt".

Dans la dernière version d'IWLA, j'ai implémenté la fusion des robots via leur identifiant ("compatible"). Quelle ne fut pas ma surprise de voir qu'en à peine 6 jours, le robot GPTBot/1.2 a téléchargé 19,5GB de contenu depuis mon site, alors que ce dernier n'évolue que très peu. Je suppose donc que GPTBot opère une ré indexation complète à chaque changement. L'utilisation de toute cette bande passante est là encore invisible pour l'utilisateur final, mais constitue, avec le stockage des données et son traitement, une consommation d'énergie très importante.

C'est pourquoi j'ai décidé de bloquer purement et simplement toutes les requêtes venant d'openai, comme je l'avais fait pour le très gourmand robot de Microsoft (bingbot).

Voici le script que j'utilise et qui est dans mon crontab. Il va analyser les logs du serveur Apache et bloquer les IP qui correspondent à un mot :

#!/bin/bash

function ban_ip()
{
    echo "Ban $1"
    nft add rule inet BAN_RU input ip saddr $1 drop
}

function ban_file()
{
    file=$1
    token=$2
    prefix_len=$3
    fields=""
    postfix=""
    case $prefix_len in
        "8")  fields="1";       postfix=".0.0.0";;
        "16") fields="1,2";     postfix=".0.0";;
        "24") fields="1,2,3";   postfix=".0";;
        "32") fields="1,2,3,4"; postfix="";;
        *) echo "Error: prefix_len must be 8, 16, 24 or 32"
           return;;
    esac
    ips=`cat $file|grep $token|cut -f2 -d' '|sort|uniq|cut -d'.' -f$fields|uniq`
    for ip in $ips ; do
        ban_ip "${ip}${postfix}/${prefix_len}"
    done
}

if [ -z "$1" -o $1 = "-h" -o $1 = "--help" ] ; then
    echo "$0 token prefix_len (8,16,24,32)"
fi

ban_file /var/log/apache2/access.log.1 $1 $2

Il se base sur le pare-feu Linux netfilter configuré comme tel :

nft create table inet BAN_RU
nft add chain inet BAN_RU input "{{ type filter hook input priority filter; }}"

La table en question est BAN_RU, déjà utilisée pour bloquer les IP venant de Russie. Le script ne supporte que des IPv4, mais je ne vois pas de connexion IPv6 de la part de robots aussi gourmands.

IWLA 0.8

Tuesday, 04 February 2025
|
Écrit par
Grégory Soutadé

Capture d'écran IWLA

Version 0.8 of IWLA (Intelligent Web Log Analyzer written in Python) is now released. While looking at the Changelog, I realized that IWLA is now 10 years old ! It's crazy to see that it's still so useful for me, I use it everyday. There is no real alternatives to it if we consider statistic analysis without cookies/embedded javascript. Only AWSTATS do the same, but it's one big unmaintainable PERL file. This is why I created my own tool which is, I think, more accurate and fine tuned. IWLA is my most actively developed personal project, but this not the only one to be old. I also developed gPass (12 years old), KissCount (15 years old), Denote (10 years old) and Dynastie (13 years old). For these projects, I only do maintenance, but I still use them a lot. For KissCount, I think it should be re wrote from scratch with a cleaner architecture. For Dynastie, there is no real alternative, any current static site generator has a dynamic/web frontend, but I think backend should be migrated to something else (more fast). Denote is quite simple and perfect for my needs.

Going back to IWLA, the changelog is :

Core

  • Awstats data updated (8.0)
  • Sanitize HTTP requests before analyze
  • Fix potential division by 0

Plugins

  • Add rule for robot : forbid "1 page and 1 hit"
  • Try to detect robots by "compatible" strings
  • Move feeds and reverse_dns plugins from post_analysis to pre_analysis
  • Move reverse DNS core management into iwla.py

HTML

  • Add domain and number of subscribers for feed parser

Config

  • Add "multimedia_re" filter to detect multimedia files by regular expression
  • Add "no_merge_feeds_parsers_list" configuration value
  • Add "robot_domains" configuration value
  • Add "ignore_url" configuration value

A demo instance (for forge.soutade.fr) is available here

TIP: Country based IP filtering

Sunday, 09 June 2024
|
Écrit par
Grégory Soutadé

Some days ago was the 80th anniversary of the d-day landings. Thousands of soldiers at the same place, the same day to flood nazi's defenses. Probability to die far away from home was huge, but they didn't escape. In the east part of Europe, URSS did the same. But, 80 years later, russia seems to have forgot what means war, nazi and dictator... Vladimir Poutine sends, for 2 years now, people to death without any concern.

This is why I first decided to redirect all people visiting my website to this thread if they're coming from an russian website. Some weeks ago, I finally decided to block every connexion that comes from russia because my website contains some computer stuff that can helps industry. I know, it's not fair for all people that just want to live normally and being informed or just want to see different things. But, even if filtering can be bypassed using a VPN, this is what I can do to help a bit Ukraine.

The script output commands for nftables (Linux kernel firewall). It reads data from one of ripe.net database (filled by AFRINIC, ARIN, APNIC, LACNIC and RIPENCC organisations) which contains allocated IP ranges for all countries. These databases are updated everyday. For an easier databases retrieval, you can look at my own project iptogeo or directly on ripe.net.

#!/usr/bin/env python3                                                                                                                                                                                             

TABLE_NAME = 'BAN_RU'
COUNTRY = 'RU'
RIPE_FILE = 'ripencc'

# Create table and add an inet filter chain                                                                                                                                                                        

print(f'nft delete table inet {TABLE_NAME}')
print(f'nft create table inet {TABLE_NAME}')
print(f'nft add chain inet {TABLE_NAME} input "{{ type filter hook input priority filter; }}"')

# ripencc|RU|ipv4|2.56.88.0|1024|20190313|allocated|caa02a36-bb09-4e4f-a834-1038f57676c1                                                                                                                           
# ripencc|RU|ipv6|2001:640::|32|19991115|allocated|ea8bf0c4-24e1-4e58-8a09-cee9da9a38f5                                                                                                                            

with open(RIPE_FILE, 'r') as fd:
   for line in fd.readlines():
        parts = line.split('|')
        if parts[1] != COUNTRY: continue
        if parts[2] == 'ipv4':
            nb_ip = int(parts[4])
            bits = (~(nb_ip - 1)) & 0xffffffff
            mask = 0
            for i in range(31,-1,-1):
                if (bits & (1 << i)) == 0: break
                mask += 1
            print(f'nft add rule inet {TABLE_NAME} input ip saddr {parts[3]}/{mask} drop')
        elif parts[2] == 'ipv6':
            mask = int(parts[4])
            print(f'nft add rule inet {TABLE_NAME} input ip6 saddr {parts[3]}/{mask} drop')
        else:
            continue

Output must be redirected to a file, then you can source it. For russia, there is about 20 000 entries.

IWLA 0.7

Sunday, 17 March 2024
|
Écrit par
Grégory Soutadé

Capture d'écran IWLA

Here is the work done for version 0.7 of IWLA (Intelligent Web Log Analyzer witten in Python) since one year and a half :

Core

  • Awstats data updated (7.9)
  • Remove detection from awstats dataset for browser
  • Don't analyze referer for non viewed hits/pages
  • Remove all trailing slashs of URL before starting analyze
  • Improve page/hit detection
  • Main key for visits is now "remote_ip" and not "remote_addr"
  • Add IP type plugin to support IPv4 and IPv6
  • --display-only switch now takes an argument (month/year), analyze is not yet necessary
  • Add --disable-display option

Plugins

  • Geo IP plugin updated (use of ip-api.com)
  • Update robot detection
  • Display visitor IP is now a filter
  • Add subdomains plugin

HTML

  • Generate HTML part in dry run mode (but don't write it to disk)
  • Set lang value in generated HTML page
  • Bugfix: flags management for feeds display
  • New way to display global statistics : with links in months names instead of "Details" button

Config

  • Add no_referrer_domains list to defaut_conf for website that defines this policy
  • Add excluded domain option
  • Set count_hit_only_visitors to False by default

A demo instance (for forge.soutade.fr) is available here

Debian stock on Cubox-i, USB issue

Sunday, 25 February 2024
|
Écrit par
Grégory Soutadé

My backup server was off for a while now. Something broken in my Sheevaplug power supply. And, if I do regular backup of my data on laptop, this is not the case for my server, so it was urgent to find a solution. I first though to buy a Cubox-M which is more powerful, but it's 250$ ! Quite expensive for this kind of stuff ! So I bought a second hand Cubox-i for for only 30€. This is a clone of my current server. I had to install everything from scratch, so I follow Solid Run instructions to prepare my SDCard with UBoot (with a new 2022 release and the ability to read ext4 partitions !).

> sudo dd if=SPL of=/dev/sdX bs=1k seek=1 conv=sync
> sudo dd if=u-boot.img of=/dev/sdX bs=1k seek=69 conv=sync

Then, I wanted to try to install a Debian distribution in stock version (with "nothing" from SolidRun) for an easier maintenance.

My SDCard partitioning looks like (partitioned with gparted) :

Cubox SDCard partitioning

On the main partition, I downloaded generic netboot console install from Debian server (netboot.tar.gz) and uncompress all files in the main partition. But I think it's better to put all in a directory named boot. Then put it in my Cubox and start to install using serial console.

> screen /dev/ttyUSB0 115200

Everything went fine, except that the image is configured for old stable release. So, I have to migrate to stable one (and don't forgot to remove installation files !).

When all was installed, I tried to put a USB key, but nothing happened... USB seems to work :

> lsusb
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

After looking for kernel logs for a while (and a bit despairs), I found the solution : Debian compile its kernel with only few drivers linked. Most of them are in modules (located in /lib/modules/kernelname). And the one missing is USB PHY driver phy-mxs-usb ! In my main server, I had it compiled because I use target imx6/7.

So, then simplest way to test is :

> sudo modprobe phy-mxs-usb

And for automatic loading at boot time :

> sudo echo phy-mxs-usb >> /etc/modules

I also added tun, dm-mod and dm-crypt.