Friday, July 19, 2024

Run a Simple PyGame program to any Browser

 Pygbag is a project that allows you to run Pygame-based Python games in the browser. It converts your Pygame projects into WebAssembly, enabling them to run in modern web browsers. Here’s a step-by-step guide on how to create a simple Pygame project and use Pygbag to run it in the browser:

Step-by-Step Guide to Creating a Pygame Project with Pygbag

1. Install Pygame:

    Make sure you have Pygame installed on your system.

pip install pygame

2.  Create a Simple Pygame Project:

     Create a directory for your project and add a simple Pygame script.


    Here’s an example main.py script:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import asyncio
import pygame
import sys

# Initialize Pygame
pygame.init()

# Set up the display
size = width, height = 800, 600
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pygbag Example")

# Set up colors
black = (0, 0, 0)
blue = (0, 0, 255)

# Set up the ball
ball = pygame.image.load("ball.png")
ballrect = ball.get_rect()

# Set up ball speed
speed = [2, 2]

async def main():
    global ballrect  # Explicitly declare ballrect as global to modify it within the function
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()

        ballrect = ballrect.move(speed)
        if ballrect.left < 0 or ballrect.right > width:
            speed[0] = -speed[0]
        if ballrect.top < 0 or ballrect.bottom > height:
            speed[1] = -speed[1]

        screen.fill(black)
        screen.blit(ball, ballrect)
        pygame.display.update()

        await asyncio.sleep(0)  # Yield control to the event loop

asyncio.run(main())

    Make sure you have an image named ball.png in the same directory as your main.py script.

3.  Install Pygbag:

    Install Pygbag using pip.

pip install pygbag

4. Run Pygbag to Package Your Game:

    Use Pygbag to package your game and run it in the browser.

pygbag <my_pygame_project>

5.  Open the Game in Your Browser:

    After running the above command, Pygbag will start a local web server and provide a URL(http://localhost:8000/). Open this URL in your web browser to play your game.

By following these steps, you can create a simple Pygame project and use Pygbag to run it in any web browser. This allows you to leverage Pygame’s capabilities while making your game accessible on the web.

Thursday, July 18, 2024

Chat with Ollama Phi3 in Python Offline

 Ollama lets you download and run local versions of LLMs of your choice. In this article, I downloaded Phi3 with 8B parameters.

To begin, download the Ollama software from their website. Then, in the DOS prompt, type ollama run phi3. The download will begin, and after downloading, it will start Phi3 right away so you can chat with Phi3 immediately.

Install the required library.

pip install langchain_community

Next, I prepared this Python program to interact with Phi3 locally, i.e., offline:

1
2
3
4
5
6
7
8
from langchain_community.llms import Ollama

llm = Ollama(
    model="phi3"
)  # assuming you have Ollama installed and have the phi3 model pulled with `ollama pull phi3`

x = llm.invoke("Tell me a joke")
print(x)

Saturday, July 13, 2024

A Simple Python Email Server for offline use

 Creating a simple offline Python email server can be achieved using the smtplib library for sending emails and a basic SMTP server for testing. This server won't connect to the internet but will allow you to send and receive emails locally.

Here’s a step-by-step guide to set up a simple offline Python email server:

  1. Install Python Libraries: Ensure you have Python installed. You may also need the smtplib and email libraries, which are typically included in the standard library.

  2. Create a Local SMTP Server: Use Python’s smtpd module to create a local SMTP server.

  3. Send Emails: Use the smtplib module to send emails through the local server.

Here’s an example implementation:

Step 1: Create a Local SMTP Server

Create a Python script (local_smtp_server.py) to start a local SMTP server:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import smtpd
import asyncore

class CustomSMTPServer(smtpd.SMTPServer):
    def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
        print('Message received from:', peer)
        print('Message addressed from:', mailfrom)
        print('Message addressed to  :', rcpttos)
        print('Message length        :', len(data))
        return

if __name__ == '__main__':
    server = CustomSMTPServer(('localhost', 1025), None)
    asyncore.loop()

Step 2: Run the Local SMTP Server

Run the script in your terminal:

1
python local_smtp_server.py

The server will start and listen for incoming emails on localhost:1025.

Step 3: Send Emails Using the Local SMTP Server

Create another Python script (send_email.py) to send emails using the local server:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import smtplib
from email.mime.text import MIMEText

def send_email(subject, body, from_email, to_email):
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = to_email

    with smtplib.SMTP('localhost', 1025) as server:
        server.sendmail(from_email, [to_email], msg.as_string())

if __name__ == '__main__':
    subject = 'Test Email'
    body = 'This is a test email sent from a local SMTP server.'
    from_email = 'sender@example.com'
    to_email = 'receiver@example.com'

    send_email(subject, body, from_email, to_email)

Step 4: Run the Email Sending Script

Run the script in your terminal:

1
python send_email.py

You should see the email details printed in the terminal where the local SMTP server is running, indicating that the email was successfully sent and received by the server.

This setup allows you to test email sending and receiving functionalities locally without the need for an internet connection.