File size: 5,138 Bytes
4bce1ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed44daf
4bce1ba
 
 
 
 
 
 
 
 
 
 
ed44daf
4bce1ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed44daf
4bce1ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed44daf
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# general
import public_ip as ip
import requests
from datetime import datetime

# for setting env
import os
from dotenv import load_dotenv

load_dotenv()

# for gemini
from google import genai
from google.genai import types

# for ui
import gradio as gr


def get_ip_address() -> str:
    """Find public IP address of user

    Args:
      No arguments

    Returns:
      A string contains public IP address of user
    """
    return ip.get()


def get_current_location() -> dict:
    """Find user current location as from public IP address

    Args:
      No arguments

    Returns:
      A dictionary contains users country,city,longitude,latitude
    """
    ip_address = get_ip_address()
    response = requests.get("http://ip-api.com/json/" + ip_address).json()
    return {
        "country": response.get("country"),
        "city": response.get("city"),
        "zip": response.get("zip"),
        "lat": response.get("lat"),
        "lon": response.get("lon"),
    }


def get_current_weather(location: str = get_current_location().get("city")) -> dict:
    """Find current weather status from given location,
        If no location given: find the currunt location from IP and give weather.

    Args:
      location: If location is avaliable, else it find from IP

    Returns:
      A dictionary contains current weather condeiton

    """
    response = requests.get(
        f"https://api.openweathermap.org/data/2.5/weather?q={location}&appid={os.getenv('WEATHER_API')}"
    ).json()

    return {
        "weather": response.get("weather"),
        "main": response.get("main"),
        "wind": response.get("wind"),
        "location": response.get("name"),
        "sunrise": response.get("sys").get("sunrise"),
        "sunset": response.get("sys").get("sunset"),
    }

    # return response


def get_time_and_date() -> datetime:
    """Find current date and time
    Args:
      No arguments

    Returns:
      Current date and time in datetime.datetime format

    """
    return datetime.now()


def get_sunrise_sunset(location: str = get_current_location().get("city")) -> dict:
    """Find  sunrise and sunset timings

    Args:
     location: location name in string format, if not given by default find current location of user

    Returns:
      sunrise and sunset  timeings in datetime format as dictionary

    """
    weather = get_current_weather(location)

    return {
        "sunrise": datetime.fromtimestamp(weather.get("sunrise")),
        "sunset": datetime.fromtimestamp(weather.get("sunset")),
    }


def get_news_headlines(topic: str = "google") -> dict:
    """Find news article, if topic provided find related news

    Args:
      topic: A string contains topic to get related news, default set to empty

    Returns:
      a dictionary of news titles and discription

    """

    response = requests.get(
        f"https://gnews.io/api/v4/search?q={topic}&lang=en&max=5&apikey={os.getenv('GNEWS_API')}"
    ).json()

    # taking only news title and description, adding to new dict
    news_articles = {}
    index = 1
    for news in response.get("articles"):
        news_articles[index] = {
            "title": news.get("title"),
            "description": news.get("description"),
        }
        index += 1

    return news_articles


def get_coordinates(location: str) -> dict:

    response = requests.get(
        f"http://api.openweathermap.org/geo/1.0/direct?q={location}&limit={1}&appid={os.getenv('WEATHER_API')}"
    ).json()

    return {"latitude": response[0].get("lat"), "longitude": response[0].get("lon")}

    # return response


def get_air_quality(latitude: float, longitude: float) -> dict:
    """Find air quality in a location from coordinates

    Args:
      latitude: lattitude value of loaction
      longitude: longitude valur of location

    Returns:
      A dictionary contains air quality details

    """

    response = requests.get(
        f"http://api.openweathermap.org/data/2.5/air_pollution?lat={latitude}&lon={longitude}&appid={os.getenv('WEATHER_API')}"
    ).json()

    return response


client = genai.Client(api_key=os.getenv("GEMINI_API"))
config = types.GenerateContentConfig(
    tools=[
        get_current_location,
        get_current_weather,
        get_time_and_date,
        get_sunrise_sunset,
        get_news_headlines,
        get_coordinates,
        get_air_quality,
    ]
)

chat = client.chats.create(model="gemini-2.5-flash", config=config)


def chat_bot(text):
    response = chat.send_message(text)

    return response.text


# import time

with gr.Blocks() as demo:
    chatbot = gr.Chatbot()
    msg = gr.Textbox()
    clear = gr.Button("Clear")

    def user(user_message, history):
        return "", [[user_message, None]]

    def bot(history):
        user_message = history[0][0]
        # print(history)
        bot_message = chat_bot(user_message)
        history[-1][1] = bot_message
        return history

    msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
        bot, chatbot, chatbot
    )
    clear.click(lambda: None, None, chatbot, queue=False)

demo.launch(share=True)