J’aime bien faire un peu de Python de temps en temps et il m’arrive parfois de vouloir jouer un son dans mes scripts pour signaler qu’un traitement est fini ou tout simplement mettre un peu de fun. Jusqu’à présent j’utilisais des libs comme Pygame, Playsound ou encore Pydub mais ces trucs-là ne sont pas forcément bien supportés par tous les OS, ou nécessitent des dépendances comme FFMpeg.
Toutefois, une lib baptisée Nava vient de faire son apparition et c’est la simplicité même. Elle fonctionne sur tous les OS (Linux, macOS, Windows), et n’utilise aucune dépendance ou logiciel tiers. Vous pouvez lui faire lire du WAV et du MP3 et la lecture se lance immédiatement.
Pour l’installer, rien de plus simple :
pip install nava
Et ensuite, il suffit de l’appeler dans votre code et de lui indiquer le morceau à jouer.
from nava import play
play("son.mp3")
Vous pouvez même lancer une lecture en asynchrone pour ne pas bloquer votre script. Dans l’exemple ci-dessous, on lance un time sleep qui peut donc couper la lecture du son au bout de 4 secondes et qui comme vous le voyez, n’est pas bloqué puisque nava est lancé en mode asynchrone avec le paramètre async_mode=True :
import time
from nava import play, stop
sound_id = play("son.wav", async_mode=True)
time.sleep(4)
stop(sound_id)
Voilà, j’espère que ça vous sera utile 🙂
Cet article a été réalisé en collaboration avec Bitdefender
Enceintes, ampoules, routeurs et même lave-linges, les objets connectés font désormais partie de notre quotidien. Grands collecteurs de données, ces appareils apprennent de vos habitudes de vie. À ce titre, ils méritent d’être sécurisés. On vous explique comment mieux protéger votre vie privée.
Cet article a été réalisé en collaboration avec Bitdefender
Il s’agit d’un contenu créé par des rédacteurs indépendants au sein de l’entité Humanoid xp. L’équipe éditoriale de Numerama n’a pas participé à sa création. Nous nous engageons auprès de nos lecteurs pour que ces contenus soient intéressants, qualitatifs et correspondent à leurs intérêts.
On n’a pas tous la chance d’être suffisamment en souffrance dans nos vies pour aimer faire de la CSS. Sauf que voilà, à un moment, y’en a forcément besoin. Surtout quand on veut mettre en place des éléments d’interfaces sympas et compatibles avec tous les navigateurs.
Que ce soit en CSS pure ou en Tailwind, sachez que vous trouverez forcement votre bonheur sur Uiverse (jeu de moooots), un site qui regroupe des milliers d’éléments d’interface que vous n’aurez plus qu’à copier coller, et éventuellement modifier un peu, avant de les mettre sur votre site web.
On y retrouve donc des boutons, des checkbox, des champs de saisie, des boutons radio, des éléments de formulaires, des animations de chargement et j’en passe. Et le plus beau là-dedans, c’est que tout ça est filtrable / triable par type de techno (CSS / Tailwind) mais également par thème ou nombre de téléchargements…etc.
Une fois que vous cliquez sur un élément UI qui vous intéresse, vous pouvez alors récupérer son code, la mettre en favoris pour plus tard ou carrément le balancer dans un de vos projets Figma.
Elle n’est pas belle la vie ?
Bref, si vous cherchez de quoi agrémenter vos interfaces gratuitement, ça se passe par ici.
Si vous codez en Python autour d’API de LLM comme celle d’OpenAI, d’Anthropic ou encore de Huggingface…etc., je vous présente LiteLLM qui risque de vous faire gagner pas mal de temps.
Il s’agit d’une lib Python capable d’interagir avec tout un tas d’API en utilisant le format de celle d’OpenAI. Elle fournit une interface simple et uniformisée pour appeler ces modèles , ce qui va vous faciliter leur utilisation pour des choses comme de la génération de texte, de la traduction ou encore du chat…
Pour l’installer, rien de plus simple :
pip install litellm
Ensuite, y’a plus qu’à créer un objet LiteLLM dans votre code, en lui fournissant l’ID et le nom du modèle à utiliser. Par exemple pour vous connecter à OpenAI, le code sera le suivant :
from litellm import completion
import os
## set ENV variables
os.environ["OPENAI_API_KEY"] = "your-api-key"
response = completion(
model="gpt-3.5-turbo",
messages=[{ "content": "Hello, how are you?","role": "user"}]
)
Pour Claude 2, ça sera ça :
from litellm import completion
import os
## set ENV variables
os.environ["ANTHROPIC_API_KEY"] = "your-api-key"
response = completion(
model="claude-2",
messages=[{ "content": "Hello, how are you?","role": "user"}]
)
Pour utiliser Ollama, ça donnerait également ça :
from litellm import completion
response = completion(
model="ollama/llama2",
messages = [{ "content": "Hello, how are you?","role": "user"}],
api_base="http://localhost:11434"
)
Donc pas grand-chose qui change.
Vous l’aurez donc compris, LiteLLM permet de pondre un seul et unique code, mais pour discuter avec tous les fournisseurs d’IA du moment (et les logiciels libres existants)
Y’a la possibilité d’avoir du stream sur les réponses (c’est à dire, le texte qui s’affiche au fur et à mesure), de la gestion des exceptions, du log, sans oublier du calcul de coût et l’usage que vous pouvez avoir de ces API afin de ne pas éclater votre compte en banque.
LiteLLM intègre également un proxy OpenAI pour rediriger vos requêtes vers le modèle de votre choix. Pour l’installer :
pip install 'litellm[proxy]'
Lancez ensuite le proxy avec le modèle de votre choix :
litellm --model huggingface/bigcode/starcoder
Et lui passer vos requêtes dans le code python directement :
import openai # openai v1.0.0+
client = openai.OpenAI(api_key="anything",base_url="http://0.0.0.0:8000") # set proxy to base_url
# request sent to model set on litellm proxy, `litellm --model`
response = client.chat.completions.create(model="gpt-3.5-turbo", messages = [
{
"role": "user",
"content": "this is a test request, write a short poem"
}
])
print(response)
Si LiteLLM vous intéresse, vous trouverez toutes les infos sur la page Github ainsi que les endpoints ici.
Si vous codez vous-même votre site web et que vous avez envie d’ajouter un peu de fiesta, de bonne humeur et de célébration à celui-ci, j’ai la lib qu’il vous faut.
Cela s’appelle Canvas Confetti et ça permet d’ajouter en animation de confetti, d’émoji ou de neige à vos pages web.
Pour l’installer, rien de plus simple:
npm install canvas-confetti
Importez ensuite la bibliothèque Canvas Confetti dans votre fichier JavaScript où vous souhaitez utiliser l’animation du confetti comme ceci :
import confetti from 'canvas-confetti';
Pour lancer l’animation du confetti, appelez la fonction confetti()
sans paramètres ou avec des options personnalisées. Voici un exemple de lancement de l’animation par défaut :
confetti();
Et voici un exemple de lancement de l’animation avec des options personnalisées :
confetti({
particleCount: 150, // Nombre de confetti à lancer
spread: 180, // Angle maximal de dispersion des confettis
startVelocity: 30, // Vitesse initiale des confettis
origin: {
x: Math.random(), // Position initiale aléatoire des confettis sur l'axe horizontal
y: Math.random() - 0.2 // Position initiale légèrement plus élevée sur l'axe vertical
},
colors: ['#ff0000', '#00ff00', '#0000ff'], // Couleurs des confettis
shapes: ['square', 'circle', 'star'], // Formes des confettis
scalar: 2 // Taille des confettis
});
Pour réinitialiser l’animation du confetti et effacer tous les confettis en cours d’animation, utilisez la méthode confetti.reset()
:
confetti.reset();
Si vous souhaitez limiter l’espace sur votre page où les confettis apparaissent, vous pouvez utiliser un canvas personnalisé. Pour cela, créez un élément <canvas>
dans votre HTML et appelez la fonction confetti.create()
en lui passant l’élément <canvas>
et des options globales facultatives :
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const myConfetti = confetti.create(canvas, { // Options globales facultatives
resize: true, // Permet de redimensionner le canvas en fonction de la fenêtre
useWorker: true // Utilise un web worker pour le rendu du confetti
});
myConfetti({ // Options personnalisées
particleCount: 100,
spread: 160
// Autres options personnalisées
});
Enfin, si vous souhaitez créer des confettis personnalisés à partir d’une forme SVG ou d’un texte, utilisez les méthodes confetti.shapeFromPath
et confetti.shapeFromText
:
const pathShape = confetti.shapeFromPath({ path: 'M0 10 L5 0 L10 10z' }); // Forme SVG
const textShape = confetti.shapeFromText({ text: '🐈', scalar: 2 }); // Texte personnalisé
confetti({
shapes: [pathShape, textShape],
scalar: 2
});
Le mieux reste d’aller faire un tour sur la page de démo qui comporte également des exemples d’intégration.
Vous le savez, je suis un grand amateur et un grand défenseur des logiciels libres et Open Source. Et je n’ai pas peur de le dire, GitHub est l’un de mes sites préférés.
On y trouve des pépites comme des scripts incroyables, des outils géniaux et j’adore ça ! Mais ce n’est pas forcément toujours simple de suivre tout ce qui se passe dans cet univers.
Enfin, ça, c’était avant parce qu’il existe un site génial qui s’appelle OSS Insight et qui offre des informations très détaillées et des tendances sur le monde de l’open source en analysant plus de 5 milliards de lignes d’événements GitHub.
Il fournit une nouvelle façon d’explorer les données GitHub en posant simplement des questions en langage naturel, ce qui est extrêmement pratique quand on veut comparer les choses.
Par exemple, OSS Insight vous permet de comparer deux dépôts à partir des mêmes indicateurs, tels que les étoiles, les forks, les issues, les commits, les pull requests, le nombre de contributeurs, les langages de programmation utilisés ou encore les lignes de code modifiées.
Imaginez que vous travaillez sur un projet et que vous souhaitez comparer deux bibliothèques open source pour déterminer laquelle est la plus populaire et la mieux maintenue. Et bien il suffit de lui demander.
Mais ça ne s’arrête pas à ça. Voici quelques exemples de questions que les gens posent à l’outil :
En plus de cela, OSS Insight offre des informations sur les tendances techniques mensuelles avec des listes de dépôts à découvrir.
Comme ça, vous pouvez suivre de près certains types d’outils populaires, comme les bases de données, les frameworks JavaScript ou encore les outils liés aux LLM. Vous pouvez également obtenir des analyses sur la productivité des développeurs et les statistiques des dépôts.
Pour tester le OSS Insight, il vous suffit de vous rendre sur leur site web et de plonger dans cet océan de données.
A new experimental antibiotic can handily knock off one of the world's most notoriously drug-resistant and deadly bacteria —in lab dishes and mice, at least. It does so with a never-before-seen method, cracking open an entirely new class of drugs that could yield more desperately needed new therapies for fighting drug-resistant infections.
The findings appeared this week in a pair of papers published in Nature, which lay out the extensive drug development work conducted by researchers at Harvard University and the Swiss-based pharmaceutical company Roche.
In an accompanying commentary, chemists Morgan Gugger and Paul Hergenrother of the University of Illinois at Urbana-Champaign discussed the findings with optimism, noting that it has been more than 50 years since the Food and Drug Administration has approved a new class of antibiotics against the category of bacteria the drug targets: Gram-negative bacteria. This category—which includes gut pathogens such as E. coli, Salmonella, Shigella, and the bacteria that cause chlamydia, the bubonic plague, gonorrhea, whooping cough, cholera, and typhoid, to name a few—is extraordinarily challenging to kill because it's defined by having a complex membrane structure that blocks most drugs, and it's good at accumulating other drug-resistance strategies
Aujourd’hui les amis, j’aimerais vous faire découvrir un outil en ligne de commande qui va bien vous aider si vous évoluez dans l’écosystème de Microsoft Azure.
En effet, en fonction de ce que vous faites avec vos instances et vos services Azure, le coût n’est pas forcément le même, et ce n’est pas super pratique de suivre tout ça uniquement via le site web. Heureusement avec l’outil Azure Cost Cli, vous allez pouvoir garder un œil sur les dépenses liées à votre utilisation des ressources, directement depuis votre terminal.
Ce logiciel utilise l’API Azure Cost Management pour récupérer les coûts et présente les résultats directement dans la console ou sous format JSON. JSON que vous pouvez ensuite exploiter dans vos outils ou scripts.
Hormis l’affichage des coûts cumulés comme vous pouvez le voir ci-dessus, il peut également afficher les coûts journaliers, extraire les ressources par coûts et répertorier les budgets.
Et il peut même détecter les anomalies éventuelles et les tendances d’évolution dans les coûts, ce qui permet d’automatiser encore plus les rapports générés.
Pour l’installer, c’est simple, ouvrez un terminal et utilisez la commande suivante (il vous faudra dotnet) :
dotnet tool install --global azure-cost-cli
Ensuite, vous pouvez commencer à afficher les couts cumulés associés à un abonnement Azure spécifique en lui passant votre ID :
azure-cost accumulatedCost -s 12345678-1234-1234-1234-123456789012
Pour générer un rapport CSV des coûts par ressource, rien de plus simple :
azure-cost costByResource -s 12345678-1234-1234-1234-123456789012 -o csv
Imaginons maintenant que vous souhaitiez afficher les coûts quotidiens pour le mois de janvier 2023, regroupés par nom de service (ServiceName
) :
azure-cost dailyCosts --dimension ServiceName --from 2023-01-01 --to 2023-01-31
Pratique non ? Et si vous souhaitez faire de la détection d’anomalie au niveau des coûts générés durant une certaine période :
azure-cost detectAnomalies -g myResourceGroup --timeframe Custom --from 2023-01-01 --to 2023-01-31
J’ai également découvert que cet outil pouvait être utilisé dans un GitHub Workflow pour obtenir le coût de notre abonnement et stocker les résultats en markdown. C’est vraiment génial pour avoir un aperçu rapide des frais liés à notre abonnement.
Voilà, si ça vous intéresse pour suivre vos coûts sur Azure, le projet Azure Cost Cli est disponible ici sur Github.
Aujourd’hui, je vous présente ARTful, une bibliothèque Android native pour modifier l’Android Runtime (ART) sur Android 13 et 14. Ça va faire plaisir aux développeurs qui veulent mettre des bâtons dans les roues des curieux qui aiment jouer avec les apps Android en les analysant d’un peu trop près.
La magie de cette bibliothèque réside dans sa capacité à changer dynamiquement l’implémentation de n’importe quelle méthode statique, éliminant l’utilisation de références en clair et entravant l’ingénierie inverse.
Pour vous donner un aperçu concret de ce que ARTful peut faire pour vous, imaginez une application où les développeurs veulent éviter que les pirates ne mettent le nez dans leur code. Grâce à ARTful, ils peuvent modifier dynamiquement les méthodes statiques pour les rendre plus résistantes à l’ingénierie inverse. Et voilà, mission accomplie !
Et pour que tout le monde puisse profiter des bienfaits de cette bibliothèque, les concepteurs ont choisi de la rendre open source ici : Github ARTful.
Eclatez-vous bien !
The Food and Drug Administration is warning health care providers not to use probiotics containing live bacteria or yeast in preterm infants after the agency began investigating the July death of a preterm, low-weight infant given such a product in an unnamed hospital.
The infant developed sepsis from the bacterium in the probiotic product—Evivo with MCT Oil made by Infinant Health—and subsequently died.
In a statement to Ars, the FDA said it quickly investigated the death after receiving an initial report on July 31. "Infant deaths are especially tragic and determining causality of preterm infant death can be particularly complicated," an agency spokesperson said. The agency reviewed medical records and laboratory tests from the case and collected clinical samples and product samples for analysis.
Vous êtes-vous déjà demandé comment utiliser de la reconnaissance faciale dans vos projets Python sans trop vous prendre la tête ?
Ne cherchez pas plus loin ! Aujourd’hui, je partage avec vous cette bibliothèque de reconnaissance faciale vraiment top : face_recognition.
Cette lib repose sur la pointe de la technologie en matière de reconnaissance faciale, notamment grâce à dlib. D’ailleurs, elle revendique une précision impressionnante de 99,38 % au benchmark Labeled Faces in the Wild.
La bibliothèque face_recognition offre une panoplie de fonctionnalités : Elle détecte les faces sur les photos, repère les traits du visage (yeux, nez, bouche et menton) et reconnaît les personnes. Vous pouvez même combiner cette bibliothèque avec d’autres libs Python pour effectuer une reconnaissance faciale en temps réel.
Pour l’installer, assurez-vous d’avoir Python 3.3+ ou Python 2.7, ainsi que macOS ou Linux. Ensuite, un simple
pip3 install face_recognition
… fera l’affaire !
La bibliothèque est également compatible avec Docker, et, si vous rencontrez des problèmes d’installation, une machine virtuelle préconfigurée est à votre disposition. De plus, des instructions d’installation pour Windows, Rasberry Pi et FreeBSD sont également dispo sur la page Github.
La bibliothèque face_recognition contient deux programmes en ligne de commande : face_recognition
et face_detection
.
Le premier programme reconnaît les visages dans une ou plusieurs photos, tandis que le second trouve les positions des visages dans les images. Petite astuce, si vous obtenez plusieurs correspondances pour une même personne, essayez d’ajuster l’option --tolerance
pour obtenir des résultats plus précis.
Pour essayer le modèle de détection de visage basé sur l’apprentissage en profondeur, je vous invite à implémenter ce code. Vous pouvez également essayer ce code ici si vous avez de nombreuses images à traiter en batch. Cet autre exemple permet de localiser automatiquement les caractéristiques faciales des visages.
Y’a de quoi bricoler !
Le projet face_recognition contient également des exemples pour reconnaître des visages à partir d’une vidéo, créer un service Web pour la reconnaissance faciale via HTTP, ou utiliser un classificateur pour reconnaître des visages sur plusieurs images par personne.
Intéressé par un exécutable autonome ? Comme d’habitude, PyInstaller est votre meilleur ami ! Cependant, une configuration personnalisée sera nécessaire pour fonctionner correctement avec cette bibliothèque.
Il est bon de noter que cette technologie présente certaines limitations. Par exemple, la reconnaissance faciale fonctionne moins bien sur les enfants et peut varier entre les groupes ethniques. Pour plus de détails, vous pouvez consulter la page wiki qui vous expliquera tout à ce sujet.
En somme, face_recognition est une bibliothèque open-source vraiment chouette permettant le développement de projets de reconnaissance faciale en Python. C’est une bonne opportunité pour vous lancer dans la création d’applications IA de reconnaissance faciale.
Voilà une news qui va faire plaisir aux amateurs de programmation réseau et de traitement de paquets. PcapPlusPlus est une bibliothèque multi-plateforme en C++ dédiée à la capture, l’analyse et la création de paquets réseau.
Conçue pour être facile à utiliser et efficace, elle offre une variété de fonctionnalités qui devrait vous plaire si vous codez des outils liés au traitement de trames réseaux.
PcapPlusPlus permet de capturer et d’envoyer ces paquets réseau grâce à des wrappers C++ pour des outils populaire comme libpcap, WinPcap, NPcap, DPDK et PF_RING.
Mais cette lib offre d’autres fonctionnalités un peu plus avancées comme le décodage et le forgeage de paquets pour une grande variété de protocoles réseau tels que TCP, UDP, IPv4, IPv6, ARP, VLAN, MPLS, ICMP, HTTP, SSL/TLS, DNS, FTP et SMTP.
Voici un exemple d’implémentation pour décoder un paquet :
// parse the raw packet into a parsed packet
pcpp::Packet parsedPacket(&rawPacket);
// check if it's an IPv4 packet
if (parsedPacket.isPacketOfType(pcpp::IPv4)) {
// extract source and dest IPs
pcpp::IPv4Address srcIP =
parsedPacket.getLayerOfType()->getSrcIPv4Address();
pcpp::IPv4Address destIP =
parsedPacket.getLayerOfType()->getDstIPv4Address();
// print source and dest IPs
std::cout <<
"Source IP is: " << srcIP << std::endl <<
"Dest IP is: " << destIP << std::endl;
Cela permet d’analyser et mais surtout de manipuler tous types de paquets réseau utilisant ces protocoles. Par exemple, comme mentionné sur cette pages, avec cette lib, vous pouvez coder des outils pour faire des trucs très cool comme :
Comme cette lib C++ est conçue pour être extrêmement rapide et légère, cela lui permet de traiter tous ces paquets très rapidement avec très peu de charge sur le système. Vous pourrez bien évidement l’utiliser sur votre OS, que ce soit du Windows, du MacOS, du Linux, de l’Android ou encore FreeBSD (les sources sont disponibles).
Voici un exemple d’implémentation pour lire des paquets :
// create a pcap file reader
pcpp::PcapFileReaderDevice pcapReader("input.pcap");
pcapReader.open();
// create a pcapng file writer
pcpp::PcapNgFileWriterDevice pcapNgWriter("output.pcapng");
pcapNgWriter.open();
// raw packet object
pcpp::RawPacket rawPacket;
// read packets from pcap reader and write pcapng writer
while (pcapReader->getNextPacket(rawPacket)) {
pcapNgWriter.writePacket(rawPacket);
}
Une interface graphique facile à utiliser permet également de lire et d’écrire ces fameuses trames réseau dans des fichiers, prenant ainsi en charge les formats de fichier PCAP et PCAPNG. De plus, il contient une implémentation unique de techniques de réassemblage de paquets, notamment le réassemblage TCP qui prend en charge la retransmission TCP, les paquets TCP hors ordre et les données TCP manquantes, ainsi que la fragmentation et le défragmentation IP pour créer et réassembler des fragments IPv4 et IPv6.
Avec PcapPlusPlus vous pourrez également filtrer les paquets ou générer des empreintes numériques TLS pour cibler et identifier les paquets réseau de manière beaucoup plus précise.
Bref, tout ça pour dire que si votre cafetière est connectée sur le réseau, PcapPlusPlus peut même faire le café !
Allez, pour installer ce truc, toute la doc est là ! Amusez vous bien !
Today, it’s easy to run Edge Impulse machine learning on any operating system, like Raspberry Pi OS, and on every cloud, like Microsoft’s Azure IoT. Evan Rust, Technology Ambassador for Edge Impulse, walks us through it.
Building enterprise-grade IoT solutions takes a lot of practical effort and a healthy dose of imagination. As a foundation, you start with a highly secure and reliable communication between your IoT application and the devices it manages. We picked our favorite integration, the Microsoft Azure IoT Hub, which provides us with a cloud-hosted solution backend to connect virtually any device. For our hardware, we selected the ubiquitous Raspberry Pi 4, and of course Edge Impulse, which will connect to both platforms and extend our showcased solution from cloud to edge, including device authentication, out-of-box device management, and model provisioning.
Edge machine learning devices fall into two categories: some are able to run very simple models locally, and others have more advanced capabilities that allow them to be more powerful and have cloud connectivity. The second group is often expensive to develop and maintain, as training and deploying models can be an arduous process. That’s where Edge Impulse comes in to help to simplify the pipeline, as data can be gathered remotely, used effortlessly to train models, downloaded to the devices directly from the Azure IoT Hub, and then run – fast.
This reference project will serve you as a guide for quickly getting started with Edge Impulse on Raspberry Pi 4 and Azure IoT, to train a model that detects lug nuts on a wheel and sends alerts to the cloud.
To begin, you’ll need a Raspberry Pi 4 with an up-to-date Raspberry Pi OS image which can be found here. After flashing this image to an SD card and adding a file named wpa_supplicant.conf
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=<Insert 2 letter ISO 3166-1 country code here>
network={
ssid="<Name of your wireless LAN>"
psk="<Password for your wireless LAN>"
}
along with an empty file named ssh
(both within the /boot
directory), you can go ahead and power up the board. Once you’ve successfully SSH’d into the device with
$ ssh pi@<IP_ADDRESS>
and the password raspberry
, it’s time to install the dependencies for the Edge Impulse Linux SDK. Simply run the next three commands to set up the NodeJS environment and everything else that’s required for the edge-impulse-linux wizard:
$ curl -sL https://deb.nodesource.com/setup_12.x | sudo bash -
$ sudo apt install -y gcc g++ make build-essential nodejs sox gstreamer1.0-tools gstreamer1.0-plugins-good gstreamer1.0-plugins-base gstreamer1.0-plugins-base-apps
$ npm config set user root && sudo npm install edge-impulse-linux -g --unsafe-perm
Since this project deals with images, we’ll need some way to capture them. The wizard supports both the Pi Camera modules and standard USB webcams, so make sure to enable the camera module first with
$ sudo raspi-config
if you plan on using one. With that completed, go to the Edge Impulse Studio and create a new project, then run the wizard with
$ edge-impulse-linux
and make sure your device appears within the Edge Impulse Studio’s device section after logging in and selecting your project.
Training accurate machine learning models requires feeding plenty of varied data, which means a lot of images are required. For this use case, I captured around 50 images of a wheel that had lug nuts on it. After I was done, I headed to the Labeling queue in the Data Acquisition page and added bounding boxes around each lug nut within every image, along with every wheel.
To add some test data, I went back to the main Dashboard page and clicked the Rebalance dataset button, which moves 20% of the training data to the test data bin.
So now that we have plenty of training data, it’s time to do something with it, namely train a model. The first block in the impulse is an Image Data block, and it scales each image to a size of 320 by 320 pixels. Next, image data is fed to the Image processing block which takes the raw RGB data and derives features from it.
Finally, these features are sent to the Transfer Learning Object Detection model which learns to recognize the objects. I set my model to train for 30
cycles at a learning rate of .15
, but this can be adjusted to fine-tune the accuracy.
As you can see from the screenshot below, the model I trained was able to achieve an initial accuracy of 35.4%, but after some fine-tuning, it was able to correctly recognize objects at an accuracy of 73.5%.
In order to verify that the model works correctly in the real world, we’ll need to deploy it to our Raspberry Pi 4. This is a simple task thanks to the Edge Impulse CLI, as all we have to do is run
$ edge-impulse-linux-runner
which downloads the model and creates a local webserver. From here, we can open a browser tab and visit the address listed after we run the command to see a live camera feed and any objects that are currently detected.
With the model working locally on the device, let’s add an integration with an Azure IoT Hub that will allow our Raspberry Pi to send messages to the cloud. First, make sure you’ve installed the Azure CLI and have signed in using az login
. Then get the name of the resource group you’ll be using for the project. If you don’t have one, you can follow this guide on how to create a new resource group. After that, return to the terminal and run the following commands to create a new IoT Hub and register a new device ID:
$ az iot hub create --resource-group <your resource group> --name <your IoT Hub name>
$ az extension add --name azure-iot
$ az iot hub device-identity create --hub-name <your IoT Hub name> --device-id <your device id>
Retrieve the connection string with
$ az iot hub device-identity connection-string show --device-id <your device id> --hub-name <your IoT Hub name>
and set it as an environment variable with
$ export IOTHUB_DEVICE_CONNECTION_STRING="<your connection string here>"
in your Raspberry Pi’s SSH session, as well as
$ pip install azure-iot-device
to add the necessary libraries. (Note: if you do not set the environment variable or pass it in as an argument, the program will not work!) The connection string contains the information required for the device to establish a connection with the IoT Hub service and communicate with it. You can then monitor output in the Hub with
$ az iot hub monitor-events --hub-name <your IoT Hub name> --output table
or in the Azure Portal.
To make sure it works, download and run this example to make sure you can see the test message. For the second half of deployment, we’ll need a way to customize how our model is used within the code. Thankfully, Edge Impulse provides a Python SDK for this purpose. Install it with
$ sudo apt-get install libatlas-base-dev libportaudio0 libportaudio2 libportaudiocpp0 portaudio19-dev
$ pip3 install edge_impulse_linux -i https://pypi.python.org/simple
There’s some simple code that can be found here on Github, and it works by setting up a connection to the Azure IoT Hub and then running the model.
Once you’ve either downloaded the zip file or cloned the repo into a folder, get the model file by running
$ edge-impulse-linux-runner --download modelfile.eim
inside of the folder you just created from the cloning process. This will download a file called modelfile.eim
. Now, run the Python program with
$ python lug_nut_counter.py ./modelfile.eim -c <LUG_NUT_COUNT>
where <LUG_NUT_COUNT>
is the correct number of lug nuts that should be attached to the wheel (you might have to use python3
if both Python 2 and 3 are installed).
Now whenever a wheel is detected the number of lug nuts is calculated. If this number falls short of the target, a message is sent to the Azure IoT Hub.
And by only sending messages when there’s something wrong, we can prevent an excess amount of bandwidth from being taken due to empty payloads.
Imagine utilizing object detection for an industrial task such as quality control on an assembly line, or identifying ripe fruit amongst rows of crops, or detecting machinery malfunction, or remote, battery-powered inferencing devices. Between Edge Impulse, hardware like Raspberry Pi, and the Microsoft Azure IoT Hub, you can design endless models and deploy them on every device, while authenticating each and every device with built-in security.
You can set up individual identities and credentials for each of your connected devices to help retain the confidentiality of both cloud-to-device and device-to-cloud messages, revoke access rights for specific devices, transmit code and services between the cloud and the edge, and benefit from advanced analytics on devices running offline or with intermittent connectivity. And if you’re really looking to scale your operation and enjoy a complete dashboard view of the device fleets you manage, it is also possible to receive IoT alerts in Microsoft’s Connected Field Service from Azure IoT Central – directly.
Feel free to take the code for this project hosted here on GitHub and create a fork or add to it.
The complete project is available here. Let us know your thoughts at hello@edgeimpulse.com. There are no limits, just your imagination at work.
The post IoT gets a machine learning boost, from edge to cloud appeared first on Raspberry Pi.
Want to dabble in the Internet of Things but don’t know where to start? Well, our friends at Microsoft have developed something fun and free just for you. Here’s Senior Cloud Advocate Jim Bennett to tell you all about their brand new online curriculum for IoT beginners.
IoT — the Internet of Things — is one of the biggest growth areas in technology, and one that, to me, is very exciting. You start with a device like a Raspberry Pi, sprinkle some sensors, dust with code, mix in some cloud services and poof! You have smart cities, self-driving cars, automated farming, robotic supermarkets, or devices that can clean your toilet after you shout at Alexa for the third time.
It feels like every week there is another survey out on what tech skills will be in demand in the next five years, and IoT always appears somewhere near the top. This is why loads of folks are interested in learning all about it.
In my day job at Microsoft, I work a lot with students and lecturers, and I’m often asked for help with content to get started with IoT. Not just how to use whatever cool-named IoT services come from your cloud provider of choice to enable digital whatnots to add customer value via thingamabobs, but real beginner content that goes back to the basics.
This is why a few of us have spent the last few months locked away building IoT for Beginners. It’s a free, open source, 24-lesson university-level IoT curriculum designed for teachers and students, and built by IoT experts, education experts and students.
The lessons are grouped into projects that you can build with a Raspberry Pi so that you can deep-dive into use cases of IoT, following the journey of food from farm to table.
You’ll build projects as you learn the concepts of IoT devices, sensors, actuators, and the cloud, including:
Grab your Raspberry Pi and some sensors from our friends at Seeed Studio and get building. Without further ado, please meet IoT For Beginners: A Curriculum!
The post Learn the Internet of Things with “IoT for Beginners” and Raspberry Pi appeared first on Raspberry Pi.
Animator/engineer Ashok Fair has put witch-level finger pointing powers in your hands by sticking a SmartEdge Agile, wirelessly controlled by Raspberry Pi Zero, to a golf glove. You could have really freaked the bejeezus out of Halloween party guests with this (if we were allowed to have Halloween parties that is).
The build uses a Smart Edge Agile IoT device with Brainium, a cloud-based tool for performing machine learning tasks.
The Rapid IoT kit is interfaced with Raspberry Pi Zero and creates a thread network connecting to light, car, and fan controller nodes.
The Brainium app is installed on Raspberry Pi and bridges between the cloud and Smart Edge device. MQTT is running on Python and processes the Rapid IoT Kit’s data.
The device is mounted onto a golf glove, giving the wearer seemingly magical powers with the wave of a hand.
To get started, the glove wearer draws a pattern above the screen attached to the Raspberry Pi to unlock it and wake up all the controller nodes.
The light controller node is turned on by drawing a clockwise circle, and turned off with an counter-clockwise circle.
The fan is turned on and off in the same way, and you can increase the fan’s speed by moving your hand upwards and reduce the speed by moving your hand down. You know it’s working by the look of the fan’s LEDs: they blinker faster as the fan speeds up.
Make a pushing motion in the air above the car to make it move forward, and you can also make it turn and reverse.
If you wear the glove while driving, it collects data in real time and logs it on the Brainium cloud so you can review your driving style.
Keep up with Ashok’s projects on Twitter or Facebook.
The post Raspberry Pi smart IoT glove appeared first on Raspberry Pi.
The new Ubuntu Appliance portfolio provides free images to help you turn your Raspberry Pi into an IoT device: just install them to your SD card and you have all the software you need to make a media server, get started with home automation, and more. Canonical’s Rhys Davies is here to tell us all about it.
We are delighted to announce the new Ubuntu Appliance portfolio. Together with NextCloud, AdGuard, Plex, Mosquitto and openHAB, we have created the first in a new class of Ubuntu derivatives. Ubuntu Appliances are software-defined projects that enable users to download everything they need to turn a Raspberry Pi into a device that does one thing – beautifully.
The Ubuntu Appliance mission is to enable you to build your own secure, self-updating, single-purpose devices. Tell us what you want to see next, or let’s talk about turning your project into the next Ubuntu Appliance in Discourse. For now, we are excited to bring these initial appliances to your attention.
Head over to the Ubuntu Appliances website, click the appliance you would like, select download, follow the instructions, and away you go. Once you get to this stage, there are links to tutorials and documentation written by the upstream project themselves, so you can get next steps from the horse’s mouth. If you run into any bother let us know with a new topic and we’ll get on it.
The problem we are trying to solve is to do with the fragmentation in IoT. We want to give publishers and developers a platform to get their software in the hands of their users and into their devices. We work with them to securely bundle the OS, their applications and configurations into a single download that is available for anyone to turn a Raspberry Pi into a dedicated device. You can go to the portfolio and download as many of the appliances as you like and start using them today.
All of this gives a stage and a secure, production-grade base to projects. There are no restrictions on who can make an Ubuntu Appliance; all you need is an application that runs on a Raspberry Pi or another certified board, and to let us know what you’ve got so we can help you over the line. If you need more information, head to our community page where you’ll find the rules and the exact steps to become featured as an Ubuntu Appliance.
All that’s left to say is to try them out. All five of the initial appliances work on Raspberry Pi, so if you have one, you can get started. And if you don’t have one – maybe your Raspberry Pi is still in the post – then you can also ‘try before you Pi’: install the appliance in a virtual machine and see what you think.
The list of appliances is already growing. This launch marks the first five appliances, but we are already working with developers on the next wave and are looking for more. Start with these ones and go to our discourse to tell us what you think.
Thanks for having me, Raspberry Pi <3
The post Build an IoT device with Ubuntu Appliance and Raspberry Pi appeared first on Raspberry Pi.
In issue 31 of HackSpace magazine, out today, PJ Evans looks at DIY smart homes and homemade Internet of Things devices.
In the last decade, various companies have come up with ‘smart’ versions of almost everything. Microcontrollers have been unceremoniously crowbarred into devices that had absolutely no need for microcontrollers, and often tied to phone apps or web services that are hard to use and don’t work well with other products.
Put bluntly, the commercial world has struggled to deliver an ecosystem of useful smart products. However, the basic principle behind the connected world is good – by connecting together sensors, we can understand our local environment and control it to make our lives better. That could be as simple as making sure the plants are correctly watered, or something far more complex.
The simple fact is that we each lead different lives, and we each want different things out of our smart homes. This is why companies have struggled to create a useful smart home system, but it’s also why we, as makers, are perfectly placed to build our own. Let’s dive in and take a look at one way of doing this – using the TICK Stack – but there are many more, and we’ll explore a few alternatives later on.
Many of our projects create data, sometimes a lot of it. This could be temperature, humidity, light, position, speed, or anything else that we can measure electronically. To be useful, that data needs to be turned into information. A list of numbers doesn’t tell you a lot without careful study, but a line graph based on those numbers can show important information in an instant. Often makers will happily write scripts to produce charts and other types of infographics, but now open-source software allows anyone to log data to a database, generate dashboards of graphs, and even trigger alerts and scripts based on the incoming data. There are several solutions out there, so we’re going to focus on just one: a suite of products from InfluxData collectively known as the TICK Stack.
The ‘I’ in TICK is the database that stores your precious data. InfluxDB is a time series database. It differs from regular SQL databases as it always indexes based on the time stamp of the incoming data. You can use a regular SQL database if you wish (and we’ll show you how later), but what makes InfluxDB compelling for logging data is not only its simplicity, but also its data-management features and built-in web-based API interface. Getting data into InfluxDB can be as easy as a web post, which places it within the reach of most internet-capable microcontrollers.
Next up is our ‘K’. Kapacitor is a complex data processing engine that acts on data coming into your InfluxDB. It has several purposes, but the common use is to generate alerts based on data readings. Kapacitor supports a wide range of alert ‘endpoints’, from sending a simple email to alerting notification services like Pushover, or posting a message to the ubiquitous Slack. Multiple alerts to multiple destinations can be configured, and what constitutes an alert status is up to you. More advanced uses of Kapacitor include machine learning and anomaly detection.
The problem with Kapacitor is the configuration. It’s a lot of work with config files and the command line. Thoughtfully, InfluxData has created Chronograf, a graphical user interface to both Kapacitor and InfluxDB. If you prefer to keep away from the command line, you can query and manage your databases here as well as set up alerts, metrics that trigger an alert, and the configurations for the various handlers. This is all presented through a web app that you can access from anywhere on your network. You can also build ‘Dashboards’ – collections of charts displayed on a single page based on your InfluxDB data.
Finally, our ’T’ in TICK. One of the most common uses for time series databases is measuring computer performance. Telegraf provides the link between the machine it is installed on and InfluxDB. After a simple install, Telegraf will start logging all kinds of data about its host machine to your InfluxDB installation. Memory usage, CPU temperatures and load, disk space, and network performance can all be logged to your database and charted using Chronograf. This is more due to the Stack’s more common use for monitoring servers, but it’s still useful for making sure the brains of our network-of-things is working properly. If you get a problem, Kapacitor can not only trigger alerts but also user-defined scripts that may be able to remedy the situation.
You can read the rest of HackSpace magazine’s DIY IoT feature in issue 31, out today and available online from the Raspberry Pi Press online store. You can also download issue 31 for free.
The post Design your own Internet of Things with HackSpace magazine appeared first on Raspberry Pi.