KAPtechies commited on
Commit
5af3eab
Β·
verified Β·
1 Parent(s): 4a8c538

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -26
app.py CHANGED
@@ -1,55 +1,62 @@
1
  import requests
2
  import gradio as gr
3
- from datetime import datetime
4
 
5
  # OpenWeather API details
6
  BASE_URL = "http://api.openweathermap.org/data/2.5/forecast?"
7
  API_KEY = "2682f6801720ebeb43c93ad55c826c5c"
8
- DAYS = 5 # Free API allows only 5 days
9
 
10
  def get_weather(city):
11
  url = f"{BASE_URL}q={city}&appid={API_KEY}&units=metric"
12
  response = requests.get(url).json()
13
 
14
- # Error handling
15
  if response.get("cod") != "200":
16
  return "❌ **Invalid city name! Please enter a correct city.**"
17
 
18
  weather_info = {}
19
 
20
- # Extracting one data point per day
21
  for entry in response["list"]:
22
- date = entry["dt_txt"].split(" ")[0] # Extract only the date part
23
- if date not in weather_info: # Store only one entry per day
24
- weather_info[date] = {
25
- "Temperature": f"{entry['main']['temp']}Β°C",
26
- "Humidity": f"{entry['main']['humidity']}%",
27
- "Pressure": f"{entry['main']['pressure']} hPa",
28
- "Wind Speed": f"{entry['wind']['speed']} m/s",
29
- "Rain": f"{entry.get('rain', {}).get('3h', 0)} mm",
30
- "Cloud Cover": f"{entry['clouds']['all']}%" # Extracting cloud data
31
- }
 
 
 
 
32
 
33
- # Format output as a Markdown table with bold values
34
- markdown_output = "**πŸ“… 5-Day Weather Forecast**\n\n"
35
- markdown_output += "<style>table { width: 100%; white-space: nowrap; }</style>\n" # Prevent word wrap
36
- markdown_output += "| **Date** | **Temperature** | **Humidity** | **Pressure** | **Wind Speed** | **Rain** | **Cloud Cover** |\n"
37
- markdown_output += "|------------|------------|----------|----------|------------|------|-------------|\n"
38
 
39
  for date, details in weather_info.items():
40
- markdown_output += f"| **{date}** | **{details['Temperature']}** | **{details['Humidity']}** | **{details['Pressure']}** | **{details['Wind Speed']}** | **{details['Rain']}** | **{details['Cloud Cover']}** |\n"
 
 
 
 
 
 
 
 
41
 
42
  return markdown_output
43
 
44
- # **Adding Background Image**
45
  custom_css = """
46
  body {
47
  background: url('https://images.unsplash.com/photo-1548337138-e87d889cc369?q=80&w=1796&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D.jpg') no-repeat center center fixed;
48
  background-size: cover;
49
- color: black; /* Set text to black */
50
  }
51
  .gradio-container {
52
- background: rgba(255, 255, 255, 0.6); /* Light overlay for readability */
53
  padding: 20px;
54
  border-radius: 10px;
55
  }
@@ -57,15 +64,36 @@ h1 {
57
  color: black;
58
  text-align: center;
59
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  """
61
 
62
  # Gradio Interface
63
  iface = gr.Interface(
64
  fn=get_weather,
65
  inputs=gr.Textbox(label="🌍 Enter City Name"),
66
- outputs=gr.Markdown(),
67
- title="🌀️Climate change model to forecast future weather patterns",
68
- description="Enter a city name to get temperature, humidity, pressure, wind speed, rain, and cloud cover for the next **5 days**.",
69
  theme="default",
70
  css=custom_css
71
  )
 
1
  import requests
2
  import gradio as gr
3
+ import pandas as pd
4
 
5
  # OpenWeather API details
6
  BASE_URL = "http://api.openweathermap.org/data/2.5/forecast?"
7
  API_KEY = "2682f6801720ebeb43c93ad55c826c5c"
 
8
 
9
  def get_weather(city):
10
  url = f"{BASE_URL}q={city}&appid={API_KEY}&units=metric"
11
  response = requests.get(url).json()
12
 
 
13
  if response.get("cod") != "200":
14
  return "❌ **Invalid city name! Please enter a correct city.**"
15
 
16
  weather_info = {}
17
 
18
+ # Organizing data by date
19
  for entry in response["list"]:
20
+ date = entry["dt_txt"].split(" ")[0] # Extract only the date
21
+ time = entry["dt_txt"].split(" ")[1] # Extract only the time
22
+ if date not in weather_info:
23
+ weather_info[date] = []
24
+
25
+ weather_info[date].append([
26
+ time,
27
+ f"{entry['main']['temp']}Β°C",
28
+ f"{entry['main']['humidity']}%",
29
+ f"{entry['main']['pressure']} hPa",
30
+ f"{entry['wind']['speed']} m/s",
31
+ f"{entry['rain']['3h']} mm" if "rain" in entry and "3h" in entry["rain"] else "0 mm",
32
+ f"{entry['clouds']['all']}%"
33
+ ])
34
 
35
+ # Formatting output as tables inside boxes
36
+ markdown_output = "<h2>πŸ“… 5-Day Weather Forecast</h2>"
 
 
 
37
 
38
  for date, details in weather_info.items():
39
+ df = pd.DataFrame(details, columns=["Time", "Temperature", "Humidity", "Pressure", "Wind Speed", "Rain", "Cloud Cover"])
40
+ table_html = df.to_html(index=False)
41
+
42
+ markdown_output += f"""
43
+ <div class='weather-box'>
44
+ <h3>πŸ“† {date}</h3>
45
+ {table_html}
46
+ </div>
47
+ """
48
 
49
  return markdown_output
50
 
51
+ # **Adding Background Image and Box Styling**
52
  custom_css = """
53
  body {
54
  background: url('https://images.unsplash.com/photo-1548337138-e87d889cc369?q=80&w=1796&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D.jpg') no-repeat center center fixed;
55
  background-size: cover;
56
+ color: black;
57
  }
58
  .gradio-container {
59
+ background: rgba(255, 255, 255, 0.6);
60
  padding: 20px;
61
  border-radius: 10px;
62
  }
 
64
  color: black;
65
  text-align: center;
66
  }
67
+ .weather-box {
68
+ background: rgba(255, 255, 255, 0.9);
69
+ border-radius: 10px;
70
+ padding: 15px;
71
+ margin-bottom: 10px;
72
+ box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.2);
73
+ }
74
+ table {
75
+ width: 100%;
76
+ border-collapse: collapse;
77
+ background: white;
78
+ }
79
+ th, td {
80
+ border: 1px solid black;
81
+ padding: 8px;
82
+ text-align: center;
83
+ }
84
+ th {
85
+ background: #4CAF50;
86
+ color: white;
87
+ }
88
  """
89
 
90
  # Gradio Interface
91
  iface = gr.Interface(
92
  fn=get_weather,
93
  inputs=gr.Textbox(label="🌍 Enter City Name"),
94
+ outputs=gr.HTML(),
95
+ title="🌀️ Weather Forecast",
96
+ description="Enter a city name to get **temperature, humidity, wind speed, and cloud cover** for the next **5 days** (grouped by date).",
97
  theme="default",
98
  css=custom_css
99
  )