File size: 1,488 Bytes
e32f334
d5aa5dc
 
e32f334
8fe992b
d5aa5dc
9b5b26a
18c495a
e32f334
 
 
 
18c495a
d5aa5dc
e32f334
 
d5aa5dc
 
 
 
 
e32f334
 
 
 
 
 
 
 
18c495a
e32f334
 
 
 
d5aa5dc
e32f334
 
d5aa5dc
e32f334
18c495a
e32f334
 
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
import datetime
import pytz
import re
import gradio as gr

def get_time(timezone_str: str) -> str:
    try:
        tz = pytz.timezone(timezone_str)
    except pytz.UnknownTimeZoneError:
        return f"Sorry, '{timezone_str}' is not a recognized timezone."
    now = datetime.datetime.now(tz)
    return now.strftime("%Y-%m-%d %H:%M:%S")

def agent_response(user_input: str) -> str:
    # Updated regex to capture timezone after 'time' and 'in'
    match = re.search(r"time\s+(?:is\s+it\s+)?in\s+([\w/_]+)", user_input, re.IGNORECASE)
    if match:
        timezone_str = match.group(1)
        time_str = get_time(timezone_str)
        return f"The current time in {timezone_str} is {time_str}"
    else:
        return ("Sorry, I can only answer questions about time in a specific timezone, "
                "e.g. 'What time is it in America/New_York?'")

def main():
    with gr.Blocks() as demo:
        gr.Markdown("## Ask me about the current time in a timezone!")
        chatbot = gr.Chatbot()
        txt = gr.Textbox(placeholder="Enter your question here...")

        def respond(user_message, chat_history):
            response = agent_response(user_message)
            chat_history = chat_history + [(user_message, response)]
            return chat_history, ""

        txt.submit(respond, inputs=[txt, chatbot], outputs=[chatbot, txt])
        txt.submit(lambda: "", None, txt)  # Clear input box after submit

    demo.launch()

if __name__ == "__main__":
    main()