Thursday, 9 February 2023

Interesting 20 Python Packages

 


Introduction

Python community has evolved so much is the past few decades, today we will see some of the useful packages from PyPI - The Python Package Index. PyPI is the repository of the software for the python programming language.


Packages


1. signal

Module: signal
Installation: Default Python Module
About:
Signals are an operating system feature that provide a means of notifying your program of an event, and having it handled asynchronously. They can be generated by the system itself, or sent from one process to another. Since signals interrupt the regular flow of your program, it is possible that some operations (especially I/O) may produce error if a signal is received in the middle.
Sample:
import signal

def alarm_received(n, stack):
return

signal.signal(signal.SIGALRM, alarm_received)

signals_to_names = {}
for n in dir(signal):
if n.startswith('SIG') and not n.startswith('SIG_'):
signals_to_names[getattr(signal, n)] = n

for s, name in sorted(signals_to_names.items()):
handler = signal.getsignal(s)
if handler is signal.SIG_DFL:
handler = 'SIG_DFL'
elif handler is signal.SIG_IGN:
handler = 'SIG_IGN'
print('%-10s (%2d):' % (name, s), handler)
'''
Output:
SIGHUP ( 1): SIG_DFL
SIGINT ( 2): <built-in function default_int_handler>
SIGQUIT ( 3): SIG_DFL
SIGILL ( 4): SIG_DFL
SIGTRAP ( 5): SIG_DFL
SIGIOT ( 6): SIG_DFL
SIGEMT ( 7): SIG_DFL
SIGFPE ( 8): SIG_DFL
SIGKILL ( 9): None
SIGBUS (10): SIG_DFL
SIGSEGV (11): SIG_DFL
SIGSYS (12): SIG_DFL
SIGPIPE (13): SIG_IGN
SIGALRM (14): <function alarm_received at 0x7fb2926bb160>
SIGTERM (15): SIG_DFL
SIGURG (16): SIG_DFL
SIGSTOP (17): None
SIGTSTP (18): SIG_DFL
SIGCONT (19): SIG_DFL
SIGCHLD (20): SIG_DFL
SIGTTIN (21): SIG_DFL
SIGTTOU (22): SIG_DFL
SIGIO (23): SIG_DFL
SIGXCPU (24): SIG_DFL
SIGXFSZ (25): SIG_IGN
SIGVTALRM (26): SIG_DFL
SIGPROF (27): SIG_DFL
SIGWINCH (28): SIG_DFL
SIGINFO (29): SIG_DFL
SIGUSR1 (30): SIG_DFL
SIGUSR2 (31): SIG_DFL
'''
Reference:
https://docs.python.org/3/library/signal.html
https://pymotw.com/2/signal/

2. scipy

Module: scipy
Installation: pip install scipy
About:
SciPy (pronounced “Sigh Pie”) is an open-source software for mathematics, science, and engineering. It includes modules for statistics, optimization, integration, linear algebra, Fourier transforms, signal and image processing, ODE solvers, and more. SciPy uses NumPy arrays as the basic data structure, and comes with modules for various commonly used tasks in scientific programming.
Sample:
# Import the required libraries
from scipy import linalg
import numpy as np
# The function takes two arrays
a = np.array([[7, 2], [4, 5]])
b = np.array([8, 10])
# Solving the linear equations
res = linalg.solve(a, b)
print(res)

'''
Output:
[0.74074074 1.40740741]
'''
Reference:
https://pypi.org/project/scipy/
https://docs.scipy.org/doc/scipy/

3. pytube

Module: pytube
Installation: pip install pytube
About:
pytube is a genuine, lightweight, dependency-free Python library (and command-line utility) for downloading YouTube videos.
pytube also makes pipelining easy, allowing you to specify callback functions for different download events, such as on progress or on complete.
Sample:
from pytube import YouTube
yt = YouTube('http://youtube.com/watch?v=2lAe1cqCOXo')
vedio_file = yt.streams.filter(progressive=True, file_extension='mp4').get_by_resolution('360p')
vedio_file.download("pycon_india.mp4")
print("download completed")

'''
Output:
>> ls
pycon_india.mp4
'''
Reference:
https://pypi.org/project/pytube/

4. pyperclip

Module: pyperclip
Installation: pip install pyperclip
About:
Pyperclip is a cross-platform Python module for copy and paste clipboard functions. If something outside your program changes the clipboard contents, the paste() function will return it. For example, if this sentence is copied to the clipboard and then paste() is called, the output would be printed.
Source:
import pyperclip
pyperclip.copy("Hello world !")
pyperclip.paste()
Reference:
https://pypi.org/project/pyperclip/

5. pyaztro

Module: pyaztro
Installation: pip install pyaztro
About:
PyAztro is a client library for aztro written in Python.
aztro provides horoscope info for sun signs such as Lucky Number, Lucky Color, Mood, Color, Compatibility with other sun signs, description of a sign for that day etc.
Sample:
import pyaztro
horoscope = pyaztro.Aztro(sign='aries')
print(horoscope.description)

'''
Output:
'Diligent'
'''
Reference:
https://pypi.org/project/pyaztro/

6. psutil

Module: psutil
Installation: pip install psutil
About:
Used to calculate the resource usage of a computer such as CPU, RAM, Disks, Network, Process, System info and so on.
Sample:
## Import
>> import psutil

## Process IDs
psutil.pids()
[1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224, 268, 1215,
1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355, 2637, 2774, 3932,
4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245, 4263, 4282, 4306, 4311,
4312, 4313, 4314, 4337, 4339, 4357, 4358, 4363, 4383, 4395, 4408, 4433,
4443, 4445, 4446, 5167, 5234, 5235, 5252, 5318, 5424, 5644, 6987, 7054,
7055, 7071]

## CPU Info
>> psutil.cpu_times()
scputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540, iowait=629.59, irq=0.0, softirq=19.42, steal=0.0, guest=0, nice=0.0)

## Memory
>> psutil.virtual_memory()
svmem(total=10367352832, available=6472179712, percent=37.6, used=8186245120, free=2181107712, active=4748992512, inactive=2758115328, buffers=790724608, cached=3500347392, shared=787554304)
>> psutil.swap_memory()
sswap(total=2097147904, used=296128512, free=1801019392, percent=14.1, sin=304193536, sout=677842944)

## Disk
>> psutil.disk_partitions()
[sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,nosuid', maxfile=255, maxpath=4096),
sdiskpart(device='/dev/sda2', mountpoint='/home', fstype='ext', opts='rw', maxfile=255, maxpath=4096)]
Reference:
https://pypi.org/project/psutil/

7. PyAutoGUI

Module: PyAutoGUI
Installation: pip install PyAutoGUI
About:
PyAutoGUI is a cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard, also can use it to take screenshots.
Sample:
import pyautogui

currentMouseX, currentMouseY = pyautogui.position() # Returns two integers, the x and y of the mouse cursor's current position.

im1 = pyautogui.screenshot() # Saves the screenshot of the current screen
im1.save('my_screenshot.png')
im2 = pyautogui.screenshot('my_screenshot2.png')

'''
Output:
2016-10-30 12:30:30
2016-10-30 12:30:30
time.struct_time(tm_year=2016, tm_mon=10, tm_mday=30, tm_hour=12, tm_min=30, tm_sec=30, tm_wday=6, tm_yday=304, tm_isdst=-1)
1477810830
'''
Reference:
https://pypi.org/project/PyAutoGUI/

8. PDFknife

Module: PDFknife
Installation: pip install PDFknife
About:
A Swiss Army Knife sort of python scripts collection to manipulate PDFs. It relies on:
pdfjam
pdftk
pdfunite (poppler)
ghostscript
mupdf-tools
Execution:
pdfknife-A5.py -- Turn a PDF in A5 format
pdfknife-even.py -- Add blank page to odd pages PDF
pdfknife-extract -- Extract images from PDF
pdfknife-merge.py -- Merge PDFs
pdfknife-recto.py -- Add blank page between each original page
pdfknife-reverse.py -- Reverse page order
pdfknife-shrink.py -- Compress a PDF
pdfknife-split.py -- Make one page per file
pdfknife-trim.py -- Change the margins
Reference:
https://pypi.org/project/PDFknife/

9. mypy

Module: mypy
Installation: pip install mypy
About:
Add type annotations to your Python programs, and use mypy to type check them. Mypy is essentially a Python linter on steroids, and it can catch many programming errors by analyzing your program, without actually having to run it. Mypy has a powerful type system with features such as type inference, gradual typing, generics and union types.
Sample:
$ pip install mypy
$ cat headlines.py
def headline(text: str, align: bool = True) -> str:
if align:
return f"{text.title()}\n{'-' * len(text)}"
else:
return f" {text.title()} ".center(50, "o")

print(headline("python type checking"))
print(headline("use mypy", align="center"))
$ mypy headlines.py
headlines.py:10: error: Argument "align" to "headline" has incompatible type "str"; expected "bool"
$ cat headlines.py
def headline(text: str, centered: bool = False):
if not centered:
return f"{text.title()}\n{'-' * len(text)}"
else:
return f" {text.title()} ".center(50, "o")

print(headline("python type checking"))
print(headline("use mypy", centered=True))
$ mypy headlines.py ## No output means no errors
Reference:
https://pypi.org/project/mypy/
https://realpython.com/lessons/type-checking-mypy/

10. modin

Module: modin
Installation: pip install modin
About:
Modin is a drop-in replacement for pandas. While pandas is single-threaded, Modin lets you instantly speed up your workflows by scaling pandas so it uses all of your cores. Modin works especially well on larger datasets, where pandas becomes painfully slow or runs out of memory.
By simply replacing the import statement, Modin offers users effortless speed and scale for their pandas workflows:
import modin.pandas as pd
Sample:
import modin.pandas as pd
import numpy as np
df = pd.read_csv("my_dataset.csv")

left_data = np.random.randint(0, 100, size=(2**8, 2**8))
right_data = np.random.randint(0, 100, size=(2**12, 2**12))

left_df = pd.DataFrame(left_data)
right_df = pd.DataFrame(right_data)

%timeit left_df.merge(right_df, how="inner", on=10)
3.59 s 107 ms per loop (mean std. dev. of 7 runs, 1 loop each)

%timeit right_df.merge(left_df, how="inner", on=10)
1.22 s 40.1 ms per loop (mean std. dev. of 7 runs, 1 loop each)
Reference:
https://pypi.org/project/modin/

11. Kivy

Module: Kivy
Installation: pip install Kivy
About:
Kivy is an open source, cross-platform Python framework for the development of applications that make use of innovative, multi-touch user interfaces.
The aim is to allow for quick and easy interaction design and rapid prototyping whilst making your code reusable and deployable.
Runs on Android, iOS, Linux, macOS, and Windows.
Support graphics engine built over the OpenGL ES 2.
Sample:
# base Class of your App inherits from the App class.
from kivy.app import App
# GridLayout arranges children in a matrix.
from kivy.uix.gridlayout import GridLayout
# Label is used to label something
from kivy.uix.label import Label
# used to take input from users
from kivy.uix.textinput import TextInput
class LoginScreen(GridLayout):
def __init__(self, **var_args):
super(LoginScreen, self).__init__(**var_args)
# super function can be used to gain access
# to inherited methods from a parent or sibling class
# that has been overwritten in a class object.
self.cols = 2 # You can change it accordingly
self.add_widget(Label(text='User Name'))
self.username = TextInput(multiline=True)
# multiline is used to take
# multiline input if it is true
self.add_widget(self.username)
self.add_widget(Label(text='password'))
self.password = TextInput(password=True, multiline=False)
# password true is used to hide it
# by * self.add_widget(self.password)
self.add_widget(Label(text='Comfirm password'))
self.password = TextInput(password=True, multiline=False)
self.add_widget(self.password)
# the Base Class of our Kivy App
class MyApp(App):
def build(self):
# return a LoginScreen() as a root widget
return LoginScreen()
if __name__ == '__main__':
MyApp().run()
Reference:
https://pypi.org/project/Kivy/
https://www.geeksforgeeks.org/python-make-a-simple-window-using-kivy/

12. fire

Module: fire
Installation: pip install fire
About:
Python Fire is a library for automatically generating command line interfaces (CLIs) with a single line of code.
It will turn any Python module, class, object, function, etc.  into a CLI. It’s called Fire because when you call Fire(), it fires off your command.
Sample:
import fire

def add(x, y):
return x + y

def multiply(x, y):
return x * y

if __name__ == '__main__':
fire.Fire()

'''
Output:
$ python example.py add 10 20
30
$ python example.py multiply 10 20
200
'''
Reference:
https://pypi.org/project/fire/

13. ExifRead

Module: ExifRead
Installation: pip install ExifRead
About:
Easy to use Python module to extract Exif metadata from digital image files.
Supported formats: TIFF, JPEG, PNG, Webp, HEIC.
Sample:
from os import path
import exifread
path_name = r'C:\Users\Desktop\sss.jpg'
filename = open(path_name, 'rb')
tags = exifread.process_file(filename)
print(tags)

'''
Output:
{'EXIF ApertureValue': (0x9202) Ratio=45/8 @ 644,
'EXIF ColorSpace': (0xA001) Short=sRGB @ 452,
'EXIF ComponentsConfiguration': (0x9101) Undefined=YCbCr @ 308,
'EXIF CustomRendered': (0xA401) Short=Normal @ 536,
....
'Image Orientation': (0x0112) Short=Horizontal (normal) @ 42,
'Image ResolutionUnit': (0x0128) Short=Pixels/Inch @ 78,
'Image Software': (0x0131) ASCII=GIMP 2.4.5 @ 182,
'Image XResolution': (0x011A) Ratio=72 @ 166,
'Image YResolution': (0x011B) Ratio=72 @ 174,
'Interoperability InteroperabilityIndex': (0x0001) ASCII=R98 @ 958,
'Interoperability InteroperabilityVersion': (0x0002) Undefined=[48, 49, 48, 48] @ 970,
'Thumbnail Compression': (0x0103) Short=JPEG (old-style) @ 1006,
'Thumbnail ResolutionUnit': (0x0128) Short=Pixels/Inch @ 1042,
'Thumbnail XResolution': (0x011A) Ratio=72 @ 1074,
'Thumbnail YResolution': (0x011B) Ratio=72 @ 1082}
'''
Reference:
https://pypi.org/project/ExifRead/

14. python-dateutil

Module: python-dateutil
Installation: pip install python-dateutil
About:
Generic parsing of dates in almost any string format. Computing of relative deltas (next month, next year, next Monday, last week of month, etc). Computing of relative deltas between two given date and/or datetime objects.
Sample:
>>> from dateutil.relativedelta import *
>>> from dateutil.easter import *
>>> from dateutil.rrule import *
>>> from dateutil.parser import *
>>> from datetime import *

>>> now = parse("Sat Oct 11 17:13:46 UTC 2003")
>>> today = now.date()
>>> print("Today is: %s" % today)
Today is: 2003-10-11

>>> year = rrule(YEARLY,dtstart=now,bymonth=8,bymonthday=13,byweekday=FR)[0].year
>>> print("Year with next Aug 13th on a Friday is: %s" % year)
Year with next Aug 13th on a Friday is: 2004

>>> rdelta = relativedelta(easter(year), today)
>>> print("How far is the Easter of that year: %s" % rdelta)
How far is the Easter of that year: relativedelta(months=+6)

>>> print("And the Easter of that year is: %s" % (today+rdelta))
And the Easter of that year is: 2004-04-11
Reference:
https://pypi.org/project/python-dateutil/

15. better-profanity

Module: better-profanity
Installation: pip install better-profanity
About:
A module that you can use to rid your text of bad words. 
Sample:
from better_profanity import profanity

custom_badwords = ['happy', 'jolly', 'merry']
profanity.add_censor_words(custom_badwords)

text = "This is sHit."
censored_text = profanity.censor(text)
print(censored_text) ## print censored string

text = "Have a merry day! :)"
print(profanity.contains_profanity(text)) ## verifies if string contains bad words
censored_text = profanity.censor(text)
print(censored_text)

'''
Output:
This is ****.
True
Have a **** day! :)
'''
Reference:
https://pypi.org/project/better-profanity/

16. BeautifulTime

Module: BeautifulTime
Installation: pip install BeautifulTime
About:
BeautifulTime is a python package for converting date string, datetime, time and timestamp.
Sample:
import BeautifulTime
date_str = '2016-10-30 12:30:30'
dt = BeautifulTime.str2datetime(date_str)
print(dt)
# with a custom format
dt = BeautifulTime.str2datetime(date_str, format='%Y-%m-%d %H:%M:%S')
print(dt)
t = BeautifulTime.str2time(date_str)
print(t)
ts = BeautifulTime.str2timestamp(date_str)
print(ts)
'''
Output:
2016-10-30 12:30:30
2016-10-30 12:30:30
time.struct_time(tm_year=2016, tm_mon=10, tm_mday=30, tm_hour=12, tm_min=30, tm_sec=30, tm_wday=6, tm_yday=304, tm_isdst=-1)
1477810830
'''
Reference:
https://pypi.org/project/BeautifulTime/

17. Bandit

Module: Bandit
Installation: pip install bandit
About:
Bandit is a tool designed to find common security issues in Python code. 
To do this Bandit processes each file, builds an AST from it, and runs appropriate plugins against the AST nodes. 
Once Bandit has finished scanning all the files it generates a report.
Bandit was originally developed within the OpenStack Security Project and later rehomed to PyCQA.
Sample:
% bandit thirukkural_sample.py
[main] INFO profile include tests: None
[main] INFO profile exclude tests: None
[main] INFO cli include tests: None
[main] INFO cli exclude tests: None
[main] INFO running on Python 3.8.5
[node_visitor] WARNING Unable to find qualified name for module: thirukkural_sample.py
Run started:2023-04-17 19:40:21.590814

Test results:
No issues identified.

Code scanned:
Total lines of code: 27
Total lines skipped (#nosec): 0

Run metrics:
Total issues (by severity):
Undefined: 0
Low: 0
Medium: 0
High: 0
Total issues (by confidence):
Undefined: 0
Low: 0
Medium: 0
High: 0
Files skipped (0):

Reference:
https://pypi.org/project/bandit/

18. arrow

Module: arrow
Installation: pip install arrow
About:
Arrow is a Python library that offers a human-friendly approach to creating, manipulating, formatting and converting dates, times and timestamps. It implements and updates the datetime type, plugging gaps in functionality and providing an intelligent module API that supports many common creation scenarios. 
Sample:
>>> import arrow
>>> arrow.get('2023-05-11T21:23:58.970460+07:00')
<Arrow [2023-05-11T21:23:58.970460+07:00]>

>>> utc = arrow.utcnow()
>>> utc
<Arrow [2023-05-11T21:23:58.970460+00:00]>

>>> utc = utc.shift(hours=-1)
>>> utc
<Arrow [2023-05-11T20:23:58.970460+00:00]>

>>> local = utc.to('US/Pacific')
>>> local
<Arrow [2023-05-11T13:23:58.970460-07:00]>

>>> local.timestamp()
1368303838.970460

>>> local.format()
'2023-05-11 13:23:58 -07:00'

>>> local.format('YYYY-MM-DD HH:mm:ss ZZ')
'2023-05-11 13:23:58 -07:00'

>>> local.humanize()
'an hour ago'

>>> local.humanize(locale='ko-kr')
'한시간 전'
Reference:
https://pypi.org/project/arrow/

19. tqdm

Module: tqdm

Installation: pip install tqdm

About:

tqdm derives from the Arabic word taqaddum (تقدّم) which can mean “progress”. Instantly make your loops show a smart progress meter - just wrap any iterable with tqdm(iterable), and you’re done!

Sample:

Reference:

https://pypi.org/project/tqdm/


20. gTTS

Module: gTTS

Installation: pip install gTTS

About:

gTTS (Google Text-to-Speech), a Python library and CLI tool to interface with Google Translate's text-to-speech API.

Sample: 

from gtts import gTTS
tts = gTTS('hello')
tts.save('hello.mp3')

Reference:

https://pypi.org/project/gTTS/


No comments:

Post a Comment

Scarcity Brings Efficiency: Python RAM Optimization

  In today’s world, with the abundance of RAM available, we rarely think about optimizing our code. But sooner or later, we hit the limits a...