analitics

Pages

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

Monday, December 15, 2025

Python Qt6 : ... tool for testing fonts.

Today I created a small Python script with PyQt6 using artificial intelligence. It is a tool that takes a folder of fonts, allows to select their size, displays the font size in pixels for Label text from the Godot engine and downloads only the selection of fonts that I like. I have not tested it to see the calculations with Godot, but it seems functional...

Saturday, December 13, 2025

Python Qt6 : ... search custom data in files with python and PyQt6.

The other day I noticed that I can't find what I worked on in the past, some files were blocked... Another task was blocking the artificial intelligence due to the number of uses. I could have used artificial intelligence to open old projects and ask where what I worked on is, but it would be a risk to waste my queries. Since I always use a specific signature when working on separate projects and the backup is distributed on storage that is always filling up, I created a simple script that would search for my custom with custom files, custom content and output a spreader with them. Here is the result of a 310-line source code script, obviously created with artificial intelligence.

Wednesday, December 10, 2025

Python 3.13.0 : ... simple script for copilot history.

NOTES: I have been using artificial intelligence since it appeared, it is obviously faster and more accurate, I recommend using testing on larger projects.
This python script will take the database and use to get copilot history and save to file copilot_conversations.txt :
import os
import sqlite3
import datetime
import requests
from bs4 import BeautifulSoup
import shutil

# Locația tipică pentru istoricul Edge (Windows)
edge_history_path = os.path.expanduser(
    r"~\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\History"
)

# Copiem fișierul History în folderul curent
def copy_history_file(src_path, dst_name="edge_history_copy.db"):
    if not os.path.exists(src_path):
        print("Nu am găsit istoricul Edge.")
        return None
    dst_path = os.path.join(os.getcwd(), dst_name)
    try:
        shutil.copy(src_path, dst_path)
        print(f"Am copiat baza de date în {dst_path}")
        return dst_path
    except Exception as e:
        print(f"Eroare la copiere: {e}")
        return None

def extract_copilot_links(db_path):
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    cursor.execute("""
        SELECT url, title, last_visit_time
        FROM urls
        WHERE url LIKE '%copilot%'
    """)

    results = []
    for url, title, last_visit_time in cursor.fetchall():
        ts = datetime.datetime(1601, 1, 1) + datetime.timedelta(microseconds=last_visit_time)
        results.append({
            "url": url,
            "title": title,
            "last_visit": ts.strftime("%Y-%m-%d %H:%M:%S")
        })

    conn.close()
    return results

def fetch_conversation(url):
    try:
        resp = requests.get(url)
        if resp.status_code == 200:
            soup = BeautifulSoup(resp.text, "html.parser")
            texts = soup.get_text(separator="\n", strip=True)
            return texts
        else:
            return f"Eroare acces {url}: {resp.status_code}"
    except Exception as e:
        return f"Eroare acces {url}: {e}"

if __name__ == "__main__":
    copy_path = copy_history_file(edge_history_path)
    if copy_path:
        chats = extract_copilot_links(copy_path)
        if chats:
            with open("copilot_conversations.txt", "w", encoding="utf-8") as f:
                for chat in chats:
                    content = fetch_conversation(chat["url"])
                    f.write(f"=== Conversație: {chat['title']} ({chat['last_visit']}) ===\n")
                    f.write(content)
                    f.write("\n\n")
            print("Am salvat conversațiile în copilot_conversations.txt")
        else:
            print("Nu am găsit conversații Copilot în istoricul Edge.")

Saturday, December 6, 2025

News : Python 3.14.1 and Python 3.13.10 are now available!

... these are good news from 2 december 2025:
Python 3.14.1 is the first maintenance release of 3.14, containing around 558 bugfixes, build improvements and documentation changes since 3.14.0.
Python 3.13.10 is the tenth maintenance release of 3.13, containing around 300 bugfixes, build improvements and documentation changes since 3.13.9.
Read more on the official blogger.

Friday, December 5, 2025

Python Qt6 : ... data generator tool for a custom format file.

Today I finished a data generator tool for a custom format for a game. The idea is that PyQt6 is versatile and very useful for a developer. This tool generates data in the 2D area of a screen and saves them in a defined format, in this case a position and a size for a text ...
Here is the class for custom range selection sliders.
class RangeSlider(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._min, self._max = 0, 1000
        self._start, self._end = 0, 1000
        self._dragging = None
        self.setMinimumHeight(24)

    def setRange(self, minimum, maximum):
        self._min, self._max = minimum, maximum
        self._start, self._end = minimum, maximum
        self.update()

    def setStart(self, val):
        self._start = max(self._min, min(val, self._end))
        self.update()

    def setEnd(self, val):
        self._end = min(self._max, max(val, self._start))
        self.update()

    def start(self): return self._start
    def end(self): return self._end

    def _pos_to_val(self, x):
        w = self.width()
        ratio = max(0, min(x, w)) / w if w else 0
        return int(self._min + ratio*(self._max-self._min))

    def _val_to_pos(self, val):
        w = self.width()
        return int((val-self._min)/(self._max-self._min)*w) if self._max>self._min else 0

    def mousePressEvent(self, e):
        x = e.position().x()
        sx, ex = self._val_to_pos(self._start), self._val_to_pos(self._end)
        self._dragging = "start" if abs(x-sx)<abs(x-ex) else "end"
        self.mouseMoveEvent(e)

    def mouseMoveEvent(self, e):
        if self._dragging:
            val = self._pos_to_val(int(e.position().x()))
            if self._dragging=="start": self.setStart(val)
            else: self.setEnd(val)

    def mouseReleaseEvent(self,e): self._dragging=None

    def paintEvent(self,e):
        p=QPainter(self); rect=self.rect()
        sx,ex=self._val_to_pos(self._start),self._val_to_pos(self._end)
        p.fillRect(rect,QColor(220,220,220))
        p.fillRect(QRect(QPoint(sx,0),QPoint(ex,rect.height())),QColor(100,200,100,120))
        p.setBrush(QColor(50,120,200)); p.setPen(Qt.PenStyle.NoPen)
        p.drawEllipse(QPoint(sx,rect.center().y()),6,6)
        p.drawEllipse(QPoint(ex,rect.center().y()),6,6)

Wednesday, December 3, 2025

Python 3.13.0 : ... playwright - part 001.

Playwright for Python is a modern automation library that allows developers to control browsers like Chromium, Firefox, and WebKit. It is widely used for testing, scraping, and simulating real user interactions.
The package provides an asynchronous API, enabling fast and reliable automation. Developers can launch browsers, navigate to pages, fill forms, click buttons, and capture results with minimal code.
In practice, Playwright is useful for tasks such as automated testing, repetitive searches, data collection, and simulating human-like browsing behavior across multiple browsers.
The example script demonstrates how to open Firefox, navigate to Google, perform a series of searches, scroll the page, and pause between actions to mimic natural user activity.
Additionally, the script saves each search query into a text file, creating a simple log of performed searches. This shows how Playwright can combine browser automation with file handling for practical workflows.
I used the pip tool then I install the playwright:
pip install playwright
playwright install
Let's see the script:
import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.firefox.launch(headless=False)
        context = await browser.new_context()
        page = await context.new_page()

        await page.goto("https://www.google.com")

        queries = [
            "python automation",
            "playwright tutorial",
            "google search automation"
        ]

        with open("results.txt", "w", encoding="utf-8") as f:
            for q in queries:
                # Fill search box
                await page.fill("textarea[name='q']", q)
                await page.press("textarea[name='q']", "Enter")
                await page.wait_for_load_state("domcontentloaded")

                # Scroll + pause
                await page.evaluate("window.scrollBy(0, document.body.scrollHeight)")
                await page.wait_for_timeout(3000)

                # Extract search results (titles + links)
                results = await page.query_selector_all("h3")
                f.write(f"\nResults for: {q}\n")
                for r in results[:5]:  # primele 5 rezultate
                    title = await r.inner_text()
                    link_el = await r.evaluate_handle("node => node.parentElement")
                    link = await link_el.get_attribute("href")
                    f.write(f"- {title} ({link})\n")

                print(f"Saved results for: {q}")

        await browser.close()

asyncio.run(main())
Then I run with this command:
python google_search_test_001.py
Saved results for: python automation
Saved results for: playwright tutorial
Saved results for: google search automation
Need to click to accept on browser ... , and some basic result on results.txt file:

Results for: python automation

Results for: playwright tutorial
- Playwright: Fast and reliable end-to-end testing for modern ... 

Sunday, November 30, 2025

News : the xonsh shell language and command prompt.

Xonsh is a modern, full-featured and cross-platform python shell. The language is a superset of Python 3.6+ with additional shell primitives that you are used to from Bash and IPython. It works on all major systems including Linux, OSX, and Windows. Xonsh is meant for the daily use of experts and novices.
The install is easy with pip tool:
python -m pip install 'xonsh[full]'

Python 3.13.0 : mitmproxy - part 001.

Mitmproxy is an interactive, open‑source proxy tool that lets you intercept, inspect, and modify HTTP and HTTPS traffic in real time. It acts as a "man‑in‑the‑middle" between your computer and the internet, making it possible to debug, test, or analyze how applications communicate online.
Why Python?
  • Mitmproxy is built in Python and exposes a powerful addon API
  • You can write custom scripts to automate tasks and traffic manipulation
  • Block or rewrite requests and responses with flexible logic
  • Inject headers or simulate server responses for testing
  • Integrate with other Python tools for advanced automation
  • Intercept and inspect HTTP and HTTPS traffic in real time
  • Modify requests and responses dynamically with Python scripts
  • Block specific hosts or URLs to prevent unwanted connections
  • Inject custom headers into outgoing requests for debugging or control
  • Rewrite response bodies (HTML, JSON, text) using regex or custom logic
  • Log and save traffic flows for later analysis and replay
  • Simulate server responses to test client behavior offline
  • Automate testing of web applications and APIs with scripted rules
  • Monitor performance metrics such as latency and payload size
  • Integrate with other Python tools for advanced automation and analysis
  • Use a trusted root certificate to decrypt and modify HTTPS traffic securely
Let's install:
pip install mitmproxy
Let's see the python script:
# addon.py
from mitmproxy import http
from mitmproxy import ctx
import re

BLOCKED_HOSTS = {
    "hyte.com",
    "ads.example.org",
}

REWRITE_RULES = [
    # Each rule: (pattern, replacement, content_type_substring)
    (re.compile(rb"Hello World"), b"Salut lume", "text/html"),
    (re.compile(rb"tracking", re.IGNORECASE), b"observare", "text"),
]

ADD_HEADERS = {
    "X-Debug-Proxy": "mitm",
    "X-George-Tool": "true",
}

class GeorgeProxy:
    def __init__(self):
        self.rewrite_count = 0

    def load(self, loader):
        ctx.log.info("GeorgeProxy addon loaded.")

    def request(self, flow: http.HTTPFlow):
        # Block specific hosts early
        host = flow.request.host
        if host in BLOCKED_HOSTS:
            flow.response = http.Response.make(
                403,
                b"Blocked by GeorgeProxy",
                {"Content-Type": "text/plain"}
            )
            ctx.log.warn(f"Blocked request to {host}")
            return

        # Add custom headers to outgoing requests
        for k, v in ADD_HEADERS.items():
            flow.request.headers[k] = v

        ctx.log.info(f"REQ {flow.request.method} {flow.request.url}")

    def response(self, flow: http.HTTPFlow):
        # Only process text-like contents
        ctype = flow.response.headers.get("Content-Type", "").lower()
        raw = flow.response.raw_content

        if raw and any(t in ctype for t in ["text", "html", "json"]):
            new_content = raw
            for pattern, repl, t in REWRITE_RULES:
                if t in ctype:
                    new_content, n = pattern.subn(repl, new_content)
                    self.rewrite_count += n

            if new_content != raw:
                flow.response.raw_content = new_content
                # Update Content-Length only if present
                if "Content-Length" in flow.response.headers:
                    flow.response.headers["Content-Length"] = str(len(new_content))
                ctx.log.info(f"Rewrote content ({ctype}); total matches: {self.rewrite_count}")

        ctx.log.info(f"RESP {flow.response.status_code} {flow.request.url}")

addons = [GeorgeProxy()]
Let's run it:
mitmdump -s addon.py
[21:46:04.435] Loading script addon.py
[21:46:04.504] GeorgeProxy addon loaded.
[21:46:04.506] HTTP(S) proxy listening at *:8080.
[21:46:18.547][127.0.0.1:52128] client connect
[21:46:18.593] REQ GET http://httpbin.org/get
[21:46:18.768][127.0.0.1:52128] server connect httpbin.org:80 (52.44.182.178:80)
[21:46:18.910] RESP 200 http://httpbin.org/get
127.0.0.1:52128: GET http://httpbin.org/get
              << 200 OK 353b
[21:46:19.019][127.0.0.1:52128] client disconnect
[21:46:19.021][127.0.0.1:52128] server disconnect httpbin.org:80 (52.44.182.178:80)
Let's see the result:
curl -x http://127.0.0.1:8080 http://httpbin.org/get
{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Host": "httpbin.org",
    "Proxy-Connection": "Keep-Alive",
    "User-Agent": "curl/8.13.0",
    "X-Amzn-Trace-Id": "Root=1-692c9f0b-7eaf43e61f276ee62b089933",
    "X-Debug-Proxy": "mitm",
    "X-George-Tool": "true"
  },
  "origin": "84.117.220.94",
  "url": "http://httpbin.org/get"
}
This means
The request successfully went through mitmproxy running on 127.0.0.1:8080. Your addon worked: it injected the custom headers (X-Debug-Proxy, X-George-Tool). The httpbin.org echoed back the request details, showing exactly what the server received.

Python 3.13.0 : Tornado - part 001.

Python Tornado is a high‑performance web framework and asynchronous networking library designed for extreme scalability and real‑time applications. Its standout capability is handling tens of thousands of simultaneous connections efficiently, thanks to non‑blocking I/O.
This is an open source project actively maintained and available on tornadoweb.org.

Python Tornado – Key Capabilities

  • Massive Concurrency: Tornado can scale to tens of thousands of open connections without requiring huge numbers of threads.
  • Non‑blocking I/O: Its asynchronous design makes it ideal for apps that need to stay responsive under heavy load.
  • WebSockets Support: Built‑in support for WebSockets enables real‑time communication between clients and servers.
  • Long‑lived Connections: Perfect for long polling, streaming, or chat applications where connections remain open for extended periods.
  • Coroutines & Async/Await: Tornado integrates tightly with Python’s asyncio, allowing developers to write clean asynchronous code using coroutines.
  • Versatile Use Cases: Beyond web apps, Tornado can act as an HTTP client/server, handle background tasks, or integrate with other services.
Tornado setup: The script creates a web server using the Tornado framework, listening on port 8888.
Route definition: A single route /form is registered, handled by the FormHandler class.
GET request: When you visit http://localhost:8888/form, the server responds with an HTML page (form.html) that contains a simple input form.
POST request: When the form is submitted, the post() method retrieves the value of the name field using self.get_argument("name").
Response: The server then sends back a personalized message
Let's see the script:
import tornado.ioloop
import tornado.web
import os

class FormHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("form.html")  # Render an HTML form

    def post(self):
        name = self.get_argument("name")
        self.write(f"Hello, {name}!")

def make_app():
    return tornado.web.Application([
        (r"/form", FormHandler),
    ],
    template_path=os.path.join(os.path.dirname(__file__), "templates")  # <-- aici
    )

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    print("Server pornit pe http://localhost:8888/form")
    tornado.ioloop.IOLoop.current().start()

Thursday, October 30, 2025

Python 3.13.0 : xAI A.P.I. with regional endpoint on xai_sdk python package.

Grok is a family of Large Language Models (LLMs) developed by xAI.
Inspired by the Hitchhiker's Guide to the Galaxy, Grok is a maximally truth-seeking AI that provides insightful, unfiltered truths about the universe.
xAI offers an API for developers to programmatically interact with our Grok models. The same models power our consumer facing services such as Grok.com, the iOS and Android apps, as well as Grok in X experience.
If you want to use a regional endpoint, you need to specify the endpoint url when making request with SDK. In xAI SDK, this is specified through the api_host parameter.
Is not free models available for xAI A.P.I.
See this example from the official website:
import os

from xai_sdk import Client
from xai_sdk.chat import user

client = Client(
api_key=os.getenv("XAI_API_KEY"),
api_host="us-east-1.api.x.ai" # Without the https://
)

chat = client.chat.create(model="grok-4")
chat.append(user("What is the meaning of life?"))

completion = chat.sample()

Thursday, October 23, 2025

Python 3.13.0 : OneByteRadar - pymem python package.

Today, I found this GitHub project about how to write to exe files with python programming language
The author say:
CS:GO radar hack achieved by patching one byte of game memory. Written in Python 3.
I don't test it, but good to know how can use these python modules.
The pymem Python library that allows you to interact with the memory of running Windows processes.
  • Reading and writing memory values of other processes
  • Scanning memory for byte patterns
  • Allocating and freeing memory inside another process
  • Accessing modules (DLLs) loaded by a process
  • This is often used in game hacking, automation, or debugging tools.
NOTE: I used artificial intelligence to write this simple example, it is more productive in programs with more complex syntax, but the basics of programming must be known...
Let's see one example with edge browser open:
import pymem
import pymem.process
import re

# Open the Edge process (make sure it's running)
pm = pymem.Pymem("msedge.exe")

# Get the main module of the process
module = pymem.process.module_from_name(pm.process_handle, "msedge.exe")
base = module.lpBaseOfDll
size = module.SizeOfImage

# Read the module's memory
data = pm.read_bytes(base, size)

# Search for a test pattern (generic example)
pattern = re.search(rb'\x48\x89\x5C\x24\x08\x57\x48\x83', data)

if pattern:
    address = base + pattern.start()
    print(f"Pattern found at: {hex(address)}")

    # Read 8 bytes from the found address
    raw = pm.read_bytes(address, 8)
    print("Raw bytes:", raw)

    # Interpret the bytes as a little-endian integer
    value = int.from_bytes(raw, byteorder='little')
    print("Integer value:", value)

    # Write a new value (e.g., 12345678)
    new_value = (12345678).to_bytes(8, byteorder='little')
    pm.write_bytes(address, new_value, 8)
    print("Value overwritten with 12345678.")

else:
    print("Pattern not found.")

# Close the process handle
pm.close_process()
What is that patern:
pattern = re.search(rb'\x48\x89\x5C\x24\x08\x57\x48\x83', data)
These bytes correspond to x86-64 assembly instructions. For example:

48 89 5C 24 08 → mov [rsp+8], rbx
57 → push rdi
48 83 → the start of an instruction like add/sub/cmp with a 64-bit operand
This sequence is typical for the prologue of a function in compiled C++ code — saving registers to the stack.
This is a simple example, you don't see anything in edge because is just one search and one overwritten:
python pymem_exemple_002.py
Pattern found at: 0x7ff7180cb3d5
Raw bytes: b'H\x89\\$\x08WH\x83'
Integer value: 9459906709773125960
Value overwritten with 12345678.
You replaced those 8 bytes with the integer 12345678, encoded as: 4E 61 BC 00 00 00 00 00 (in hex)
This corrupts the original instruction, which may crash Edge or cause undefined behavior.
Not crash, maybe my edge browser use protections (ASLR, DEP, CFG) that can make modification unstable.
--------
1. ASLR (Address Space Layout Randomization)
2. DEP (Data Execution Prevention)
3. CFG (Control Flow Guard)

Monday, October 20, 2025

Python Qt6 : tool for remove duplicate files ...

Today I created a Python script with PyQt6 that allows me to remove duplicate files based on three ways of selecting the type of duplicate.
The script also makes an estimate of the execution time...
Because the source code is relatively simple and can be very easily reconstructed with the help of artificial intelligence, I am not adding it to the posts.
Here is what the application looks like with PyQt6.

Saturday, October 18, 2025

Blender 3D : ... simple clothing addon.

Today, I created a simple clothing addon with a two-mesh coat. The addon adds everything needed for the simulation including material types for the clothes.

Python Qt6 : tool for cutting images ...

Today I made a script that allows adding custom horizontal and vertical sliders to an image and, depending on the custom distance between them, cuts the image into squares of different sizes.

Python Qt6 : tool for renaming files with creation date .

Since this hacking and the crashes... I've always taken screenshots... Today I created a small script that takes files from a folder and renames them with the creation date in this format...yyyyMMdd_HHmmss .
... obviously artificial intelligence helped me.
This is the source code :
import sys
import os
import shutil
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QFileDialog, QMessageBox
from PyQt6.QtCore import QDateTime

class FileRenamer(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Redenumire fișiere cu dată și index")
        self.setGeometry(100, 100, 400, 150)

        layout = QVBoxLayout()

        self.button = QPushButton("Selectează folderul și redenumește fișierele")
        self.button.clicked.connect(self.rename_files)
        layout.addWidget(self.button)

        self.setLayout(layout)

    def rename_files(self):
        folder = QFileDialog.getExistingDirectory(self, "Selectează folderul")
        if not folder:
            return

        files = [f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]
        files.sort()  # Sortează pentru consistență

        for index, filename in enumerate(files, start=1):
            old_path = os.path.join(folder, filename)
            try:
                creation_time = os.path.getctime(old_path)
                dt = QDateTime.fromSecsSinceEpoch(int(creation_time))
                date_str = dt.toString("yyyyMMdd_HHmmss")
                ext = os.path.splitext(filename)[1]
                new_name = f"{date_str}_{index:03d}{ext}"
                new_path = os.path.join(folder, new_name)

                # Evită suprascrierea fișierelor existente
                if not os.path.exists(new_path):
                    shutil.move(old_path, new_path)
            except Exception as e:
                QMessageBox.critical(self, "Eroare", f"Eroare la fișierul {filename}:\n{str(e)}")
                continue

        QMessageBox.information(self, "Succes", "Fișierele au fost redenumite cu succes!")

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

Saturday, October 4, 2025

Friday, September 26, 2025

Python Qt6 : tool for game development with PNG images.

Today, I worked with art artificial intelligence, to create tool for my game development.
I used python and PyQt6 and this tool help me to remove border, resize, split, rename and save images as PNG file type for Godot game engine.

Wednesday, September 24, 2025

Python 3.10.7 : Krita and python - part 002.

A simple source code to export PNG file for Godot game engine as Texture2D .
from krita import *
from PyQt5.QtWidgets import QAction, QMessageBox
import os

class ExportGodotPNG(Extension):
    def __init__(self, parent):
        super().__init__(parent)

    def setup(self):
        pass

    def export_png(self):
        # Get the active document
        doc = Krita.instance().activeDocument()
        if not doc:
            QMessageBox.warning(None, "Error", "No document open! Please open a document and try again.")
            return

        # Create an InfoObject for PNG export
        info = InfoObject()
        info.setProperty("alpha", True)  # Keep alpha channel for transparency
        info.setProperty("compression", 0)  # No compression for maximum quality
        info.setProperty("interlaced", False)  # Disable interlacing
        info.setProperty("forceSRGB", True)  # Force sRGB for Godot compatibility

        # Build the output file path
        if doc.fileName():
            base_path = os.path.splitext(doc.fileName())[0]
        else:
            base_path = os.path.join(os.path.expanduser("~"), "export_godot")
        output_file = base_path + "_godot.png"

        # Export the document as PNG
        try:
            doc.exportImage(output_file, info)
            # Show success message with brief usage info
            QMessageBox.information(None, "Success", 
                f"Successfully exported as PNG for Godot: {output_file}\n\n"
                "This PNG has no compression, alpha channel support, and sRGB for Godot compatibility. "
                "To use in Godot, import the PNG and adjust texture settings as needed."
            )
        except Exception as e:
            QMessageBox.critical(None, "Error", f"Export failed: {str(e)}")

    def createActions(self, window):
        # Create only the export action in Tools > Scripts
        action_export = window.createAction("export_godot_png", "Export Godot PNG", "tools/scripts")
        action_export.triggered.connect(self.export_png)

# Register the plugin
Krita.instance().addExtension(ExportGodotPNG(Krita.instance()))

Thursday, September 18, 2025

Blender 3D : ... addon add all materials from folder.

This is a simple addon for Blender 3D version 3.6.x version.
The addon search recursive all blend files from one folder and take all materials.
Let's see the script:
bl_info = {
    "name": "Append Materials from Folder",
    "author": "Grok",
    "version": (1, 2),
    "blender": (3, 0, 0),
    "location": "View3D > Sidebar > Append Materials",
    "description": "Select a folder and append all materials from .blend files recursively",
    "category": "Import-Export",
}

import bpy
import os
from bpy.types import Operator, Panel, PropertyGroup
from bpy.props import StringProperty, PointerProperty

class AppendMaterialsProperties(PropertyGroup):
    folder_path: StringProperty(
        name="Folder Path",
        description="Path to the folder containing .blend files",
        default="",
        maxlen=1024,
        subtype='DIR_PATH'
    )

class APPEND_OT_materials_from_folder(Operator):
    bl_idname = "append.materials_from_folder"
    bl_label = "Append Materials from Folder"
    bl_options = {'REGISTER', 'UNDO'}
    bl_description = "Append all materials from .blend files in the selected folder and subfolders"

    def execute(self, context):
        props = context.scene.append_materials_props
        folder_path = props.folder_path

        # Normalize path to avoid issues with slashes
        folder_path = os.path.normpath(bpy.path.abspath(folder_path))
        if not folder_path or not os.path.isdir(folder_path):
            self.report({'ERROR'}, f"Invalid or no folder selected: {folder_path}")
            return {'CANCELLED'}

        self.report({'INFO'}, f"Scanning folder: {folder_path}")
        blend_files_found = 0
        materials_appended = 0
        errors = []

        # Walk recursively through the folder
        for root, dirs, files in os.walk(folder_path):
            self.report({'INFO'}, f"Checking folder: {root}")
            for file in files:
                if file.lower().endswith('.blend'):
                    blend_files_found += 1
                    blend_path = os.path.join(root, file)
                    self.report({'INFO'}, f"Found .blend file: {blend_path}")
                    try:
                        # Open the .blend file to inspect materials
                        with bpy.data.libraries.load(blend_path, link=False) as (data_from, data_to):
                            if data_from.materials:
                                data_to.materials = data_from.materials
                                materials_appended += len(data_from.materials)
                                self.report({'INFO'}, f"Appended {len(data_from.materials)} materials from: {blend_path}")
                            else:
                                self.report({'WARNING'}, f"No materials found in: {blend_path}")
                    except Exception as e:
                        errors.append(f"Failed to process {blend_path}: {str(e)}")
                        self.report({'WARNING'}, f"Error in {blend_path}: {str(e)}")

        # Final report
        if blend_files_found == 0:
            self.report({'WARNING'}, f"No .blend files found in {folder_path} or its subfolders!")
        else:
            self.report({'INFO'}, f"Found {blend_files_found} .blend files, appended {materials_appended} materials.")
        if errors:
            self.report({'WARNING'}, f"Encountered {len(errors)} errors: {'; '.join(errors)}")

        return {'FINISHED'}

class VIEW3D_PT_append_materials(Panel):
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'
    bl_category = "Append Materials"
    bl_label = "Append Materials from Folder"

    def draw(self, context):
        layout = self.layout
        props = context.scene.append_materials_props
        layout.prop(props, "folder_path")
        layout.operator("append.materials_from_folder", text="Append Materials")

def register():
    bpy.utils.register_class(AppendMaterialsProperties)
    bpy.utils.register_class(APPEND_OT_materials_from_folder)
    bpy.utils.register_class(VIEW3D_PT_append_materials)
    bpy.types.Scene.append_materials_props = PointerProperty(type=AppendMaterialsProperties)

def unregister():
    bpy.utils.unregister_class(VIEW3D_PT_append_materials)
    bpy.utils.unregister_class(APPEND_OT_materials_from_folder)
    bpy.utils.unregister_class(AppendMaterialsProperties)
    del bpy.types.Scene.append_materials_props

if __name__ == "__main__":
    register()