Python: convert procedural script to class and object (oop) style - python

I am still learning to code in python and I am struggling to code object-oriented way. I have written a code using pytessarct library and with the extracted words I have tried to make a simple detector by using keywords as a filter. I want to redo it in class and object format strictly as a learning exercise. Will be highly grateful if anybody can extend any help. Thank you
import pytesseract
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
import os
import cv2
from PIL import Image
import matplotlib.pyplot as plt
from PIL import ImageFilter
import re
img_path = 'C:/Users/RAJ/realtest/'
for i in os.listdir(img_path):
images=Image.open(img_path+'//'+i)
plt.imshow(images)
plt.show()
images_new=images.convert('LA')
im_SHARPEN2 = images_new.filter(filter=ImageFilter.SHARPEN)
extract = pytesseract.image_to_string(im_SHARPEN2, lang = 'eng')
extract2 = pytesseract.image_to_string(images_new,lang = 'eng')
final= extract+extract2
x = re.search(r"INCOME|TAX|Account|GOVT.", final,re.M|re.I)
y = re.search(r"GOVERNMENT|DOB|Male|Female.", final,re.M|re.I)
if x == None and y== None:
print('Not a pan card or adhaar card')
elif type(x)== re.Match:
print('This is a pan card')
else:
print('adhaar card detected')

import pytesseract
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
import os
import cv2
from PIL import Image
import matplotlib.pyplot as plt
from PIL import ImageFilter
import re
class is_pan_card():
def __init__(self,path):
self.img_path = path
for i in os.listdir(self.img_path):
images=Image.open(self.img_path+'//'+i)
plt.imshow(images)
plt.show()
images_new=images.convert('LA')
im_SHARPEN2 = images_new.filter(filter=ImageFilter.SHARPEN)
extract = pytesseract.image_to_string(im_SHARPEN2, lang = 'eng')
extract2 = pytesseract.image_to_string(images_new,lang = 'eng')
final= extract+extract2
x = re.search(r"INCOME|TAX|Account|GOVT.", final,re.M|re.I)
y = re.search(r"GOVERNMENT|DOB|Male|Female.", final,re.M|re.I)
if x == None and y== None:
print('Not a pan card or adhaar card')
elif type(x)== re.Match:
print('This is a pan card')
else:
print('adhaar card detected')
is_pan =is_pan_card('C:/Users/RAJ/realtest/')

Related

Detect beep sound from Audio file using python

Detect beep sound from Audio file using python
this code I found from somewhere but it is not giving the actual beep result
means in the audio where beep is not there then also this code is showing beep in it
from moviepy.editor import *
import matplotlib.pyplot as plt
import cv2
#from time import sleep
import sounddevice as sd
from scipy.io import wavfile
import numpy as np
filename = 'C:/Users/YahyaSirguroh/Downloads/output.mp4'
video = VideoFileClip(filename)
audio = video.audio
duration = video.duration
audio.write_audiofile("audio.wav")
#sleep(0.3)
samplerate, data = wavfile.read('audio.wav')
step = 30
audio_signal = []
cnt = 0
flag = 0
text = ''
for t in range(int(duration*step)):
t = t/step
if cnt:
flag+=1
if t > audio.duration or t > video.duration: break
audio_frame = audio.get_frame(t) #numpy array representing mono/stereo values
audio_signal.extend(list(audio_frame))
if (audio_frame>0.6).sum()==2:
cnt+=1
if cnt>=2:
print('beep detected at %5.2f' %(t))
text = 'beep detected at %d' %(np.round(t))
if flag>=4:
cnt=0
flag=0

after using pyinstaller to convert py to exe it doesn't work

I want to monitor one area but after converting it doesn't work.
There is no message when I used cmd to find some error.
when I start it, it just blink few minutes and then black out.
It work well in python.
please help.
here is the code.
import multiprocessing
from re import A
from PIL import Image
import pytesseract
import time
import threading
from PIL import ImageGrab
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract'
import pyautogui
import keyboard
import winsound
from multiprocessing import Process
def screenshot():
pyautogui.screenshot("C:\\Users\\youngseb\\Desktop\\screenshot1.png", region = region1)
img1 = Image.open("C:\\Users\\youngseb\\Desktop\\screenshot1.png")
A1 = pytesseract.image_to_string(img1,lang='kor+eng')
#print(T)
strings = A1.split()
print(strings)
time.sleep(5)
pyautogui.screenshot("C:\\Users\\youngseb\\Desktop\\screenshot1.png", region = region1)
img1 = Image.open("C:\\Users\\youngseb\\Desktop\\screenshot1.png")
A2 = pytesseract.image_to_string(img1,lang='kor+eng')
strings = A2.split()
print(strings)
if (A1 == A2):
winsound.Beep(2000,500)
print("ERROR")
else :
time.sleep(0.5)
threading.Timer(5, screenshot).start()
if __name__ == '__main__' :
P1 = Process(target=screenshot)
P1.start()
P1.join()
region1 = (572,333,35,15)

rdkit: how to draw high resolution chemical structure

I am using jupyter lab to draw chemical structures. But the output image resolution is too low. How can I improve it?
from rdkit import Chem
from rdkit.Chem import Draw
smiles = 'C1=CC(=C(C=C1C2=C(C(=O)C3=C(C=C(C=C3O2)O)O)O)O)O'
m = Chem.MolFromSmiles(smiles)
Draw.MolToImage(m)
Thanks a lot
I have found a solution, more information can be found here
from rdkit import Chem
from rdkit.Chem.Draw import IPythonConsole
from rdkit.Chem import rdDepictor
from rdkit.Chem.Draw import rdMolDraw2D
from IPython.display import SVG
smiles = 'C1=CC(=C(C=C1C2=C(C(=O)C3=C(C=C(C=C3O2)O)O)O)O)O'
m = Chem.MolFromSmiles(smiles)
def moltosvg(mol, molSize = (300,300), kekulize = True):
mc = Chem.Mol(mol.ToBinary())
if kekulize:
try:
Chem.Kekulize(mc)
except:
mc = Chem.Mol(mol.ToBinary())
if not mc.GetNumConformers():
rdDepictor.Compute2DCoords(mc)
drawer = rdMolDraw2D.MolDraw2DSVG(molSize[0],molSize[1])
drawer.DrawMolecule(mc)
drawer.FinishDrawing()
svg = drawer.GetDrawingText()
return svg.replace('svg:','')
SVG(moltosvg(m))
For those looking for a solution with higher resolution molecule output AND export. The cairosvg library (also command-line program) has export options for file types including .svg, .pdf, .png, .eps (https://cairosvg.org/).
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem.Draw import rdMolDraw2D
import cairosvg
import io
def molecule_to_pdf(mol, file_name, width=300, height=300):
"""Save substance structure as PDF"""
# Define full path name
full_path = f"./figs/2Dstruct/{file_name}.pdf"
# Render high resolution molecule
drawer = rdMolDraw2D.MolDraw2DSVG(width, height)
drawer.DrawMolecule(mol)
drawer.FinishDrawing()
# Export to pdf
cairosvg.svg2pdf(bytestring=drawer.GetDrawingText().encode(), write_to=full_path)
# Example
m = Chem.MolFromSmiles('Cn1cnc2n(C)c(=O)n(C)c(=O)c12')
molecule_to_pdf(m, "myfav")

face recognition can't detect if image face is not on portrait

I try using face recognition from this link: face recognition
then modif the code like this, main.py:
#!/usr/bin/env python
import cgitb, cgi
cgitb.enable()
print("Content-Type: text/html;charset=utf-8")
print "Content-type:text/html\r\n\r\n"
import base64
import simplejson as json
import re
import face_recognition
import numpy as np
import io
from imageio import imread
from PIL import Image
import datetime
import os, errno
import shutil
params = cgi.FieldStorage()
now = datetime.datetime.now()
date = str(now)
date2 = date.replace(" ","")
img = params.getvalue('img')
data1 = json.loads(img)
data2 = data1['img2']['data']
numparray = data1['img1']
numparray2 = numparray.replace(" ", "+")
b=bytes(numparray2)
imgdata = base64.b64decode(b)
os.makedirs(date2)
with open(date2+"/img1.png", "wb") as f:
f.write(imgdata)
image = face_recognition.load_image_file(date2+'/img1.png')
try:
face_encode = face_recognition.face_encodings(image)[0]
#print("face_encode = ".format(face_encode))
except IndexError:
print("encode image failed")
quit()
known_faces = []
y = 1
for images in data2:
ir = images.replace(" ", "+")
ib = bytes(ir)
imagedata = base64.b64decode(ib)
x = str(y)
with open(date2+"/compare"+x+".png", "wb") as g:
g.write(imagedata)
compare = face_recognition.load_image_file(date2+"/compare"+x+".png")
try:
compare_encode = face_recognition.face_encodings(compare)[0]
#print("face_encode = ".format(face_encode))
except IndexError:
print("encode image compare failed")
quit()
known_faces.append(compare_encode)
y = y+1
results = face_recognition.face_distance(known_faces, face_encode)
datahasil = []
#hasilakhir = "{"
for i, face_distance in enumerate(results):
h = "{:.2}".format(face_distance, i)
#hasilakhir = hasilakhir+"compare{}"
datahasil.append(h)
hasilakhir = ','.join(datahasil)
shutil.rmtree(date2, ignore_errors=True)
print("{\"hasilcompare\" : \"" +hasilakhir+ "\"}")
the final result is compare between 2 image and give the score, in case photo of image is potrait compare is successfull, but when one of image is not on potrait (face not on potrait potision) or like face angle more than 90 degree, that give error message in catch encode failed..
i have try another way with face detection before sending 2 image to main.py to detect the image in face but when it can't detect faces i try to rotate the image untill the code detect face, but sometimes face detection can detect face with angle 90degree but in face recognition(main.py) still can't read the face.
code of rotate is here, rotate.py:import numpy as np
import cv2
from scipy import ndimage, misc
import os
from PIL import Image
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
for counter in range (0, 4):
img = cv2.imread('img/1.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
if(len(faces) == 1):
i = False
print ("face found")
break
else:
print("no face found")
i = False
img = Image.open("img/1.jpg")
img.rotate(90).save("img/1.jpg")
Yes, I think this is the problem with the library. I tested it on the same image. Once after rotation and once on the original image. It does not detect in the rotated image, both the face_locations and face_encodings are empty lists.

Windows Python Code not working on Linux Debian

The code generates a QR code and prints it, but It is not working on the Debian Os due to not supporting the imported libraries (win32print, Win32ui).
Can anyone tell me how to run it on the Debian without changing the whole code.
from random import randint
import win32print
import win32ui
from PIL import Image, ImageWin
from PIL._imaging import font
from PIL import ImageFont
from PIL import ImageDraw
HORZRES = 8
VERTRES = 10
LOGPIXELSX = 88
LOGPIXELSY = 90
PHYSICALWIDTH = 110
PHYSICALHEIGHT = 111
PHYSICALOFFSETX = 112
PHYSICALOFFSETY = 113
__author__ = 'masoodhussain'
import qrcode
import subprocess
import os
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data('Masooddkjfdlfs,kokdfds sddshfhkjshfljsdhkjfdrtyyhtfhfghgh3')
qr.make(fit=True)
"subprocess.call(['lp', 'foo.png'])"
printer_name = win32print.GetDefaultPrinter()
img = qr.make_image()
img.show()
random_number= randint(0,10000)
img.save('label_'+str(random_number)+'.png')
file_name = 'label_'+str(random_number)+'.png'
print(file_name)
hDC = win32ui.CreateDC ()
hDC.CreatePrinterDC (printer_name)
printable_area = hDC.GetDeviceCaps (HORZRES), hDC.GetDeviceCaps (VERTRES)
printer_size = hDC.GetDeviceCaps (PHYSICALWIDTH), hDC.GetDeviceCaps (PHYSICALHEIGHT)
printer_margins = hDC.GetDeviceCaps (PHYSICALOFFSETX), hDC.GetDeviceCaps (PHYSICALOFFSETY)
bmp = Image.open (file_name)
if bmp.size[0] > bmp.size[1]:
bmp = bmp.rotate (90)
ratios = [1.0 * printable_area[0] / bmp.size[0], 1.0 * printable_area[1] / bmp.size[1]]
scale = min (ratios)
hDC.StartDoc (file_name)
hDC.StartPage ()
dib = ImageWin.Dib (bmp)
scaled_width, scaled_height = [int (scale * i) for i in bmp.size]
x1 = int ((printer_size[0] - scaled_width) / 2)
y1 = int ((printer_size[1] - scaled_height) / 2)
x2 = x1 + scaled_width
y2 = y1 + scaled_height
dib.draw (hDC.GetHandleOutput (), (x1, y1, x2, y2))
hDC.EndPage ()
hDC.EndDoc ()
hDC.DeleteDC ()
when I run the code by removing the unsupported libraries it gives an error on this part: error importing
import qrcode
I am trying to import whole folder for using there other files. In Windows it was working perfectly. Any help would be appreciated.Thanks
This code is equivalent to the code posted in Question.
from random import randint
import cups
from PIL import Image, ImageWin
from PIL._imaging import font
from PIL import ImageFont
from PIL import ImageDraw
__author__ = 'masoodhussain'
import qrcode
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=5,
border=2,
)
qr.add_data('localhost:5070productinfo')
qr.make(fit=True)
conn= cups.Connection()
printer_name = conn.getPrinters()
printer_name = printer_name.keys()[0]
printqueuelength = len(conn.getJobs())
img = qr.make_image()
img.show()
random_number= randint(0,10000)
img.save('label_'+str(random_number)+'.png')
file_name = 'label_'+str(random_number)+'.png'
print(file_name)
conn.printFile(printer_name,file_name,"Hello", options ={'media':'25x25mm'})
Important part is the installation of required libraries and changing your media to the required size.
Even if you install qrcode, your code will still fail because of the Windows specific library. You need to check on which system you are working and preferably put the whole print function in a separate function.
Here are some useful links: https://stackoverflow.com/a/1857/2776376 and https://pypi.python.org/pypi/pycups
import platform
if platform.system() = 'Linux':
import libcups
elif platform.system() = 'Windows':
import win32print
import win32ui
else:
print('Unsupported OS. Exiting....')
sys.exit(1)
def my_printer_function():
if platform.system() = 'Linux':
#now call the Linux printer
elif platform.system() = 'Windows':
#use your old Windows code

Categories

Resources