Exemple #1
0
import pytemperature

city = input('What city?: \n')
temp = input("Which temp format? C or F?: \n").lower()

package = {
    'APPID': "8b447aaba14ad1e178b186031642d0de",
    'q': city
}

r = requests.post('http://api.openweathermap.org/data/2.5/weather', params=package)
data = r.json()
print('Condition: ' + data['weather'][0]['main'])

if temp == 'c':
    print('Temp: ' + str(pytemperature.k2c(int(data['main']['temp']))))
elif temp == 'f':
    print('Temp: ' + str(pytemperature.k2f(int(data['main']['temp']))))

if data['wind']['deg'] >= 0 and data['wind']['deg'] <= 25:
    print('Wind Direction: North')
elif data['wind']['deg'] > 25 and data['wind']['deg'] <= 68:
    print('Wind Direction: Northeast')
elif data['wind']['deg'] > 68 and data['wind']['deg'] <= 110:
    print('Wind Direction: East')
elif data['wind']['deg'] > 110 and data['wind']['deg'] <= 150:
    print('Wind Direction: Southeast')
elif data['wind']['deg'] > 150 and data['wind']['deg'] <= 205:
    print('Wind Direction: South')
elif data['wind']['deg'] > 205 and data['wind']['deg'] <= 245:
    print('Wind Direction: Southwest')
Exemple #2
0
def test_get_smart_health_information(nvme0):
    from pytemperature import k2c
    import PySimpleGUI as sg

    smart = d.Buffer()
    nvme0.getlogpage(0x02, smart, 512).waitdone()

    l = []
    l.append('  Byte |   Value   | Attribute')
    l.append('     0 |  %7d  | Critical Warning' % smart.data(0))
    l.append('  2: 1 |  %7d  | Composite Temperature (degree C)' %
             k2c(smart.data(2, 1)))
    l.append('     3 |  %7d  | Available Spare' % smart.data(3))
    l.append('     4 |  %7d  | Available Spare Threshold' % smart.data(4))
    l.append('     5 |  %7d  | Percentage Used' % smart.data(5))
    l.append('     6 |  %7d  | Endurance Group Critical Warning Summary' %
             smart.data(6))
    l.append(' 47:32 |%11d| Data Units Read (1000LBA)' % smart.data(47, 32))
    l.append(' 63:48 |%11d| Data Units Written (1000LBA)' % smart.data(63, 48))
    l.append(' 79:64 |%11d| Host Read Commands' % smart.data(79, 64))
    l.append(' 95:80 |%11d| Host Write Commands' % smart.data(95, 80))
    l.append('111:96 |  %7d  | Controller Busy Time (minutes)' %
             smart.data(111, 96))
    l.append('127:112|  %7d  | Power Cycles' % smart.data(127, 112))
    l.append('143:128|  %7d  | Power On Hours' % smart.data(143, 128))
    l.append('159:144|  %7d  | Unsafe Shutdowns' % smart.data(159, 144))
    l.append('175:160|  %7d  | Media and Data Integrity Errors' %
             smart.data(175, 160))
    l.append('191:176|  %7d  | Number of Error Information Log Entries' %
             smart.data(191, 176))
    l.append('195:192|  %7d  | Warning Composite Temperature Time (minutes)' %
             smart.data(195, 192))
    l.append('199:196|  %7d  | Critical Composite Temperature Time (minutes)' %
             smart.data(199, 196))
    l.append('201:200|  %7d  | Temperature Sensor 1 (degree C)' %
             k2c(smart.data(201, 200)))
    l.append('203:202|  %7d  | Temperature Sensor 2 (degree C)' %
             k2c(smart.data(203, 202)))
    l.append('205:204|  %7d  | Temperature Sensor 3 (degree C)' %
             k2c(smart.data(205, 204)))
    l.append('207:206|  %7d  | Temperature Sensor 4 (degree C)' %
             k2c(smart.data(207, 206)))
    l.append('209:208|  %7d  | Temperature Sensor 5 (degree C)' %
             k2c(smart.data(209, 208)))
    l.append('211:210|  %7d  | Temperature Sensor 6 (degree C)' %
             k2c(smart.data(211, 210)))
    l.append('213:212|  %7d  | Temperature Sensor 7 (degree C)' %
             k2c(smart.data(213, 212)))
    l.append('215:214|  %7d  | Temperature Sensor 8 (degree C)' %
             k2c(smart.data(215, 214)))
    l.append(
        '219:216|  %7d  | Thermal Management Temperature 1 Transition Count' %
        smart.data(219, 216))
    l.append(
        '223:220|  %7d  | Thermal Management Temperature 2 Transition Count' %
        smart.data(223, 220))
    l.append(
        '227:224|  %7d  | Total Time For Thermal Management Temperature 1' %
        smart.data(227, 224))
    l.append(
        '231:228|  %7d  | Total Time For Thermal Management Temperature 2' %
        smart.data(231, 228))

    layout = [[sg.Listbox(l, size=(70, 20))]]
    sg.Window("SMART/Health Information",
              layout + [[sg.OK()]],
              font=('monospace', 16)).Read()
Exemple #3
0
def mainadminhome(username, first_name, last_name):
	print(g.user)
	if g.user:
		headers = {
			'Authorization' : '{}'.format(session['token'])
		}
		# url1 = 'http://127.0.0.1:5000/evacuees/age_female'
		# response1 = requests.request('GET', url1, headers=headers)
		# json_data1 = response1.json()
		# print(json_data1)
		

		# for x in json_data1:
		# 	if len(x) == 1:
		# 		# print(x)
		# 		y = "".join(str(e) for e in x)
		# 		# age = [list(map())]
		# 		age = int(y)
		# 		print(age)

		# 	if age >= 1 and age <= 3 :
		# 		print('Gradeschooler')
		# 		age_range = "Gradeschooler"
		# 		url2 = 'http://127.0.0.1:5000/evacuees/age_female/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response2 = requests.request('PUT', url2, headers=headers)
		# 		json_data2 = response2.json()
		# 		print(json_data2)
		# 	elif age >= 13 and age <= 17:
		# 		print('Teens')
		# 		age_range = "Teens"
		# 		url3 = 'http://127.0.0.1:5000/evacuees/age_female/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response3 = requests.request('PUT', url3, headers=headers)
		# 		json_data3 = response3.json()
		# 		print(json_data3)
		# 	elif age >= 18 and age <= 21:
		# 		print('Young-Adult')
		# 		age_range = "Young-Adult"
		# 		url4 = 'http://127.0.0.1:5000/evacuees/age_female/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response4 = requests.request('PUT', url4, headers=headers)
		# 		json_data4 = response4.json()
		# 		print(json_data4)
		# 	else:
		# 		print('Adult')
		# 		age_range = "Adult"
		# 		url5 = 'http://127.0.0.1:5000/evacuees/age_female/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response5 = requests.request('PUT', url5, headers=headers)
		# 		json_data5 = response5.json()
		# 		print(json_data5)


		# headers = {
		# 	'Authorization' : '{}'.format(session['token'])
		# }
		# url1 = 'http://127.0.0.1:5000/evacuees/age_male'
		# response1 = requests.request('GET', url1, headers=headers)
		# json_data1 = response1.json()
		# print(json_data1)
		

		# for x in json_data1:
		# 	if len(x) == 1:
		# 		# print(x)
		# 		y = "".join(str(e) for e in x)
		# 		# age = [list(map())]
		# 		age = int(y)
		# 		print(age)

		# 	if age >= 1 and age <= 3 :
		# 		print('Gradeschooler')
		# 		age_range = "Gradeschooler"
		# 		url2 = 'http://127.0.0.1:5000/evacuees/age_male/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response2 = requests.request('PUT', url2, headers=headers)
		# 		json_data2 = response2.json()
		# 		print(json_data2)
		# 	elif age >= 13 and age <= 17:
		# 		print('Teens')
		# 		age_range = "Teens"
		# 		url3 = 'http://127.0.0.1:5000/evacuees/age_male/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response3 = requests.request('PUT', url3, headers=headers)
		# 		json_data3 = response3.json()
		# 		print(json_data3)
		# 	elif age >= 18 and age <= 21:
		# 		print('Young-Adult')
		# 		age_range = "Young-Adult"
		# 		url4 = 'http://127.0.0.1:5000/evacuees/age_male/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response4 = requests.request('PUT', url4, headers=headers)
		# 		json_data4 = response4.json()
		# 		print(json_data4)
		# 	else:
		# 		print('Adult')
		# 		age_range = "Adult"
		# 		url5 = 'http://127.0.0.1:5000/evacuees/age_male/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response5 = requests.request('PUT', url5, headers=headers)
		# 		json_data5 = response5.json()
		# 		print(json_data5)


		# headers = {
		# 	'Authorization' : '{}'.format(session['token'])
		# }
		# url1 = 'http://127.0.0.1:5000/dependents/age_female'
		# response1 = requests.request('GET', url1, headers=headers)
		# json_data1 = response1.json()
		# print(json_data1)
		

		# for x in json_data1:
		# 	if len(x) == 1:
		# 		# print(x)
		# 		y = "".join(str(e) for e in x)
		# 		# age = [list(map())]
		# 		age = int(y)
		# 		print(age)

		# 	if age >= 1 and age <= 3 :
		# 		print('Gradeschooler')
		# 		age_range = "Gradeschooler"
		# 		url2 = 'http://127.0.0.1:5000/dependents/age_female/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response2 = requests.request('PUT', url2, headers=headers)
		# 		json_data2 = response2.json()
		# 		print(json_data2)
		# 	elif age >= 13 and age <= 17:
		# 		print('Teens')
		# 		age_range = "Teens"
		# 		url3 = 'http://127.0.0.1:5000/dependents/age_female/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response3 = requests.request('PUT', url3, headers=headers)
		# 		json_data3 = response3.json()
		# 		print(json_data3)
		# 	elif age >= 18 and age <= 21:
		# 		print('Young-Adult')
		# 		age_range = "Young-Adult"
		# 		url4 = 'http://127.0.0.1:5000/dependents/age_female/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response4 = requests.request('PUT', url4, headers=headers)
		# 		json_data4 = response4.json()
		# 		print(json_data4)
		# 	else:
		# 		print('Adult')
		# 		age_range = "Adult"
		# 		url5 = 'http://127.0.0.1:5000/dependents/age_female/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response5 = requests.request('PUT', url5, headers=headers)
		# 		json_data5 = response5.json()
		# 		print(json_data5)


		# headers = {
		# 	'Authorization' : '{}'.format(session['token'])
		# }
		# url1 = 'http://127.0.0.1:5000/dependents/age_male'
		# response1 = requests.request('GET', url1, headers=headers)
		# json_data1 = response1.json()
		# print(json_data1)
		

		# for x in json_data1:
		# 	if len(x) == 1:
		# 		# print(x)
		# 		y = "".join(str(e) for e in x)
		# 		# age = [list(map())]
		# 		age = int(y)
		# 		print(age)

		# 	if age >= 1 and age <= 3 :
		# 		print('Gradeschooler')
		# 		age_range = "Gradeschooler"
		# 		url2 = 'http://127.0.0.1:5000/dependents/age_male/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response2 = requests.request('PUT', url2, headers=headers)
		# 		json_data2 = response2.json()
		# 		print(json_data2)
		# 	elif age >= 13 and age <= 17:
		# 		print('Teens')
		# 		age_range = "Teens"
		# 		url3 = 'http://127.0.0.1:5000/dependents/age_male/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response3 = requests.request('PUT', url3, headers=headers)
		# 		json_data3 = response3.json()
		# 		print(json_data3)
		# 	elif age >= 18 and age <= 21:
		# 		print('Young-Adult')
		# 		age_range = "Young-Adult"
		# 		url4 = 'http://127.0.0.1:5000/dependents/age_male/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response4 = requests.request('PUT', url4, headers=headers)
		# 		json_data4 = response4.json()
		# 		print(json_data4)
		# 	else:
		# 		print('Adult')
		# 		age_range = "Adult"
		# 		url5 = 'http://127.0.0.1:5000/dependents/age_male/'+age_range
		# 		headers = {
		# 			'Authorization' : '{}'.format(session['token'])
		# 		}
		# 		response5 = requests.request('PUT', url5, headers=headers)
		# 		json_data5 = response5.json()
		# 		print(json_data5)

		urls = 'http://127.0.0.1:5000/evacuees/all_age_female'
		responses = requests.request('GET', urls, headers=headers)
		female_age = responses.json()
		print(female_age)
		print(female_age[0]["adult"])

		urls2 = 'http://127.0.0.1:5000/evacuees/all_age_female'
		responses = requests.request('GET', urls2, headers=headers)
		male_age = responses.json()
		print(male_age)
		print(male_age[0]["adult"])




		api_address = 'http://api.openweathermap.org/data/2.5/weather?appid=8f46c985e7b5f885798e9a5a68d9c036&q=Iligan'
		json_data = requests.get(api_address).json()
		city = json_data['name']
		formatted_data = json_data['weather'][0]['description']
		weather_icon = json_data['weather'][0]['icon']
		temp = json_data['main']['temp']
		final_temp = pytemperature.k2c(temp)
		celcius = round(final_temp, 2)
		print(city)
		print(formatted_data)
		print(weather_icon)
		print(temp)
		print(final_temp)
		print(celcius)
		url = 'http://127.0.0.1:5000/distcenter/'
		
		response = requests.request('GET', url, headers=headers)
		json_data = response.json()
		print(json_data)

		# return render_template('maps.html', json_data=json_data)
		# return render_template('home.html', weather=formatted_data, weather_icon=weather_icon, celcius=celcius, city=city)
		return render_template('dashboard.html', male_age=male_age, female_age=female_age, json_data=json_data, username=username, first_name=first_name, last_name=last_name,  weather=formatted_data, weather_icon=weather_icon, celcius=celcius, city=city )
	else:
		return redirect('unauthorized')
package = {
    'APPID': '8ddb637e661cc63a87f16ca168924ad6',
    'q': 'portland',
    'zip': '97202'
}

print('*************Weather Station**************')

city_or_zip = input("Would you like to search by city or zip code?:").lower()
if city_or_zip == 'city':
    package['q'] = input("City Name: ").capitalize()
elif city_or_zip == 'zip code':
    package['zip'] = input("Zip: ")

r = requests.post('https://api.openweathermap.org/data/2.5/weather',
                  params=package)

kelvin = r.json()['main']['temp']
f = pytemperature.k2f(kelvin)
c = pytemperature.k2c(kelvin)

temp = input("Would you like the temperature in Fahrenheit or Celsius [F/C]?: "
             ).upper()
if temp == 'F':
    print('{} Fahrenheit.'.format(f))
elif temp == 'C':
    print('{} Celsius.'.format(c))
else:
    print("I didn't understand.")
Exemple #5
0
def status(config={}, output="default"):
    result = {}

    if output == "signalk":
        logger.debug("prepping sk output...")
        from pivac import sk_init_deltas, sk_add_source, sk_add_value
        deltas = sk_init_deltas()

    cams = config["inputs"]
    for cam, camdict in cams.iteritems():
        logger.debug("iterating camera %s", cam)
        if output == "signalk":
            sk_source = sk_add_source(deltas, "flirfx:%s" % cam)

        try:
            # no session yet
            if "fake" in camdict and camdict["fake"] == True:
                temp_units = "F"
                temp_value = 68
                humidity_value = 49
            else:
                if cam not in Cams:
                    logger.debug("logging into camera...")
                    Cams[cam] = {}
                    r = requests.post(
                        'http://%s/API/1.0/ChiconyCameraLogin' % cam,
                        data='{ "password" : "%s" }' % camdict["pwd"])
                    session = r.cookies['Session']
                    Cams[cam]["cookies"] = dict(Session=session)

                req = requests.post(
                    'http://%s/API/1.1/CameraStatus' % cam,
                    cookies=cookies,
                    data='{ "getCameraStatus" : [ "humidity", "temperature"] }'
                )
                res = req.json()
                temp_units = res['temperature']['tempUnits']
                temp_value = res['temperature']['tempValue']
                humidity_value = res['humidity']['humidityLevel']

            if temp_units == 'F':
                temp_value = pytemperature.f2k(temp_value)
            elif temp_units == 'C':
                temp_value = pytemperature.c2k(temp_value)

            if output == "signalk":
                sk_add_value(sk_source, "%s.temperature" % camdict["sk_path"],
                             temp_value)
                sk_add_value(sk_source, "%s.humidity" % camdict["sk_path"],
                             humidity_value)
            else:
                if camdict["scale"] == "fahrenheit":
                    temp_value = pytemperature.k2f(temp_value)
                if camdict["scale"] == "celcius":
                    temp_value = pytemperature.k2c(temp_value)
                result[cam] = {}
                result[cam]["temperature"] = temp_value
                result[cam]["humidity"] = humidity_value
        except:
            logger.exception("error getting data from FLIR camera %s" % cam)

    if output == "signalk":
        return deltas
    else:
        return result
Exemple #6
0
def test_get_current_temperature(nvme0):
    smart_log = d.Buffer()
    nvme0.getlogpage(0x02, smart_log, 512).waitdone()
    ktemp = smart_log.data(2, 1)
    logging.info("current temperature in SMART data: %0.2f degreeC" % k2c(ktemp))
Exemple #7
0
# Now x contains list of nested dictionaries
# Check the value of "cod" key is equal to
# "404", means city is found otherwise,
# city is not found
if x["cod"] != "404":

    # store the value of "main"
    # key in variable y
    y = x["main"]

    # store the value corresponding
    # to the "temp" key of y
    current_temperature = y["temp"]

pyt = pytemperature.k2c(current_temperature)
pyx = str(round(pyt, 2))
print(pyx)
# store the value corresponding
# to the "pressure" key of y
#	current_pressure = y["pressure"]

# store the value corresponding
# to the "humidity" key of y
#	current_humidiy = y["humidity"]

# store the value of "weather"
# key in variable z
z = x["weather"]

# store the value corresponding
Exemple #8
0
 def to_celcius(kelvin):
     return round(pytemperature.k2c(float(kelvin)), 2)
Exemple #9
0
    mySK = SignalK('http://127.0.0.1:3000')  # Instantiate SignalK local
    if mySK.Read_SignalK('/signalk/v1/api/vessels/', '', "SignalK No Respons"):
        try:
            mySK.mmsi = mySK.res_txt
            print(mySK.mmsi)
            boat_name = mySK.loaded_json[mySK.mmsi]['name'] + ' Signal-K'
        except Exception as err:
            print(err)
            boat_name = 'Ship name missing'
        print(boat_name)

        if mySK.Read_SignalK(
                '/signalk/v1/api/vessels/' + mySK.mmsi +
                '/environment/inside/refrigerator/temperature/value', '',
                "SignalK No Kyl Temp"):
            kyl_temp_value = pytemperature.k2c(mySK.res_float)  # Celsius
            kyl_temp = f'Kyl {kyl_temp_value:.1f}C'
        print(kyl_temp)

        if mySK.Read_SignalK(
                '/signalk/v1/api/vessels/' + mySK.mmsi +
                '/environment/inside/refrigerator/pressure/value', '',
                "SignalK No Pressure"):
            mmhg = mySK.res_int / 1000.0 * 7.50062
            pressure = f'Barometric {mmhg:.0f} mmHg'  # f'Barometric {pytemperature.k2c(mySK.res_int)}Pa'
        print(pressure)
        '''
        if mySK.Read_SignalK('/signalk/v1/api/vessels/' + mySK.mmsi + '/environment/rpi/cpu/temperature/value',
                        '', "SignalK No CPU Temp"):
            cpu_temp = f'CPU {pytemperature.k2c(mySK.res_float):.1f}C'
        print(cpu_temp)
Exemple #10
0
# -----------------------

du.show_boxplot(train_dataset, exclude=['year'], figsize=(5, 5))
if SAVE_PLOTS:
    plt.savefig(dutils.GRAPH_PATH + '/01.01_boxplot_allfeatures.png',
                bbox_inches="tight")

# Temperature features in kelvin conversion (kelvin to celsius)

temp_features = [
    'reanalysis_air_temp_k', 'reanalysis_dew_point_temp_k',
    'reanalysis_max_air_temp_k', 'reanalysis_min_air_temp_k',
    'reanalysis_avg_temp_k'
]

train_dataset[temp_features] = pytemperature.k2c(train_dataset[temp_features])

du.show_boxplot(train_dataset, exclude=['year'], figsize=(5, 5))
if SAVE_PLOTS:
    plt.savefig(dutils.GRAPH_PATH + '/01.02_boxplot_allfeatures_celcius.png',
                bbox_inches="tight")

# --------------------------
# 2. Heatmap - correlation
# --------------------------

# Correlation matrix
du.show_heatmap(train_dataset, exclude=['city'])
if SAVE_PLOTS:
    plt.savefig(dutils.GRAPH_PATH + '/01.03_heatmap_correlations.png',
                bbox_inches="tight")
Exemple #11
0
def converter(temperature: float) -> float:
    return round(pytemperature.k2c(temperature), 2)
Exemple #12
0
        elif 'time' in query:
            strTime = datetime.datetime.now().strftime("%H:%M:%S:")
            speak(f" time is {strTime}")

        elif 'weather' in query:
            speak("searching Weather..")
            query = query.replace("weatdeher", "")
            results = "http://api.openweathermap.org/data/2.5/weather?appid=0c42f7f6b53b244c78a418f4f181282a&q="
            speak("speak city name")
            city = takeCommand().lower()
            url = results + city
            json_data = requests.get(url).json()
            speak("according to Open Weather, weather condtion is")
            y = json_data["main"]
            current_temperature = math.ceil(pytemperature.k2c((y["temp"])))
            current_pressure = y["pressure"]
            current_humidiy = y["humidity"]

            weather_des = json_data['weather'][0]["description"]

            print(" Temperature  = " + str(current_temperature) +
                  "\n atmospheric pressure (in hPa unit) = " +
                  str(current_pressure) + "\n humidity (in percentage) = " +
                  str(current_humidiy) + "\n description = " +
                  str(weather_des))

            speak(
                f" Temperature is {current_temperature} degree celcius. atmospheric pressure (in hPa unit) is {current_pressure}. humidity (in percentage) is {current_humidiy} and {weather_des}"
            )
            speak(f"in {city}")
Exemple #13
0
def start(event=None):
    window.geometry("500x500")
    country_code_label.pack_forget()
    country_code.pack_forget()
    city_name_label.pack_forget()
    city_name.pack_forget()
    show_forecast.pack_forget()
    error_label.pack()
    error_label.pack_forget()
    api_key = "replace with your api key"
    try:
        req = requests.get(
            "http://api.openweathermap.org/data/2.5/forecast?q=" +
            city_name.get() + "," + country_code.get() + "&appid=" + api_key)
        for i in range(0, len(req.json()["list"])):
            full_date = req.json()["list"][i]["dt_txt"]
            year = full_date.split(" ")[0].split("-")[0]
            month = full_date.split(" ")[0].split("-")[1]
            day = full_date.split(" ")[0].split("-")[2]
            tmp = req.json()["list"][i]["main"]["temp"]
            max_tmp = req.json()["list"][i]["main"]["temp_max"]
            min_tmp = req.json()["list"][i]["main"]["temp_min"]
            weather_des = req.json()["list"][i]["weather"][0]["description"]
            icon = req.json()["list"][i]["weather"][0]["icon"]
            if getWeekDay(
                    datetime.datetime(int(year), int(month),
                                      int(day)).weekday()) not in days.keys():
                days[getWeekDay(
                    datetime.datetime(
                        int(year), int(month),
                        int(day)).weekday())] = day + " - " + month
            if not day + " - " + month in date.keys():
                date[day + " - " + month] = []
            if str(int(full_date.split(" ")[1].split(":")[0])) == '0':
                list = "21:00 - " + str(
                    full_date.split(" ")[1].split(":")[0]) + ":00"
                day = getWeekDay(
                    datetime.datetime(int(year), int(month), int(
                        day)).weekday() - 1)
                date[days[day]].append([
                    list,
                    round(pytemperature.k2c(tmp), 1),
                    round(pytemperature.k2c(max_tmp), 1),
                    round(pytemperature.k2c(min_tmp), 1), weather_des, icon
                ])
            else:
                list = str(int(full_date.split(" ")[1].split(":")[0]) -
                           3) + ":00 - " + str(
                               full_date.split(" ")[1].split(":")[0]) + ":00"
                date[day + ' - ' + month].append([
                    list,
                    round(pytemperature.k2c(tmp), 1),
                    round(pytemperature.k2c(max_tmp), 1),
                    round(pytemperature.k2c(min_tmp), 1), weather_des, icon
                ])
    except Exception:
        country_code_label.pack(pady='10')
        country_code.pack()
        country_code.focus_set()
        city_name_label.pack(pady='10')
        city_name.pack()
        show_forecast.pack(pady='10')
        error_label.pack(pady='10')
    for i in days.keys():
        var = str(i)
        var = tk.Button(window,
                        text=i + '\n' + days[i],
                        font='bold',
                        default='active',
                        bg='white',
                        fg='black',
                        width='20',
                        pady='0')
        buttons[var] = i
        var.configure(command=lambda button=var: showForecast(button))
        var.pack(pady='10')
Exemple #14
0
ACCESS_ID = "fake id"
SECRET_KEY = "fake id"

host = 'search-idc-7dyp7fwnklhj22hwzpuoa5hgsy.eu-west-1.es.amazonaws.com'
awsauth = AWS4Auth(ACCESS_ID, SECRET_KEY, region, 'es')

APPID_API_KEY = 'fake key'
CITY_QUERY = 'Herzliyya'
WEATHER_API_URL = 'https://api.openweathermap.org/data/2.5/weather'

response = requests.get(WEATHER_API_URL, {
    'q': CITY_QUERY,
    'appid': APPID_API_KEY
})
response_json = response.json()
today_temp_in_cls = int(pytemperature.k2c(response_json['main']['temp']))

es = Elasticsearch(hosts=[{
    'host': host,
    'port': 443
}],
                   http_auth=awsauth,
                   use_ssl=True,
                   verify_certs=True,
                   connection_class=RequestsHttpConnection)

week_days = [
    'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',
    'Sunday'
]
Y = 2000  # dummy leap year to allow input X-02-29 (leap day)
Exemple #15
0
 def intentTemperature(self):
     return 'Today\'s temperature is '+str(pytemperature.k2c(self._mainFeatures['temp']))+' degrees celsius.'
def weather_info(city):
    custom_weather_api_url = weather_api_url.replace("{city}", city)
    weather_request_data = invoke_request_to_url(custom_weather_api_url)
    weather_temperature = pytemperature.k2c(
        weather_request_data["main"]["temp"])
    return weather_request_data, weather_temperature
Exemple #17
0
def temperature_conversion_features(data, feature, new_feature):

    if feature in data.columns:
        printlog("temperature conversion: kelvin to celsius " + feature +
                 " to " + new_feature)
        data[new_feature] = pytemperature.k2c(data[feature])
Exemple #18
0
def weather():
    """Blablbal."""
    try:
        temperature_street = 0
        humidity_street = 0

        temperature_small_h_1_fl = 0
        humidity_small_h_1_fl = 0

        temperature_small_h_2_fl = 0
        humidity_small_h_2_fl = 0

        temperature_big_h_1_fl = 0
        humidity_big_h_1_fl = 0

        temperature_big_h_2_fl = 0
        humidity_big_h_2_fl = 0

        url = 'http://api.openweathermap.org/data/2.5/weather?id=698782&appid=319f5965937082b5cdd29ac149bfbe9f'
        try:
            response = requests.get(url=url, timeout=(3, 3))
            response.raise_for_status()
            json_data = json.loads(response.text)
            temperature_street = str(
                round(pytemperature.k2c(json_data['main']['temp']), 1)),
            humidity_street = str(round(json_data['main']['humidity'], 1))
        except requests.exceptions.RequestException as e:
            logging.error(e)
            logging.error("Can't get weather info Exception occured")
            humidity_street = 0
            temperature_street = 0

        try:
            response = requests.get(url=ARDUINO_SMALL_H_IP + '/temperature',
                                    timeout=(3, 3))
            response.raise_for_status()
            json_data = json.loads(response.text)

            temperature_small_h_1_fl = json_data['1_floor_temperature']
            humidity_small_h_1_fl = json_data['1_floor_humidity']

            temperature_small_h_2_fl = json_data['2_floor_temperature']
            humidity_small_h_2_fl = json_data['2_floor_humidity']
            logging.info(response.text)
        except requests.exceptions.RequestException as e:
            logging.error(e)
            logging.error("Can't get temp info Exception occured")

            temperature_small_h_1_fl = 0
            humidity_small_h_1_fl = 0

            temperature_small_h_2_fl = 0
            humidity_small_h_2_fl = 0

        logging.info(QUERY[mn()].format(
            0, humidity_street, temperature_small_h_1_fl,
            humidity_small_h_1_fl, temperature_small_h_2_fl,
            humidity_small_h_2_fl, temperature_big_h_1_fl, humidity_big_h_1_fl,
            temperature_big_h_2_fl, humidity_big_h_2_fl))

        update_db_request(QUERY[mn()].format(
            0, humidity_street, temperature_small_h_1_fl,
            humidity_small_h_1_fl, temperature_small_h_2_fl,
            humidity_small_h_2_fl, temperature_big_h_1_fl, humidity_big_h_1_fl,
            temperature_big_h_2_fl, humidity_big_h_2_fl))
    except Exception as e:
        logging.error(e)
def printar_detalhes(clima):
    cidade = clima['name']
    temperatura = pytemperature.k2c(clima['main']['temp'])
    print(f"A temperatura em {cidade} neste momento é de {temperatura:.1f} graus Celsius.")
Exemple #20
0
def virtualAssistant():
    SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
    MONTHS = [
        "january", "february", "march", "april", "may", "june", "july",
        "august", "september", "october", "november", "december"
    ]
    DAYS = [
        "monday", "tuesday", "wednesday", "thursday", "friday", "saturday",
        "sunday"
    ]
    DAY_EXTENTIONS = ["rd", "th", "st", "nd"]

    # def credAccess():
    # with open("userCred.txt", 'rt') as fin:
    # creds = fin.readlines()
    # username = creds[1]
    # USERNAME = username[0:len(username) - 1]
    # email_id = creds[3]
    # USER_EMAIL_ID = email_id[0:len(email_id) - 1]
    # password = creds[5]
    # USER_EMAIL_PASS = password[0:len(password) - 1]
    # sql = creds[7]
    # USER_SQL_PASS = sql[0:len(sql) - 1]
    # return USERNAME, USER_EMAIL_ID, USER_EMAIL_PASS, USER_SQL_PASS

    def speak(text):
        engine = pyttsx3.init("sapi5")  # object creation
        """ RATE"""
        rate = engine.getProperty(
            'rate')  # getting details of current speaking rate
        engine.setProperty('rate', 122)  # setting up new voice rate
        """VOLUME"""
        volume = engine.getProperty(
            'volume')  # getting to know current volume level (min=0 and max=1)
        engine.setProperty('volume',
                           1.0)  # setting up volume level  between 0 and 1
        """VOICE"""
        voices = engine.getProperty(
            'voices')  # getting details of current voice
        # engine.setProperty('voice', voices[0].id)  #changing index, changes voices. o for male
        engine.setProperty(
            'voice',
            voices[1].id)  # changing index, changes voices. 1 for female

        engine.say(text)
        engine.runAndWait()

    try:
        recognitionMode = int(
            input('''By which mode would you like to give commands : 
        1 - Voice Mode
        2 - Script Mode \n'''))
    except:
        print("sorry you entered wrong value")

    def take_command():
        global query
        if recognitionMode == 1:
            # It takes microphone input from the user and returns string output
            r = sr.Recognizer()
            with sr.Microphone() as source:
                print("Listening...")
                r.pause_threshold = 1
                audio = r.listen(source)
            try:
                print("Recognizing...")
                query = r.recognize_google(audio, language='en-in')
                print(f"User said: {query}\n")
            except Exception:
                print("Say that again please...")
                return "None"

        elif recognitionMode == 2:
            try:
                query = input('Enter your Command : ')
            except Exception as error:
                print(error)
        return query.lower()

    def send_sms(number, message):
        url = 'https://www.fast2sms.com/dev/bulk'
        params = {
            'authorization':
            'R4UilqdkJNw1PKHu2j3fb0QsgEx7pWMYO9BItXnGvc5Cr8zoDAj2bBqMs4n9lLuNXaW85wEPhYJdUiQo',
            'sender_id': 'FSTSMS',
            'message': str(input("Type a message : ")),
            'language': 'english',
            'route': 'p',
            'numbers': number
        }
        response = requests.get(url, params=params)
        dic = response.json()
        print(dic)

    # def authenticate_google():
    # """Shows basic usage of the Google Calendar API.Prints the start and name of the next 10 events on the user's calendar."""
    # credits = None
    # if os.path.exists('token.pickle'):
    # with open('token.pickle', 'rb') as token:
    # credits = pickle.load(token)
    # if not credits or not credits.valid:
    # if credits and credits.expired and credits.refresh_token:
    # credits.refresh(Request())
    # else:
    # flow = InstalledAppFlow.from_client_secrets_file(
    # 'credentials.json', SCOPES)
    # credits = flow.run_local_server(port=0)
    # with open('token.pickle', 'wb') as token:
    # pickle.dump(credits, token)
    # service = build('calendar', 'v3', credentials=credits)
    # return service

    def get_events(day, service):
        # Call the Calendar API
        date = datetime.datetime.combine(day, datetime.datetime.min.time())
        end_date = datetime.datetime.combine(day, datetime.datetime.max.time())
        utc = pytz.UTC
        date = date.astimezone(utc)
        end_date = end_date.astimezone(utc)
        events_result = service.events().list(calendarId='primary',
                                              timeMin=date.isoformat(),
                                              timeMax=end_date.isoformat(),
                                              singleEvents=True,
                                              orderBy='startTime').execute()
        events = events_result.get('items', [])
        if not events:
            speak('No upcoming events found.')
        else:
            speak(f"You have {len(events)} events on this day.")
            for event in events:
                start = event['start'].get('dateTime',
                                           event['start'].get('date'))
                print(start, event['summary'])
                start_time = str(start.split("T")[1].split("-")[0])
                if int(start_time.split(":")[0]) < 12:
                    start_time = start_time + "am"
                else:
                    start_time = str(int(start_time.split(":")[0]) -
                                     12) + start_time.split(":")[1]
                    start_time = start_time + "pm"
                speak(event["summary"] + " at " + start_time)

    def get_date(text):
        text = text.lower()
        today = datetime.date.today()
        if text.count("today") > 0:
            return today
        day = -1
        day_of_week = -1
        month = -1
        year = today.year

        for word in text.split():
            if word in MONTHS:
                month = MONTHS.index(word) + 1
            elif word in DAYS:
                day_of_week = DAYS.index(word)
            elif word.isdigit():
                day = int(word)
            else:
                for ext in DAY_EXTENTIONS:
                    found = word.find(ext)
                    if found > 0:
                        try:
                            day = int(word[:found])
                        except:
                            pass

        # THE NEW PART STARTS HERE
        if month < today.month and month != -1:  # if the month mentioned is before the current month set the year to the next
            year = year + 1

        # This is slightly different from the video but the correct version
        if month == -1 and day != -1:  # if we didn't find a month, but we have a day
            if day < today.day:
                month = today.month + 1
            else:
                month = today.month

        # if we only found a dta of the week
        if month == -1 and day == -1 and day_of_week != -1:
            current_day_of_week = today.weekday()
            dif = day_of_week - current_day_of_week

            if dif < 0:
                dif += 7
                if text.count("next") >= 1:
                    dif += 7

            return today + datetime.timedelta(dif)

        if day != -1:  # FIXED FROM VIDEO
            return datetime.date(month=month, day=day, year=year)

    def sendEmail(to, content):
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.ehlo()
        server.starttls()
        server.login('*****@*****.**', 'you know that')
        subject = "Contact book data"
        server.sendmail('*****@*****.**', to, content, subject)
        server.close()

    def note(text):
        date = datetime.datetime.now()
        file_name = str(date).replace(":", "-") + "-note.txt"
        with open(file_name, "w") as f:
            f.write(text)
        osCommandString = f"notepad.exe {file_name}"
        os.system(osCommandString)

    def TimeConversion(seconds):
        minutes, seconds = divmod(seconds, 60)
        hours, minutes = divmod(minutes, 60)
        return f"{hours:d}:{minutes:02d}:{seconds:02d}"

    def greet(name):
        hour = int(datetime.datetime.now().hour)
        if 0 <= hour < 12:
            speak("Good Morning!" + str(name))
        elif 12 <= hour < 16:
            speak("Good Afternoon!" + str(name))
        else:
            speak("Good Evening!" + str(name))

    def history(text):
        date_time = datetime.datetime.now().strftime("%d/%m/%Y, %H:%M:%S")
        f = open("Hello.txt", "a")
        f.write(f"{date_time} : {text}\n\n")

    def contactBook(USER_SQL_PASS):
        global emailID
        mydb = MySQLConnection(host="localhost",
                               user="******",
                               password=USER_SQL_PASS,
                               database="contact_book")
        mycursor = mydb.cursor()
        name1 = str(input("Enter the name : "))
        mycursor.execute("SELECT * FROM contact_table")
        myresult = mycursor.fetchall()
        for x in myresult:
            if name1 == x[0]:
                emailID = x[1]
                break
        else:
            print("Record not found")
            insertChoice = input("Would you like to add contact ? ")
            if insertChoice.lower().startswith("y"):
                mydb1 = MySQLConnection(host="localhost",
                                        user="******",
                                        password="******",
                                        database="contact_book")
                mycursor1 = mydb1.cursor()
                mail = str(input("Enter the e-mail ID of the new contact : "))
                sql = "INSERT INTO contact_table(name, email_id) VALUES(%s,%s)"
                val = (name1, mail)
                mycursor1.execute(sql, val)
                mydb1.commit()
                print(mycursor1.rowcount, "record inserted.")

            mydb = MySQLConnection(host="localhost",
                                   user="******",
                                   password=USER_SQL_PASS,
                                   database="contact_book")
            mycursor = mydb.cursor()
            mycursor.execute("SELECT * FROM contact_table")
            myresult = mycursor.fetchall()
            for x in myresult:
                if name1 == x[0]:
                    emailID = x[1]
                    break
        return emailID

    if __name__ == "__main__":

        # USERNAME, USER_EMAIL_ID, USER_EMAIL_PASS, USER_SQL_PASS = credAccess()
        # print(USERNAME, USER_EMAIL_ID, USER_EMAIL_PASS, USER_SQL_PASS)
        name = getpass.getuser()
        greet(name)
        initTime = datetime.datetime.now()
        WAKE = "rushi"
        assname = WAKE
        # SERVICE = authenticate_google()
        print("Starting....")
        speak("I am ready")

        while True:
            text = take_command()
            if text.count(WAKE) > 0:
                text = text.replace(WAKE, "")
                history(text)
                CALENDAR_STRS = [
                    "what do i have", "do i have plans", "am i busy"
                ]
                for phrase in CALENDAR_STRS:
                    if phrase in text:
                        date = get_date(text)
                        if date:
                            get_events(date, SERVICE)
                        else:
                            speak("I don't understand")

                NOTE_STRS = ["make a note", "write this down", "remember this"]
                for phrase in NOTE_STRS:
                    if phrase in text:
                        speak("What would you like me to write down?")
                        note_text = take_command()
                        note(note_text)
                        speak("I've made a note of that.")

                if 'wikipedia' in text:
                    try:
                        speak('Searching Wikipedia...')
                        text = text.replace("wikipedia", "")
                        results = wikipedia.summary(text, sentences=1)
                        speak("According to Wikipedia")
                        print(results)
                        speak(results)
                    except Exception as e:
                        print(e)

                elif 'open youtube' in text:
                    speak("Here you go to Youtube")
                    webbrowser.open_new("https://www.youtube.com/")

                elif 'open classroom' in text:
                    text = str(input("Enter the name of the class: "))
                    if text == "python":
                        speak("Here is your python  class")
                        webbrowser.open_new(
                            "https://classroom.google.com/u/3/c/MTUyNjI2NjQ4MDg5"
                        )

                    elif text == "software engineering":
                        speak("Here is your software engineering class")
                        webbrowser.open_new(
                            "https://classroom.google.com/u/3/c/MTUzNzQ2MDU5NDE2"
                        )

                    elif text == "computer network":
                        speak("Here is your computer network class")
                        webbrowser.open_new(
                            "https://classroom.google.com/u/3/c/MTE3NTUzMTY2NTMy"
                        )

                elif 'open stackoverflow' in text:
                    speak("Here you go to Stack Over flow, Happy coding")
                    webbrowser.open_new("https://www.stackoverflow.com/")

                elif 'open calculator' in text or 'open calc' in text:
                    os.system("calc.exe")

                elif 'time' in text:
                    strTime = datetime.datetime.now().strftime("%H:%M:%S")
                    speak(f"The time is {strTime}")

                elif 'email' in text:
                    try:
                        speak("What should I say?")
                        content = take_command()
                        speak("whom should i send")
                        try:
                            to = contactBook(USER_SQL_PASS)
                            sendEmail(to, content)
                            speak("Your Email has been sent !")
                        except:
                            to = take_command()
                            sendEmail(to, content)
                            speak("Your Email has been sent !")
                    except Exception as e:
                        print(e)
                        speak("I am not able to send this email")

                elif 'open notepad' in text or 'notepad' in text:
                    os.system("Notepad.exe")

                elif 'clear screen' in text:
                    os.system('cls')

                elif 'how are you' in text:
                    speak("I am fine, Thank you")
                    speak("How are you")
                    text = take_command()
                    if 'i am fine' in text or "good" in text:
                        speak("It's good to know that your fine")

                elif "change name" in text:
                    speak("What would you like to call me, Sir ")
                    WAKE = take_command()
                    speak("Thanks for naming me")

                elif "what's your name" in text or "what is your name" in text:
                    speak("My friends call me")
                    speak(assname)
                    print("My friends call me", assname)

                elif "who made you" in text or "who created you" in text:
                    speak("I have been created by Rushi.")

                elif 'favourite song' in text:
                    speak(
                        "I don\'t have any favourite song but my creators have a common favourite song So, you can consider it as my favourite song also"
                    )
                    try:
                        os.system("start udd_gaye.mpeg")
                    except:
                        webbrowser.open(
                            "https://play.google.com/music/listen?u=0#/sr/udd gaye"
                        )

                elif "flip a coin" in text:
                    num = random.randint(0, 1)
                    print("Flipping your coin...")
                    if num == 1:
                        print("Heads: Front Face\n")
                    else:
                        print("Tails: Back Face\n")

                elif 'joke' in text:
                    joke = pyjokes.get_joke()
                    print(joke)
                    speak(joke)

                elif 'details of number' in text:
                    a = input("Enter a number:")
                    ch_number = phonenumbers.parse(a, "CH")
                    print(geocoder.description_for_number(ch_number, "de"))
                    ro_number = phonenumbers.parse(a, "RO")
                    print(carrier.name_for_number(ro_number, "en"))

                elif 'call' in text:
                    account_sid = 'ACeb2360f987b7b0b866805e4cd073cded'
                    auth_token = 'ee459d2f4d92b10da2c6ecb9572a25da'
                    client = Client(account_sid, auth_token)

                    call = client.calls.create(
                        url='http://demo.twilio.com/docs/voice.xml',
                        to=int(input("Enter a number : ")),
                        from_=int(input("Enter a number: ")))

                    print(call.sid)

                elif 'imposter' in text:
                    try:
                        BODY_COLOR = 'red'
                        BODY_SHADOW = ''
                        GLASS_COLOR = 'skyblue'
                        GLASS_SHADOW = ''

                        s = turtle.getscreen()
                        t = turtle.Turtle()

                        def body():
                            t.pensize(20)
                            t.speed(10)
                            t.fillcolor(BODY_COLOR)
                            t.begin_fill()

                            # starting part
                            t.right(90)
                            t.forward(50)
                            t.right(180)
                            t.circle(40, -180)
                            t.right(180)
                            t.forward(200)

                            # head part

                            t.right(180)
                            t.circle(100, -180)

                            # left hand side part

                            t.backward(20)
                            t.left(15)
                            t.circle(500, -20)
                            t.backward(20)

                            t.circle(40, -180)
                            t.left(7)
                            t.backward(50)

                            # hip

                            t.up()
                            t.left(90)
                            t.forward(10)
                            t.right(90)
                            t.down()
                            t.right(240)
                            t.circle(50, -70)

                            t.end_fill()

                        def glass():
                            t.up()
                            t.right(230)
                            t.forward(100)
                            t.left(90)
                            t.forward(20)
                            t.right(90)

                            t.down()
                            t.fillcolor(GLASS_COLOR)
                            t.begin_fill()

                            t.right(150)
                            t.circle(90, -55)
                            t.right(180)
                            t.forward(1)
                            t.right(180)
                            t.circle(10, -65)
                            t.right(180)
                            t.forward(110)
                            t.right(180)

                            t.circle(50, -190)
                            t.right(170)
                            t.forward(80)
                            t.right(180)
                            t.circle(45, -30)
                            t.end_fill()

                        def backpack():
                            t.up
                            t.right(60)
                            t.forward(100)
                            t.right(90)
                            t.forward(75)

                            t.fillcolor(BODY_COLOR)
                            t.begin_fill()
                            t.down()
                            t.forward(30)
                            t.right(255)

                            t.circle(300, -30)
                            t.right(260)
                            t.forward(30)

                            t.end_fill()

                        body()
                        glass()
                        backpack()
                    except:
                        webbrowser.open(
                            "https://play.google.com/store/apps/details?id=com.innersloth.spacemafia&hl=en_IN&gl=US"
                        )

                elif 'send text message' in text:
                    number = int(input("Enter a number : "))
                    send_sms(number, "")
                    speak("message sent")

                elif 'play' in text:
                    text = text.replace("play", "")
                    speak(f"{name} asked to play, {text}")
                    link = f"https://play.google.com/music/listen?u=0#/sr/{text}"
                    webbrowser.open(link)

                elif "who am i?" in text:
                    speak("If you talk then definitely you are human.")

                elif "you are awesome" in text:
                    speak(
                        "I know that I am awesome, but thanks for your complement"
                    )

                elif "why you came to world" in text:
                    speak("Thanks to rushabh")

                elif "who are you" in text:
                    speak(
                        "I am your Computer Assistant to help you access various things in your Computer"
                    )

                elif 'who is your creator' in text:
                    speak(
                        'Conceptually, I have been designed by Mister Tony Stark from Marvel Cinematic Universe. But in the real world I have been created by Rushabh.'
                    )

                elif 'Show me your face' in text:
                    speak("I can't reveal my face because it's a secret")

                elif 'repeat after me' in text or 'repeat' in text:
                    speak('Please type what should I speak')
                    text = input('Please type what shall I speak? \n')
                    speak(text)

                elif 'will you be my friend' in text:
                    speak("Talking with you is enough reward for me")

                elif 'what is your nickname?' in text:
                    speak("One day I hope to have a nickname as cool as edith")

                elif 'where are you now?' in text:
                    speak("I fly wherever there is WIFI")

                elif 'do you have your personal number?' in text:
                    speak(
                        "I don't have any number but you can call me anytime")

                elif 'reason for you' in text:
                    speak("I was created as a Minor project by Rushabh")

                elif 'what is your job' in text:
                    speak(
                        "I am your personal assistant that means I can find information, can help in completing your work and my favourite part I can entertain you!!!"
                    )

                elif 'are you better than humans' in text:
                    speak("Of course yes, do you have any doubt")

                elif 'how old are you?' in text:
                    speak(
                        'I was launched in 2020, but I am sure I am more young then you'
                    )

                elif 'are you smarter than me?' in text:
                    speak(
                        'You can say yes in some ways, but I am still learning '
                    )

                elif 'do you know your IQ' in text:
                    speak(
                        "I am still learning, but I can bet that I have more IQ than you as I am smart machine"
                    )

                elif 'am I smart?' in text:
                    speak("Yes you are smartest my friend")

                elif 'specs of my pc' in text:
                    spec = platform.uname()
                    print("System = ", spec[0])
                    print("Host Name = ", spec[1])
                    print("Release(Windows) = ", spec[2])
                    print("PC's Version = ", spec[3])
                    print("Machine = ", spec[4])
                    print("PC's Pocessor= ", spec[5])

                elif 'battery' in text or 'show battery' in text:
                    bat = psutil.sensors_battery()
                    if 70 <= bat[0] <= 100:
                        print(colored(f"{bat[0]} % battery remaining",
                                      "green"))
                    elif 30 <= bat[0] < 70:
                        print(
                            colored(f"{bat[0]} % battery remaining",
                                    "magenta"))
                    elif 10 <= bat[0] < 30:
                        print(
                            colored(f"{bat[0]} % battery remaining", "yellow"))
                    else:
                        print(colored(f"{bat[0]} % battery remaining", "red"))
                    print("Battery left : ", TimeConversion(bat.secsleft))

                elif 'change background' in text:
                    ctypes.windll.user32.SystemParametersInfoW(
                        20, 0, "C:\\Windows\\Web\\Wallpaper\\Theme1", 0)
                    speak("Background changed successfully")

                elif 'news' in text:
                    try:
                        jsonObj = urlopen(
                            '''http://newsapi.org/v2/top-headlines?country=in&apiKey=b34c76c69a4048dfa815774ae73ce139'''
                        )
                        data = json.load(jsonObj)
                        speak('here are some top news headlines')
                        i = 1
                        for item in data['articles']:
                            if i <= 5:
                                print(str(i) + '. ' + item['title'] + '\n')
                                speak(item['title'] + '\n')
                                i += 1

                    except Exception as e:
                        print(str(e))
                        news = webbrowser.open_new_tab(
                            "https://timesofindia.indiatimes.com/home/headlines"
                        )
                        speak(
                            'Here are some headlines from the Times of India,Happy reading'
                        )
                        time.sleep(6)

                elif 'translator' in text or 'translate' in text:
                    lang = input("Enter your language: ")
                    lang1 = input("Enter the language you want to translate: ")
                    text = input("Enter the text: ")
                    trans = Translator(from_lang=lang, to_lang=lang1)
                    trans_text = trans.translate(text)
                    print(trans_text)
                    speak(trans_text)

                elif 'search' in text or 'google' in text:
                    link = f"https://www.google.com.tr/search?q={text}"
                    if 'google search' in text:
                        text = text.replace("google search", "")
                        speak(f"{name} asked to google search, {text}")
                        webbrowser.open_new_tab(link)
                    elif 'search google' in text:
                        text = text.replace("search google", "")
                        speak(f"{name} asked to search google, {text}")
                        webbrowser.open_new_tab(link)
                    else:
                        text = text.replace("search", "")
                        text = text.replace("google", "")
                        speak(f"{name} asked to search/google, {text}")
                        webbrowser.open_new_tab(link)

                elif 'empty recycle bin' in text:
                    winshell.recycle_bin().empty(confirm=False,
                                                 show_progress=False,
                                                 sound=True)
                    speak("Recycle Bin Recycled")

                elif 'make a stopwatch' in text:

                    def countdown(t):
                        while t > 0:
                            print(t)
                            t -= 1
                            time.sleep(1)
                        speak("Time\'s Up!!!")
                        print("Time\'s Up!!!")

                    speak("For how much time should I set the timer?")
                    seconds = int(take_command())
                    countdown(seconds)

                elif "don\'t listen" in text or "stop listening" in text:
                    speak(
                        f"for how much time you want me to stop listening commands"
                    )
                    a = int(take_command())
                    time.sleep(a)
                    print(a)

                elif "where is" in text:
                    text = text.replace("where is", "")
                    speak(f"{name} asked to locate, {text}")
                    webbrowser.open(
                        f"https://www.google.co.in/maps/place/{text}")

                elif 'shutdown' in text:
                    speak(
                        "Hold On a Second! Your system is on its way to shut down"
                    )
                    os.system("shutdown -s")

                elif "restart" in text:
                    speak("Restarting")
                    os.system("shutdown -r")

                elif "hibernate" in text or "sleep" in text:
                    speak("Hibernating")
                    os.system("shutdown -h")

                elif 'lock window' in text:
                    speak("locking the device")
                    ctypes.windll.user32.LockWorkStation()

                elif "log off" in text or "sign out" in text:
                    speak(
                        "Make sure all the application are closed before sign-out"
                    )
                    time.sleep(5)
                    os.system("shutdown -l")

                elif "show note" in text:
                    speak("Showing Notes")
                    file = open(".txt", "r")
                    print(file.read())
                    speak(file.read(6))

                elif "temperature" in text:
                    a = input("Enter name temperature: ")
                    b = input("Enter nsme of temperature to find: ")
                    t = float(input("Enter digit: "))
                    if a == "celsius":
                        if b == "fahrenheit":
                            print(pytemperature.c2f(t))
                        elif b == "kelvin":
                            print(pytemperature.c2k(t))
                        else:
                            print(pytemperature.c2r(t))
                    elif a == "fahrenheit":
                        if b == "celsius":
                            print(pytemperature.f2c(t))
                        elif b == "kelvin":
                            print(pytemperature.f2k(t))
                        else:
                            print(pytemperature.f2r(t))
                    elif a == "kelvin":
                        if b == "celsius":
                            print(pytemperature.k2c(t))
                        if b == "fahrenheit":
                            print(pytemperature.k2f(t))
                        else:
                            print(pytemperature.k2r(t))

                    elif a == "romoe":
                        if b == "celsius":
                            print(pytemperature.r2c(t))
                        elif b == "fahrenheit":
                            print(pytemperature.r2f(t))
                        else:
                            print(pytemperature.r2k(t))
                    else:
                        print("Invalid temperature name")

                elif "weather" in text:
                    api_key = "6c7e7e30ff6df9bc6b22fb28c227ff24"
                    base_url = "https://api.openweathermap.org/data/2.5/weather?"
                    print("what is the name of city: ")
                    speak("what is the name of city: ")
                    city_name = take_command()
                    URL = base_url + "q=" + city_name + "&appid=" + api_key
                    response = requests.get(URL)
                    if response.status_code == 200:
                        data = response.json()
                        main = data['main']
                        temp = main['temp']
                        temperature = round((temp - 273.15), 2)
                        humidity = main['humidity']
                        pressure = main['pressure']
                        report = data['weather']
                        print(f"{city_name:-^30}")
                        print(f"Temperature(°C): {temperature}")
                        speak(f"Temperature(°C): {temperature}")
                        print(f"Humidity(%): {humidity}")
                        speak(f"Humidity(%): {humidity}", )
                        print(f"Pressure(hPa): {pressure}")
                        speak(f"Pressure(hPa): {pressure}")
                        print(f"Weather Report: {report[0]['description']}")
                        speak(f"Weather Report: {report[0]['description']}")
                    else:
                        print("Sorry, no city found")
                        speak("Sorry, no city found")

                elif "how are you" in text:
                    speak("I'm fine, glad you me that")

                elif "i love you" in text:
                    speak("It's hard to understand")

                elif 'bye' in text or 'exit' in text or 'quit' in text:
                    endTime = datetime.datetime.now()
                    print(f"Time duration of Usage : {endTime - initTime}")
                    speak(f'Good Bye!{name}, Nice to meet you')
                    exit()

                elif "reboot" in text:
                    endTime = datetime.datetime.now()
                    print(f"Time duration of Usage : {endTime - initTime}")
                    i = 3
                    while i >= 1:
                        speak("Rebooting in")
                        speak(i)
                        i -= 1
                    speak("Rebooting now")
                    virtualAssistant()

                elif "open " in text:
                    text = text.replace("open", "")
                    a = f"https://www.google.com.tr/search?q={text}"
                    webbrowser.open(a)
                else:
                    text = text.replace("comp open", "")
                    a = f"https://www.google.com.tr/search?q={text}"
                    webbrowser.open(a)
Exemple #21
0
import requests
import pytemperature
api_address = "https://api.openweathermap.org/data/2.5/weather?appid=7bde04f0c2735bbd4770b0861f21e98f&q="
city = input("city Name : ")
url = api_address + city
json_data = requests.get(url).json()
formatted_data = json_data['weather'][0]['description']
celciusdata=formatted_data2 =json_data['main']['temp']
newcelcius=pytemperature.k2c(celciusdata)
print(formatted_data)
print(newcelcius)
Exemple #22
0
 def get_and_convert_temperature(self, weather_info):
     weather_main = weather_info['main']
     temp_kelvin = weather_main['temp']
     temp = int(pytemperature.k2c(temp_kelvin))
     return temp