Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
+
from bs4 import BeautifulSoup
|
| 4 |
+
|
| 5 |
+
# Function to fetch and scrape weather data from a public website
|
| 6 |
+
def get_weather_from_web(query):
|
| 7 |
+
try:
|
| 8 |
+
# Use the query to construct the search URL, e.g., search weather in Lahore
|
| 9 |
+
search_url = f"https://www.google.com/search?q=weather+in+{query}"
|
| 10 |
+
|
| 11 |
+
# Send a GET request to fetch the web page
|
| 12 |
+
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"}
|
| 13 |
+
response = requests.get(search_url, headers=headers)
|
| 14 |
+
|
| 15 |
+
# If the request was successful, parse the HTML content
|
| 16 |
+
if response.status_code == 200:
|
| 17 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 18 |
+
|
| 19 |
+
# Find the weather information in the page content
|
| 20 |
+
weather_info = soup.find("div", {"class": "BNeawe iBp4i AP7Wnd"})
|
| 21 |
+
temperature = weather_info.text if weather_info else "Weather data not found."
|
| 22 |
+
|
| 23 |
+
# Extract the condition of the weather
|
| 24 |
+
condition_info = soup.find("div", {"class": "BNeawe tAd8D AP7Wnd"})
|
| 25 |
+
condition = condition_info.text if condition_info else "Condition data not found."
|
| 26 |
+
|
| 27 |
+
# Return the formatted weather information
|
| 28 |
+
weather_report = f"Temperature: {temperature}\nCondition: {condition}"
|
| 29 |
+
return weather_report
|
| 30 |
+
else:
|
| 31 |
+
return "Error: Unable to fetch data."
|
| 32 |
+
|
| 33 |
+
except Exception as e:
|
| 34 |
+
return f"Error: {str(e)}"
|
| 35 |
+
|
| 36 |
+
# Create a Gradio interface
|
| 37 |
+
def main():
|
| 38 |
+
with gr.Blocks() as demo:
|
| 39 |
+
gr.Markdown("# Weather Search App")
|
| 40 |
+
gr.Markdown("### Enter a city to get the current weather (without API key).")
|
| 41 |
+
|
| 42 |
+
# Textbox for user input
|
| 43 |
+
query_input = gr.Textbox(label="Search City (e.g., Lahore)", value="Lahore", interactive=True)
|
| 44 |
+
|
| 45 |
+
# Textbox to display the result
|
| 46 |
+
result_output = gr.Textbox(label="Weather Info", interactive=False)
|
| 47 |
+
|
| 48 |
+
# Trigger the search on submit
|
| 49 |
+
query_input.submit(get_weather_from_web, inputs=query_input, outputs=result_output)
|
| 50 |
+
|
| 51 |
+
demo.launch()
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
main()
|