AttributeError: 'Audio' object has no attribute 'to_intensity' - python

Hello cool guys ı am trying to do desktop . I'm trying to get a voice file and remove the noise.
import parselmouth
import librosa
import librosa.display
import json
import os
from scipy.io import wavfile
import math
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler as MMS
from scipy.ndimage import gaussian_filterld
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
file_path = "C://Users//minky//france.wav"
warnings.filterwarnings("ignore")
data = "C://Users//minky//france.wav"
path_dir = "C://Users//minky"from pydub import AudioSegment
from pydub.playback import play
data = Audio(file_path)
def _vad(sdata):
intensity = data.to_intensity()
intensity = intensity.values.squeeze()
intensity[intensity <= 0] = 0
intensity = _length(intensity)
length= _length(intensity)
intensity_mean = len(intensity)
temp = []
AttributeError: 'Audio' object has no attribute 'to_intensity'
So, I'm trying to get the audio data and put it into a function to remove the noise. However, as shown below, I can't do it because of an error like that... :( I searched hard on the Internet, but I couldn't figure out where to change the data... how the format was wrong... Please help me.. Awesome Coding Doctors.. Thanks in advance:)

Related

How to import and use my own function from .py file in Python Pandas?

In Jupyter Notebook I created my own function in my_fk.py file like below:
import pandas as pd
def missing_val(df):
df= pd.DataFrame(df.dtypes, columns=["type"])
df["missing"] = pd.DataFrame(df.isna().any())
df["sum_miss"] = pd.DataFrame(df.isna().sum())
df["perc_miss"] = round((df.apply(pd.isna).mean()*100),2)
return df
Then when I try to import and run my function using below code:
import pandas as pd
import numpy as np
import my_fk as fk
df = pd.read_csv("my_data.csv")
fk.missing_val(df)
I have error like below. Error suggests that in my my_fk.py file there is no pandas as pd, but there IS line with code "import pandas as pd". How can I import and use my own function from python file ?
NameError: name 'pd' is not defined
Missing "as". Then place your pd.read_csv() after importing pandas, not before
import pandas as pd
import numpy as np
import my_fk as fk
df = pd.read_csv("my_data.csv")
fk.missing_val(df)

Extracting data from table and saving it. Layout parser package

I am new in working with python and I am using Melissa Dell's package to extract data from a table image. My image looks like this:
enter image description here
And my code, for now, is the following one:
pip install layoutparser[ocr]
import layoutparser as lp
import matplotlib.pyplot as plt
%matplotlib inline
import pandas as pd
import numpy as np
import cv2
from google.cloud.vision_v1 import types
import json
import re
from google.cloud import vision
pip show google-cloud-vision
ocr_agent = lp.GCVAgent.with_credential('mycredebtials.json',
languages = ['es'])
img = plt.imread(r'D:\pdfDispacher.do_Página_2.jpg', cv2.IMREAD_COLOR)
print(img)
plt.imshow(img)
res = ocr_agent.detect(img, return_response=True)
texts = ocr_agent.gather_text_annotations(res)
layout = ocr_agent.gather_full_text_annotation(res, agg_level=lp.GCVFeatureType.WORD)
lp.draw_box(img, layout)
lp.draw_text(img, layout, font_size=12, with_box_on_text=True,
text_box_width=1)
What I need is to tell python to get all the columns and rows and save them in CSV format. But I am not able to get this done.
I really appreciate it if anyone can help me with the next lines.

Is there a way to scan QR codes in colab?

I have a colab notebook and have been fruitlessly trying to find a way to scan a QR code that would be held up to my webcam. I have code to capture an image, if live QR code detection is a problem (I yoinked it from another notebook which is why its kind of weird):
from IPython.display import display, Javascript
from google.colab.output import eval_js
from base64 import b64decode
def take_photo(filename='photo.jpg', quality=0.8):
js = Javascript('''
async function takePhoto(quality) {
const div = document.createElement('div');
const capture = document.createElement('button');
capture.textContent = 'Capture';
div.appendChild(capture);
const video = document.createElement('video');
video.style.display = 'block';
const stream = await navigator.mediaDevices.getUserMedia({video: true});
document.body.appendChild(div);
div.appendChild(video);
video.srcObject = stream;
await video.play();
// Resize the output to fit the video element.
google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);
// Wait for Capture to be clicked.
await new Promise((resolve) => capture.onclick = resolve);
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0);
stream.getVideoTracks()[0].stop();
div.remove();
return canvas.toDataURL('image/jpeg', quality);
}
''')
display(js)
data = eval_js('takePhoto({})'.format(quality))
binary = b64decode(data.split(',')[1])
with open(filename, 'wb') as f:
f.write(binary)
return filename
from IPython.display import Image
try:
filename = take_photo()
print('Saved to {}'.format(filename))
# Show the image which was just taken.
display(Image(filename))
except Exception as err:
# Errors will be thrown if the user does not have a webcam or if they do not
# grant the page permission to access it.
print(str(err))
I have tried things with pyzbar (followed tutorials) and many other ways, but none of them seem to work for me.
The ultimate goal is to take the data from the qr codes, and append it into lists that I would convert into a .csv (all data comes in the qr code like "name,email,phone#"). It would be great to have it work with live camera, so it just automatically does this every time it sees a QR code. Is there a way to do this?
Thanks for all your help!
hi you can use this pyzbar
from pyzbar.pyzbar import decode
from PIL import Image
decode(Image.open('pyzbar/tests/code128.png'))
Write to install:
pip install pyzbar[scripts] or !pip install pyzbar[scripts]
!apt install libzbar0
Later import some these, but the principal is pyzbar:
import shutil
import os
import random
import re
import cv2
import numpy as np
import pytesseract
from pytesseract import Output
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
import glob
import pyzbar.pyzbar
from PIL import Image
And check this:
from pyzbar.pyzbar import decode
from PIL import Image

Viewing images from pickle file in python

I am a newbie in Machine Learning.I have a dataset of images present in .p format(pickle).
How to view the images present inside the file ? I seached the internet but I didn't any appropriate answers.
Please help me to solve this issue.
Code I used:
import pandas as pd
import pickle
objects = []
with (open("full_CNN_train.p", "rb")) as openfile:
while True:
try:
objects.append(pickle.load(openfile))
except EOFError:
break
print(objects)
My output when I tried pickle.load()
It's probably just a standard image matrix, just try using matplotlib.pyplot.imshow()
from matplotlib import pyplot as plt
img = ... # pickle load or whatever
plt.imshow(img)
plt.show()
Just load the pickle file, and use the "imshow" method to visualize.
import pickle
import matplotlib.pyplot as plt
pkl = open('pickled_image.pickle', 'rb')
im = pickle.load(pkl)
plt.imshow(im)

UsageError: Line magic function `%cd..` not found

I get the error:
UsageError: Line magic function `%cd..` not found.
when running my python code that i usually run from Jupyter Notebook through a shell command.
I use %cd and %ls all the time in Jupiter notebooks and do not get why i can not run it from shell.
I both tried:
python test.py
and
ipython test.py
this is the relevant part of my code:
import csv
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import pandas as pd
import sys
import os
import IPython
from scipy.misc import imread
import matplotlib.cbook as cbook
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
def main():
script = sys.argv[0]
map_name = sys.argv[1]
callPenalty()
def callPenalty():
%cd standalone-penalty
os.system("octave-cli penalty.m map_bit.bmp 50 1 1 150 150")
%cd..
main()
Does anyone know how to solve that?

Categories

Resources