analitics

Pages

Friday, April 25, 2025

Python 3.13.0rc1 : using gTTS version 2.5.4 python package.

gTTS (Google Text-to-Speech), a Python library and CLI tool to interface with Google Translate text-to-speech API
pip install gTTS
Collecting gTTS
  Downloading gTTS-2.5.4-py3-none-any.whl.metadata (4.1 kB)
...
Installing collected packages: gTTS
Successfully installed gTTS-2.5.4
simple python script with one example : create an audio file in romanian language.
from gtts import gTTS
tts = gTTS('Azi este 25 aprilie 2025', lang='ro', tld='ro')
tts.save('azi25.mp3')

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!")

Saturday, April 5, 2025

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()