Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,34 +1,153 @@
|
|
| 1 |
-
|
| 2 |
-
from pydantic import BaseModel
|
| 3 |
from datetime import datetime
|
| 4 |
import pytz
|
|
|
|
| 5 |
|
| 6 |
# Pakistan timezone
|
| 7 |
pakistan_tz = pytz.timezone("Asia/Karachi")
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
return {"message": "🇵🇰 Pakistan Time Bot API is running!"}
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
# Validate and extract message
|
| 23 |
-
if request.data and isinstance(request.data, list):
|
| 24 |
-
user_message = request.data[0].lower()
|
| 25 |
-
else:
|
| 26 |
-
return {"data": ["Invalid input. Use: {\"data\": [\"time\"]}"]}
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
|
|
|
| 2 |
from datetime import datetime
|
| 3 |
import pytz
|
| 4 |
+
import json
|
| 5 |
|
| 6 |
# Pakistan timezone
|
| 7 |
pakistan_tz = pytz.timezone("Asia/Karachi")
|
| 8 |
|
| 9 |
+
def chatbot(message):
|
| 10 |
+
# Handle JSON input from ESP8266
|
| 11 |
+
try:
|
| 12 |
+
# Parse the JSON input
|
| 13 |
+
data = json.loads(message)
|
| 14 |
+
|
| 15 |
+
# Extract the actual message from the "data" array
|
| 16 |
+
if "data" in data and isinstance(data["data"], list) and len(data["data"]) > 0:
|
| 17 |
+
user_message = data["data"][0].lower()
|
| 18 |
+
else:
|
| 19 |
+
return json.dumps({"data": ["I can only tell you the current time in Pakistan. Try asking: 'What is the time?'"]})
|
| 20 |
+
except:
|
| 21 |
+
# If it's not JSON, treat it as a regular string (for direct Gradio interface testing)
|
| 22 |
+
user_message = message.lower()
|
| 23 |
+
|
| 24 |
+
# Process the message
|
| 25 |
+
if "time" in user_message:
|
| 26 |
+
now_pk = datetime.now(pakistan_tz)
|
| 27 |
+
time_str = f"{now_pk.strftime('%I:%M %p')}"
|
| 28 |
+
# Return in the expected JSON format
|
| 29 |
+
return json.dumps({"data": [time_str]})
|
| 30 |
+
else:
|
| 31 |
+
return json.dumps({"data": ["I can only tell you the current time in Pakistan. Try asking: 'What is the time?'"]})
|
| 32 |
|
| 33 |
+
# Create a more comprehensive interface
|
| 34 |
+
with gr.Blocks(title="Pakistan Time Bot", theme=gr.themes.Soft()) as demo:
|
| 35 |
+
gr.Markdown("# 🇵🇰 Pakistan Time Bot")
|
| 36 |
+
gr.Markdown("This bot tells you the current time in Pakistan. It's designed to work with both direct queries and ESP8266 devices.")
|
| 37 |
+
|
| 38 |
+
with gr.Tab("Chat Interface"):
|
| 39 |
+
gr.Markdown("### Talk to the Time Bot")
|
| 40 |
+
with gr.Row():
|
| 41 |
+
with gr.Column():
|
| 42 |
+
input_text = gr.Textbox(label="Your Message", placeholder="Ask me about the time in Pakistan...")
|
| 43 |
+
text_button = gr.Button("Get Time")
|
| 44 |
+
with gr.Column():
|
| 45 |
+
output_text = gr.Textbox(label="Bot Response", interactive=False)
|
| 46 |
+
|
| 47 |
+
examples = gr.Examples(
|
| 48 |
+
examples=["What's the time?", "Time please", "Current time in Pakistan"],
|
| 49 |
+
inputs=input_text
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
with gr.Tab("ESP8266 Integration"):
|
| 53 |
+
gr.Markdown("### ESP8266 Integration")
|
| 54 |
+
gr.Markdown("""
|
| 55 |
+
This bot is designed to work with ESP8266 microcontrollers. Here's how to set it up:
|
| 56 |
+
|
| 57 |
+
1. Use the code below in your Arduino IDE
|
| 58 |
+
2. Replace `YOUR_WIFI_SSID` and `YOUR_WIFI_PASSWORD` with your WiFi credentials
|
| 59 |
+
3. Update the `serverName` to point to your deployed Hugging Face Space
|
| 60 |
+
4. Upload the code to your ESP8266
|
| 61 |
+
""")
|
| 62 |
+
|
| 63 |
+
esp_code = """
|
| 64 |
+
#include <ESP8266WiFi.h>
|
| 65 |
+
#include <ESP8266HTTPClient.h>
|
| 66 |
|
| 67 |
+
const char* ssid = "YOUR_WIFI_SSID";
|
| 68 |
+
const char* password = "YOUR_WIFI_PASSWORD";
|
|
|
|
| 69 |
|
| 70 |
+
// Hugging Face Space API endpoint
|
| 71 |
+
String serverName = "https://your-username-time-bot.hf.space/run/predict";
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
+
WiFiClientSecure client; // use WiFiClientSecure for HTTPS
|
| 74 |
+
|
| 75 |
+
void setup() {
|
| 76 |
+
Serial.begin(115200);
|
| 77 |
+
WiFi.begin(ssid, password);
|
| 78 |
+
|
| 79 |
+
Serial.print("Connecting to WiFi...");
|
| 80 |
+
while (WiFi.status() != WL_CONNECTED) {
|
| 81 |
+
delay(500);
|
| 82 |
+
Serial.print(".");
|
| 83 |
+
}
|
| 84 |
+
Serial.println(" Connected!");
|
| 85 |
+
|
| 86 |
+
// For HTTPS: skip certificate verification
|
| 87 |
+
client.setInsecure();
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
void loop() {
|
| 91 |
+
if (WiFi.status() == WL_CONNECTED) {
|
| 92 |
+
HTTPClient http;
|
| 93 |
+
|
| 94 |
+
http.begin(client, serverName);
|
| 95 |
+
http.addHeader("Content-Type", "application/json");
|
| 96 |
+
|
| 97 |
+
// Sending request
|
| 98 |
+
String jsonData = "{\\"data\\":[\\"time\\"]}";
|
| 99 |
+
int httpResponseCode = http.POST(jsonData);
|
| 100 |
+
|
| 101 |
+
if (httpResponseCode > 0) {
|
| 102 |
+
String response = http.getString();
|
| 103 |
+
Serial.println("Response:");
|
| 104 |
+
Serial.println(response);
|
| 105 |
+
} else {
|
| 106 |
+
Serial.print("Error code: ");
|
| 107 |
+
Serial.println(httpResponseCode);
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
http.end();
|
| 111 |
+
} else {
|
| 112 |
+
Serial.println("WiFi Disconnected");
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
delay(10000); // request every 10 seconds
|
| 116 |
+
}
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
gr.Code(value=esp_code, language="cpp", label="ESP8266 Code")
|
| 120 |
+
|
| 121 |
+
gr.Markdown("### Test ESP8266 Request")
|
| 122 |
+
gr.Markdown("Click the button below to simulate the JSON request that an ESP8266 would send:")
|
| 123 |
+
test_button = gr.Button("Test ESP8266 Request")
|
| 124 |
+
test_output = gr.Textbox(label="JSON Response", interactive=False)
|
| 125 |
+
|
| 126 |
+
with gr.Tab("API Info"):
|
| 127 |
+
gr.Markdown("### API Information")
|
| 128 |
+
gr.Markdown("""
|
| 129 |
+
The bot accepts two types of requests:
|
| 130 |
+
|
| 131 |
+
1. **Direct text input**: Simply send a text message containing the word "time"
|
| 132 |
+
2. **JSON API** (for ESP8266): Send a JSON object in the format `{"data": ["time"]}`
|
| 133 |
+
|
| 134 |
+
The response will always be a JSON object with the format:
|
| 135 |
+
```json
|
| 136 |
+
{"data": ["08:45 PM"]}
|
| 137 |
+
```
|
| 138 |
+
""")
|
| 139 |
+
|
| 140 |
+
gr.Markdown("### Direct API Testing")
|
| 141 |
+
with gr.Row():
|
| 142 |
+
api_input = gr.Textbox(value='{"data": ["time"]}', label="JSON Input")
|
| 143 |
+
api_button = gr.Button("Send API Request")
|
| 144 |
+
api_output = gr.Textbox(label="API Response")
|
| 145 |
+
|
| 146 |
+
# Set up event handlers
|
| 147 |
+
text_button.click(chatbot, inputs=input_text, outputs=output_text)
|
| 148 |
+
input_text.submit(chatbot, inputs=input_text, outputs=output_text)
|
| 149 |
+
test_button.click(chatbot, inputs=gr.Textbox(value='{"data": ["time"]}'), outputs=test_output)
|
| 150 |
+
api_button.click(chatbot, inputs=api_input, outputs=api_output)
|
| 151 |
+
|
| 152 |
+
if __name__ == "__main__":
|
| 153 |
+
demo.launch()
|