Spaces:
Sleeping
Sleeping
| 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?'"]}) | |
| # Create a more comprehensive interface | |
| with gr.Blocks(title="Pakistan Time Bot", theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# 🇵🇰 Pakistan Time Bot") | |
| gr.Markdown("This bot tells you the current time in Pakistan. It's designed to work with both direct queries and ESP8266 devices.") | |
| with gr.Tab("Chat Interface"): | |
| gr.Markdown("### Talk to the Time Bot") | |
| with gr.Row(): | |
| with gr.Column(): | |
| input_text = gr.Textbox(label="Your Message", placeholder="Ask me about the time in Pakistan...") | |
| text_button = gr.Button("Get Time") | |
| with gr.Column(): | |
| output_text = gr.Textbox(label="Bot Response", interactive=False) | |
| examples = gr.Examples( | |
| examples=["What's the time?", "Time please", "Current time in Pakistan"], | |
| inputs=input_text | |
| ) | |
| with gr.Tab("ESP8266 Integration"): | |
| gr.Markdown("### ESP8266 Integration") | |
| gr.Markdown(""" | |
| This bot is designed to work with ESP8266 microcontrollers. Here's how to set it up: | |
| 1. Use the code below in your Arduino IDE | |
| 2. Replace `YOUR_WIFI_SSID` and `YOUR_WIFI_PASSWORD` with your WiFi credentials | |
| 3. Update the `serverName` to point to your deployed Hugging Face Space | |
| 4. Upload the code to your ESP8266 | |
| """) | |
| esp_code = """ | |
| #include <ESP8266WiFi.h> | |
| #include <ESP8266HTTPClient.h> | |
| const char* ssid = "YOUR_WIFI_SSID"; | |
| const char* password = "YOUR_WIFI_PASSWORD"; | |
| // Hugging Face Space API endpoint | |
| String serverName = "https://your-username-time-bot.hf.space/run/predict"; | |
| WiFiClientSecure client; // use WiFiClientSecure for HTTPS | |
| void setup() { | |
| Serial.begin(115200); | |
| WiFi.begin(ssid, password); | |
| Serial.print("Connecting to WiFi..."); | |
| while (WiFi.status() != WL_CONNECTED) { | |
| delay(500); | |
| Serial.print("."); | |
| } | |
| Serial.println(" Connected!"); | |
| // For HTTPS: skip certificate verification | |
| client.setInsecure(); | |
| } | |
| void loop() { | |
| if (WiFi.status() == WL_CONNECTED) { | |
| HTTPClient http; | |
| http.begin(client, serverName); | |
| http.addHeader("Content-Type", "application/json"); | |
| // Sending request | |
| String jsonData = "{\\"data\\":[\\"time\\"]}"; | |
| int httpResponseCode = http.POST(jsonData); | |
| if (httpResponseCode > 0) { | |
| String response = http.getString(); | |
| Serial.println("Response:"); | |
| Serial.println(response); | |
| } else { | |
| Serial.print("Error code: "); | |
| Serial.println(httpResponseCode); | |
| } | |
| http.end(); | |
| } else { | |
| Serial.println("WiFi Disconnected"); | |
| } | |
| delay(10000); // request every 10 seconds | |
| } | |
| """ | |
| gr.Code(value=esp_code, language="cpp", label="ESP8266 Code") | |
| gr.Markdown("### Test ESP8266 Request") | |
| gr.Markdown("Click the button below to simulate the JSON request that an ESP8266 would send:") | |
| test_button = gr.Button("Test ESP8266 Request") | |
| test_output = gr.Textbox(label="JSON Response", interactive=False) | |
| with gr.Tab("API Info"): | |
| gr.Markdown("### API Information") | |
| gr.Markdown(""" | |
| The bot accepts two types of requests: | |
| 1. **Direct text input**: Simply send a text message containing the word "time" | |
| 2. **JSON API** (for ESP8266): Send a JSON object in the format `{"data": ["time"]}` | |
| The response will always be a JSON object with the format: | |
| ```json | |
| {"data": ["08:45 PM"]} | |
| ``` | |
| """) | |
| gr.Markdown("### Direct API Testing") | |
| with gr.Row(): | |
| api_input = gr.Textbox(value='{"data": ["time"]}', label="JSON Input") | |
| api_button = gr.Button("Send API Request") | |
| api_output = gr.Textbox(label="API Response") | |
| # Set up event handlers | |
| text_button.click(chatbot, inputs=input_text, outputs=output_text) | |
| input_text.submit(chatbot, inputs=input_text, outputs=output_text) | |
| test_button.click(chatbot, inputs=gr.Textbox(value='{"data": ["time"]}'), outputs=test_output) | |
| api_button.click(chatbot, inputs=api_input, outputs=api_output) | |
| if __name__ == "__main__": | |
| demo.launch() |