analitics

Pages

Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Friday, June 27, 2025

Python 3.13.5 : the manim python module - part 001.

I used this package few days ago and now I wrote about how can used it.
Update the new release of pip is available: 25.0.1 -> 25.1.1 , run this command:
python.exe -m pip install --upgrade pip
The documentation can be found on the official website.
pip install manim
Collecting manim
  Downloading manim-0.19.0-py3-none-any.whl.metadata (11 kB)
...
Successfully installed Pillow-11.2.1 Pygments-2.19.1 audioop-lts-0.2.1 av-13.1.0 beautifulsoup4-4.13.4 click-8.2.1 cloup-3.0.7 colorama-0.4.6 decorator-5.2.1 glcontext-3.0.0 isosurfaces-0.1.2 manim-0.19.0 manimpango-0.6.0 mapbox-earcut-1.0.3 markdown-it-py-3.0.0 mdurl-0.1.2 moderngl-5.12.0 moderngl-window-3.1.1 networkx-3.5 numpy-2.3.0 pycairo-1.28.0 pydub-0.25.1 pyglet-2.1.6 pyglm-2.8.2 rich-14.0.0 scipy-1.15.3 screeninfo-0.8.1 skia-pathops-0.8.0.post2 soupsieve-2.7 srt-3.5.3 svgelements-1.9.6 tqdm-4.67.1 typing-extensions-4.14.0 watchdog-6.0.0
Let's see how can be used to see the help area:
python.exe -m manim render --help
Manim Community v0.19.0

Usage: python -m manim render ...
Let's use this source code:
from manim import *

class AdvancedAnimation(Scene):
    def construct(self):
        # Scene 1: Introduction
        title = Text("Advanced Animation with Manim").scale(0.76)
        self.play(FadeIn(title))
        self.wait(2)

        # Scene 2: Custom Animation
        circle = Circle().set_fill(color=BLUE, opacity=0.5)
        square = Square().set_fill(color=RED, opacity=0.5)
        self.add(circle, square)
        self.play(
            Rotate(circle, angle=TAU),
            Rotate(square, angle=-TAU),
            run_time=2,
            rate_func=linear
        )
        self.wait()

        # Scene 3: Text Animation
        text = Text("This is a custom text animation", font_size=40).to_edge(UP)
        self.play(Write(text), run_time=2)
        self.wait()

        # Scene 4: Shapes Manipulation
        triangle = Triangle().shift(RIGHT * 2)
        self.play(GrowFromCenter(triangle), run_time=1.5)
        self.wait()

        # Scene 5: Transition to next scene
        self.play(Uncreate(triangle), FadeOut(text))

        # Scene 6: Final Animation
        final_text = Text("This is the end of our animation", font_size=50).to_edge(DOWN)
        self.play(FadeIn(final_text), run_time=1.5)
        self.wait(2)

# Run the animation
AdvancedAnimation()
Use this command to render:
python.exe -m manim render manim_test_001.py AdvancedAnimation -p
AdvancedAnimation -p
Manim Community v0.19.0

[06/27/25 19:52:43] INFO     Animation 0 : Partial movie file      scene_file_writer.py:588
                             written in
                             'D:\PythonProjects\manim_projects\med
                             ia\videos\manim_test_001\1080p60\part
                             ial_movie_files\AdvancedAnimation\397
                             7891868_355746014_223132457.mp4'
...
[06/27/25 19:53:56] INFO     Previewed File at:                             file_ops.py:237
                             'D:\PythonProjects\manim_projects\media\videos
                             \manim_test_001\1080p60\AdvancedAnimation.mp4'
The result comes with many files, see this 1080p60 video result:

Python Qt6 : ... simple processing file.

Today I will show you an simple python script with PyQt6.
This script ai build using the artificial inteligence and I tested will process your files by slections : copy to another folder , zip all selected and delete all selected.
import sys
import os
import re
import shutil
import zipfile
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                            QPushButton, QListWidget, QFileDialog, QMessageBox, QDialog, QLabel)
from PyQt6.QtCore import Qt

class CriteriaDialog(QDialog):
    def __init__(self, folder, parent=None):
        super().__init__(parent)
        self.setWindowTitle(f"Processing Folder: {folder}")
        self.layout = QVBoxLayout(self)
        self.layout.addWidget(QLabel(f"Selected folder: {folder}"))
        self.ok_button = QPushButton("OK")
        self.ok_button.clicked.connect(self.accept)
        self.layout.addWidget(self.ok_button)

class DuplicateFinder(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Duplicate File Finder")
        self.setGeometry(100, 100, 600, 400)
        
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.layout = QVBoxLayout(self.central_widget)
        
        self.file_list = QListWidget()
        self.file_list.setSelectionMode(QListWidget.SelectionMode.MultiSelection)
        self.layout.addWidget(self.file_list)
        
        button_layout = QHBoxLayout()
        self.select_button = QPushButton("Select Folder")
        self.select_button.clicked.connect(self.select_folder)
        button_layout.addWidget(self.select_button)
        
        self.copy_button = QPushButton("Copy To")
        self.copy_button.clicked.connect(self.copy_files)
        button_layout.addWidget(self.copy_button)
        
        self.zip_button = QPushButton("Zip All")
        self.zip_button.clicked.connect(self.zip_files)
        button_layout.addWidget(self.zip_button)
        
        self.delete_button = QPushButton("Delete All")
        self.delete_button.clicked.connect(self.delete_files)
        button_layout.addWidget(self.delete_button)
        
        self.layout.addLayout(button_layout)
        
        self.files = []
        self.selected_folder = ""
        
    def select_folder(self):
        folder = QFileDialog.getExistingDirectory(self, "Select Folder")
        if folder:
            self.selected_folder = folder
            dialog = CriteriaDialog(folder, self)
            if dialog.exec():
                self.files = []
                self.file_list.clear()
                self.scan_folder(folder)
                self.find_duplicates()
            
    def scan_folder(self, folder):
        for root, _, files in os.walk(folder):
            for file in files:
                file_path = os.path.join(root, file)
                self.files.append({
                    'path': file_path,
                    'name': os.path.basename(file_path),
                    'size': os.path.getsize(file_path),
                    'extension': os.path.splitext(file_path)[1]
                })
                
    def find_duplicates(self):
        duplicates = self.find_by_similar_name()
        self.display_duplicates(duplicates)
        
    def find_by_similar_name(self):
        duplicates = []
        name_groups = {}
        pattern = r'(.+?)(?:[\s_-]*\d{3,}|[\s_-]*\d{1,2}|_)?(?:\.\w+)?$'
        
        for file in self.files:
            match = re.match(pattern, file['name'])
            if match:
                base_name = match.group(1)
                if base_name in name_groups:
                    name_groups[base_name].append(file)
                else:
                    name_groups[base_name] = [file]
        
        for base_name, files in name_groups.items():
            if len(files) > 1:
                duplicates.extend(files)
                
        return duplicates
    
    def display_duplicates(self, duplicates):
        self.file_list.clear()
        for file in duplicates:
            self.file_list.addItem(file['path'])
            
    def copy_files(self):
        if not self.file_list.selectedItems():
            QMessageBox.warning(self, "Warning", "No files selected!")
            return
        dest_folder = QFileDialog.getExistingDirectory(self, "Select Destination Folder")
        if dest_folder:
            for item in self.file_list.selectedItems():
                file_path = item.text()
                dest_path = os.path.join(dest_folder, os.path.basename(file_path))
                shutil.copy2(file_path, dest_path)
            QMessageBox.information(self, "Success", "Files copied!")
            
    def zip_files(self):
        if not self.file_list.selectedItems():
            QMessageBox.warning(self, "Warning", "No files selected!")
            return
        zip_path = QFileDialog.getSaveFileName(self, "Save Zip File", "", "Zip Files (*.zip)")[0]
        if zip_path:
            with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
                for item in self.file_list.selectedItems():
                    file_path = item.text()
                    zipf.write(file_path, os.path.basename(file_path))
            QMessageBox.information(self, "Success", "Files zipped!")
        
    def delete_files(self):
        if not self.file_list.selectedItems():
            QMessageBox.warning(self, "Warning", "No files selected!")
            return
        reply = QMessageBox.question(self, "Confirm", "Delete selected files?",
                                  QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
        if reply == QMessageBox.StandardButton.Yes:
            for item in self.file_list.selectedItems():
                os.remove(item.text())
            self.file_list.clear()
            QMessageBox.information(self, "Success", "Files deleted!")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = DuplicateFinder()
    window.show()
    sys.exit(app.exec())

Tuesday, June 24, 2025

Python 3.13.5 : Get bookmarks from Edge browser with python.

Today I tested with these python modules json and pathlib.
This python script will get all bookmarks from Edge browser:
import json
from pathlib import Path

bookmark_path = Path.home() / "AppData/Local/Microsoft/Edge/User Data/Default/Bookmarks"

with open(bookmark_path, "r", encoding="utf-8") as f:
    data = json.load(f)

# Exemplu: listăm toate titlurile bookmark-urilor
def extract_bookmarks(bookmark_node):
    bookmarks = []
    if "children" in bookmark_node:
        for child in bookmark_node["children"]:
            bookmarks.extend(extract_bookmarks(child))
    elif bookmark_node.get("type") == "url":
        bookmarks.append((bookmark_node["name"], bookmark_node["url"]))
    return bookmarks

all_bookmarks = extract_bookmarks(data["roots"]["bookmark_bar"])
for name, url in all_bookmarks:
    print(f"{name}: {url}")

Friday, June 20, 2025

Python 3.13.5 : testing with flask, request and playwright python module.

Today some testing with these python modules: flask, request and playwright.
I used pip to install flask python package:
pip install flask
Collecting flask
  Downloading flask-3.1.1-py3-none-any.whl.metadata (3.0 kB)
...
Installing collected packages: markupsafe, itsdangerous, blinker, werkzeug, jinja2, flask
Successfully installed blinker-1.9.0 flask-3.1.1 itsdangerous-2.2.0 jinja2-3.1.6 markupsafe-3.0.2 werkzeug-3.1.3
pip install requests
...
Installing collected packages: urllib3, idna, charset_normalizer, certifi, requests
Successfully installed certifi-2025.6.15 charset_normalizer-3.4.2 idna-3.10 requests-2.32.4 urllib3-2.5.0
pip install playwright
Collecting playwright
...
Installing collected packages: pyee, greenlet, playwright
Successfully installed greenlet-3.2.3 playwright-1.52.0 pyee-13.0.0
...
playwright install
Downloading Chromium 136.0.7103.25 ...
This will download a lot fo files and the will install the playwright tool.
First script is simple one will try to get cloudflare header on default ip:
from flask import Flask, request

app = Flask(__name__)

@app.route("/")
def detecteaza_ipuri():
    ip_client = request.headers.get('CF-Connecting-IP', 'Necunoscut')
    ip_cloudflare = request.remote_addr
    return (
        f"IP real vizitator: {ip_client}
" f"IP Cloudflare (vizibil de server): {ip_cloudflare}" ) if __name__ == "__main__": app.run(debug=True)
The next one will check more ...
from flask import Flask, request
import requests
import ipaddress

app = Flask(__name__)

def este_ip_cloudflare(ip):
    try:
        raspuns = requests.get("https://www.cloudflare.com/ips-v4")
        raspuns.raise_for_status()
        subneturi = raspuns.text.splitlines()

        for subnet in subneturi:
            if ipaddress.ip_address(ip) in ipaddress.ip_network(subnet):
                return True
        return False
    except Exception as e:
        return f"Eroare la verificarea IP-ului Cloudflare: {e}"

@app.route("/")
def detecteaza_ipuri():
    ip_client = request.headers.get('CF-Connecting-IP', 'Necunoscut')
    ip_cloudflare = request.remote_addr
    rezultat = este_ip_cloudflare(ip_cloudflare)

    return (
        f"IP real vizitator: {ip_client}
" f"IP Cloudflare (forwarder): {ip_cloudflare}
" f"Este IP-ul din rețeaua Cloudflare? {'DA' if rezultat == True else 'NU' if rezultat == False else rezultat}" ) if __name__ == "__main__": app.run(host="0.0.0.0", port=5000)
Now, the script with the request python module:
import requests

url = "https://cobalt.tools"
headers = {
    "User-Agent": "Mozilla/5.0",  # Simulează un browser real
}

try:
    r = requests.get(url, headers=headers, timeout=10)
    content = r.text.lower()

    print(f"Cod răspuns HTTP: {r.status_code}")

    if "cloudflare" in content or "cf-ray" in content or "attention required" in content:
        print("Cloudflare a intermediat cererea sau a blocat-o cu o pagină specială.")
    else:
        print("Cererea a fost servită normal.")
except Exception as e:
    print(f"Eroare la conexiune: {e}")
The last one will use the playwright python module:
import sys
import re
from urllib.parse import urlparse
from pathlib import Path
from playwright.sync_api import sync_playwright

def converteste_url_in_nume_fisier(url):
    parsed = urlparse(url)
    host = parsed.netloc.replace('.', '_')
    path = parsed.path.strip('/').replace('/', '_')
    if not path:
        path = 'index'
    return f"{host}_{path}.txt"

if len(sys.argv) != 2:
    print("Utilizare: python script.py https://exemplu.com")
    sys.exit(1)

url = sys.argv[1]
fisier_output = converteste_url_in_nume_fisier(url)

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    pagina = browser.new_page()
    pagina.goto(url, wait_until='networkidle')
    continut = pagina.content()
    Path(fisier_output).write_text(continut, encoding='utf-8')
    browser.close()

print(f"Conținutul a fost salvat în: {fisier_output}")
This will create a file with the source code of web page.

Sunday, June 8, 2025

News : Python-Fiddle online tool.

Python-Fiddle is an online Python playground where you can write, run, and share Python code directly from the browser without any need to install and maintain Python and packages on your computer. This platform was created make Python programming accessible to everyone and everywhere. We hope to make this a useful tool for learning, teaching, sharing, and collaborating on Python projects.
You can find this online tool on the official website.

Tuesday, May 20, 2025

Python : ... time-travel debugging project.

... ime-travel debugging, a technique that allows developers to "rewind" their code execution and inspect past states.
This is an old GitHub project from four years old.
  • Execution Recording – The debugger logs each step of execution, including variable states and function calls.
  • State Snapshots – It captures snapshots of memory at different points in execution.
  • Reverse Execution – Developers can step backward through the code to analyze previous states.
  • IDE Integration – Some tools integrate with VSCode and PyCharm for seamless debugging
This project is dependent on the following technologies:
  • Node.js / Express
  • Python 3
  • SQLite
  • better-sqlite3
  • Nearley.js / Moo.js
  • TypeScript
  • HTML5 Canvas
  • Webpack
  • gcc / automake
Unfortunately, the Time Traveling Debugger project has only been tested on OSX and Linux, and Windows support is not officially available

Sunday, May 11, 2025

Python Qt6 : simple animation with sprites.

Today I created with addon for Blender 3D and result is an image with sprites ...
I used that image with sprites and PyQt6 to animate my desktop screen, see the result:
This is the source code I used:
import sys
from PyQt6.QtWidgets import QApplication, QLabel, QWidget, QVBoxLayout, QMenu

# diff PyQt6 versus old PyQt
from PyQt6.QtGui import QAction

from PyQt6.QtGui import QPixmap, QIcon
from PyQt6.QtCore import QTimer, Qt

class AnimatedWindow(QWidget):
    def __init__(self):
        super().__init__()

        # set window
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)

        # build layout 
        layout = QVBoxLayout()
        self.label = QLabel(self)
        layout.addWidget(self.label)
        self.setLayout(layout)

        # load sprite sheet from Camera_256px.png file name
        sprite_sheet = QPixmap("Camera_256px.png")  
        self.frame_width = sprite_sheet.width() // 11  # because I have 11 sprite on image
        self.sprites = [sprite_sheet.copy(i * self.frame_width, 0, self.frame_width, sprite_sheet.height()) for i in range(11)]
        self.current_frame = 0

        # 
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_animation)
        self.timer.start(150)  # Schimbă frame-ul la fiecare 150 ms

        # 
        self.resize(self.frame_width, sprite_sheet.height())

        # left down on screen 
        screen = QApplication.primaryScreen().geometry()
        self.move(10, screen.height() - self.height() - 10)

    def update_animation(self):
        """Actualizează sprite-ul în QLabel"""
        self.label.setPixmap(self.sprites[self.current_frame])
        self.current_frame = (self.current_frame + 1) % len(self.sprites)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = AnimatedWindow()
    window.show()
    sys.exit(app.exec())

Saturday, May 3, 2025

Python 3.13.3 : ... Nuitka package works with python 3.12 and MinGW.

Nuitka is licensed under the Apache License, Version 2.0; you may not use it except in compliance with the License.
Nuitka is the Python compiler. It is written in Python. It is a seamless replacement or extension to the Python interpreter and compiles every construct that Python 2 (2.6, 2.7) and Python 3 (3.4 - 3.13) have, when itself run with that Python version.
Nuitka translates the Python modules into a C level program that then uses libpython and static C files of its own to execute in the same way as CPython does.
I used the pip command:
python -m pip install -U nuitka
Collecting nuitka
  Downloading Nuitka-2.7.tar.gz (3.9 MB)
...
Successfully built nuitka
Installing collected packages: zstandard, ordered-set, nuitka
Successfully installed nuitka-2.7 ordered-set-4.1.0 zstandard-0.23.0

[notice] A new release of pip is available: 25.0.1 -> 25.1.1
[notice] To update, run: python.exe -m pip install --upgrade pip
This version of python : 3.13.0rc1 not work !!!
I need to upgrade my version to 3.13.3 version today after I open an issue on github repo!
python.exe -m pip install --upgrade pip
...
Successfully installed pip-25.1.1

python -m nuitka --version
2.7
Commercial: None
Python: 3.13.0rc1 (tags/v3.13.0rc1:e4a3e78, Jul 31 2024, 20:58:38) [MSC v.1940 64 bit (AMD64)]
Flavor: CPython Official
GIL: yes
Executable: C:\Python313\python.exe
OS: Windows
Arch: x86_64
WindowsRelease: 10
Nuitka-Scons:WARNING: Windows SDK must be installed in Visual Studio for it to be usable
Nuitka-Scons:WARNING: with Nuitka. Use the Visual Studio installer for adding it.
Version C compiler: ~\AppData\Local\Nuitka\Nuitka\Cache\downloads\gcc\x86_64\14.2.0posix-19.1.1-12.0.0-msvcrt-r2\mingw64\bin\gcc.exe (gcc 14.2.0).
After upgrade the nuitka show me these results:
python -m nuitka --version
2.7
Commercial: None
Python: 3.13.3 (tags/v3.13.3:6280bb5, Apr  8 2025, 14:47:33) [MSC v.1943 64 bit (AMD64)]
Flavor: CPython Official
GIL: yes
Executable: C:\Python313\python.exe
OS: Windows
Arch: x86_64
WindowsRelease: 10
Nuitka-Scons:WARNING: Windows SDK must be installed in Visual Studio for it to be usable
Nuitka-Scons:WARNING: with Nuitka. Use the Visual Studio installer for adding it.
Version C compiler: ~\AppData\Local\Nuitka\Nuitka\Cache\downloads\gcc\x86_64\14.2.0posix-19.1.1-12.0.0-msvcrt-r2\mingw64\bin\gcc.exe (gcc 14.2.0).
Same error, I uninstall the Python: 3.13.3 version and I install the python version 3.13.0 and use the pip again to install this python package.
python -m pip install -U nuitka
Collecting nuitka
...
Installing collected packages: zstandard, ordered-set, nuitka
Successfully installed nuitka-2.7 ordered-set-4.1.0 zstandard-0.23.0

[notice] A new release of pip is available: 24.2 -> 25.1.1
[notice] To update, run: python.exe -m pip install --upgrade pip
python.exe -m pip install --upgrade pip
Requirement already satisfied: pip in c:\python_3_13_0\lib\site-packages (24.2)
...
Successfully installed pip-25.1.1
Using this version tell me same error with Windows and Visual Studio, but the MinGW is install from the first version.
The solution from artificial intelligence is to use another python version.
I used these commands:
py -3.12 -m pip install -U nuitka
Collecting nuitka
  Using cached Nuitka-2.7.tar.gz (3.9 MB)
  Installing build dependencies ... done
  ...
  Installing collected packages: zstandard, ordered-set, nuitka
Successfully installed nuitka-2.7 ordered-set-4.1.0 zstandard-0.23.0

[notice] A new release of pip is available: 24.2 -> 25.1.1
[notice] To update, run: C:\Python312\python.exe -m pip install --upgrade pip
py -0
 -V:3.13 *        Python 3.13 (64-bit)
 -V:3.12          Python 3.12 (64-bit)
py -3.12 -m nuitka --mingw64 hello.py
Nuitka-Options: Used command line options:
Nuitka-Options:   --mingw64 hello.py
Nuitka-Options:WARNING: You did not specify to follow or include anything but main
Nuitka-Options:WARNING: program. Check options and make sure that is intended.
Nuitka: Starting Python compilation with:
Nuitka:   Version '2.7' on Python 3.12 (flavor 'CPython Official')
Nuitka:   commercial grade 'not installed'.
Nuitka: Completed Python level compilation and optimization.
Nuitka: Generating source code for C backend compiler.
Nuitka: Running data composer tool for optimal constant value handling.
Nuitka: Running C compilation via Scons.
Nuitka-Scons: Backend C compiler: gcc (gcc 14.2.0).
Nuitka-Scons: Backend C linking with 6 files (no progress information available for
Nuitka-Scons: this stage).
Nuitka-Scons: Compiled 6 C files using ccache.
Nuitka-Scons: Cached C files (using ccache) with result 'cache miss': 6
Nuitka: Keeping build directory 'hello.build'.
Nuitka: Successfully created 'D:\PythonProjects\hello.exe'.
Nuitka: Execute it by launching 'hello.cmd', the batch file needs to set environment.
The test is a simple python script from the official website:
def talk(message):
    return "Talk " + message

def main():
    print(talk("Hello World"))

if __name__ == "__main__":
    main()
... and this python version works well with MinGW, the artificial intelligence used to fix these errors was ChatGPT.
hello.exe
Talk Hello World

Thursday, April 24, 2025

Python 3.13.0rc1 : ... fal artificial intelligence and python test.

We have the most-popular models implemented and available as API endpoints for you to start crafting your own AI-powered app today. From the fal.ai website !
You need to set your A.P.I. key from this url.
system32>setx.exe FAL_KEY "e6fd708c-8065-4c73-ac2a-e3c73c6ff0fe:f70e0adb08362a3073993efa31b6acee"

SUCCESS: Specified value was saved.
Open a new terminal and with your editor create this simple example ...
import fal_client

response = fal_client.run("fal-ai/fast-sdxl", arguments={"prompt": "a cute cat, realistic, orange"})
print(response["images"][0]["url"])
Into the terminal run the python script and you will find the url of the image :
python test_fal_client_001.py
https://v3.fal.media/files/rabbit/kY2MZG6LLkzjyIT8J3oiI.jpe
This is the result output of the running source code as 1024px image, see the resize 112px I created:

Tuesday, April 22, 2025

News : Pydantic Releases Sandboxed Python Execution Server.

Pydantic officially announced its broader support for the MCP within the PydanticAI framework around March 20, and now the new tool leverages the Model Context Protocol (MCP), an open standard initiated by Anthropic.
The server achieves isolation by executing code using Pyodide, a Python runtime compiled to WebAssembly.
give AI agents the ability to perform Python-based tasks safely
You can find the Pydantic’s documentation for the tool, available at ai.pydantic.dev .
The Model Context Protocol itself try to solve difficulties in connecting AI models to the diverse external tools and data sources they often need.

Wednesday, April 16, 2025

Python Qt6 : Simple tool to convert HTML.

This is based on old tutorial from this post.
I add a class AgentPY class with all features for processing input and HtmlEditor class for .
Maybe I will use the agentpy module , but now works well without agents.
This is the source code:
from PyQt6.QtWidgets import QApplication, QMainWindow, QTextEdit, QMenu
from bs4 import BeautifulSoup

class AgentPy:
    """Clasă pentru procesarea și curățarea HTML-ului."""
    @staticmethod
    def clean_all_styles(html_content):
        soup = BeautifulSoup(html_content, 'html.parser')
        for tag in soup.find_all(True):
            if tag.name == "a":
                attrs_to_keep = {"href": tag.attrs.get("href")} if "href" in tag.attrs else {}
                tag.attrs = attrs_to_keep
            else:
                tag.attrs = {}
        return str(soup)

    @staticmethod
    def clean_empty_tags(html_content):
        soup = BeautifulSoup(html_content, 'html.parser')
        for tag in soup.find_all(True):
            if not tag.contents or all(str(content).strip() == "" for content in tag.contents):
                tag.decompose()
        return str(soup)

    @staticmethod
    def clean_duplicate_tags(html_content):
        soup = BeautifulSoup(html_content, 'html.parser')
        unique_tags = {}
        for tag in soup.find_all(True):
            tag_key = (tag.name, str(tag.attrs))
            if tag_key in unique_tags:
                tag.decompose()
            else:
                unique_tags[tag_key] = tag
        return str(soup)

    @staticmethod
    def convert_to_html(source_code):
        """Convertim caractere speciale din cod sursă în entități HTML."""
        # Creăm un dicționar pentru conversia caracterelor
        html_entities = {
            '<': '<',
            '>': '>',
            '&': '&',
            '"': '"',
            "'": ''',
            '[': '[',
            ']': ']',
        }
        # Înlocuim caracterele în codul sursă
        for char, entity in html_entities.items():
            source_code = source_code.replace(char, entity)
        return source_code

class HtmlEditor(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("catafest-cleaner-HTML")
        self.setGeometry(100, 100, 800, 600)

        # Editor de text
        self.editor = QTextEdit(self)
        self.setCentralWidget(self.editor)

        # Meniu contextual
        self.editor.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.editor.customContextMenuRequested.connect(self.show_context_menu)

    def show_context_menu(self, position):
        menu = QMenu(self)
        clean_styles_action = menu.addAction("Clean basic HTML")
        clean_styles_action.triggered.connect(self.clean_all_styles)
        clean_empty_tags_action = menu.addAction("Clean Empty Tags")
        clean_empty_tags_action.triggered.connect(self.clean_empty_tags)
        clean_agentpy_action = menu.addAction("Clean AgentPy")
        clean_agentpy_action.triggered.connect(self.clean_duplicate_tags)
        convert_to_html_action = menu.addAction("Convert to HTML")  # Noua opțiune
        convert_to_html_action.triggered.connect(self.convert_to_html)
        menu.exec(self.editor.mapToGlobal(position))

    def clean_all_styles(self):
        html_content = self.editor.toPlainText()
        clean_html = AgentPy.clean_all_styles(html_content)
        self.editor.setPlainText(clean_html)

    def clean_empty_tags(self):
        html_content = self.editor.toPlainText()
        clean_html = AgentPy.clean_empty_tags(html_content)
        self.editor.setPlainText(clean_html)

    def clean_duplicate_tags(self):
        html_content = self.editor.toPlainText()
        clean_html = AgentPy.clean_duplicate_tags(html_content)
        self.editor.setPlainText(clean_html)

    def convert_to_html(self):
        source_code = self.editor.toPlainText()
        html_content = AgentPy.convert_to_html(source_code)
        self.editor.setPlainText(html_content)

if __name__ == "__main__":
    import sys
    from PyQt6.QtCore import Qt
    app = QApplication(sys.argv)
    window = HtmlEditor()
    window.show()
    sys.exit(app.exec())

Sunday, April 13, 2025

Saturday, April 12, 2025

Python Qt6 : Simple tool for clean HTML.

Today I make a simple tool to clean the HTML from style and more. I used artificial inteligence from copilot.
This is the result of this simple tool.
from PyQt6.QtWidgets import QApplication, QMainWindow, QTextEdit, QMenu
from bs4 import BeautifulSoup

class HtmlEditor(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("catafest-cleaner-HTML")  # Titlu actualizat
        self.setGeometry(100, 100, 800, 600)

        # Editor de text
        self.editor = QTextEdit(self)
        self.setCentralWidget(self.editor)

        # Meniu contextual
        self.editor.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.editor.customContextMenuRequested.connect(self.show_context_menu)

    def show_context_menu(self, position):
        menu = QMenu(self)
        clean_styles_action = menu.addAction("Clean basic HTML")
        clean_styles_action.triggered.connect(self.clean_all_styles)
        clean_empty_tags_action = menu.addAction("Clean Empty Tags")
        clean_empty_tags_action.triggered.connect(self.clean_empty_tags)
        menu.exec(self.editor.mapToGlobal(position))

    def clean_all_styles(self):
        # Obține conținutul HTML din editor
        html_content = self.editor.toPlainText()

        # Utilizează BeautifulSoup pentru a procesa HTML-ul
        soup = BeautifulSoup(html_content, 'html.parser')

        # Elimină toate atributele, cu excepția celor din ancorele <a>
        for tag in soup.find_all(True):
            if tag.name == "a":  # Păstrează doar atributul 'href' pentru <a>
                attrs_to_keep = {"href": tag.attrs.get("href")} if "href" in tag.attrs else {}
                tag.attrs = attrs_to_keep
            else:
                tag.attrs = {}  # Elimină toate atributele pentru celelalte tag-uri

        # Actualizează conținutul editorului
        clean_html = str(soup)
        self.editor.setPlainText(clean_html)

    def clean_empty_tags(self):
        # Obține conținutul HTML din editor
        html_content = self.editor.toPlainText()

        # Utilizează BeautifulSoup pentru a procesa HTML-ul
        soup = BeautifulSoup(html_content, 'html.parser')

        # Elimină tag-urile goale
        for tag in soup.find_all(True):
            # Verifică tag-uri goale
            if not tag.contents or all(str(content).strip() == "" for content in tag.contents):  
                tag.decompose()  # Elimină tag-ul complet

        # Actualizează conținutul editorului
        clean_html = str(soup)
        self.editor.setPlainText(clean_html)

if __name__ == "__main__":
    import sys
    from PyQt6.QtCore import Qt
    app = QApplication(sys.argv)
    window = HtmlEditor()
    window.show()
    sys.exit(app.exec())

Friday, April 11, 2025

Python 3.13.0rc1 : pig for AI-powered automation.

Pig is an API for AI-powered automation of Windows desktop applications and workflows. It allows AI agents to remotely navigate user interfaces and interact with software on Windows computers, even for applications without public APIs. Organizations might use Pig to automate complex, repetitive tasks involving legacy enterprise software, overcome limitations of traditional robotic process automation tools, and reduce the need for manual data handling by human workers.
Follow the install from the official website.
pip install pig-python
Collecting pig-python
...
Successfully installed aiohttp-retry-2.9.1 click-8.1.8 iso8601-2.1.0 pig-python-0.1.2 simple-term-menu-1.6.6 tabulate-0.9.0
From the API Keys url get the key and run a server:
piglet join --secret the_API_key
Display dimensions: 1280x720
Local server running at http://localhost:3000
Connected to control server
The local machine can be found on this webpage.
I go to machine chat and I ask to create a source script in python for test the artificial intelligence.
It looks like you're encountering an error with the Pig API. The error message indicates that the API key hasn't been set properly. To resolve this issue, you need to set the PIG_SECRET_KEY environment variable or pass the API key directly to the Client constructor when initializing the Pig client. Would you like me to help you with setting up the environment variable or modifying your code to include the API key in the Client constructor? yes , I need a python script example
The remote artificial intelligence machine move the mouse and open notepad, add source code and save to my desktop.
I add my API key and I run it, see the result:
This source script is the result of artificial intelligence processing
"""
Example script showing how to properly initialize the Pig client with an API key
using both environment variable and direct constructor methods.
"""

import os
from pig import Client

# Example API key (replace with your actual API key in production)
API_KEY = "SK-..."

def initialize_with_env_variable():
    """
    Method 1: Initialize Pig client using environment variable
    This is the recommended approach for production environments
    """
    # Set the environment variable
    os.environ["PIG_SECRET_KEY"] = API_KEY
    
    # Initialize the client (it will automatically use the environment variable)
    client = Client()
    
    print("Client initialized using environment variable")
    return client

def initialize_with_direct_key():
    """
    Method 2: Initialize Pig client by passing the API key directly
    Useful for testing or when environment variables are not preferred
    """
    # Initialize the client by passing the API key directly to the constructor
    client = Client(api_key=API_KEY)
    
    print("Client initialized by passing API key directly")
    return client

if __name__ == "__main__":
    # Example 1: Using environment variable
    client1 = initialize_with_env_variable()
    
    # Example 2: Passing API key directly
    client2 = initialize_with_direct_key()
    
    # Both methods achieve the same result
    print("Both initialization methods are complete!")

Thursday, April 3, 2025

Python 3.13.0rc1 : Draw L-System with turtle package.

You can find the turtle python package documentation on the official webpage.
The random python package is default on any python.
import turtle
import random

# Funcții L-System
def generate_lsystem(axiom, rules, iterations):
    """Generarea L-System bazată pe reguli de producție."""
    for _ in range(iterations):
        new_axiom = ""
        for char in axiom:
            new_axiom += rules.get(char, char)
        axiom = new_axiom
    return axiom

def draw_lsystem(axiom, length):
    """Desenarea L-System utilizând turtle."""
    for char in axiom:
        if char == "|":  # Desenează linia
            turtle.forward(length)
        elif char == "+":  # Rotire la dreapta
            angle = random.choice([0,60,120])  # Alegere aleatorie a unghiului
            turtle.right(angle)
            print(f"Rotire dreapta cu {angle} grade.")
        elif char == "-":  # Rotire la stânga
            angle = random.choice([-120,-60])  # Alegere aleatorie a unghiului
            turtle.left(angle)
            print(f"Rotire stânga cu {angle} grade.")
    return angle

# Setări pentru L-System
#axiom = "|---|--+|-+-|+--|+--|+-+|-+-"  # Axioma de bază
axiom = "|---|---|---|---|---+|---+|---" 
rules = {
    "|": "|+|--|-",  # Reguli pentru extensia liniei cu rotații aleatorii
    "+": "+",
    "-": "-"
}

# Generare axiomă nouă după reguli
iterations = 3  # Număr de iterații pentru dezvoltarea L-System
length = 10 # Lungimea fiecărei linii
final_axiom = generate_lsystem(axiom, rules, iterations)


# Inițializare Turtle
turtle.speed(0)
turtle.penup()
turtle.goto(0, 0)  # Poziționare inițială
turtle.pendown()

# Desenare L-System
draw_lsystem(final_axiom, length)

# Finalizare
turtle.hideturtle()
turtle.done()

Wednesday, March 26, 2025

Python 3.11.11 : Colab simple test with CogVideoX-5B model and default example - part 050.

I tested this GitHub project from THUDM user on my colab google account and works well with CogVideoX-5B model.
You can find the default implementation on my colab GitHub repo.
The default example comes with thjs prompt:
prompt = ( "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. " "The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other " "pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, " "casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. " "The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical " "atmosphere of this unique musical performance." )
The speed of rendering starts from :
38% ... 19/50 [30:54<50:57, 98.61s/it] using T4 GPU
... then run at :
100% ... 50/50 [1:26:09<00:00, 109.87s/it]
when the video render was 100% somehow google give this error, but the source code run well:
OutOfMemoryError: CUDA out of memory. Tried to allocate 1.32 GiB. GPU 0 has a total capacity of 14.74 GiB of which 654.12 MiB is free. Process 26970 has 14.10 GiB memory in use. Of the allocated memory 12.97 GiB is allocated by PyTorch, and 1.00 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)
I think is need to set some extra memory on CUDA but this require to parse some documentation and is not a task for me now.

Saturday, March 22, 2025

Python 3.11.11 : Colab simple test with VGG16 - part 049.

VGG16 is a deep convolutional neural network (CNN) trained on a massive image dataset called ImageNet. This architecture is known for its remarkable performance in image classification tasks and is widely used in various computer vision applications.
You can find one simple example on my GitHub project.

Saturday, March 15, 2025

Python 3.13.0rc1 : strange crash of Python running ...

... my windows 10 crash the python running ... this is the output of crash:

Python Qt6 : Dependency checker for python packages with pipdeptree and PyQt6.

Today I created this python script to test and check python package dependency.
You need to install the pipdeptree with the pip tool.
I used the Python 3.13.0rc1 version and the result is this:
This is the source code I used:
import sys
import subprocess
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QVBoxLayout, QTreeWidget, QTreeWidgetItem, QWidget
)
from PyQt6.QtWidgets import QHeaderView
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QStyle


class DependencyViewer(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Dependency Checker")

        # Maximizarea ferestrei la lansare
        self.showMaximized()

        # Creează un QTreeWidget pentru afișarea dependențelor
        self.tree_widget = QTreeWidget()
        self.tree_widget.setHeaderLabels(["Dependency", "Status"])

        # Ajustează aliniamentul central pentru fiecare coloană
        for i in range(2):  # Pentru cele două coloane
            self.tree_widget.headerItem().setTextAlignment(i, Qt.AlignmentFlag.AlignCenter)

        # Configurarea automată a lățimii coloanelor
        self.tree_widget.header().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)

        # Layout
        layout = QVBoxLayout()
        layout.addWidget(self.tree_widget)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

        # Obține și afișează dependențele
        self.display_dependencies()

    def display_dependencies(self):
        try:
            # Rulează pipdeptree pentru a obține ierarhia dependențelor
            result = subprocess.run(['pipdeptree', '--warn', 'silence'], capture_output=True, text=True)
            dependencies = result.stdout.splitlines()

            for line in dependencies:
                # Determină nivelul de indentare pentru ierarhia dependențelor
                indent_level = len(line) - len(line.lstrip())
                dependency_name = line.strip()

                # Creează un item pentru fiecare dependență
                item = QTreeWidgetItem([dependency_name])

                # Atribuie iconițe pe baza compatibilității (exemplu simplificat)
                if "(*)" in dependency_name:  # Exemplu de incompatibilitate (poți schimba după caz)
                    item.setIcon(0, self.style().standardIcon(QStyle.StandardPixmap.SP_DialogCancelButton))
                    item.setText(1, "Incompatible")
                else:
                    item.setIcon(0, self.style().standardIcon(QStyle.StandardPixmap.SP_DialogApplyButton))
                    item.setText(1, "Compatible")

                # Adaugă item-ul în arbore
                if indent_level == 0:
                    self.tree_widget.addTopLevelItem(item)
                else:
                    # Alege ultimul item părinte și adaugă dependența ca sub-item
                    parent_item = self.tree_widget.topLevelItem(self.tree_widget.topLevelItemCount() - 1)
                    parent_item.addChild(item)

            # Extinde toate elementele din arbore
            self.tree_widget.expandAll()

        except Exception as e:
            error_item = QTreeWidgetItem(["Error", str(e)])
            error_item.setIcon(0, self.style().standardIcon(QStyle.StandardPixmap.SP_MessageBoxCritical))
            self.tree_widget.addTopLevelItem(error_item)


if __name__ == "__main__":
    from PyQt6.QtCore import Qt

    app = QApplication(sys.argv)
    viewer = DependencyViewer()
    viewer.show()
    sys.exit(app.exec())

Wednesday, March 12, 2025

Python 3.13.0rc1 : testing the new Kivy-2.3.1 with default examples.

Today I tested the Kivy-2.3.1 with Python 3.13.0rc1.
Read more on the official webpage.
The install step is easy with the pip tool:
python -m pip install kivy
Collecting kivy
...
Installing collected packages: kivy-deps.sdl2, kivy-deps.glew, kivy-deps.angle, filetype, pypiwin32, pygments, docutils, Kivy-Garden, kivy
Successfully installed Kivy-Garden-0.1.5 docutils-0.21.2 filetype-1.2.0 kivy-2.3.1 kivy-deps.angle-0.4.0 kivy-deps.glew-0.3.1 kivy-deps.sdl2-0.8.0 pygments-2.19.1 pypiwin32-223
Let's install the kivy examples source code:
python -m pip install --pre "kivy[base]" kivy_examples
Collecting kivy_examples
...
Installing collected packages: kivy_examples
Successfully installed kivy_examples-2.3.1
You can test these examples with this command into the python folder:
C:\Python313\share\kivy-examples>python demo\showcase\main.py
[WARNING] [Config      ] Older configuration version detected (0 instead of 27)
[WARNING] [Config      ] Upgrading configuration in progress.
[DEBUG  ] [Config      ] Upgrading from 0 to 1
This is the result: