Skip to content

Commit

Permalink
Hello admin , i added here my Location and weather ditection file., w…
Browse files Browse the repository at this point in the history
…e can detect or access loction by voice command
  • Loading branch information
Nayan2003 committed Nov 7, 2024
1 parent 7420854 commit 2809fb8
Show file tree
Hide file tree
Showing 3 changed files with 189 additions and 0 deletions.
18 changes: 18 additions & 0 deletions location_and_weather_detection/Local_ip.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# ipadd.py
import socket

def get_local_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(0)
try:
# Connect to an external server (doesn't actually connect)
s.connect(('10.254.254.254', 1))
local_ip = s.getsockname()[0]
except:
local_ip = '127.0.0.1' # Default to localhost if no network
finally:
s.close()
return local_ip

# You can print the local IP for debugging
print("Local IP Address:", get_local_ip())
46 changes: 46 additions & 0 deletions location_and_weather_detection/location.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import requests
from Local_ip import get_local_ip # Import your function to get the local IP

def get_public_ip():
"""Fetch your public IP address using ipify"""
try:
response = requests.get('https://api.ipify.org')
return response.text # Return the public IP address
except requests.exceptions.RequestException as e:
return f"Error: {str(e)}"

def get_location_from_ip(ip_address):
"""Fetch location data using ipinfo.io API"""
url = f'https://ipinfo.io/{ip_address}/json'

try:
# Send GET request to ipinfo.io API
response = requests.get(url)
data = response.json()

# Check if the response is successful
if response.status_code == 200:
location_info = {
"IP": ip_address,
"City": data.get("city"),
"Region": data.get("region"),
"Country": data.get("country"),
"Org":data.get("org"),
"Location (Latitude, Longitude)": data.get("loc"),
"Postal Code": data.get("postal"),
"Timezone": data.get("timezone")
}
return location_info
else:
return f"Error: Unable to fetch location data. API returned status code {response.status_code}"

except requests.exceptions.RequestException as e:
return f"Error: {str(e)}"

# Fetch the public IP address
public_ip = get_public_ip()

# Use the public IP to fetch location data
location = get_location_from_ip(public_ip)
print("Public IP:", public_ip)
print("Location Info:", location)
125 changes: 125 additions & 0 deletions location_and_weather_detection/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import speech_recognition as sr
import pyttsx3
import requests

# Function to get public IP address using ipify
def get_public_ip():
try:
response = requests.get('https://api.ipify.org')
return response.text # Return the public IP address
except requests.exceptions.RequestException as e:
return f"Error: {str(e)}"

# Function to fetch location details from ipinfo.io
def get_location_from_ip(ip_address):
url = f'https://ipinfo.io/{ip_address}/json'

try:
response = requests.get(url)
data = response.json()

# Check if the response is successful
if response.status_code == 200:
location_info = {
"IP": ip_address,
"City": data.get("city"),
"Region": data.get("region"),
"Country": data.get("country"),
"Location (Latitude, Longitude)": data.get("loc"),
"Postal Code": data.get("postal"),
"Timezone": data.get("timezone")
}
return location_info
else:
return f"Error: Unable to fetch location data. API returned status code {response.status_code}"

except requests.exceptions.RequestException as e:
return f"Error: {str(e)}"

# Function to get weather information using wttr.in
def get_weather(city_name):
url = f"http://wttr.in/{city_name}?format=%C+%t+%w" # Fetch weather in a simple format
try:
response = requests.get(url)
return response.text.strip() # Return the weather information as text
except requests.exceptions.RequestException as e:
return f"Error: {str(e)}"

# Function to speak the assistant's response
def speak(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()

# Function to listen for a voice command
def listen_for_command():
recognizer = sr.Recognizer()
mic = sr.Microphone()

# Listen for command
with mic as source:
print("Listening for your command...")
recognizer.adjust_for_ambient_noise(source) # Adjust for background noise
audio = recognizer.listen(source)

try:
command = recognizer.recognize_google(audio).lower() # Convert speech to text
print("You said:", command)
return command
except sr.UnknownValueError:
speak("Sorry, I didn't understand that.")
return None
except sr.RequestError:
speak("Sorry, there was an error with the speech service.")
return None

# Main function to run the assistant
def run_assistant():
speak("How can I assist you today?")
while True:
command = listen_for_command()

if command:
if "location" in command or "where am i" in command or "my ip" in command:
speak("Fetching your location automatically...")
public_ip = get_public_ip()
location = get_location_from_ip(public_ip)

if isinstance(location, dict):
location_info = f"Your IP is {location['IP']}. You are in {location['City']}, {location['Region']}, {location['Country']}. Your coordinates are {location['Location (Latitude, Longitude)']}. The postal code is {location['Postal Code']}."
print(location_info)
speak(location_info)

else:
speak(location) # Speak the error message if any

elif "weather" in command or "climate" in command:
speak("Fetching your weather automatically...")
public_ip = get_public_ip()
location = get_location_from_ip(public_ip)

if isinstance(location, dict):
city_name = location["City"]
if city_name:
weather = get_weather(city_name)

if weather:
weather_info = f"The current weather in {city_name} is {weather}."
print(weather_info)
speak(weather_info)

else:
speak("Sorry, I couldn't fetch the weather details.")
else:
speak("Sorry, I couldn't detect your city automatically for the weather.")


elif "exit" in command or "stop" in command or "bye" in command:
speak("Goodbye!")
break
else:
speak("Sorry, I can only tell you your location or weather. Please ask me about that or say 'exit' to quit.")

# Run the assistant
if __name__ == "__main__":
run_assistant()

0 comments on commit 2809fb8

Please sign in to comment.