惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
Visual Studio Blog
大猫的无限游戏
大猫的无限游戏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
量子位
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
腾讯CDC
S
Securelist
Know Your Adversary
Know Your Adversary
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
博客园 - 【当耐特】
V2EX - 技术
V2EX - 技术
J
Java Code Geeks
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Hugging Face - Blog
Hugging Face - Blog
Cisco Talos Blog
Cisco Talos Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
阮一峰的网络日志
阮一峰的网络日志
美团技术团队
W
WeLiveSecurity
S
SegmentFault 最新的问题
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
宝玉的分享
宝玉的分享
博客园 - Franky
S
Security Affairs
博客园 - 司徒正美
V
V2EX
K
Kaspersky official blog
T
Threatpost
NISL@THU
NISL@THU
博客园 - 叶小钗
Help Net Security
Help Net Security
PCI Perspectives
PCI Perspectives
IT之家
IT之家
小众软件
小众软件
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Last Week in AI
Last Week in AI
Jina AI
Jina AI
爱范儿
爱范儿
罗磊的独立博客
N
News and Events Feed by Topic
博客园 - 三生石上(FineUI控件)
有赞技术团队
有赞技术团队
P
Proofpoint News Feed
L
LINUX DO - 热门话题
Google Online Security Blog
Google Online Security Blog
雷峰网
雷峰网
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint

夜行人

回家路上 第一期的直播演示项目 震动检测器 正能量 在线参观CodeLab Neverland 发布 CodeLab Adapter 3.3.1 DynamicTable 之 纸糊方向盘 CodeLab DynamicTable: 一个可实施的技术方案 CodeLab Insight 发布 Alpha 版 情人节 Home Assistant 周报 && IoT 周报 (02) Joplin: 关注隐私的 Evernote 开源替代软件 浏览器的未来与 Web 传感器 Home Assistant 周报 && IoT 周报 (01) 百宝箱(01) 论自由 介绍 WebThings Home Assistant 周报 && iot 周报 (00) 百宝箱(00) 毛姆读书心得 传世之作 周末徒步 CodeLab Adapter ❤️ Jupyter/Python 航班 躲雨 夏令营途中 [译]思想--作为一种技术 The future of coding 美国之行 三门问题的程序模拟 从Python转向Pharo https://blog.just4fun.site/post/iot/iot-open-source-projects/ Python异步编程笔记 https://blog.just4fun.site/post/iot/iot-open-source-hardware-community/ 万物积木化开发者社区 CodeLab ❤️ Blender Scratch3技术分析之云变量 API(第7篇) [译]对管道(Pipes)的偏爱 [译]提出正确的问题比得到正确答案更重要 蓝牙设备与Scratch3.0 创建你的第一个Scratch3.0 Extension Scratch3技术分析之项目内部数据(第6篇) Scratch3技术分析之社区 API(第5篇) Scratch3技术分析之User API(第4篇) Scratch3技术分析之项目主页API(第3篇) Scratch3技术分析之静态资源API(第2篇) Scratch3.0、micro:bit与Windows7 https://blog.just4fun.site/post/iot/zerynth-vs-micropython/ 核聚变、方所与半宅空间 可视化编程为何是个糟糕的主意 codelab.club周末聚会 关于codelab.club '下一件大事'是一个房间 Hungry Robot - Eat everything 编程作为一种思考方式 今日简史 史蒂夫·乔布斯传 罗素自选文集 https://blog.just4fun.site/post/edx/tianjin-scratch-ai/ https://blog.just4fun.site/post/edx/richie-cms-openedx/ 徒步武功山 WebUSB与micro:bit 积木化编程与3D场景 夜宿武功山顶 scratch3-adapter接入优必选Alpha系列机器人 https://blog.just4fun.site/post/edx/video-migration-note/ scratch3-adapter重构笔记 https://blog.just4fun.site/post/edx/edx-community-members/ 两种硬件编程风格的比较 使用micro:bit自制PPT翻页笔 柏拉图对话集 scratch3.0 + micro:bit 七月电影放映计划 非营利组织的管理 Screenly--用树莓派让任何屏幕变为可编程的数字标牌 以最佳实践开始你的Django项目 micro:bit与事件驱动 为Scratch3.0设计的插件系统(上篇) OCR应用一例 近两年读过的一些好书 blockly开发之使用python驱动浏览器中的turtle(2) 牛顿新传 文学理论入门 逻辑的引擎 人生的意义 blockly开发之生成并运行js代码(1) blockly开发之hello world(0) micro:bit使用笔记 神器之Termux https://blog.just4fun.site/post/iot/micropython-notes/ Cozmo what is this Scratch的前世今生 下段旅程 我行在远方 爆裂 途中杂记 https://blog.just4fun.site/post/edx/open-edx-startup/ cozmo系列之入门 - 有性格且可编程的机器人 PaperWeekly开发笔记 创业二三事
Python function for Snap!
种瓜 · 2024-05-11 · via 夜行人

中文版本

The JavaScript function of Snap! is simple, flexible, and powerful. I want to emulate it to build a Python function.

Preface

Usage scenarios

With the Python function, we can:

  • Use the vast number of third-party libraries in the Python ecosystem(opencv-python, numpy…)
  • Use various algorithms that have been implemented by the Python community(such as TheAlgorithms)

We can both access the vast tools accumulated in the Python ecosystem within the Snap! environment and use Snap! to enhance the liveness of Python.

Select a Python Interpreter

There are multiple Python interpreters that can work in the browser environment. Pyodide is the most powerful. It allows us to use a large number of libraries from the Python ecosystem, such as: opencv-python, Pillow, pyparsing, requests, retrying, scikit-image, and a large number of scientific libraries (scipy, sympy, numpy, pandas).

Pyodide supports any library implemented in pure Python (built as python wheel packaging standard), and libraries using C/C++ code (such as numpy) compiled to WebAssembly can also be used in pyodide.

We decided to build the Python function based on Pyodide.

Introduce Pyodide into Snap!

Goals

Just like in our previous article where we mediapipe in Snap! into Snap!, we hope to achieve the following 2 goals:

No need to update the Snap! platform, no developer intervention required, all work is done in the user environment (just a Snap! project), which means ordinary users can continue to extend these capabilities. (This is an example of end-user programming)

We can fully utilize the liveness of Snap! and enjoy an efficient and pleasant development experience.

Since it is just a Snap! project, you can adjust it as you like, and even use other Python interpreters instead of Pyodide.

Import pyodide

Unlike mediapipe , Pyodide is not released as a JavaScript module. Pyodide takes a more traditional approach to bundling code, We can import it using the src_load(url) primitive of Snap! .

The version of Pyodide we are using is 0.25.1 , and the corresponding Python version is 3.11. We used the official CDN,

Demo

Using requests to interact with the network

Snap! has a block for interacting with the network, but it is not convenient to use. The API of requests is designed to be easy to use:

requests demo

Parse XML

There is no built-in XML library in Snap!, but the built-in XML library of Python is useful, we can use it to extract information from blog RSS feeds.

Notice: you can also use JavaScript function to do it.

This example demonstrates fetching the latest RSS from my blog, parsing it using the XML library of Python, and storing the parsed results in the posts variable of Snap!. Then, each blog post is displayed as a clone:

  • The costume of the clone is the article title
  • When the mouse hovers over a clone, the clone will say the article summary
  • Clicking on a clone will open the article link

XML demo

Regular expression

Snap! Lacks support for regular expressions, we can use the regular expression library of Python to enhance it.

Passing Lists Between Python and Snap!

This example demonstrates how to pass lists (any nesting depth!) between Python and Snap!

Lists can represent any data structure. The list functions of Python and Snap! are extremely powerful (Snap! , a kind of Lisp, has even more powerful list expressiveness). Now, the two can interoperate seamlessly.

Images, audio, and other multimedia data can all be represented as lists, and all the data can now flow freely between the two systems.

A typical use case is that the capabilities of numpy(just like the hyperblock of Snap!) can be integrated into Snap!, and Snap! can provide enhanced liveness for numpy.

Passing Lists demo

numpy demo

numpy demo

OpenCV demo

OpenCV demo

Pillow demo

Pillow demo

Third-party libraries

As mentioned:

Pyodide supports any library implemented in pure Python (built as python wheel packaging standard)

We tried to install the furl library, which is used to conveniently handle URLs

Pyodide will install this library from PyPI (you can also install your libraries from a specified URL).

furl demo

FAQ

How to save global state?

Functions are usually stateless, the Python function is a function.

If you expect to operate on the same state(variable) across multiple function calls, you can store it in the window global variable

1
2
3
import js
js.window._result = "hello"
# Accessible in devtool: console.log(window.a)

And of course, you can persistently store it in localstorage or indexeddb, so that even if you refresh the browser, you can still find these states.

How to access Bluetooth, serial port, and other browser APIs

This demo (click to run) shows how to use Python to connect to MicroBlocks’ Bluetooth service.

Where is the third-party library loaded from?

The load package block is used to load third-party libraries from the network. It uses micropip internally.

Python packages can be loaded from multiple sources:

  • The official Pyodide has compiled these Python libraries. If you load these libraries, they will be loaded from the Pyodide repository.
  • Other libraries are loaded from PyPI by default

You can also load libraries directly from the URL (you can host them on your own server), such as: https://wwj718.github.io/post/img/furl-2.1.3-py2.py3-none-any.whl

How to pass image files between Snap! and Python?

The common practice for transferring media information (audio, images) across languages/systems is to use the base64 data format. The example in this article also uses it.

In this conversation, ChatGPT explained the PNG data of base64 encoding.

You can directly paste the base64 encoded string (such as: data:image/png;base64,iVBORxxxx...) int the oaddress bar of Chrome to view the image.

How to compile blocks into Python code?

Generally speaking, this is not a good idea. the lisp code of Snap! is more powerful (because it is isomorphic with the blocks). If you really need to compile to Python, you can refer to this project.

How to use a more professional Python editor?

How to use a more professional Python editor, since writing Python code in Snap! blocks cannot use features like auto-completion.

One approach is to use the iframe library to introduce a more professional Python editor like pyscrit(pyscrit-editor) (pyscrit-editor) or marimo, and then use dynatalk-over-postmessage for message passing.

Conclusion

This article introduces Python function in the same style as JavaScript function, running in the browser without any external dependencies. All work is done within the Snap! IDE without modifying any Snap! source code.

The most satisfying part is that all this extensibility is in the hands of ordinary users themselves, without the need for developers’ intervention or source code updates. Everything is just an Snap! project!

References