File size: 1,492 Bytes
8540d02
 
 
6e6b438
8540d02
 
 
 
 
6e6b438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8540d02
6e6b438
 
 
8540d02
6e6b438
8540d02
 
 
 
 
 
6e6b438
8540d02
 
 
6e6b438
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
import gradio as gr
from datetime import datetime
import pytz
import json

# Pakistan timezone
pakistan_tz = pytz.timezone("Asia/Karachi")

def chatbot(message):
    # Handle JSON input from ESP8266
    try:
        # Parse the JSON input
        data = json.loads(message)
        
        # Extract the actual message from the "data" array
        if "data" in data and isinstance(data["data"], list) and len(data["data"]) > 0:
            user_message = data["data"][0].lower()
        else:
            return json.dumps({"data": ["I can only tell you the current time in Pakistan. Try asking: 'What is the time?'"]})
    except:
        # If it's not JSON, treat it as a regular string (for direct Gradio interface testing)
        user_message = message.lower()
    
    # Process the message
    if "time" in user_message:
        now_pk = datetime.now(pakistan_tz)
        time_str = f"{now_pk.strftime('%I:%M %p')}"
        # Return in the expected JSON format
        return json.dumps({"data": [time_str]})
    else:
        return json.dumps({"data": ["I can only tell you the current time in Pakistan. Try asking: 'What is the time?'"]})

iface = gr.Interface(
    fn=chatbot,
    inputs=gr.Textbox(lines=2, placeholder="Ask me the time in Pakistan..."),
    outputs="text",
    title="Pakistan Time Bot",
    description="A simple bot that tells you the current time in Pakistan. It accepts JSON input for ESP8266 compatibility."
)

if __name__ == "__main__":
    iface.launch()