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()