analitics

Pages

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

Wednesday, October 18, 2023

Python 3.12.0 : PyAutoGUI example.

PyAutoGUI lets your Python scripts control the mouse and keyboard to automate interactions with other applications.
Make sure the modal dialog window is active and the desired text is visible before running the script.
This script waits for the user to activate the modal dialog window (for example, by clicking on the dialog window) and then moves the cursor to the coordinates of the label in the dialog window.
Copies the selected text to the clipboard using the classic Ctr and C keys.
Let's see the source code that does this.
import pyautogui
import time

# Display a short notification to prompt the user to activate the modal dialog window
print("Please activate the modal dialog window.")

# Wait for the user to activate the modal dialog window (you can click in the dialog window)
time.sleep(10) # Wait 10 seconds or enough time to activate the window

# Get the coordinates where you want to read the text on the label
x_label = 200 # Replace with the correct x coordinates
y_label = 300 # Replace with the correct y coordinates

# Move the mouse cursor to the coordinates of the label
pyautogui.moveTo(x_label, y_label)

# Select the text in the label using the mouse
pyautogui.dragTo(x_label + 200, y_label, duration=1) # Substitute the appropriate coordinates and duration

# Copies the selected text to the clipboard
pyautogui.hotkey("ctrl", "c")

# You can use the clipboard to access the read text
import clipboard
text_copied = clipboard.paste()

Friday, October 13, 2023

Blender 3D and python scripting - part 026.

Today I tested the bpy python module from Blender 3D software version 3.5 and I made this lite addon that showed me a modal dialog and checked and installed the Pillow python module.
The script don't install Pillow because is not fixed.
The main reason was to add my Python tools and features to Blender 3D and share with you.
bl_info = {
    "name": "Tools by catafest",
    "blender": (3, 0, 0),
    "category": "3D View",
}

import bpy
from bpy.types import Operator, Panel
from bpy.props import StringProperty

try:
    import importlib
    importlib.import_module("Pillow")
    PIL_installed = True
except ImportError:
    PIL_installed = False

def install_pillow():
    import subprocess
    try:
        subprocess.run([bpy.app.binary_path, '--python-exit-code', '1', '-m', 'ensurepip'])
        subprocess.check_call([bpy.app.binary_path, '-m', 'pip', 'install', 'Pillow'])
    except subprocess.CalledProcessError as e:
        print("Eroare la instalarea Pillow:", e)

# Operator pentru a afișa fereastra modală cu informații despre instalarea Pillow
class CATAFEST_IMAGES_OT_show_pillow_message(Operator):
    bl_idname = "catafest.show_pillow_message"
    bl_label = "Show Pillow Message"

    def execute(self, context):
        global PIL_installed
        message = "Pillow este instalat." if PIL_installed else "Pillow nu este instalat."

        # Dacă Pillow nu este instalat, încercați să-l instalați
        if not PIL_installed:
            install_pillow()
            try:
                import importlib
                importlib.import_module("Pillow")
                PIL_installed = True
                message = "Pillow a fost instalat cu succes!" if PIL_installed else "Eroare la instalarea Pillow."
            except ImportError:
                PIL_installed = False

        # Afișați fereastra modală în centrul ecranului
        bpy.ops.catafest.show_modal_message('INVOKE_DEFAULT', title="Starea Pillow", message=message)
        return {'FINISHED'}

    def invoke(self, context, event):
        return self.execute(context)

# Operator pentru a afișa fereastra modală personalizată
class CATAFEST_IMAGES_OT_show_modal_message(Operator):
    bl_idname = "catafest.show_modal_message"
    bl_label = "Show Modal Message"

    title: bpy.props.StringProperty(default="Message")
    message: bpy.props.StringProperty(default="")

    def execute(self, context):
        return {'FINISHED'}

    def invoke(self, context, event):
        wm = context.window_manager
        return wm.invoke_props_dialog(self, width=400)

    def draw(self, context):
        layout = self.layout
        layout.label(text=self.message)

# Panel pentru bara laterală din 3D View
class VIEW3D_PT_tools_image(Panel):
    bl_label = "Images"
    bl_idname = "VIEW3D_PT_tools_image"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'
    bl_category = 'Tools by catafest'

    def draw(self, context):
        layout = self.layout
        layout.operator(CATAFEST_IMAGES_OT_show_modal_message.bl_idname)
        layout.operator(CATAFEST_IMAGES_OT_show_pillow_message.bl_idname)

def register():
    bpy.utils.register_class(CATAFEST_IMAGES_OT_show_modal_message)
    bpy.utils.register_class(CATAFEST_IMAGES_OT_show_pillow_message)
    bpy.utils.register_class(VIEW3D_PT_tools_image)

def unregister():
    bpy.utils.unregister_class(CATAFEST_IMAGES_OT_show_modal_message)
    bpy.utils.unregister_class(CATAFEST_IMAGES_OT_show_pillow_message)
    bpy.utils.unregister_class(VIEW3D_PT_tools_image)

if __name__ == "__main__":
    register()

Monday, September 18, 2023

News : Amazon free python audible audiobook.

Although Python programming language comes with many learning resources, you can find a lot of free audiobooks on Amazon.
You can try a free trial then you need to pay $14.95 a month after 30 days - cancel online anytime.

Saturday, September 9, 2023

News : Python 3.12.0 release candidate 2 now available.

This new release comes with many improvements for developers.
Here are some of them.
Modules from the standard library are now potentially suggested as part of the error messages displayed by the interpreter ...
NameError: name 'sys' is not defined. Did you forget to import 'sys'?
  • Many large and small performance improvements like - PEP 709;
  • Support for the Linux perf profiler to report Python function names in traces;
  • New type annotation syntax for generic classes - PEP 695;
  • More flexible f-string parsing, allowing many things previously disallowed - PEP 701;
  • Support for the buffer protocol in Python code - PEP 688;
  • A new debugging/profiling API - PEP 669;
  • Support for isolated sub interpreters with separate Global Interpreter Locks - PEP 684;
All PEPs can be found on this GitHub project.

Saturday, September 2, 2023

Python 3.11.4 : Issues in Fedora with PyGobject and sway-tests

Today I wanted to test this repo named sway-tests.
I followed the steps there and received an error from gi.repository.
This error is related to another issue related to PyGobject.
In Fedora Linux distro, installing PyGobject is done with pip like this:
$ pip install PyGobject
In order to have no errors, the dnf or dnf5 tool should be used like this ...
I tested the functionality of this installation with a simple example:
import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

win = Gtk.Window()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
It worked very well.
After solving this issue, I returned to the initial one and tested the sway-tests.
$ whereis sway
$ env/bin/pytest --sway=/usr/bin/sway
$ sudo env/bin/pytest --sway=/usr/bin/sway
I used the command both with and without sudo.
Both generated the same errors.
For the following command I had to install ... xorg-x11-server-Xephyr:
Xephyr is an X server which has been implemented as an ordinary X application. It runs in a window just like other X applications, but it is an X server ...
... the fixed centered black window specific to the xorg runtime appeared and somewhere on the side the terminal showed me a bunch of errors.
... obviously, I don't know how well sway-tests is implemented, now it's an archived repo, but I solved the use of PyGobject in python on the Fedora linux distribution.

Friday, September 1, 2023

Python 3.11.0 : Use python to set your R application on shinyapps.io.

If you use the R programming language and shinyapps.io then you can use Python to set up your application.
I create my folder and I install the rsconnect-python python package.
mkdir rsconnect-python-001
cd rsconnect-python-001
pip install rsconnect-python --user
Collecting rsconnect-python
From the shinyapps webpage, I got my token and my secret for my account and I used this command:
rsconnect add --account catafest --name catafest --token YOUR_TOKEN --secret YOUR_SECRET
Detected the following inputs:
    name: COMMANDLINE
    insecure: DEFAULT
    account: COMMANDLINE
    token: COMMANDLINE
    secret: COMMANDLINE
Checking shinyapps.io credential...              [OK]
Added shinyapps.io credential "catafest".
You can see is set and working.
I used a simple R source code named app.r:
library(shiny)

# Definirea interfeței utilizatorului
ui <- fluidPage(
  titlePanel("Aplicație Shiny Simplă"),
  sidebarLayout(
    sidebarPanel(
      numericInput("num", "Introduceți un număr:", value = 1),
      actionButton("goButton", "Generează")
    ),
    mainPanel(
      textOutput("rezultat")
    )
  )
)

# Definirea serverului
server <- function(input, output) {
  observeEvent(input$goButton, {
    num <- input$num
    output$rezultat <- renderText({
      paste("Numărul introdus este:", num)
    })
  })
}

# Crearea aplicației Shiny
shinyApp(ui, server)
The app.py file has this source code:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

# Creați o aplicație Dash
app = dash.Dash(__name__)

# Definiți aspectul și structura aplicației
app.layout = html.Div([
    html.H1("Aplicație Dash Simplă"),
    dcc.Graph(id='grafic'),
    dcc.Input(id='input-numar', type='number', value=1),
    html.Div(id='rezultat')
])

# Definiți funcția callback pentru actualizarea graficului
@app.callback(
    Output('grafic', 'figure'),
    Input('input-numar', 'value')
)
def actualizare_grafic(numar):
    # Implementați logica de actualizare a graficului aici
    # Exemplu simplu: Un grafic cu o linie dreaptă cu panta egală cu numărul introdus
    import plotly.express as px
    import pandas as pd
    
    data = pd.DataFrame({'x': range(10), 'y': [numar * x for x in range(10)]})
    
    fig = px.line(data, x='x', y='y', title='Graficul personalizat')
    
    return fig

# Rulează aplicația
if __name__ == '__main__':
    app.run_server(debug=True)
I run this command into the RGUI command :
shiny::runApp("C:/PythonProjects/rsconnect-python-001/")

Listening on http://127.0.0.1:7036
The result on browser is this:
I used this command to deploy the application on shinyapps.io:
>rsconnect deploy shiny . --name catafest --title test
[WARNING] 2023-09-01T22:28:10+0300 Can't determine entrypoint; defaulting to 'app'
    Warning: Capturing the environment using 'pip freeze'.
             Consider creating a requirements.txt file instead.
...
Task done: Stopping old instances
Application successfully deployed to https://catafest.shinyapps.io/test/
...
  deploying - Starting instances
Task done: Stopping old instances
Application successfully deployed to https://catafest.shinyapps.io/rsconnect-python-001/
←[32;20m        [OK]
←[0m←[0mSaving deployed information...←[0m←[32;20m      [OK]
←[0m
The result can be found on the shinyapps.io - admin.
I need to fix this error, but first test without app.py was deploy on web.
[notice] A new release of pip is available: 23.1.2 -> 23.2.1
[notice] To update, run: /srv/connect/venv/bin/python3 -m pip install --upgrade pip
[2023-09-01T22:43:31.378864990+0000] Copying file manifest.json
←[31;20m        [ERROR]: Application deployment failed with error: Unhandled Exception: Child Task 1332185768 error: 
Unhandled Exception: 599
←[0mError: Application deployment failed with error: Unhandled Exception: Child Task 1332185768 error: 
Unhandled Exception: 599
I will come with better results.

Wednesday, August 23, 2023

Python 3.11.0 : Testing PE executable files x64 with capstone and pefile python modules.

You need to install the capstone python module.
pip install capstone --user
Collecting capstone
  Obtaining dependency information for capstone from https://files.pythonhosted.org/packages/d0/dd/b28df50316ca193
  
  dd1275a4c47115a720796d
  
  9e1501c1888c4bfa5dc2260/capstone-5.0.1-py3-none-win_amd64.whl.metadata
  
  Downloading capstone-5.0.1-py3-none-win_amd64.whl.metadata (3.5 kB)
Downloading capstone-5.0.1-py3-none-win_amd64.whl (1.3 MB)
   ---------------------------------------- 1.3/1.3 MB 1.6 MB/s eta 0:00:00
Installing collected packages: capstone
Successfully installed capstone-5.0.1
You need to install the pefile.
pip install pefile --user
Collecting pefile
  Downloading pefile-2023.2.7-py3-none-any.whl (71 kB)
     ---------------------------------------- 71.8/71.8 kB 564.7 kB/s eta 0:00:00
Installing collected packages: pefile
Successfully installed pefile-2023.2.7
I used an old simple PE64 executable create with fasm tool from this source code:
format PE64 GUI 5.0
entry start
include 'INCLUDE\win64a.inc'
section '.text' code readable executable
  start:
        push    rbp
        invoke  GetModuleHandle,0
        invoke  DialogBoxParam,rax,37,HWND_DESKTOP,DialogProc,0
        invoke  ExitProcess,0
proc DialogProc uses rbx rsi rdi,hWnd,wMsg,wParam,lParam
        mov             [hWnd],rcx
        mov             [wMsg],rdx
        mov             [wParam],r8
        mov             [lParam],r9

        cmp     [wMsg],WM_COMMAND
        je      wmcommand
        cmp     [wMsg],WM_CLOSE
        je      wmclose
        cmp     [wMsg],WM_SYSCOMMAND
        je      wmsyscommand
        xor     rax,rax
        jmp     finish
wmsyscommand:
        cmp     [wParam],SC_RESTORE
        je      sc_restore
        invoke  DefWindowProc,[hWnd],[wMsg],[wParam],[lParam]
        ret
   sc_restore:
        invoke  AnimateWindow,[hWnd],DWORD 1000,0x00040004      ;HERE IT IS
        invoke  ShowWindow,[hWnd],SW_RESTORE
        mov     rax,1
        ret
wmcommand:
        cmp     [wParam],BN_CLICKED shl 16 + IDOK
        jne     processed
        invoke  ShowWindow,[hWnd],SW_MINIMIZE
        ret
wmclose:
        invoke  EndDialog,[hWnd],0
processed:
        mov     rax,1
        ret ; this no need and use cmp to get error
;        cmp rax,0
;        je show_error
;        show_error:
;        invoke  GetLastError ;must call this first and save the result before doing anything else
;        invoke  wsprintf,...
;        invoke  MessageBox,...
finish:
        ret
endp
section '.idata' import data readable writeable
  library kernel,'KERNEL32.DLL',\
          user,'USER32.DLL'
  import kernel,\
         GetModuleHandle,'GetModuleHandleA',\
         ExitProcess,'ExitProcess'
  import user,\
         DialogBoxParam,'DialogBoxParamA',\
         CheckRadioButton,'CheckRadioButton',\
         GetDlgItemText,'GetDlgItemTextA',\
         IsDlgButtonChecked,'IsDlgButtonChecked',\
         MessageBox,'MessageBoxA',\
         DefWindowProc,'DefWindowProcA',\
         EndDialog,'EndDialog',\
         AnimateWindow,'AnimateWindow',\
         ShowWindow,'ShowWindow'
section '.rsrc' resource data readable
  directory RT_DIALOG,dialogs
  resource dialogs,\
           37,LANG_ENGLISH+SUBLANG_DEFAULT,demonstration
  dialog demonstration,'Create message box',70,70,190,175,WS_CAPTION+WS_POPUP+WS_SYSMENU+DS_MODALFRAME
       dialogitem 'BUTTON','OK',IDOK,85,150,45,15,WS_VISIBLE+WS_TABSTOP+BS_DEFPUSHBUTTON
  enddialog
This is the source code for python script:
import pefile
from capstone import *

exe_file = 'test_001_no_err_imp.EXE'
pe = pefile.PE(exe_file)

# find text section
offset = False
for section in pe.sections:
    if section.Name == b'.text\x00\x00\x00':
        offset = section.VirtualAddress
        codePtr = section.PointerToRawData
        codeEndPtr = codePtr+section.SizeOfRawData
        break

code = pe.get_memory_mapped_image()[codePtr:codeEndPtr]

# start disassembling text section
md = Cs(CS_ARCH_X86, CS_MODE_32)
md.detail = True
if offset:
    for i in md.disasm(code, offset):
        print('0x%x:\t%s\t%s' % (i.address, i.mnemonic, i.op_str))
This is the result:
python capstone_test_001.py
0x1000: push    ebp
0x1001: dec     eax
0x1002: sub     esp, 0x20
0x1005: dec     eax
0x1006: mov     ecx, 0
0x100c: call    dword ptr [0x105e]
0x1012: dec     eax
0x1013: add     esp, 0x20
0x1016: dec     eax
0x1017: sub     esp, 0x30
0x101a: dec     eax
0x101b: mov     ecx, eax
0x101d: dec     eax
0x101e: mov     edx, 0x25
0x1024: dec     ecx
0x1025: mov     eax, 0
0x102b: dec     ecx
0x102c: mov     ecx, 0x40105a
0x1032: dec     eax
0x1033: mov     dword ptr [esp + 0x20], 0
0x103b: call    dword ptr [0x109f]
0x1041: dec     eax
0x1042: add     esp, 0x30
0x1045: dec     eax
0x1046: sub     esp, 0x20
0x1049: dec     eax
0x104a: mov     ecx, 0
0x1050: call    dword ptr [0x1022]
0x1056: dec     eax
0x1057: add     esp, 0x20
0x105a: push    ebp
0x105b: dec     eax
0x105c: mov     ebp, esp
0x105e: dec     eax
0x105f: sub     esp, 8
0x1062: push    ebx
0x1063: push    esi
0x1064: push    edi
0x1065: dec     eax
0x1066: mov     dword ptr [ebp + 0x10], ecx
0x1069: dec     eax
0x106a: mov     dword ptr [ebp + 0x18], edx
0x106d: dec     esp
0x106e: mov     dword ptr [ebp + 0x20], eax
0x1071: dec     esp
0x1072: mov     dword ptr [ebp + 0x28], ecx
0x1075: dec     eax
0x1076: cmp     dword ptr [ebp + 0x18], 0x111
0x107d: je      0x1110
0x1083: dec     eax
0x1084: cmp     dword ptr [ebp + 0x18], 0x10
0x1088: je      0x1135
0x108e: dec     eax
0x108f: cmp     dword ptr [ebp + 0x18], 0x112
0x1096: je      0x10a0
0x1098: dec     eax
0x1099: xor     eax, eax
0x109b: jmp     0x115a
0x10a0: dec     eax
0x10a1: cmp     dword ptr [ebp + 0x20], 0xf120
0x10a8: je      0x10cd
0x10aa: dec     eax
0x10ab: sub     esp, 0x20
0x10ae: dec     eax
0x10af: mov     ecx, dword ptr [ebp + 0x10]
0x10b2: dec     eax
0x10b3: mov     edx, dword ptr [ebp + 0x18]
0x10b6: dec     esp
0x10b7: mov     eax, dword ptr [ebp + 0x20]
0x10ba: dec     esp
0x10bb: mov     ecx, dword ptr [ebp + 0x28]
0x10be: call    dword ptr [0x1024]
0x10c4: dec     eax
0x10c5: add     esp, 0x20
0x10c8: pop     edi
0x10c9: pop     esi
0x10ca: pop     ebx
0x10cb: leave
0x10cc: ret
0x10cd: dec     eax
0x10ce: sub     esp, 0x20
0x10d1: dec     eax
0x10d2: mov     ecx, dword ptr [ebp + 0x10]
0x10d5: mov     edx, 0x3e8
0x10da: dec     ecx
0x10db: mov     eax, 0x40004
0x10e1: call    dword ptr [0x1011]
0x10e7: dec     eax
0x10e8: add     esp, 0x20
0x10eb: dec     eax
0x10ec: sub     esp, 0x20
0x10ef: dec     eax
0x10f0: mov     ecx, dword ptr [ebp + 0x10]
0x10f3: dec     eax
0x10f4: mov     edx, 9
0x10fa: call    dword ptr [0x1000]
0x1100: dec     eax
0x1101: add     esp, 0x20
0x1104: dec     eax
0x1105: mov     eax, 1
0x110b: pop     edi
0x110c: pop     esi
0x110d: pop     ebx
0x110e: leave
0x110f: ret
0x1110: dec     eax
0x1111: cmp     dword ptr [ebp + 0x20], 1
0x1115: jne     0x114e
0x1117: dec     eax
0x1118: sub     esp, 0x20
0x111b: dec     eax
0x111c: mov     ecx, dword ptr [ebp + 0x10]
0x111f: dec     eax
0x1120: mov     edx, 6
0x1126: call    dword ptr [0xfd4]
0x112c: dec     eax
0x112d: add     esp, 0x20
0x1130: pop     edi
0x1131: pop     esi
0x1132: pop     ebx
0x1133: leave
0x1134: ret
0x1135: dec     eax
0x1136: sub     esp, 0x20
0x1139: dec     eax
0x113a: mov     ecx, dword ptr [ebp + 0x10]
0x113d: dec     eax
0x113e: mov     edx, 0
0x1144: call    dword ptr [0xfa6]
0x114a: dec     eax
0x114b: add     esp, 0x20
0x114e: dec     eax
0x114f: mov     eax, 1
0x1155: pop     edi
0x1156: pop     esi
0x1157: pop     ebx
0x1158: leave
0x1159: ret
0x115a: pop     edi
0x115b: pop     esi
0x115c: pop     ebx
0x115d: leave
0x115e: ret
0x115f: add     byte ptr [eax], al
0x1161: add     byte ptr [eax], al
0x1163: add     byte ptr [eax], al
0x1165: add     byte ptr [eax], al
0x1167: add     byte ptr [eax], al
0x1169: add     byte ptr [eax], al
0x116b: add     byte ptr [eax], al
0x116d: add     byte ptr [eax], al
0x116f: add     byte ptr [eax], al
0x1171: add     byte ptr [eax], al
0x1173: add     byte ptr [eax], al
0x1175: add     byte ptr [eax], al
0x1177: add     byte ptr [eax], al
0x1179: add     byte ptr [eax], al
0x117b: add     byte ptr [eax], al
0x117d: add     byte ptr [eax], al
0x117f: add     byte ptr [eax], al
0x1181: add     byte ptr [eax], al
0x1183: add     byte ptr [eax], al
0x1185: add     byte ptr [eax], al
0x1187: add     byte ptr [eax], al
0x1189: add     byte ptr [eax], al
0x118b: add     byte ptr [eax], al
0x118d: add     byte ptr [eax], al
0x118f: add     byte ptr [eax], al
0x1191: add     byte ptr [eax], al
0x1193: add     byte ptr [eax], al
0x1195: add     byte ptr [eax], al
0x1197: add     byte ptr [eax], al
0x1199: add     byte ptr [eax], al
0x119b: add     byte ptr [eax], al
0x119d: add     byte ptr [eax], al
0x119f: add     byte ptr [eax], al
0x11a1: add     byte ptr [eax], al
0x11a3: add     byte ptr [eax], al
0x11a5: add     byte ptr [eax], al
0x11a7: add     byte ptr [eax], al
0x11a9: add     byte ptr [eax], al
0x11ab: add     byte ptr [eax], al
0x11ad: add     byte ptr [eax], al
0x11af: add     byte ptr [eax], al
0x11b1: add     byte ptr [eax], al
0x11b3: add     byte ptr [eax], al
0x11b5: add     byte ptr [eax], al
0x11b7: add     byte ptr [eax], al
0x11b9: add     byte ptr [eax], al
0x11bb: add     byte ptr [eax], al
0x11bd: add     byte ptr [eax], al
0x11bf: add     byte ptr [eax], al
0x11c1: add     byte ptr [eax], al
0x11c3: add     byte ptr [eax], al
0x11c5: add     byte ptr [eax], al
0x11c7: add     byte ptr [eax], al
0x11c9: add     byte ptr [eax], al
0x11cb: add     byte ptr [eax], al
0x11cd: add     byte ptr [eax], al
0x11cf: add     byte ptr [eax], al
0x11d1: add     byte ptr [eax], al
0x11d3: add     byte ptr [eax], al
0x11d5: add     byte ptr [eax], al
0x11d7: add     byte ptr [eax], al
0x11d9: add     byte ptr [eax], al
0x11db: add     byte ptr [eax], al
0x11dd: add     byte ptr [eax], al
0x11df: add     byte ptr [eax], al
0x11e1: add     byte ptr [eax], al
0x11e3: add     byte ptr [eax], al
0x11e5: add     byte ptr [eax], al
0x11e7: add     byte ptr [eax], al
0x11e9: add     byte ptr [eax], al
0x11eb: add     byte ptr [eax], al
0x11ed: add     byte ptr [eax], al
0x11ef: add     byte ptr [eax], al
0x11f1: add     byte ptr [eax], al
0x11f3: add     byte ptr [eax], al
0x11f5: add     byte ptr [eax], al
0x11f7: add     byte ptr [eax], al
0x11f9: add     byte ptr [eax], al
0x11fb: add     byte ptr [eax], al
0x11fd: add     byte ptr [eax], al

Sunday, August 20, 2023

News : supervision python package.

We write your reusable computer vision tools. Whether you need to load your dataset from your hard drive, draw detections on an image or video, or count how many detections are in a zone. You can count on us!
I tested today with Fedora 39 Linux Distro using the GitHub project.
The installation from the source code worked with the following commands:
# clone repository and navigate to root directory
git clone https://github.com/roboflow/supervision.git
cd supervision

# setup python environment and activate it
python3 -m venv venv
source venv/bin/activate

# headless install
pip install -e "."

# desktop install
pip install -e ".[desktop]"
You can see more examples with this python package on this twitter account - skalskip92 !

Wednesday, May 24, 2023

Python 3.11.0 : Exo - domain-specific programming language in python.

Exo is a domain-specific programming language that helps low-level performance engineers transform very simple programs that specify what they want to compute into very complex programs that do the same thing as the specification, only much, much faster.
You can find it on GitHub project and on the official webpage.
Let's install it with pip tool:
C:\PythonProjects>mkdir exo-lang_001

C:\PythonProjects>cd exo-lang_001

C:\PythonProjects\exo-lang_001>pip install exo-lang --user
Collecting exo-lang
  Downloading exo_lang-0.0.2-py3-none-any.whl (142 kB)
  ...
Successfully installed PySMT-0.9.5 asdl-0.1.5 asdl-adt-0.1.0 astor-0.8.1 exo-lang-0.0.2 tomli-2.0.1 
yapf-0.33.0 z3-solver-4.12.2.0
Let's test with this default example but using virtual environments
This allow me to install Python packages in an isolated location from the rest of your system instead of installing them system-wide.
C:\PythonProjects\exo-lang_001>pip install virtualenv --user
...
C:\PythonProjects\exo-lang_001>python -m venv venv
C:\PythonProjects\exo-lang_001>venv\Scripts\activate.bat

(venv) C:\PythonProjects\exo-lang_001>python -m pip install -U setuptools wheel
Successfully installed setuptools-67.8.0 wheel-0.40.0

[notice] A new release of pip available: 22.3 -> 23.1.2
[notice] To update, run: python.exe -m pip install --upgrade pip
(venv) C:\PythonProjects\exo-lang_001>python.exe -m pip install --upgrade pip
Requirement already satisfied: pip in c:\pythonprojects\exo-lang_001\venv\lib\site-packages (22.3)
Collecting pip
  Using cached pip-23.1.2-py3-none-any.whl (2.1 MB)
...
Successfully installed pip-23.1.2
(venv) C:\PythonProjects\exo-lang_001>python -m pip install exo-lang
...
Installing collected packages: z3-solver, PySMT, asdl, tomli, numpy, attrs, astor, yapf, asdl-adt, exo-lang
Successfully installed PySMT-0.9.5 asdl-0.1.5 asdl-adt-0.1.0 astor-0.8.1 attrs-23.1.0 exo-lang-0.0.2 numpy-1.24.3
tomli-2.0.1 yapf-0.33.0 z3-solver-4.12.2.0
Let's try a simple example from official webpage:
(venv) C:\PythonProjects\exo-lang_001>notepad example.py
# example.py
from __future__ import annotations
from exo import *

@proc
def example_sgemm(
    M: size,
    N: size,
    K: size,
    C: f32[M, N] @ DRAM,
    A: f32[M, K] @ DRAM,
    B: f32[K, N] @ DRAM,
):
    for i in seq(0, M):
        for j in seq(0, N):
            for k in seq(0, K):
                C[i, j] += A[i, k] * B[k, j]
Use this command and check the out folder:
(venv) C:\PythonProjects\exo-lang_001>cd out
(venv) C:\PythonProjects\exo-lang_001\out>dir 
...
 example.c   example.h
If you want to know more see this video from youtube:

Sunday, May 21, 2023

Python 3.11.3 : Using Jupyter Lab on Fedora linux distro.

JupyterLab is the latest web-based interactive development environment for notebooks, code, and data. Its flexible interface allows users to configure and arrange workflows in data science, scientific computing, computational journalism, and machine learning.
Follow these steps:
  1. Install the jupyterlab python package using pip. This will allow you to run Jupyter notebooks in the terminal.
    pip install jupyterlab
  2. Open a Jupyter Lab session in the terminal using the command:
    jupyter lab
  3. Create a new notebook file and save it with the .ipynb extension.
  4. In the notebook file, add the source code to work with the Python programming language and save the file notebook.
See the next screenshot how this works:

Saturday, April 29, 2023

Extension for inkscape with python.

Today, I created the first Python extension for Inkscape, and although in theory, it seems easy, it is not really so.
You have to study a little and search the web, but I created a tutorial on one of my website.
The idea is to use at least two files with different extensions.
I named one catafest_extension.inx and the other catafest_extension.py.
For the Python file, I used this source code:
#!/usr/bin/env python
# coding=utf-8
#
# Copyright (C) 2023 Catalin George Festila, catafest@yahoo.com
#

"""
Simple test extension for inkscape
"""

import inkex
# add by me 

from lxml import etree
def draw_SVG_square(w,h, x,y, parent):
    style = { 'stroke'        : 'none',
              'stroke-width'  : '1',
              'fill'          : '#0000FF'
            }

    attribs = {
        'style'     : str(inkex.Style(style)),
        'height'    : str(h),
        'width'     : str(w),
        'x'         : str(x),
        'y'         : str(y)
            }
    patrat = etree.SubElement(
        parent, inkex.addNS('rect','svg'), attribs )
    return patrat

class MyExtension(inkex.Effect):
    def __init__(self):
        super().__init__()

    def effect(self):
        self.msg("This is an empty extension created by catafest !")
        parent = self.svg.get_current_layer()
        draw_SVG_square(100,100, 0,0, parent)

if __name__ == '__main__':
    MyExtension().run()
The result is this

Tuesday, April 11, 2023

Python 3.11.0 : about consolemenu .

This simple console menu can help to create menus, you can find the project on GitHub project.
pip install console-menu --user
For testing, I used the default example, and works well.
# Import the necessary packages
from consolemenu import *
from consolemenu.items import *

# Create the menu
menu = ConsoleMenu("Title", "Subtitle")

# Create some items

# MenuItem is the base class for all items, it doesn't do anything when selected
menu_item = MenuItem("Menu Item")

# A FunctionItem runs a Python function when selected
function_item = FunctionItem("Call a Python function", input, ["Enter an input"])

# A CommandItem runs a console command
command_item = CommandItem("Run a console command",  "touch hello.txt")

# A SelectionMenu constructs a menu from a list of strings
selection_menu = SelectionMenu(["item1", "item2", "item3"])

# A SubmenuItem lets you add a menu (the selection_menu above, for example)
# as a submenu of another menu
submenu_item = SubmenuItem("Submenu item", selection_menu, menu)

# Once we're done creating them, we just add the items to the menu
menu.append_item(menu_item)
menu.append_item(function_item)
menu.append_item(command_item)
menu.append_item(submenu_item)

# Finally, we call show to show the menu and allow the user to interact
menu.show()

Saturday, April 8, 2023

Create an ovoid with python on Blender 3D.

Blender 3D use python version 3.10.9 and you can write your scripts with the Blender 3D features. This script can also be found on the website where I write tutorials. This Python script for Blender 3D creates an ovoid model using the math formula for ovoid:
import bpy
import math

# Define the parameters of the ovoid
a = 1.9
b = 1.5
c = 1.5

# Define the number of vertices in each direction
n_long = 32
n_lat = 16

# Create a new mesh
mesh = bpy.data.meshes.new(name="Ovoid")

# Create the vertices
verts = []
for j in range(n_lat):
    lat = (j / (n_lat - 1)) * math.pi
    for i in range(n_long):
        lon = (i / (n_long - 1)) * 2 * math.pi
        x = a * math.sin(lat) * math.cos(lon)
        y = b * math.sin(lat) * math.sin(lon)
        z = c * math.cos(lat)
        verts.append((x, y, z))

# Create the faces
faces = []
for j in range(n_lat - 1):
    for i in range(n_long - 1):
        v1 = j * n_long + i
        v2 = j * n_long + i + 1
        v3 = (j + 1) * n_long + i + 1
        v4 = (j + 1) * n_long + i
        faces.append((v1, v2, v3, v4))

# Create the mesh and object
mesh.from_pydata(verts, [], faces)
obj = bpy.data.objects.new(name="Ovoid", object_data=mesh)

# Add the object to the scene
scene = bpy.context.scene
scene.collection.objects.link(obj)

Saturday, April 1, 2023

Python 3.11.0 : about execnet python package - part 001.

The execnet Python package allows you to use lightweight interprocess communication using remote Python interpreters. It provides a simple way to execute code in a remote Python interpreter, allowing for easy distribution of work across multiple machines or processes.
With this package, you can create gateways to remote Python interpreters and then execute Python code in that interpreter.
This package provides a simple interface for creating these gateways and for executing code on them, making it easy to distribute work and run code in parallel.
It can be particularly useful for running tests on multiple versions of Python or for distributing computational tasks across multiple machines.
Let's see the first example:
import execnet

def multiplier(channel, factor):
    while not channel.isclosed():
        param = channel.receive()
        channel.send(param * factor)

gw = execnet.makegateway()
channel = gw.remote_exec(multiplier, factor=10)
print(channel)
for i in range(5):
    channel.send(i)
    result = channel.receive()
    print(result)
    assert result == i * 10
gw.exit()
This is the result
<Channel id=1 open>
0
10
20
30
40
Let's see the next example:
import execnet

gw = execnet.makegateway() 
channel = gw.remote_exec("""
    def multiply(x, y):
        return x * y
    
    result = 0
    for i in range(10):
        result += multiply(i, 1)
        print("This is result for ",i," ",result)    
    channel.send(result)

""")

result = channel.receive()
print("This is channel receive result : ", result)
assert result == 45
This is result:
This is channel receive result :  45

Wednesday, March 29, 2023

Python : Open3D cannot be used on Windows 10 and Fedora Linux Distro .

Open3D is an open-source library that supports rapid development of software that deals with 3D data. The Open3D frontend exposes a set of carefully selected data structures and algorithms in both C++ and Python. The backend is highly optimized and is set up for parallelization. Open3D was developed from a clean slate with a small and carefully considered set of dependencies. It can be set up on different platforms and compiled from source with minimal effort. The code is clean, consistently styled, and maintained via a clear code review mechanism. Open3D has been used in a number of published research projects and is actively deployed in the cloud. We welcome contributions from the open-source community.
Today I tested this python package with Windows 10 and Fedora Linux Distro with python versions 11 and 10 ...
This package does not work and you will see why ...
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.

...
According to this issue number 4796 and my test on Windows 10 with a Python version greater than 10 and on Fedora Linux Distro you cannot use this python package.
You can try an older version of Python and try it, see this example:
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_
...
Basically, this python package cannot be used with an old python version in Windows 10.

Sunday, March 26, 2023

Python 3.11.0 : Image generation with OpenAI.

In this tutorial I will show you a python script with PyQt6 and OpenAI that generates an image based on OpenAI token keys and a text that describes the image.
The script is quite simple and requires the installation of python packets: PyQt6,openai.
In the script you can find a python class called MainWindow in which graphic user interface elements are included and openai elements for generating images.
You also need a token key from the official openai page to use for generation.
The script runs with the command python numa_script.py and in the two editboxes is inserted chaie from token API OpenAI and the text that will describe the image to be generated.
This is the python script with the source code:
#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()
This is the result of the source script:

Wednesday, March 22, 2023

Python 3.11.0 : clean from frequent folder and the list of recent files.

This python script that clears all entries in the Windows File Explorer from frequent folder and the list of recent files:
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))

Monday, March 20, 2023

Python 3.11.0 : PySimpleGUI - part 001.

PySimpleGUI runs on Windows, Linux and Mac, just like tkinter, Qt, WxPython and Remi do.
pip install PySimpleGUI --user
Collecting PySimpleGUI
  Downloading PySimpleGUI-4.60.4-py3-none-any.whl (509 kB)
     ---------------------------------------- 510.0/510.0 kB 2.5 MB/s eta 0:00:00
Installing collected packages: PySimpleGUI
Successfully installed PySimpleGUI-4.60.4
I try the default source code and works well:
import PySimpleGUI as sg
sg.theme('DarkAmber')   # Add a little color to your windows
# All the stuff inside your window. This is the PSG magic code compactor...
layout = [  [sg.Text('Some text on Row 1')],
            [sg.Text('Enter something on Row 2'), sg.InputText()],
            [sg.OK(), sg.Cancel()]]

# Create the Window
window = sg.Window('Window Title', layout)
# Event Loop to process "events"
while True:             
    event, values = window.read()
    if event in (sg.WIN_CLOSED, 'Cancel'):
        break

window.close()

Wednesday, March 1, 2023

Python 3.11.0 : The sunpy python package - part 002.

In the last article tutorial, I show some simple examples with the sunpy python package.
Today I installed it again with all of these python packages using the pip tool.
You don't need all of these if you just start, but in time you will need to install them:
pip install sunpy --user
Collecting sunpy
  Downloading sunpy-4.1.3.tar.gz (3.6 MB)
     ---------------------------------------- 3.6/3.6 MB 3.6 MB/s eta 0:00:00
     ...
     Successfully installed PyYAML-6.0 aioftp-0.21.4 astropy-5.2.1 pyerfa-2.0.0.1 sunpy-4.1.3
...
pip install zeep --user
Collecting zeep
  Using cached zeep-4.2.1-py3-none-any.whl (101 kB)  
  ...
  Successfully installed isodate-0.6.1 pytz-2022.7.1 requests-file-1.5.1 requests-toolbelt-0.10.1 zeep-4.2.1
  ...
pip install drms --user
Collecting drms
  Downloading drms-0.6.3-py3-none-any.whl (35 kB)
  ...
  Successfully installed drms-0.6.3 pandas-1.5.3
pip install hvpy --user
Collecting hvpy
  Downloading hvpy-1.0.1-py3-none-any.whl (44 kB)
     ---------------------------------------- 44.0/44.0 kB 359.5 kB/s eta 0:00:00
     ...
     Successfully installed hvpy-1.0.1
pip install scipy --user
Collecting scipy
  Downloading scipy-1.10.1-cp311-cp311-win_amd64.whl (42.2 MB)
     ---------------------------------------- 42.2/42.2 MB 7.4 MB/s eta 0:00:00
     ...
     Successfully installed scipy-1.10.1 
pip install glymur --user
Collecting glymur
  Downloading Glymur-0.12.2-py3-none-any.whl (2.7 MB)
     ---------------------------------------- 2.7/2.7 MB 4.2 MB/s eta 0:00:00
     ...
     Successfully installed glymur-0.12.2
     
Let's use the 1600 Angstrom from these all data of spectral range: 335 Angstrom, 131 Angstrom, 191-195 Angstrom, 211 Angstrom, 1600 Angstrom, 1700 Angstrom, 4500 Angstrom, 171-175 Angstrom, 304 Angstrom, 94 Angstrom
from datetime import datetime
from hvpy import createMovie, DataSource, create_events, create_layers
createMovie(
     startTime=datetime(2023, 2, 27),                    # start from 1st September 2022
     endTime=datetime(2023, 2, 28),                      # end at 5th September 2022
     layers=create_layers([(DataSource.AIA_1600, 100)]), # use AIA_193 Lens with 100% Opacity
     events=create_events(["CH"]),                      # show the Active regions
     eventsLabels=True,                                 # event labels should be included
     imageScale=1,                                      # Image scale in arcseconds per pixel
     hq=True,                                           # Download a higher-quality movie file
     timeout=10,                                        # Wait 10 minutes to get a response
     overwrite=True
)
The result is a video that looks like this :
There are easier ways to get information about the sun…
You can take one screenshot using the api.helioviewer.org feature in your browser.
https://api.helioviewer.org/v2/takeScreenshot/?imageScale=1&layers=[SDO,AIA,AIA,304,1,100]&events=&eventLabels=true&scale=true&scaleType=earth&scaleX=0&scaleY=0&date=2023-02-28T15:00:00.000Z&x1=-1100.0&x2=1100.0&y1=-1100.0&y2=1100.0&display=true&watermark=true&events=[CH,all,1]
You can find movies of the last two days of HMI magnetograms and intensitygrams on this webpage.

Monday, February 27, 2023

Python 3.11.0 : EbookLib python library - part 002.

The last version 3.3 of this file type was published by the EPUB 3 Working Group as a Candidate Recommendation Snapshot on 21 February 2023 ...
I haven't written about the ePub format and python since 2022 because I was busy with all kinds of tasks.
Then I presented a short introduction with some examples on how to create an ePUB file, see that tutorial article.
I like this file type, especially the last format that allows many features, including inserting SVG vector files.
Installing the package is easy on a windows 10 with the pip utility.
pip install ebooklib --user
In the folder with the svg image named cover.svg I created a python file with this content.
from ebooklib import epub

# Create a new EPUB book
book = epub.EpubBook()

# Set the book metadata
book.set_title('My EPUB Book')
book.set_language('en')

# Add a cover image
cover_svg = epub.EpubItem(uid="cover_svg", file_name="cover.svg", media_type="image/svg+xml", content=open("cover.svg").read())
book.add_item(cover_svg)

# Create a new chapter for the cover page
cover_page = epub.EpubHtml(title='Cover Page', file_name='cover.xhtml', lang='en')
cover_page.content = '<img alt="Cover Image" src="cover.svg" />'

# Add the cover page to the book
book.add_item(cover_page)

# Add a chapter to the book
chapter1 = epub.EpubHtml(title='Chapter 1', file_name='chap_1.xhtml', lang='en')
chapter1.content = '<h1>Chapter 1</h1><p>This is the first chapter of my book.</p>'

# Add the chapter to the book
book.add_item(chapter1)

# Create the spine
book.spine = [cover_page, chapter1]

# Generate the EPUB file
epub.write_epub('my_book.epub', book, {})
after running the script this was the result a epub file named my_book.epub.
The result is this simple epub with an SVG file from Wikipedia, see the screenshot take with the Sumatra PDF free software.