Spaces:
Sleeping
Sleeping
File size: 5,347 Bytes
d4ef7e3 8540d02 d4ef7e3 8540d02 d4ef7e3 8a645dd d4ef7e3 8a645dd d4ef7e3 8a645dd d4ef7e3 8540d02 d4ef7e3 |
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 |
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() |