File size: 3,426 Bytes
5273d83
 
 
 
bf2caaf
 
 
 
 
 
 
 
 
5273d83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77a878e
 
 
 
 
 
 
 
 
5273d83
bf2caaf
 
 
 
 
 
 
2b3239a
bf2caaf
 
 
 
5273d83
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import requests
from bs4 import BeautifulSoup as bs
import src.constants as constants_utils

import logging
logging.basicConfig(
    format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
    level=logging.INFO,
    datefmt="%Y-%m-%d %H:%M:%S"
)
logger = logging.getLogger(__name__)



class WEATHER:
    def __init__(self):
        self.base_url = 'https://nwp.imd.gov.in/blf/blf_temp'
        self.headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        }

        self.state_names_codes = {}
        self.districts = []


    def get_state_names_codes(
        self
    ):
        response = requests.get(
            self.base_url,
            headers=self.headers,
        )

        soup = bs(response.text, 'html.parser')
        for option in soup.find_all('option'):
            if option.text.strip() == 'Select':
                continue
            self.state_names_codes[option.text.strip()] = str(option['value'].split('=')[-1][:2])
        
        return self.state_names_codes


    def get_district_names(
        self,
        state_name
    ):
        url = f"{self.base_url}/dis.php?value={constants_utils.WEATHER_FORECAST_STATE_CODES.get(state_name, '') + state_name}"
        response = requests.get(
            url,
            headers=self.headers,
        )

        soup = bs(response.text, 'html.parser')
        self.districts = soup.findAll('select', {'name': 'dis'}, limit=None)
        self.districts = [district.strip() for district in self.districts[0].text.split('\n') if district and district != 'Select']
        return self.districts


    # Weather forecast from Govt. website
    def get_weather_forecast(
        self,
        state,
        district,
        is_block_level=False
    ):
        self.district_url = f"{self.base_url}/block.php?dis={constants_utils.WEATHER_FORECAST_STATE_CODES.get(state, '') + district}"
        self.block_url = f'{self.base_url}/table2.php'

        response = requests.get(self.district_url if not is_block_level else self.block_url)
        soup = bs(response.text, 'html.parser')
        scripts = soup.findAll('font')[0]
        return scripts.text


    # Weather using Google weather API
    def get_weather(
        self,
        city
    ):
        city = city + " weather"
        city = city.replace(" ", "+")
        
        soup = bs(
            requests.get(f"https://www.google.com/search?q=weather+{city}").content,
            'html.parser'
        )
        temperature = soup.find('div', attrs={'class': 'BNeawe iBp4i AP7Wnd'}).text.strip()
        time = soup.find('div', attrs={'class': 'BNeawe tAd8D AP7Wnd'}).text.split('\n')[0].strip()
        time = ' '.join(time.split())
        info = soup.find('div', attrs={'class': 'BNeawe tAd8D AP7Wnd'}).text.split('\n')[1].strip()

        # Convert temperature from Ferenheit to Celcius
        if '°F' in temperature:
            temp = temperature.split('°')[0]
            if temp:
                try:
                    temp = int(temp)
                    celcius = int((temp - 32) * (5/9))
                    temperature = str(celcius) + '°C'
                except Exception as e:
                    logger.error(f'Cannot convert temperature from Ferenheit to Celcius!')
                    pass

        return time, info, temperature