AssertionError: Audio source must be entered before listening, are you using ``source`` outside of a ``with`` statement? - artificial-intelligence

I am getting this error for taking the voice instruction:
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\speech_recognition\__init__.py", line 651, in listen
assert source.stream is not None, "Audio source must be entered before listening, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?"
AssertionError: Audio source must be entered before listening, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?
Here's the code:
import speech_recognition as mic
import pyttsx3
import pywhatkit
import datetime
import wikipedia
assistant = pyttsx3.init()
listener= mic.Recognizer()
def respond(text):
assistant.say(text)
assistant.runAndWait()
def inputInstructions():
with mic.Microphone() as source:
listener.pause_threshold = 1
print(source)
speech = listener.listen(source)
instruction = listener.recognize_google(speech)
instruction = instruction.lower()
if("stark") in instruction:
instruction = instruction.replace('stark',"")
print(instruction)
return instruction
I tried the above code but it is not working

Related

ValueError: Face could not be detected in DeepFace

I am implementing a code segment to detect video frames with faces and store them in an array. For this purpose I am using DeepFace library. (Go to deepface github repository).
Below is my code segment:
# Import Libraries
from deepface import DeepFace
import matplotlib.pyplot as plt
import cv2
# Path of the video
video_file_path = '/content/drive/My Drive/Colab Notebooks/FYP Project/Data Preprocessing/youtube_clip_001.mp4'
# Reading the video
vidcap = cv2.VideoCapture(video_file_path)
# Extracting the frames
frames = []
while True:
ret, frame = vidcap.read()
if not ret:
break
# Extracting the face from the frame
faces = DeepFace.detectFace(frame)
if len(faces) > 0:
frames.append(frame)
Each and every frame in the video file I am using may not have human faces. That is why I need to extract only the frames with human faces. But it does give the following error:
ValueError: Face could not be detected. Please confirm that the
picture is a face photo or consider to set enforce_detection param to
False.
But when I make faces = DeepFace.detectFace(frame, enforce_detection=False) as suggested in the error, then it add not only the frames with human faces, but also all the frames in the video to the array including frames without faces.
Can somebody please help me to solve this issue?
Here is the link to the video file I am using: https://drive.google.com/file/d/1vAJyjbQYAYFJS4DVN0UWDYb21wf0r0TL/view?usp=sharing
In face detection by deepface, it checks for a face in the frame and if not throws an exception. As mentioned in this GitHub issue also, if I make enforce_detection=False then it reduces the accuracy. Therefore the best option available is to handle the exception without breaking the code.
Therefore you can modify the above code snippet as follows:
while True:
ret, frame = vidcap.read()
if not ret:
break
# Extracting the face from the frame
try:
faces = DeepFace.detectFace(frame)
if len(faces) > 0:
frames.append(frame)
except:
print('exception')
Following is another example I tried with again:

Python Selenium Failing to Acquire data

I am trying to download the 24-month data from www1.nseindia.com and it fails on Chrome and Firefox drivers. It just freezes after filling all the values in the required places and does not click. The webpage does not respond...
Below is the code that I am trying to execute:
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
id_list = ['ACC', 'ADANIENT']
# Chrome
def EOD_data_Chrome():
driver = webdriver.Chrome(executable_path="C:\Py388\Test\chromedriver.exe")
driver.get('https://www1.nseindia.com/products/content/equities/equities/eq_security.htm')
s1= Select(driver.find_element_by_id('dataType'))
s1.select_by_value('priceVolume')
s2= Select(driver.find_element_by_id('series'))
s2.select_by_value('EQ')
s3= Select(driver.find_element_by_id('dateRange'))
s3.select_by_value('24month')
driver.find_element_by_name("symbol").send_keys("ACC")
driver.find_element_by_id("get").click()
time.sleep(9)
s6 = Select(driver.find_element_by_class_name("download-data-link"))
s6.click()
# FireFox(Gecko)
def EOD_data_Gecko():
driver = webdriver.Firefox(executable_path="C:\Py388\Test\geckodriver.exe")
driver.get('https://www1.nseindia.com/products/content/equities/equities/eq_security.htm')
s1= Select(driver.find_element_by_id('dataType'))
s1.select_by_value('priceVolume')
s2= Select(driver.find_element_by_id('series'))
s2.select_by_value('EQ')
s3= Select(driver.find_element_by_id('dateRange'))
s3.select_by_value('24month')
driver.find_element_by_name("symbol").send_keys("ACC")
driver.find_element_by_id("get").click()
time.sleep(9)
s6 = Select(driver.find_element_by_class_name("download-data-link"))
s6.click()
EOD_data_Gecko()
# Change the above final line to "EOD_data_Chrome()" and still it just remains stuck...
Kindly help with what is missing in that code to download the 24-month data... When I perform the same in a normal browser, with manual clicks, it is successful...
When you are manually doing it in a browser, you can change the values as below:
Set first drop down to : Security wise price volume data
"Enter Symbol" : ACC
"Select Series" : EQ
"Period" (radio button: "For Past") : 24 Months
Then click on the button, "Get Data", and in about 3-5seconds, the data loads, and then when you click on "Download file in CSV format", you can have the CSV file in your downloads
Need help using any library you know for scraping in Python: Selenium, Beautifulsoup, Requests, Scrappy, etc... Doesn't really matters unless it is python...
Edit: #Patrick Bormann, pls find the screenshot... The get data button works..
When you say that it works manually, have you try to simulate a click with action chains instead of the internal click function
from selenium.webdriver.common.action_chains import ActionChains
easy_apply = Select(driver.find_element_by_id('dateRange'))
actions = ActionChains(driver)
actions.move_to_element(easy_apply)
actions.click(easy_apply)
actions.perform()
and then you simulate a mouse movement to the specific value?
In addition, I tried it on my own and I didnt get any data when pushing on the button Get Data, as it seems to have a class of "get" as you mentioned, but this button doesnt work, but as you can see there exists a second button called full download, perhaps ypu try to use this one? Because the GetData Button doesnt work on Firefox and Chrome (when i tested it).
Did you already try to catch it through the link?
Update
As the OP asks for help in this urgent matter I delivered a working solution.
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time
from selenium.webdriver.support.ui import Select
chrome_driver_path = "../chromedriver.exe"
driver = webdriver.Chrome(executable_path=chrome_driver_path)
driver.get('https://www1.nseindia.com/products/content/equities/equities/eq_security.htm')
driver.execute_script("document.body.style.zoom='zoom 25%'")
time.sleep(2)
price_volume = driver.find_element_by_xpath('//*[#id="dataType"]/option[2]').click()
time.sleep(2)
date_range = driver.find_element_by_xpath('//*[#id="dateRange"]/option[8]').click()
time.sleep(2)
series = driver.find_element_by_name('series')
time.sleep(2)
drop = Select(series)
drop.select_by_value("EQ")
time.sleep(2)
driver.find_element_by_name("symbol").send_keys("ACC")
ez_download = driver.find_element_by_xpath('//*[#id="wrapper_btm"]/div[1]/div[3]/a')
actions = ActionChains(driver)
actions.move_to_element(ez_download)
actions.click(ez_download)
actions.perform()
Here you go, sorry, took a little, had to bring my son to bed...
This solution provides this output: I hope its correct. If you want to select other drop down menus you can change the string in the select (string because of too much indezes too handle) or the number in the xpath as the number highlights the index. The time is normally only for elements which need time to build themselves up on a webpage. But I made the experience that a too fast change sometimes causes errors. Feel free to change the time limit and see if it still works.
I hope you can now go on again in making some money for your living in India.
All the best Patrick,
Do not hesitate to ask if you have any questions.
UPDATE2
After one long night and another day we figured out that the Freezing originates from the website, as the website uses:
Boomerang | Akamai Developer developer.akamai.com/tools/… Boomerangis
a JavaScript library forReal User Monitoring (commonly called RUM).
Boomerang measures the performance characteristics of real-world page
loads and interactions. The documentation on this page is for mPulse’s
Boomerang. General API documentation for Boomerang can be found
atdocs.soasta.com/boomerang-api/.
.
What I discovered from the html header.
This is clearly a bot detection network/javascript. With the help of this SO post:
Can a website detect when you are using Selenium with chromedriver?
And the second paragraph from that post:https://piprogramming.org/articles/How-to-make-Selenium-undetectable-and-stealth--7-Ways-to-hide-your-Bot-Automation-from-Detection-0000000017.html
I finally solved the issue:
we changed the
var_key in chromedriver to something else like:
var key = '$dsjfgsdhfdshfsdiojisdjfdsb_';
In addition I changed the code to:
import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.options import Options
options = webdriver.ChromeOptions()
chrome_driver_path = "../chromedriver.exe"
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--disable-blink-features=AutomationControlled')
driver = webdriver.Chrome(executable_path=chrome_driver_path, options=options)
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
driver.get('http://www1.nseindia.com/products/content/equities/equities/eq_security.htm')
driver.execute_script("document.body.style.zoom='zoom 25%'")
time.sleep(5)
price_volume = driver.find_element_by_xpath('//*[#id="dataType"]/option[2]').click()
time.sleep(3)
date_range = driver.find_element_by_xpath('//*[#id="dateRange"]/option[8]').click()
time.sleep(5)
series = driver.find_element_by_name('series')
time.sleep(3)
drop = Select(series)
drop.select_by_value("EQ")
time.sleep(4)
driver.find_element_by_name("symbol").send_keys("ACC")
actions = ActionChains(driver)
ez_download = driver.find_element_by_xpath('/html/body/div[2]/div[3]/div[2]/div[1]/div[3]/div/div[1]/form/div[2]/div[3]/p/img')
actions.move_to_element(ez_download)
actions.click(ez_download)
actions.perform()
#' essential because the button has to be loaded
time.sleep(5)
driver.find_element_by_class_name('download-data-link').click()
The code finally worked and the OP is happy.
I have edited the chromedriver.exe using hex editor and replaced cdc_ with dog_ and saved it. Then executed the below code using chrome driver.
import selenium
from selenium import webdriver
from selenium.webdriver.support.select import Select
import time
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_argument("--disable-blink-features")
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options)
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'})
print(driver.execute_script("return navigator.userAgent;"))
# Open the website
driver.get('https://www1.nseindia.com/products/content/equities/equities/eq_security.htm')
symbol_box = driver.find_element_by_id('symbol')
symbol_box.send_keys('20MICRONS')
driver.implicitly_wait(10)
#rd_period=driver.find_element_by_id('rdPeriod')
#rd_period.click()
list_daterange=driver.find_element_by_id('dateRange')
list_daterange=Select(list_daterange)
list_daterange.select_by_value('24month')
driver.implicitly_wait(10)
btn_getdata=driver.find_element_by_xpath('//*[#id="get"]')
btn_getdata.click()
driver.implicitly_wait(100)
print("Clicked button")
lnk_downloadData=driver.find_element_by_xpath('/html/body/div[2]/div[3]/div[2]/div[1]/div[3]/div/div[3]/div[1]/span[2]/a')
lnk_downloadData.click()
This code is working fine as of now. But the problem is that - this is not a permanent solution. NSE keeps on updating the logic to detect BOT execution in a better way. Like NSE, we will also have update our code. Please let me know if this code is not working. Will figure out some other solution.

scala - Gatling - I can't seem to use Session Variables stored from a request in a subsequent Request

The code:
package simulations
import io.gatling.core.Predef._
import io.gatling.http.Predef._
class StarWarsBasicExample extends Simulation
{
// 1 Http Conf
val httpConf = http.baseUrl("https://swapi.dev/api/films/")
// 2 Scenario Definition
val scn = scenario("Star Wars API")
.exec(http("Get Number")
.get("4")
.check(jsonPath("$.episode_id")
.saveAs("episodeId"))
)
.exec(session => {
val movie = session("episodeId").as[String]
session.set("episode",movie)
}).pause(4)
.exec(http("$episode")
.get("$episode"))
// 3 Load Scenario
setUp(
scn.inject(atOnceUsers(1)))
.protocols(httpConf)
}
Trying to grab a variable from the first Get request, and inject that variable into a second request, but unable to do so despite using the documentation. There might be something I'm not understanding.
When I use breakpoints, and navigate through the process, it appears the session execution happens AFTER both of the other requests have been completed (by which time is too late). Can't seem to make that session execution happen between the two requests.
Already answered on Gatling's community mailing list.
"$episode" is not correct Gatling Expression Language syntax. "${episode}" is correct.

Sentinel import inside Terraform Cloud confusion: key "find_resources" doesn't support function calls

I'm using a Sentinel policy inside a Terraform Cloud workspace. My policy is rather simple:
import "tfplan/v2" as tfplan
allBDs = tfplan.find_resources("aci_bridge_domain")
violatingBDs = tfplan.filter_attribute_does_not_match_regex(allBDs,
"description", "^demo(.+)", true)
main = rule {
length(violatingBDs["messages"]) is 0
}
Unfortunately, it fails when invoked with this message:
An error occurred: 1 error occurred:
* ./allowed-terraform-version.sentinel:3:10: key "find_resources" doesn't support function calls
The documentation and source for find_resources (doc) expects a string, yet the Sentinel interpreter seems to think I'm invoking a method of tfplan? It's quite unclear why that is, and the documentation doesn't really help.
Any ideas?
OK I found the issue. If I paste the code for find_resources and its dependencies (to_string, evaluate_attribute) then everything works as expected.
So I have a simple import problem and need to figure out how to properly import https://raw.githubusercontent.com/hashicorp/terraform-guides/master/governance/third-generation/common-functions/tfplan-functions/tfplan-functions.sentinel

Read request body with Akka-Http and send each line to the message queue on an Actor

I'm googling for an example that could fit my use case, but I haven't found any so far.
I'm writing an Akka WebService that should process a potentially huge plain text request body sending each line to an Actor's incoming message queue.
Could any of you write some code here or just head me to an example page?
I actually have no idea from where to start: the big problem to me is dealing with streams in general (in my case I want to use Akka streaming library)
To get the request body you can use the extractRequestEntity directive to create your route. Once you have the entity stream you can simply dispatch each line of text to the Actor:
import akka.stream.scaladsl.Framing.delimiter
import akka.util.ByteString
import akka.actor.ActorRef
import akka.http.scaladsl.server.Directives.{extractRequestEntity, onComplete}
val maxLineLength = 256
val streamSplitter = delimiter(ByteString("\n"), maxLineLength)
val actorRef : ActorRef = ??? //not specified in question
val route : Route =
extractRequestEntity { entity =>
onComplete {
entity
.dataBytes
.via(streamSplitter)
.map(_.utf8String)
.runForeach(line => actorRef ! line)
} { _ =>
complete("all lines sent to actor")
}
}
The question doesn't specify whether or not the response is dependent on the results of the Actor processing so the above example simply sends the lines to the Actor and then completes the request with a response containing a simple message.
The route can now form the basis of a server.

Resources