Hasan Yousef
Hasan Yousef
MModular
Created by Hasan Yousef on 10/24/2024 in #questions
Python integration: address not mapped to object
I wrote the below simple python code at jupyter notebook for stamping my pdf documents:
import fitz # PyMuPDF
def add_signature(input_pdf, output_pdf, signature_image, x, y, stamp_width, stamp_height):
doc = fitz.open(input_pdf)

# Iterate through each page and insert the signature
for page in doc:
rect = fitz.Rect(x, y, x + stamp_width, y + stamp_height) # Use defined width and height
page.insert_image(rect, filename=signature_image)

doc.save(output_pdf)
doc.close()

print(f"Signature added to {output_pdf}.")
import fitz # PyMuPDF
def add_signature(input_pdf, output_pdf, signature_image, x, y, stamp_width, stamp_height):
doc = fitz.open(input_pdf)

# Iterate through each page and insert the signature
for page in doc:
rect = fitz.Rect(x, y, x + stamp_width, y + stamp_height) # Use defined width and height
page.insert_image(rect, filename=signature_image)

doc.save(output_pdf)
doc.close()

print(f"Signature added to {output_pdf}.")
I tried writing a mojo code for the same, so wrote:
from python import Python

def add_signature(input_pdf: String, output_pdf: String, signature_image: String, x: Int, y: Int, stamp_width: Int, stamp_height: Int):

var fitz = Python.import_module("fitz")
var doc = fitz.open(input_pdf)

for page in doc:
rect = fitz.Rect(x, y, x + stamp_width, y + stamp_height) # Define rectangle for the signature
page.insert_image(rect, filename=signature_image) # Insert the image

doc.save(output_pdf)
doc.close()

print("Signature added to ", output_pdf)
from python import Python

def add_signature(input_pdf: String, output_pdf: String, signature_image: String, x: Int, y: Int, stamp_width: Int, stamp_height: Int):

var fitz = Python.import_module("fitz")
var doc = fitz.open(input_pdf)

for page in doc:
rect = fitz.Rect(x, y, x + stamp_width, y + stamp_height) # Define rectangle for the signature
page.insert_image(rect, filename=signature_image) # Insert the image

doc.save(output_pdf)
doc.close()

print("Signature added to ", output_pdf)
I'm calling the function, in bot python and mojo using:
input_pdf = "input.pdf"
output_pdf = "signed_output.pdf"
signature_image = "my_stamp.png"
x_position = 300 # X position for signature
y_position = 600 # Y position for signature
stamp_width = 200 # Set desired width
stamp_height = 100 # Set desired height

add_signature(input_pdf, output_pdf, signature_image, x_position, y_position, stamp_width, stamp_height)
input_pdf = "input.pdf"
output_pdf = "signed_output.pdf"
signature_image = "my_stamp.png"
x_position = 300 # X position for signature
y_position = 600 # Y position for signature
stamp_width = 200 # Set desired width
stamp_height = 100 # Set desired height

add_signature(input_pdf, output_pdf, signature_image, x_position, y_position, stamp_width, stamp_height)
With python I got the output.dpf correctly, but with mojo I got the error:
error: Execution was interrupted, reason: signal SIGSEGV: address not mapped to object (fault address: 0x4d).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
error: Execution was interrupted, reason: signal SIGSEGV: address not mapped to object (fault address: 0x4d).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
What could be my mistake here?
2 replies
MModular
Created by Hasan Yousef on 9/27/2024 in #questions
ARM support
No description
2 replies
MModular
Created by Hasan Yousef on 9/24/2024 in #questions
MOJO embeded
Can I use mojo like mictopython for programming Raspberry PI Pico 2. https://store.rpipress.cc/products/get-started-with-micropython-on-raspberry-pi-pico-2nd-edition
3 replies
MModular
Created by Hasan Yousef on 9/21/2024 in #questions
Compile to Shared Library
Can I compile mojo code as a shared library,? If yes, how?
6 replies
MModular
Created by Hasan Yousef on 9/19/2024 in #questions
Define Tuple with PuthonObject
Trying to convert the below opencv python code to mojolang:
import cv2 as cv

cap = cv.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
# Capture frame-by-frame
ret, frame = cap.read()

# if frame is read correctly ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# Our operations on the frame come here
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# Display the resulting frame
cv.imshow('frame', gray)
if cv.waitKey(1) == ord('q'):
break

# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
import cv2 as cv

cap = cv.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
# Capture frame-by-frame
ret, frame = cap.read()

# if frame is read correctly ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# Our operations on the frame come here
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# Display the resulting frame
cv.imshow('frame', gray)
if cv.waitKey(1) == ord('q'):
break

# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
So, I wrote the below:
from python import Python

def main():
# This is equivalent to Python's `import numpy as np`
cv = Python.import_module("cv2")

cap = cv.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
# exit()
while True:
# Capture frame-by-frame
var ret, frame = cap.read() # I get the error here

# if frame is read correctly ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# Our operations on the frame come here
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# Display the resulting frame
cv.imshow('frame', gray)
if cv.waitKey(1) == ord('q'):
break

# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
from python import Python

def main():
# This is equivalent to Python's `import numpy as np`
cv = Python.import_module("cv2")

cap = cv.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
# exit()
while True:
# Capture frame-by-frame
var ret, frame = cap.read() # I get the error here

# if frame is read correctly ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# Our operations on the frame come here
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# Display the resulting frame
cv.imshow('frame', gray)
if cv.waitKey(1) == ord('q'):
break

# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
I got the error: declaration must have either a type or an initializer at the line var ret, frame = cap.read()
8 replies
MModular
Created by Hasan Yousef on 9/17/2024 in #questions
Example of parallel computing
I read the this, but unfortunately could not understand how can I do parallel computing at MOJO, can any help help with simple code sample. Thanks https://docs.modular.com/mojo/stdlib/algorithm/functional/parallelize
8 replies
MModular
Created by Hasan Yousef on 9/14/2024 in #questions
How can I convert String to StringLiteral
I understood that str() is required to convert things to String like (StringLiteral, Int, Bool, ...), but is there a way to covert String to LiteralString. As part of learning Mojolang I'm trying the below code, then this conversion issue poped up.
from collections import List
from sys.ffi import external_call

alias system = external_call["system", Int, StringLiteral]

fn run_commands(arg0: String, args: List[String]) -> Int:
var command: String = arg0
for arg in args:
command += " " + arg[]
return system(command) # invalid indirect call: argument #0 cannot be converted from 'String' to 'StringLiteral'

fn system2(arg0: String, args: List[String]) -> Int:
var command: String = arg0
for arg in args:
command += " " + arg[] # Access the element inside the list
return external_call["system", Int, String](command)

fn main():
# var args = List[String]("kill", "-9", "$(lsof -t -i :8000)")
var args = List[String]("ls")
_ = run_commands(args[0], args[1:])
_ = system2(args[0], args[1:])
from collections import List
from sys.ffi import external_call

alias system = external_call["system", Int, StringLiteral]

fn run_commands(arg0: String, args: List[String]) -> Int:
var command: String = arg0
for arg in args:
command += " " + arg[]
return system(command) # invalid indirect call: argument #0 cannot be converted from 'String' to 'StringLiteral'

fn system2(arg0: String, args: List[String]) -> Int:
var command: String = arg0
for arg in args:
command += " " + arg[] # Access the element inside the list
return external_call["system", Int, String](command)

fn main():
# var args = List[String]("kill", "-9", "$(lsof -t -i :8000)")
var args = List[String]("ls")
_ = run_commands(args[0], args[1:])
_ = system2(args[0], args[1:])
5 replies
MModular
Created by Hasan Yousef on 9/14/2024 in #questions
C/C++ Interop
My understaffed is horror we can get something like: https://docs.modular.com/mojo/roadmap#cc-interop And for clib interop we have sys.ffi.external_call My question is if I have a foo-lib.so that is a c/c++ lob, how can I call it's functions, and do I need the foo.h also?
5 replies
MModular
Created by Hasan Yousef on 9/12/2024 in #questions
Embedding
Hi all, not sure if I have to ask here or at MAX channek, is there embedding, vector database and similarity search in MAX that I can use with LLM?
3 replies
MModular
Created by Hasan Yousef on 2/13/2024 in #questions
Printf - print format
Is there a print format in mojo، how can I rewrite this python in mojo:
def fun (arg):
print(f'arg = {arg}')
bar = [5, 10, 15, 20]
def fun (arg):
print(f'arg = {arg}')
bar = [5, 10, 15, 20]
1 replies
MModular
Created by Hasan Yousef on 1/28/2024 in #questions
import gpu.Function
No description
4 replies
MModular
Created by Hasan Yousef on 1/6/2024 in #questions
Reducing binary size
No description
4 replies
MModular
Created by Hasan Yousef on 12/23/2023 in #questions
Running Mojo executable at Alpine docker
I created a mojo dockerfile the is working fine:
FROM ubuntu:latest
FROM ubuntu:latest
And wanted to use it as a builder image:
#Builder
FROM mojo-sdk:latest as builder
WORKDIR /app
COPY main.mojo /app/main.mojo
RUN /root/.modular/pkg/packages.modular.com_mojo/bin/mojo build /app/main.mojo

#Final
FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/main /app/main
RUN chmod +x /app/main
ENTRYPOINT ["tail"]
CMD ["-f", "/dev/null"]
#Builder
FROM mojo-sdk:latest as builder
WORKDIR /app
COPY main.mojo /app/main.mojo
RUN /root/.modular/pkg/packages.modular.com_mojo/bin/mojo build /app/main.mojo

#Final
FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/main /app/main
RUN chmod +x /app/main
ENTRYPOINT ["tail"]
CMD ["-f", "/dev/null"]
But I could not run the executable at the alpine based docker, and got the error:
/app # ls
main
/app # ./main
sh: ./main: not found
/app # ls -l
total 1040
-rwxr-xr-x 1 root root 1061752 Dec 23 18:27 main
/app # ls
main
/app # ./main
sh: ./main: not found
/app # ls -l
total 1040
-rwxr-xr-x 1 root root 1061752 Dec 23 18:27 main
I guess there are some dependencies that are exisiting at ubuntu and not exisiting at the Alpine docker, that is making the executable not be seen, noting that I just built the simpletst "heelo world" example.
1 replies
MModular
Created by Hasan Yousef on 12/15/2023 in #questions
Building Shared and Dynamic library
Can I build an executable and a library with mojo lang or executable only?
3 replies
MModular
Created by Hasan Yousef on 12/8/2023 in #questions
Distributing the binary as a docker image
I'm playing with mojo at ArchLinux and I am very excited about it, considering it is not yet supporting Windows, nor cross compilation, I would like to build a docker image of my binary, and import it at my Windows docker desktop, I would like to import from the scratch docker, what is the minimal setup or dependencies that should be including in my docker image to get the binary built using mojo run smoothly?
5 replies
MModular
Created by Hasan Yousef on 11/18/2023 in #questions
Running code at GPU
How can I write a mojo code that is executed at the GPU instead of the CPU?
14 replies
MModular
Created by Hasan Yousef on 10/19/2023 in #questions
Create a CSR
I can create CSR in Go as below, is there something similar in Mojo
package main

import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
)

func main() {
// Generate a new private key.
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Println(err)
return
}

// Create a simple template for the CSR.
csrTemplate := x509.CertificateRequest{
Subject: pkix.Name{
CommonName: "example.com",
Organization: []string{"Example, LLC"},
},
SignatureAlgorithm: x509.SHA256WithRSA,
}

// Create the CSR.
csrBytes, err := x509.CreateCertificateRequest(rand.Reader, &csrTemplate, priv)
if err != nil {
fmt.Println(err)
return
}

// PEM encode the CSR.
csrPEM := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE REQUEST",
Bytes: csrBytes,
})

fmt.Printf("%s\n", csrPEM)
}
package main

import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
)

func main() {
// Generate a new private key.
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Println(err)
return
}

// Create a simple template for the CSR.
csrTemplate := x509.CertificateRequest{
Subject: pkix.Name{
CommonName: "example.com",
Organization: []string{"Example, LLC"},
},
SignatureAlgorithm: x509.SHA256WithRSA,
}

// Create the CSR.
csrBytes, err := x509.CreateCertificateRequest(rand.Reader, &csrTemplate, priv)
if err != nil {
fmt.Println(err)
return
}

// PEM encode the CSR.
csrPEM := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE REQUEST",
Bytes: csrBytes,
})

fmt.Printf("%s\n", csrPEM)
}
2 replies
MModular
Created by Hasan Yousef on 9/28/2023 in #questions
Parallelism and multithreading
I couldn't find a sample code of Mojo multithreading, Can anyone guide me where I can find the proper guide, or provide me with sample snippets to learn from. thanks
3 replies
MModular
Created by Hasan Yousef on 9/25/2023 in #questions
HOWTO fetch internet resources
Is there a way in mojo that can be used for fetching websites, get and post?
14 replies