I've studied the PyOWM and OWM API guides and some code recipes and have things working fine in a larger bit of code but I just can't work out how to get get the current weather icon for todays forecast? Here's a code snippet that works apart from the icon:
from pyowm.owm import OWM
from pyowm.utils import timestamps
import requests, json
def checkInternetRequests(url='http://www.google.com/', timeout=3):
try:
r = requests.head(url, timeout=timeout)
return True
except requests.ConnectionError as ex:
print(ex)
return False
def get_weather():
if checkInternetRequests() == True:
# 52.5766° N, 1.5438° W
print ("Internet Up")
CITY = "Atherstone, GB"
LON = 1.54
LAT = 52.576
API_KEY = "myapikey"
ICON_URL_1 = "http://openweathermap.org/img/wn/"
ICON_URL_2 = "#2x.png"
owm = OWM(API_KEY)
mgr = owm.weather_manager()
one_call = mgr.one_call(lat=LAT, lon=LON)
print (one_call.forecast_hourly[3]) #works - 3hrs from now
print ("===========================")
print (one_call.forecast_daily[0]) # works - Today
print ("===========================")
print (one_call.forecast_daily[0].weather.icon)
else:
print ("Internet Down")
time.sleep(10)
get_weather()
I'm getting the following error:
Traceback (most recent call last):
File "weather1.py", line 37, in <module>
get_weather()
File "weather1.py", line 31, in get_weather
print (one_call.forecast_daily[0].weather.icon)
AttributeError: 'Weather' object has no attribute 'weather'
Where am I going wrong ? Thanks!
OK - After a few beers and some food plus 4hrs of messing with the code I have this working !
one_call.forecast_daily[0].weather_icon_url()
gives me a url I can use to display the forecast icon in my code for today.
import pyowm
from pyowm.utils import timestamps, formatting
from pyowm.owm import OWM
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
observation = mgr.weather_at_place('London')
w = observation.weather
icon = w.weather_icon_url(size='2x')
img = mpimg.imread(icon)
plt.imshow(img)
plt.show()
Related
i was trying to make the user input file audio in wav or mp3 format to low pass filter it
i am supposed to use tkinter to create GUI so that use can use two buttons one to input file and other to call function runlow which is the filter i dont know where i went wrong
i don't know why i need to add details to the question though stackflow ?
but i got this error :
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\ezz\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\ezz\desktop\voicerecorder.py", line 173, in runlow
filtered = running_mean(channels[0], N).astype(channels.dtype)
TypeError: 'NoneType' object is not subscriptable
here is the main code
from cProfile import label
from doctest import master
from importlib.metadata import files
from pydoc import text
from tkinter import *
from tkinter import filedialog
import matplotlib.pyplot as plt
from functools import partial
import numpy as np
from tkinter.filedialog import asksaveasfile
from tkinter import ttk
import wave
import math
import contextlib
import warnings
outname = (r"filtered.wav")
def fileaudio():
global fname1
fname1 = filedialog.askopenfilename(filetypes=(("Audio files", "*.wav;*.mp3"),
("All files", "*.*") ))
print(fname1)
return fname1
warnings.simplefilter("ignore", DeprecationWarning)
# Change label contents
root =Tk()
root.geometry("1280x800")
root.resizable(False,False)
root.title("Audio filter")
root.configure(background="white")
#icon
image_icon=PhotoImage(file="filter.png")
root.iconphoto(False,image_icon)
#logo
photo=PhotoImage(file="filter.png")
myimage=Label(image=photo,background="white")
myimage.pack(padx=5,pady=5)
#name
Label(text="Audio filter",font="ariel 30 bold",background="black",fg="white").pack()
#entry box
def runlow():
cutOffFrequency = 400.0
# from http://stackoverflow.com/questions/13728392/moving-average-or-running-mean
def running_mean(x, windowSize):
cumsum = np.cumsum(np.insert(x, 0, 0))
return (cumsum[windowSize:] - cumsum[:-windowSize]) / windowSize
# from http://stackoverflow.com/questions/2226853/interpreting-wav-data/2227174#2227174
def interpret_wav(raw_bytes, n_frames, n_channels, sample_width, interleaved = True):
if sample_width == 1:
dtype = np.uint8 # unsigned char
elif sample_width == 2:
dtype = np.int16 # signed 2-byte short
else:
raise ValueError("Only supports 8 and 16 bit audio formats.")
channels = np.fromstring(raw_bytes, dtype=dtype)
if interleaved:
# channels are interleaved, i.e. sample N of channel M follows sample N of channel M-1 in raw data
channels.shape = (n_frames, n_channels)
channels = channels.T
else:
# channels are not interleaved. All samples from channel M occur before all samples from channel M-1
channels.shape = (n_channels, n_frames)
return channels
with contextlib.closing(wave.open(fname1,'rb')) as spf:
sampleRate = spf.getframerate()
ampWidth = spf.getsampwidth()
nChannels = spf.getnchannels()
nFrames = spf.getnframes()
# Extract Raw Audio from multi-channel Wav File
signal = spf.readframes(nFrames*nChannels)
spf.close()
channels = interpret_wav(signal, nFrames, nChannels, ampWidth, True)
# get window size
# from http://dsp.stackexchange.com/questions/9966/what-is-the-cut-off-frequency-of-a-moving-average-filter
freqRatio = (cutOffFrequency/sampleRate)
N = int(math.sqrt(0.196196 + freqRatio**2)/freqRatio)
# Use moviung average (only on first channel)
filtered = running_mean(channels[0], N).astype(channels.dtype)
wav_file = wave.open(outname, "w")
wav_file.setparams((1, ampWidth, sampleRate, nFrames, spf.getcomptype(), spf.getcompname()))
wav_file.writeframes(filtered.tobytes('C'))
wav_file.close()
#button
record=Button(root,font="ariel 20",text="Input",bg="black",fg="white",border=0,command=fileaudio).pack(pady=30)
record2=Button(root,font="ariel 20",text="Filter",bg="black",fg="white",border=0,command=runlow).pack(pady=30)
#functions to integrate
# from http://stackoverflow.com/questions/13728392/moving-average-or-running-mean
root.mainloop()
You forgot to return the filename from your input() function.
def input():
fname = filedialog.askopenfilename(filetypes=(("Audio files", "*.wav;*.mp3"),
("All files", "*.*") ))
print(fname)
return fname # <== you dropped this
fname = input()
Also there's another error, you must use askinputfilename, not askinputfile.
FWIW you should not use the name input() for your function since it overwrites and disables python's built-in input function.
import requests
import pandas as pd
import plotly.graph_objects as go
import pandas as pd
from datetime import datetime
def income_statement(stock):
number_yrs = input('how many yr(s)?').strip()
api_key = 'd5abd8f1620e04709eeb05ebafa9af7e'
IS = requests.get(f'https://financialmodelingprep.com/api/v3/balance-sheet-statement/{stock}?limit={number_yrs}&apikey={api_key}').json()
IS = pd.DataFrame.from_dict(IS)
IS = IS.T
print(IS.T)
save_to_csv = input('save_to_csv? y or n').strip()
if save_to_csv == 'y':
IS.to_csv('IS' + stock + '.csv')
while True:
command = input('stock?')
stock = comman.split(' ')[1]
if comman == 'IS ' + stock:
income_statement(stock)
elif comman == 'quit':
break
else:
print('Invalid Command.')
I am learning python for finance right now. I would like to build a stock research terminal that allows me to call income statement, balance sheet, historical price etc. of a stock from the Internet. I used the above code but when I type IS TSLA, it still gives me the income statement of AAPL. I wonder which parts of the code go wrong? Thanks!
I am trying to display an image inside a Tkinter window through Web Scraping displaying a message from a certain point on the website that says in Portuguese "Capella Ganhou" or "Procyon Ganhou".
I tried to look in different forums for a solution but I couldn't find any that fixes the error in my situation. I also tested with print to make sure the string exists and is returning its value and also encapsulated it into a variable.
The source code and the error are below .
from tkinter import *
import urllib.request
from bs4 import BeautifulSoup
from IPython.display import Image, display
from PIL import Image, ImageTk
import io
def capella_tg():
resultado_tg = StringVar()
resultado_tg.set(soup.find_all("font")[5].string)
label_resultado_tg = Label(root, textvariable=resultado_tg).pack()
def procyon_tg():
resultado_tg = StringVar()
resultado_tg.set(soup.find_all("font")[4].string[3:])
label_resultado_tg = Label(root, textvariable=resultado_tg).pack()
def img_capella():
raw_data = urllib.request.urlopen("https://i.imgur.com/AHLqtt0.jpg").read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label1 = Label(root, image=image).pack()
def img_procyon():
raw_data = urllib.request.urlopen("https://i.imgur.com/TQyCnfD.jpg").read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label1 = Label(root, image=image).pack()
root = Tk()
with urllib.request.urlopen("http://www.cabaleasy.com") as url: page = url.read()
soup = BeautifulSoup(page, "html.parser")
#print(soup.find_all("font")[5].string)
try:
capella_tg()
except:
procyon_tg()
if capella_tg():
img_capella()
elif procyon_tg():
img_procyon()
root.mainloop()
-------ERROR---------
Traceback (most recent call last):
File "C:/Users/LucasDEV/PycharmProjects/LucasDEV/WEB_SCRAPPING/TESTES.py", line 49, in <module>
elif procyon_tg():
File "C:/Users/LucasDEV/PycharmProjects/LucasDEV/WEB_SCRAPPING/TESTES.py", line 17, in procyon_tg
resultado_tg.set(soup.find_all("font")[4].string[3:])
TypeError: 'NoneType' object is not subscriptable
#Dipen Shah That is why I used the try/except structure for. But it's not working and I'm getting the same error. I also tried this way:
def capella_tg():
resultado_tg = StringVar()
try:
resultado_tg.set(soup.find_all("font")[5].string)
label_resultado_tg = Label(root, textvariable=resultado_tg).pack()
except:
pass
i tested just using text and it works:
import urllib.request
from bs4 import BeautifulSoup
with urllib.request.urlopen("http://www.cabaleasy.com") as url: page = url.read()
soup = BeautifulSoup(page, "html.parser")
try:
print(soup.find_all("font")[5].string)
#At this moment, it will not be showing, cuz the status changes every hour
except:
print(soup.find_all("font")[4].string[3:])
I got an error when I use the code in cmd by using the code:
python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record""
Usage:
# From tensorflow/models/
# Create train data:
python generate_tfrecord.py --csv_input=data/train_labels.csv --output_path=train.record
# Create test data:
python generate_tfrecord.py --csv_input=data/test_labels.csv --output_path=test.record
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import os
import io
import pandas as pd
import tensorflow as tf
from PIL import Image
from object_detection.utils import dataset_util
from collections import namedtuple, OrderedDict
flags = tf.compat.v1.flags
flags.DEFINE_string('csv_input', '', 'Path to the CSV input')
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
flags.DEFINE_string('image_dir', '', 'Path to images')
FLAGS = flags.FLAGS
# TO-DO replace this with label map
def class_text_to_int(row_label):
if row_label == 'put your selected items':
return 1
else:
None
def split(df, group):
data = namedtuple('data', ['filename', 'object'])
gb = df.groupby(group)
return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]
def create_tf_example(group, path):
with tf.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid:
encoded_jpg = fid.read()
encoded_jpg_io = io.BytesIO(encoded_jpg)
image = Image.open(encoded_jpg_io)
width, height = image.size
filename = group.filename.encode('utf8')
image_format = b'jpg'
xmins = []
xmaxs = []
ymins = []
ymaxs = []
classes_text = []
classes = []
for index, row in group.object.iterrows():
xmins.append(row['xmin'] / width)
xmaxs.append(row['xmax'] / width)
ymins.append(row['ymin'] / height)
ymaxs.append(row['ymax'] / height)
classes_text.append(row['class'].encode('utf8'))
classes.append(class_text_to_int(row['class']))
tf_example = tf.train.Example(features=tf.train.Features(feature={
'image/height': dataset_util.int64_feature(height),
'image/width': dataset_util.int64_feature(width),
'image/filename': dataset_util.bytes_feature(filename),'image/source_id': dataset_util.bytes_feature(filename),
'image/encoded': dataset_util.bytes_feature(encoded_jpg),
'image/format': dataset_util.bytes_feature(image_format),
'image/object/bbox/xmin': dataset_util.float_list_feature(xmins)'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
'image/object/class/label': dataset_util.int64_list_feature(classes),
}))
return tf_example
def main(_):
writer = tf.python_io.TFRecordWriter(FLAGS.output_path)
path = os.path.join(FLAGS.image_dir)
examples = pd.read_csv(FLAGS.csv_input)
grouped = split(examples, 'filename')
for group in grouped:
tf_example = create_tf_example(group, path)
writer.write(tf_example.SerializeToString())
writer.close()
output_path = os.path.join(os.getcwd(), FLAGS.output_path)
print('Successfully created the TFRecords: {}'.format(output_path))
if __name__ == '__main__':
tf.app.run()
tf.app.run()
The error message got was:
Traceback (most recent call last): File "generate_tfrecord.py", line
102, in
tf.app.run()
AttributeError: module 'tensorflow' has no attribute 'app'
Can any one help me?
If you're using TensorFlow v2, app.run has been moved to tf.compat.v1.app.run, as shown here.
If you downgrade your tensorflow to other version i.e 1.x.
It should work fine then.
Do that by using the command pip install tensorflow==1.7.0
just try replacing import tensorflow as tf with import tensorflow.compat.v1 as tf and nothing else, i was facing the same issue .This worked for me.
use abseil if you don't want to downgrade
from absl import app
if __name__ == '__main__':
app.run(main)
I am working on an AI, like Jarvis in python3. I am using the python speech_recognition module and pyaudio and everything else required acording to this page.
https://pypi.python.org/pypi/SpeechRecognition/
I have it on a raspberry pi now, before i was using my mac which was working fine. Now sometimes i get an error when running my Jarvis code on my Raspberry pi! Not always but frequetly enough to put a wrench in our progress. And not knowing when the error will come is a big problem and we need to get rid of it. Iḿ using a blue Snowball mic. Here is my code and my error if you could help, that would be great thanks!
Traceback (most recent call last):
File "/media/pi/TRAVELDRIVE/Jarvis(10.0).py", line 172, in <module>
with m as source: r.adjust_for_ambient_noise(source)
File "/usr/local/lib/python3.4/dist-packages/speech_recognition/__init__.py", line 140, in __enter__
input=True, # stream is an input stream
File "/usr/local/lib/python3.4/dist-packages/pyaudio.py", line 750, in open
stream = Stream(self, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/pyaudio.py", line 441, in __init__
self._stream = pa.open(**arguments)
OSError: [Errno -9999] Unanticipated host error
Jarvis.py
#JARVIS mark 10. python 3.5.1 version
#JUST.A.RATHER.VERY.INTELEGENT.SYSTEM.
##import speech_recognition
##import datetime
##import os
##import random
##import datetime
##import webbrowser
##import time
##import calendar
from difflib import SequenceMatcher
import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.tokenize import PunktSentenceTokenizer
import speech_recognition as sr
import sys
from time import sleep
import os
import random
r = sr.Recognizer()
m = sr.Microphone()
#Brain functions, vocab!
what_i_should_call_someone = [""]
Good_Things = ["love","sweet","nice","happy","fun","awesome","great"]
Bad_Things = ["death","kill","hurt","harm","discomfort","rape","pain","sad","depression","depressed","angry","mad","broken","raging","rage"]
# Words that you might says in the beginning of your input, for example: "um hey where are we!?!"
Slang_Words = ["um","uh","hm","eh"]
# Put all greetings in here
Static_Greetings = ["Hey","Hi","Hello"]
# Put your AIs Name and other names just in case.
Name = ["jarvis"]
posible_answer_key_words = ["becuase","yes","no"]
Chance_that_question_was_asked_1 = 0
Chance_that_question_was_asked_2 = 0
certainty_question_was_asked = 0
Me_statment_keywords = ["you","your","yours"]
You_statment_keywords = ["i","i'm","me"]
global certainty_person_is_talking_to_me
what_i_said = ("")
Just_asked_querstion = False
the_last_thing_i_said = ("")
the_last_thing_person_said = ("")
what_person_said = ("")
what_person_said_means = [""]
what_im_about_to_say = [""]
why_im_about_to_say_it = [""]
who_im_talking_to = [""]
how_i_feel = [""]
why_do_i_feel_the_way_i_do = [""]
what_i_am_thinking = ("")
# ways to describe the nouns last said
it_pronouns = ["it","they","she","he"]
# last person place or thing described spoken or descussed!
last_nouns = [""]
# Sample of random questions so Jarvis has somthing to index to know what a question is!
Sample_Questions = ["what is the weather like","where are we today","why did you do that","where is the dog","when are we going to leave","why do you hate me","what is the Answer to question 8",
"what is a dinosour","what do i do in an hour","why do we have to leave at 6.00", "When is the apointment","where did you go","why did you do that","how did he win","why won’t you help me",
"when did he find you","how do you get it","who does all the shipping","where do you buy stuff","why don’t you just find it in the target","why don't you buy stuff at target","where did you say it was",
"when did he grab the phone","what happened at seven am","did you take my phone","do you like me","do you know what happened yesterday","did it break when it dropped","does it hurt everyday",
"does the car break down often","can you drive me home","where did you find me"
"can it fly from here to target","could you find it for me"]
Sample_Greetings = ["hey","hello","hi","hey there","hi there","hello there","hey jarvis","hey dude"]
Question_Keyword_Answer = []
Int_Question_Keywords_In_Input = []
Possible_Question_Key_Words = ["whats","what","where","when","why","isn't","whats","who","should","would","could","can","do","does","can","can","did"]
Possible_Greeting_Key_Words = ["hey","hi","hello",Name]
# In this function: Analyze the user input find out if it's (Question, Answer, Command. Etc) and what is being: Asked, Commanded, ETC.
def Analyze():
def Analyze_For_Greeting():
def Greeting_Keyword_Check():
global Possible_Greeting_Key_Words
Int_Greeting_Keywords_In_Input = []
for words in what_person_said_l_wt:
if words in Possible_Greeting_Key_Words:
Int_Greeting_Keywords_In_Input.append(words)
Amount_Greeting_Keywords = (len(Int_Greeting_Keywords_In_Input))
if Amount_Greeting_Keywords > 0:
return True
def Greeting_Sentence_Match():
for Ran_Greeting in Sample_Greetings:
Greeting_Matcher = SequenceMatcher(None, Ran_Greeting, what_person_said_l).ratio()
if Greeting_Matcher > 0.5:
print (Greeting_Matcher)
print ("Similar to Greeting: "+Ran_Greeting)
return True
Greeting_Keyword_Check()
Greeting_Sentence_Match()
#In this function: determin if the input is a question or not.
def Analyze_For_Question():
# In this function: if there is atleast one question keyword in the user input then return true.
def Question_Keyword_Check():
global Possible_Question_Key_Words
Int_Question_Keywords_In_Input = []
for words in what_person_said_l_wt:
if words in Possible_Question_Key_Words:
Int_Question_Keywords_In_Input.append(words)
Amount_Question_keywords = (len(Int_Question_Keywords_In_Input))
if Amount_Question_keywords > 0:
return True
# In this function: if the users input is simular to other sample questions, return true.
def Question_Sentence_Match():
for Ran_Question in Sample_Questions:
Question_Matcher = SequenceMatcher(None, Ran_Question, what_person_said_l).ratio()
if Question_Matcher > 0.5:
print (Question_Matcher)
print ("Similar to Question: "+Ran_Question)
return True
# In this function: if the first word of the users input is a question keyword and there is a different question keyword in the input return true.
def Question_Verb_Noun_Check():
#if you say "hey jarvis" before somthing like a question or command it will still understand
try:
for word in what_person_said_l_wt:
if word in Static_Greetings or word in Name:
print (word)
Minus_Begin_Greet1 = what_person_said_l_wt.remove(word)
print (Minus_Begin_Greet1)
return True
except IndexError:
pass
Question_Keyword_Check()
Question_Sentence_Match()
Question_Verb_Noun_Check()
if Question_Keyword_Check()==True and Question_Sentence_Match()==True and Question_Verb_Noun_Check()==True:
return True
else:
return False
# All the funtions in Analyze
Analyze_For_Greeting()
Analyze_For_Question()
Conversation=True
Conversation_Started=False
while Conversation==True:
try:
if Conversation_Started==False:
#Greeting()
Conversation_Started=True
with m as source: r.adjust_for_ambient_noise(source)
print(format(r.energy_threshold))
print("Say something!") # just here for now and testing porposes so we know whats happening
with m as source: audio = r.listen(source)
print("Got it! Now to recognize it...")
try:
# recognize speech using Google Speech Recognition
value = r.recognize_google(audio)
# we need some special handling here to correctly print unicode characters to standard output
if str is bytes: # this version of Python uses bytes for strings (Python 2)
print(u"You said {}".format(value).encode("utf-8"))
else: # this version of Python uses unicode for strings (Python 3+)
print("You said {}".format(value))
what_person_said_l = value.lower()
what_person_said_l_wt = word_tokenize(what_person_said_l)
Analyze()
except sr.UnknownValueError:
print ("what was that?")
except sr.RequestError as e:
print("Uh oh! Sorry sir Couldn't request results from Google Speech Recognition service; {0}".format(e))
except KeyboardInterrupt:
pass