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.

Is a blog about python programming language. You can see my work with python programming language, tutorials and news.
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())
python catafest_build_package_001.py
🔍 Verificare module standard...
[✓] Modul standard 'json' este disponibil.
[✓] Modul standard 'subprocess' este disponibil.
[✓] Modul standard 'platform' este disponibil.
[✓] Modul standard 'datetime' este disponibil.
[✓] Modul standard 'os' este disponibil.
[✓] Modul standard 'sys' este disponibil.
📦 Verificare și instalare module pip...
[✓] Modulul 'PyQt6' este deja instalat.
[✓] Modulul 'build' este deja instalat.
* Creating isolated environment: venv+pip...
* Installing packages in isolated environment:
- setuptools
- wheel
...
import os
import subprocess
from PyQt6.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QPushButton,
QListWidget, QMessageBox
)
# fisier download : yt-dlp.exe -vU https://www.youtube.com/watch?v=xxxxxx -f bestvideo*+bestaudio/best
FOLDER_PATH = r"D:\Software"
class FFmpegMerger(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Combinare Video + Audio cu FFmpeg")
self.resize(600, 400)
self.layout = QVBoxLayout()
self.file_list = QListWidget()
self.process_button = QPushButton("Prelucrează în MP4")
self.layout.addWidget(self.file_list)
self.layout.addWidget(self.process_button)
self.setLayout(self.layout)
self.process_button.clicked.connect(self.process_files)
self.populate_file_list()
def populate_file_list(self):
files = os.listdir(FOLDER_PATH)
video_files = [f for f in files if f.endswith(".f401.mp4")]
audio_files = [f for f in files if f.endswith(".f251-9.webm")]
base_names = set(f.split(".f401.mp4")[0] for f in video_files)
candidates = []
for base in base_names:
audio_name = f"{base}.f251-9.webm"
output_name = f"{base}.mp4"
if audio_name in audio_files and output_name not in files:
candidates.append(base)
for name in candidates:
self.file_list.addItem(name)
def process_files(self):
for i in range(self.file_list.count()):
base = self.file_list.item(i).text()
video_path = os.path.join(FOLDER_PATH, f"{base}.f401.mp4")
audio_path = os.path.join(FOLDER_PATH, f"{base}.f251-9.webm")
output_path = os.path.join(FOLDER_PATH, f"{base}.mp4")
cmd = [
"ffmpeg",
"-i", video_path,
"-i", audio_path,
"-c:v", "copy",
"-c:a", "aac",
"-strict", "experimental",
output_path
]
try:
subprocess.run(cmd, check=True)
except subprocess.CalledProcessError as e:
QMessageBox.critical(self, "Eroare", f"Eroare la procesarea {base}: {e}")
return
QMessageBox.information(self, "Succes", "Toate fișierele au fost prelucrate cu succes!")
if __name__ == "__main__":
app = QApplication([])
window = FFmpegMerger()
window.show()
app.exec()
# Generate star polygon vertices
points_cw = []
points_ccw = []
for i in range(steps):
t = 2 * math.pi * i / steps
r = outer_radius if i % 2 == 0 else inner_radius
x_cw = center[0] + r * math.cos(t)
y_cw = center[1] + r * math.sin(t)
x_ccw = center[0] + r * math.cos(-t + math.pi / max(lobes, 1))
y_ccw = center[1] + r * math.sin(-t + math.pi / max(lobes, 1))
points_cw.append((x_cw, y_cw))
points_ccw.append((x_ccw, y_ccw))
import os
import unittest
from PIL import Image, ImageDraw, ImageFont, ImageQt
import shutil
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QFileDialog, QLabel, QVBoxLayout, QWidget, QComboBox
from PyQt6.QtGui import QPixmap
from PyQt6.QtCore import Qt
import sys
def create_test_image(path, size, number):
img = Image.new('RGBA', size, (255, 255, 255, 255))
draw = ImageDraw.Draw(img)
# Simplified to just draw the number with a basic color background
draw.rectangle((0, 0, size[0], size[1]), fill=(0, 100 * number % 255, 0, 255))
try:
font = ImageFont.load_default()
except:
font = None
draw.text((size[0]//2-5, size[1]//2-5), str(number), fill=(255, 255, 255, 255), font=font)
img.save(path, 'PNG')
def merge_sprites(folder_path, output_horizontal, output_vertical):
images = [Image.open(os.path.join(folder_path, f)) for f in os.listdir(folder_path) if f.endswith(('.png', '.jpg', '.jpeg'))]
if not images:
return None, None
width, height = images[0].size
# Horizontal merge
total_width = width * len(images)
horizontal_image = Image.new('RGBA', (total_width, height))
for i, img in enumerate(images):
horizontal_image.paste(img, (i * width, 0))
horizontal_image.save(output_horizontal, 'PNG')
# Vertical merge
total_height = height * len(images)
vertical_image = Image.new('RGBA', (width, total_height))
for i, img in enumerate(images):
vertical_image.paste(img, (0, i * height))
vertical_image.save(output_vertical, 'PNG')
return horizontal_image, vertical_image
class TestSpriteMerger(unittest.TestCase):
def setUp(self):
self.test_folder = 'test_images'
self.size = (50, 20)
os.makedirs(self.test_folder, exist_ok=True)
for i in range(3):
create_test_image(os.path.join(self.test_folder, f'test_{i+1}.png'), self.size, i+1)
def test_merge_horizontal(self):
output_h = 'test_merged_horizontal.png'
output_v = 'test_merged_vertical.png'
h_img, _ = merge_sprites(self.test_folder, output_h, output_v)
self.assertIsNotNone(h_img, "Horizontal merge failed")
self.assertEqual(h_img.size, (self.size[0] * 3, self.size[1]))
def test_merge_vertical(self):
output_h = 'test_merged_horizontal.png'
output_v = 'test_merged_vertical.png'
_, v_img = merge_sprites(self.test_folder, output_h, output_v)
self.assertIsNotNone(v_img, "Vertical merge failed")
self.assertEqual(v_img.size, (self.size[0], self.size[1] * 3))
def tearDown(self):
if os.path.exists(self.test_folder):
shutil.rmtree(self.test_folder)
for f in ['test_merged_horizontal.png', 'test_merged_vertical.png']:
if os.path.exists(f):
os.remove(f)
class SpriteMergerApp(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Sprite Merger")
self.setGeometry(100, 100, 800, 600)
self.folder_path = ""
layout = QVBoxLayout()
self.select_button = QPushButton("Select Folder")
self.select_button.clicked.connect(self.select_folder)
layout.addWidget(self.select_button)
self.merge_type = QComboBox()
self.merge_type.addItems(["Horizontal", "Vertical"])
layout.addWidget(self.merge_type)
self.process_button = QPushButton("Process Selected Folder")
self.process_button.clicked.connect(self.process_folder)
layout.addWidget(self.process_button)
self.test_button = QPushButton("Run Unit Test")
self.test_button.clicked.connect(self.run_unit_test)
layout.addWidget(self.test_button)
self.result_label = QLabel("No image processed")
layout.addWidget(self.result_label)
self.image_label = QLabel()
layout.addWidget(self.image_label)
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
def select_folder(self):
self.folder_path = QFileDialog.getExistingDirectory(self, "Select Sprite Folder")
self.result_label.setText(f"Selected: {self.folder_path}")
def process_folder(self):
if not self.folder_path:
self.result_label.setText("Please select a folder first")
return
h_img, v_img = merge_sprites(self.folder_path, 'merged_horizontal.png', 'merged_vertical.png')
selected_type = self.merge_type.currentText()
img = h_img if selected_type == "Horizontal" else v_img
if img:
pixmap = QPixmap.fromImage(ImageQt.ImageQt(img))
self.image_label.setPixmap(pixmap.scaled(700, 500, aspectRatioMode=Qt.AspectRatioMode.KeepAspectRatio))
self.result_label.setText(f"{selected_type} merge completed")
else:
self.result_label.setText(f"{selected_type} merge failed")
def run_unit_test(self):
suite = unittest.TestLoader().loadTestsFromTestCase(TestSpriteMerger)
result = unittest.TextTestRunner().run(suite)
test_folder = 'test_images'
os.makedirs(test_folder, exist_ok=True)
for i in range(3):
create_test_image(os.path.join(test_folder, f'test_{i+1}.png'), (50, 20), i+1)
h_img, v_img = merge_sprites(test_folder, 'test_merged_horizontal.png', 'test_merged_vertical.png')
selected_type = self.merge_type.currentText()
img = h_img if selected_type == "Horizontal" else v_img
if img:
pixmap = QPixmap.fromImage(ImageQt.ImageQt(img))
self.image_label.setPixmap(pixmap.scaled(700, 500, aspectRatioMode=Qt.AspectRatioMode.KeepAspectRatio))
self.result_label.setText(f"Unit tests: {result.testsRun} run, {len(result.failures)} failed, showing {selected_type.lower()} merge")
else:
self.result_label.setText(f"Unit tests: {result.testsRun} run, {len(result.failures)} failed, merge failed")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = SpriteMergerApp()
window.show()
sys.exit(app.exec())
import sys
import os
from datetime import datetime
from PyQt6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton, QFileDialog, QLineEdit, QCheckBox, QLabel, QMessageBox
from PyQt6.QtCore import Qt
from PIL import Image
class ResizeApp(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Image Resizer")
self.setGeometry(100, 100, 400, 200)
layout = QVBoxLayout()
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
self.folder_button = QPushButton("Select Folder")
self.folder_button.clicked.connect(self.select_folder)
layout.addWidget(self.folder_button)
self.width_edit = QLineEdit("800")
self.width_edit.setPlaceholderText("Width (px)")
layout.addWidget(QLabel("Width:"))
layout.addWidget(self.width_edit)
self.height_edit = QLineEdit("600")
self.height_edit.setPlaceholderText("Height (px)")
layout.addWidget(QLabel("Height:"))
layout.addWidget(self.height_edit)
self.aspect_ratio = QCheckBox("Maintain Aspect Ratio")
self.aspect_ratio.setChecked(True)
layout.addWidget(self.aspect_ratio)
self.resize_button = QPushButton("Resize Images")
self.resize_button.clicked.connect(self.resize_images)
layout.addWidget(self.resize_button)
self.folder_path = ""
def select_folder(self):
self.folder_path = QFileDialog.getExistingDirectory(self, "Select Image Folder")
if self.folder_path:
self.folder_button.setText(f"Selected: {os.path.basename(self.folder_path)}")
def resize_images(self):
if not self.folder_path:
QMessageBox.warning(self, "Error", "Please select a folder.")
return
try:
width = int(self.width_edit.text())
height = int(self.height_edit.text())
except ValueError:
QMessageBox.warning(self, "Error", "Please enter valid width and height.")
return
if width <= 0 or height <= 0:
QMessageBox.warning(self, "Error", "Width and height must be positive.")
return
date_str = datetime.now().strftime("%d%m%y_%H%M")
aspect_str = "asp_on" if self.aspect_ratio.isChecked() else "asp_off"
output_folder = os.path.join(self.folder_path, f"resized_{date_str}_{height}_{aspect_str}")
os.makedirs(output_folder, exist_ok=True)
for file_name in os.listdir(self.folder_path):
if file_name.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
image_path = os.path.join(self.folder_path, file_name)
try:
with Image.open(image_path) as img:
if self.aspect_ratio.isChecked():
img.thumbnail((width, height), Image.Resampling.LANCZOS)
else:
img = img.resize((width, height), Image.Resampling.LANCZOS)
output_path = os.path.join(output_folder, f"resized_{date_str}_{height}_{aspect_str}_{file_name}")
img.save(output_path)
except Exception as e:
QMessageBox.warning(self, "Error", f"Failed to process {file_name}: {str(e)}")
QMessageBox.information(self, "Success", f"Images resized and saved to {output_folder}!")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = ResizeApp()
window.show()
sys.exit(app.exec())
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
piglet join --secret the_API_key
Display dimensions: 1280x720
Local server running at http://localhost:3000
Connected to control server
"""
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!")
pip install elevenlabs
Collecting elevenlabs
...
Installing collected packages: websockets, sniffio, pydantic-core, h11, annotated-types, pydantic, httpcore, anyio, httpx,
elevenlabs
Successfully installed annotated-types-0.7.0 anyio-4.8.0 elevenlabs-1.52.0 h11-0.14.0 httpcore-1.0.7 httpx-0.28.1
pydantic-2.10.6the official website pydantic-core-2.27.2 sniffio-1.3.1 websockets-15.0
...
pip install playsound
Collecting playsound
...
Installing collected packages: playsound
Successfully installed playsound-1.3.0
...
python elevenlabs_test_001.py
Fișierul audio a fost salvat la generated_audio.mp3
import io # Importarea bibliotecii io
from elevenlabs import ElevenLabs
from playsound import playsound
import tempfile
import os
# API Key pentru ElevenLabs
api_key = "API_KEY"
voice_id = "JBFqnCBsd6RMkjVDRZzb"
# Configurarea clientului ElevenLabs
client = ElevenLabs(api_key=api_key )
# Textul pe care vrei să-l convertești în audio
text = 'Hello! This is a test without mpv.'
# Generarea audio
audio_generator = client.generate(text=text, voice=voice_id)
# Colectarea datelor din generator într-un obiect BytesIO
audio_data = io.BytesIO()
for chunk in audio_generator:
audio_data.write(chunk)
audio_data.seek(0) # Resetarea pointerului la începutul streamului
# Specificarea căii de salvare pentru fișierul audio
save_path = 'generated_audio.mp3'
# Salvarea audio într-un fișier temporar
with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as temp_audio:
temp_audio.write(audio_data.read())
temp_audio_path = temp_audio.name
# Redarea fișierului audio utilizând playsound
playsound(temp_audio_path)
# Salvarea fișierului audio generat într-o locație specificată
with open(save_path, 'wb') as f:
audio_data.seek(0) # Resetarea pointerului la începutul streamului pentru a citi din nou datele
f.write(audio_data.read())
print(f'Fișierul audio a fost salvat la {save_path}')
import subprocess
import os
import json
from PIL import Image, ImageOps
class OllamaProcessor:
def __init__(self, config_file):
self.config_file = config_file
self.model_methods = self.load_config()
def load_config(self):
try:
with open(self.config_file, 'r') as file:
config = json.load(file)
print("Configuration loaded successfully.")
return config
except FileNotFoundError:
print(f"Configuration file {self.config_file} not found.")
raise
except json.JSONDecodeError:
print(f"Error decoding JSON from the configuration file {self.config_file}.")
raise
def check_ollama(self):
try:
result = subprocess.run(["ollama", "--version"], capture_output=True, text=True, check=True)
print("Ollama is installed. Version:", result.stdout)
except subprocess.CalledProcessError as e:
print("Ollama is not installed or not found in PATH. Ensure it's installed and accessible.")
raise
...
python ollama_test_001.py
Configuration file ollama_config.json created successfully.
Configuration loaded successfully.
Ollama is installed. Version: ollama version is 0.5.7
Available models: ['NAME']
pulling manifest
pulling 170370233dd5... 100% ▕██████████████▏ 4.1 GB
pulling 72d6f08a42f6... 100% ▕██████████████▏ 624 MB
pulling 43070e2d4e53... 100% ▕██████████████▏ 11 KB
pulling c43332387573... 100% ▕██████████████▏ 67 B
pulling ed11eda7790d... 100% ▕██████████████▏ 30 B
pulling 7c658f9561e5... 100% ▕██████████████▏ 564 B
verifying sha256 digest
writing manifest
success
Model llava pulled successfully for method process_images_in_folder.
bl_info = {
"name": "3D File Renderer by catafest",
"blender": (4, 3, 2),
"category": "Object",
"author": "Catalin George Festila\n"
"nicknames: catafest and mythcat\n"
"country: Romania\n"
"mail: catafest [at] yahoo.com",
"version": (1, 0),
"blender": (2, 80, 0),
"location": "View3D > UI > 3D File Renderer",
"description": "Addon for rendering 3D files",
"warning": "",
"doc_url": "https://github.com/catafest",
"tracker_url": "https://github.com/catafest/issues",
"support": "COMMUNITY",
}
import bpy
import os
class FileRendererProperties(bpy.types.PropertyGroup):
input_directory: bpy.props.StringProperty(
name="Input Directory",
description="Directory containing 3D files",
default="",
maxlen=1024,
subtype='DIR_PATH'
)
output_directory: bpy.props.StringProperty(
name="Output Directory",
description="Directory to save rendered images",
default="",
maxlen=1024,
subtype='DIR_PATH'
)
class RENDER_OT_files(bpy.types.Operator):
bl_idname = "render.files"
bl_label = "Start render 3D files for all files"
def execute(self, context):
input_directory = context.scene.file_renderer_props.input_directory
output_directory = context.scene.file_renderer_props.output_directory
if not input_directory or not output_directory:
self.report({'ERROR'}, "Input and Output directories must be set.")
return {'CANCELLED'}
if not os.path.exists(output_directory):
os.makedirs(output_directory)
def render_file(file_path, output_path):
try:
bpy.ops.wm.read_factory_settings(use_empty=True)
ext = os.path.splitext(file_path)[1].lower()
if ext == ".glb":
bpy.ops.import_scene.gltf(filepath=file_path)
elif ext == ".obj":
bpy.ops.import_scene.obj(filepath=file_path)
elif ext == ".fbx":
bpy.ops.import_scene.fbx(filepath=file_path)
else:
raise ValueError("Unsupported file format")
bpy.ops.object.camera_add(location=(0, -3, 1.5), rotation=(1.1, 0, 0))
camera = bpy.context.scene.objects['Camera']
bpy.context.scene.camera = camera
bpy.ops.object.light_add(type='POINT', location=(0, -3, 3))
light = bpy.context.view_layer.objects.active
light.data.energy = 1000
bpy.context.scene.render.resolution_x = 512
bpy.context.scene.render.resolution_y = 512
bpy.context.scene.render.filepath = output_path
bpy.ops.render.render(write_still=True)
except Exception as e:
# Generate a red image with "BAD FILE" text using Blender
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.mesh.primitive_plane_add(size=2)
plane = bpy.context.active_object
mat = bpy.data.materials.new(name="BadFileMaterial")
mat.diffuse_color = (1, 0, 0, 1) # Red
plane.data.materials.append(mat)
# Add "BAD FILE" text
bpy.ops.object.text_add(location=(0, 0, 0.1))
text_obj = bpy.context.active_object
text_obj.data.body = "BAD FILE"
text_obj.data.size = 0.5
text_obj.data.align_x = 'CENTER'
text_obj.data.align_y = 'CENTER'
text_obj.rotation_euler = (1.5708, 0, 0)
# Set camera and light
bpy.ops.object.camera_add(location=(0, -3, 1.5), rotation=(1.1, 0, 0))
camera = bpy.context.scene.objects['Camera']
bpy.context.scene.camera = camera
bpy.ops.object.light_add(type='POINT', location=(0, -3, 3))
light = bpy.context.view_layer.objects.active
light.data.energy = 1000
bpy.context.scene.render.resolution_x = 512
bpy.context.scene.render.resolution_y = 512
bpy.context.scene.render.filepath = output_path
bpy.ops.render.render(write_still=True)
for filename in os.listdir(input_directory):
if filename.lower().endswith((".glb", ".obj", ".fbx")):
file_path = os.path.join(input_directory, filename)
output_path = os.path.join(output_directory, os.path.splitext(filename)[0] + ".png")
render_file(file_path, output_path)
self.report({'INFO'}, "Rendering of files is complete.")
return {'FINISHED'}
class ABOUT_OT_dialog(bpy.types.Operator):
bl_idname = "wm.about_dialog"
bl_label = "About this addon"
def execute(self, context):
return context.window_manager.invoke_props_dialog(self)
def draw(self, context):
layout = self.layout
layout.label(text="3D File Renderer by catafest")
layout.label(text="Author: Catalin George Festila")
layout.label(text="Nicknames: catafest and mythcat")
layout.label(text="Country: Romania")
layout.label(text="Email: catafest [at] yahoo.com")
layout.operator("wm.url_open", text="LinkedIn").url = "https://www.linkedin.com/in/c%C4%83t%C4%83lin-george-fe%C8%99til%C4%83-05780a67"
layout.operator("wm.url_open", text="Author Site").url = "https://sites.google.com/view/festila-george-catalin"
layout.operator("wm.url_open", text="catafest GitHub").url = "https://github.com/catafest"
layout.operator("wm.url_open", text="catafest-work GitHub").url = "https://github.com/catafest-work"
class FileRendererPanel(bpy.types.Panel):
bl_label = "3D File Renderer by catafest"
bl_idname = "OBJECT_PT_file_renderer"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'File Renderer'
def draw(self, context):
layout = self.layout
scene = context.scene
file_renderer_props = scene.file_renderer_props
layout.prop(file_renderer_props, "input_directory")
layout.prop(file_renderer_props, "output_directory")
# Styling the render button
render_button = layout.operator("render.files", text="Start render 3D files for all files")
layout.separator()
layout.operator("wm.about_dialog", text="About this addon")
def register():
bpy.utils.register_class(FileRendererProperties)
bpy.utils.register_class(RENDER_OT_files)
bpy.utils.register_class(ABOUT_OT_dialog)
bpy.utils.register_class(FileRendererPanel)
bpy.types.Scene.file_renderer_props = bpy.props.PointerProperty(type=FileRendererProperties)
def unregister():
bpy.utils.unregister_class(FileRendererProperties)
bpy.utils.unregister_class(RENDER_OT_files)
bpy.utils.unregister_class(ABOUT_OT_dialog)
bpy.utils.unregister_class(FileRendererPanel)
del bpy.types.Scene.file_renderer_props
if __name__ == "__main__":
register()
import os
import sys
from PIL import Image
def convert_webp_to_png(directory):
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(".webp"):
webp_path = os.path.join(root, file)
png_path = os.path.splitext(webp_path)[0] + ".png"
with Image.open(webp_path) as img:
img.save(png_path, "PNG")
print(f"webp to png file: {webp_path} -> {png_path}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("How to use: python convert.py path_to_folder_with_webp_files")
sys.exit(1)
directory = sys.argv[1]
if not os.path.isdir(directory):
print(f"{directory} folder is not valid.")
sys.exit(1)
convert_webp_to_png(directory)
print("Finished !")
from PIL import Image, ImageDraw, ImageFont
import os
# Font size and image dimensions
font_size = 88
width = 640
height = 480
# Use Symbola.ttf from current directory
font_path = "Symbola.ttf"
# Create image
img = Image.new('RGB', (width, height), color='white')
draw = ImageDraw.Draw(img)
# Get font
font = ImageFont.truetype(font_path, font_size)
# Emoji matrix
emoji_matrix = [
['😀', '😁', '😂', '🤣', '😃'],
['😄', '😅', '😆', '😇', '😈'],
['😉', '😊', '😋', '😌', '😍'],
['😎', '😏', '😐', '😑', '😒']
]
# Calculate spacing
x_spacing = font_size + 10
y_spacing = font_size + 10
# Calculate starting position to center the grid
start_x = (width - (len(emoji_matrix[0]) * x_spacing)) // 2
start_y = (height - (len(emoji_matrix) * y_spacing)) // 2
# Draw emojis
for i, row in enumerate(emoji_matrix):
for j, emoji in enumerate(row):
x = start_x + (j * x_spacing)
y = start_y + (i * y_spacing)
draw.text((x, y), emoji, font=font, fill='black')
# Save the image
img.save('emoji_art.png')
print("Emoji art has been created successfully! Check emoji_art.png")
C:\PythonProjects\Open3D001>git clone https://github.com/isl-org/Open3D.git
Cloning into 'Open3D'...
remote: Enumerating objects: 67435, done.
remote: Counting objects: 100% (2280/2280), done.
remote: Compressing objects: 100% (1894/1894), done.
remote: Total 67435 (delta 886), reused 599 (delta 385), pack-reused 65155
Receiving objects: 100% (67435/67435), 237.23 MiB | 17.11 MiB/s, done.
Resolving deltas: 100% (50682/50682), done.
Updating files: 100% (2315/2315), done.
C:\PythonProjects\Open3D001>cd Open3D
C:\PythonProjects\Open3D001\Open3D>mkdir build
C:\PythonProjects\Open3D001\Open3D>cd build
C:\PythonProjects\Open3D001\Open3D\build>cmake -DBUILD_SHARED_LIBS=ON -DCMAKE_INSTALL_PREFIX=C:\open3d_install ..
-- Building for: Visual Studio 17 2022
-- Setting build type to Release as none was specified.
-- CMAKE_BUILD_TYPE is set to Release.
-- Downloading third-party dependencies to C:/PythonProjects/Open3D001/Open3D/3rdparty_downloads
CMake Deprecation Warning at CMakeLists.txt:189 (cmake_policy):
The OLD behavior for policy CMP0072 will be removed from a future version
of CMake.
The cmake-policies(7) manual explains that the OLD behaviors of all
policies are deprecated and that a policy should be set to OLD only under
specific short-term circumstances. Projects should be ported to the NEW
behavior and not rely on setting a policy to OLD.
...
C:\PythonProjects\Open3D001>C:\Python310\python.exe -m pip install --user open3d --no-warn-script-location
C:\PythonProjects\Open3D001>C:\Python310\python.exe -c "import open3d as o3d; print(o3d)"
Traceback (most recent call last):
...
from open3d.cpu.pybind import (core, camera, data, geometry, io, pipelines,
ImportError: DLL load failed while importing pybind: A dynamic link library (DLL) initialization routine failed.
...
pip install pybind --user
Collecting pybind
Using cached pybind-0.1.35.tar.gz (15.5 MB)
ERROR: Could not install packages due to an OSError: [WinError 206] The filename or extension is too
long: 'C:\\Users\\catafest\\AppData\\Local\\Temp\\pip-install-7ccpzu3z\\pybind_
...
#create_image.py
import os
import openai
from PyQt6.QtCore import Qt, QSize
from PyQt6.QtGui import QImage, QPixmap
from PyQt6.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QVBoxLayout, QHBoxLayout, QPushButton
import requests
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.resize(500, 500)
self.setWindowTitle("AI Data Input")
# create widgets
self.image_label = QLabel(self)
self.image_label.setFixedSize(QSize(300, 300))
self.url_edit = QLineEdit(self)
self.api_key = QLineEdit(self)
self.send_button = QPushButton("Send data to AI", self)
self.send_button.clicked.connect(self.on_send_button_clicked)
# create layout
layout = QVBoxLayout()
url_layout = QHBoxLayout()
url_layout.addWidget(QLabel("Text request AI: "))
url_layout.addWidget(self.url_edit)
api_layout = QHBoxLayout()
api_layout.addWidget(QLabel("OpenAI API Key: "))
api_layout.addWidget(self.api_key)
layout.addLayout(url_layout)
layout.addLayout(api_layout)
layout.addWidget(self.image_label, alignment=Qt.AlignmentFlag.AlignCenter)
layout.addWidget(self.send_button, alignment=Qt.AlignmentFlag.AlignCenter)
self.setLayout(layout)
def on_send_button_clicked(self):
#openai.api_key = "your api key generated by OpenAI API"
openai.api_key = self.api_key.text()
PROMPT = self.url_edit.text()
url = openai.Image.create(
prompt=PROMPT,
n=1,
size="256x256",
)
# extract the url value
url_value = url['data'][0]['url']
if url_value :
response = requests.get(url_value)
if response.status_code == 200:
image = QImage.fromData(response.content)
pixmap = QPixmap.fromImage(image)
self.image_label.setPixmap(pixmap)
self.image_label.setScaledContents(True)
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec()
import os
import shutil
# Quick Access folder path on Windows
quick_access_path = os.path.join(os.environ['USERPROFILE'], 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Recent', 'AutomaticDestinations')
# List all files in the Quick Access folder
files = os.listdir(quick_access_path)
print(files)
# Loop through all files in the Quick Access folder
for file in files:
# Check if the file name contains "tmp" or "temp"
if 'tmp' in file.lower() or 'temp' in file.lower():
# Construct the full file path
file_path = os.path.join(quick_access_path, file)
# Delete the file
os.remove(file_path)
# Print a message to the console
print(f"{file_path} deleted successfully.")
# Clear Frequent folder
frequent_folder = os.path.join(os.environ['APPDATA'], 'Microsoft', 'Windows', 'Recent', 'AutomaticDestinations')
os.system('del /f /q "{}\*"'.format(frequent_folder))
# Clear Recent files list
recent_folder = os.path.join(os.environ['APPDATA'], 'Microsoft', 'Windows', 'Recent')
os.system('del /f /q "{}\*"'.format(recent_folder))
import hashlib
import os
def file_sha1(filename):
BUF_SIZE = 65536 # read stuff in 64kb chunks!
get_sha1 = hashlib.sha1()
with open(filename, 'rb') as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
get_sha1.update(data)
return get_sha1.hexdigest()
# I add this comment after first to see the hash difference.
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
h = file_sha1(f)
print(h)
Let's test the source code with the default directory and two files.[mythcat@desk Projects_Python]$ ls
test_hash_file.py test_numpy_001.py
[mythcat@desk Projects_Python]$ python test_hash_file.py
98b2833527ad3d9fe263542c6aa06c04182d3dfb
b222523567a8a806382b86578717ddbd00e0f4b4
[mythcat@desk Projects_Python]$ python test_hash_file.py
98b2833527ad3d9fe263542c6aa06c04182d3dfb
2134660551cc67812413a3a75fd12efb05d591ef
import os
import twitter
# for save to file import by python version
try:
import cPickle as pickle
except:
import pickle
consumer_key=' '
consumer_secret=' '
token_key=' '
token_secret=' '
if __name__ == "__main__":
api = twitter.Api(consumer_key=consumer_key,
consumer_secret=consumer_secret,
access_token_key=token_key,
access_token_secret=token_secret)
screen_name = 'catafest'
# print all users of this account authentificated
# you can use GetFriends(screen_name=screen_name)
users = api.GetFriends()
print([u.screen_name for u in users])
# get followers
followers = api.GetFollowers(screen_name=screen_name)
# print followers
print([f.screen_name for f in followers])
# ... and save into a binary file
followers_file = "followers_file.bin"
if not os.path.exists(followers_file):
pickle.dump(followers, open(followers_file, "wb"), protocol=pickle.HIGHEST_PROTOCOL)
# load binary file
if os.path.exists(followers_file):
followers_read = pickle.load(open(followers_file, "rb"))
print(followers_read)
python.exe .\test_webpage_001.py
['SnapChick', 'NASA', 'andor_saga', 'blendermarket', 'Minehut', 'Aternos', 'axnro', 'Flexi23',
...
['PStackoverflow', 'SamLeac86078418', 'Sohanurr559', 'jasonalba', 'avkorablev', 'dotnetfiddle',
...
[User(ID=1260415029855256583, ScreenName=PStackoverflow),
...