text-jarvis / app.py
ShoaibAI's picture
Update app.py
9b52b76 verified
Raw History Blame Contribute Delete
29.4 kB
import random
import re
from datetime import datetime
import urllib.request
import urllib.parse
import json
print("=" * 60)
print("πŸŽ™οΈ Jarvis AI Assistant with Web Search")
print("=" * 60)
# Complete HTML/CSS/JS interface with Advanced Commands
html_template = """
<!DOCTYPE html>
<html>
<head>
<title>Jarvis AI - Advanced Voice Assistant</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 1200px;
margin: 0 auto;
background: white;
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}
.header h1 {
font-size: 2.5em;
margin-bottom: 10px;
}
.header p {
font-size: 1.1em;
opacity: 0.9;
}
.voice-status {
margin-top: 15px;
padding: 10px;
background: rgba(255,255,255,0.2);
border-radius: 10px;
display: inline-block;
}
.chat-area {
height: 400px;
overflow-y: auto;
padding: 20px;
background: #f7f7f7;
}
.message {
margin-bottom: 15px;
display: flex;
animation: fadeIn 0.3s ease-in;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.user-message {
justify-content: flex-end;
}
.bot-message {
justify-content: flex-start;
}
.message-content {
max-width: 70%;
padding: 12px 18px;
border-radius: 20px;
word-wrap: break-word;
}
.user-message .message-content {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-bottom-right-radius: 5px;
}
.bot-message .message-content {
background: white;
color: #333;
border: 1px solid #e0e0e0;
border-bottom-left-radius: 5px;
}
.input-area {
padding: 20px;
background: white;
border-top: 1px solid #e0e0e0;
}
.input-group {
display: flex;
gap: 10px;
margin-bottom: 10px;
}
input[type="text"] {
flex: 1;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 10px;
font-size: 16px;
transition: border-color 0.3s;
}
input[type="text"]:focus {
outline: none;
border-color: #667eea;
}
button {
padding: 12px 24px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 10px;
cursor: pointer;
font-size: 16px;
font-weight: bold;
transition: transform 0.2s;
}
button:hover {
transform: translateY(-2px);
}
button:active {
transform: translateY(0);
}
.voice-btn {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}
.voice-btn.listening {
animation: pulse 1.5s infinite;
background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
}
@keyframes pulse {
0% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.05); opacity: 0.8; }
100% { transform: scale(1); opacity: 1; }
}
.clear-btn {
background: #dc3545;
}
.clear-btn:hover {
background: #c82333;
}
.quick-buttons {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 10px;
}
.quick-btn {
padding: 6px 12px;
background: #f0f0f0;
color: #667eea;
font-size: 12px;
border: none;
border-radius: 15px;
cursor: pointer;
transition: background 0.2s;
}
.quick-btn:hover {
background: #e0e0e0;
transform: none;
}
.status {
text-align: center;
padding: 10px;
background: #f0f0f0;
color: #666;
font-size: 12px;
}
.voice-indicator {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background: #ccc;
margin-right: 5px;
}
.voice-indicator.active {
background: #4caf50;
animation: blink 1s infinite;
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0.3; }
}
.search-result {
background: #f8f9fa;
padding: 10px;
border-radius: 10px;
margin-top: 10px;
}
@media (max-width: 600px) {
.message-content {
max-width: 85%;
}
.header h1 {
font-size: 1.8em;
}
button {
padding: 8px 16px;
font-size: 14px;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>πŸŽ™οΈ Jarvis AI</h1>
<p>Your Advanced Voice-Controlled Assistant</p>
<div class="voice-status">
<span class="voice-indicator" id="voiceIndicator"></span>
<span id="voiceStatusText">Click 🎀 to speak</span>
</div>
</div>
<div class="chat-area" id="chatArea">
<div class="message bot-message">
<div class="message-content">
<strong>🎯 Advanced Jarvis is Ready!</strong><br><br>
<strong>πŸ” Web Search:</strong><br>
β€’ "Search for Python tutorials"<br>
β€’ "Google how to make pizza"<br>
β€’ "Find restaurants near me"<br><br>
<strong>πŸ’» System Control (Local PC Only):</strong><br>
β€’ "Shutdown computer"<br>
β€’ "Open Chrome"<br>
β€’ "Open my documents folder"<br><br>
<strong>πŸ“ Other Commands:</strong><br>
β€’ "What time is it?"<br>
β€’ "Tell me a joke"<br>
β€’ "Calculate 25 times 4"<br>
β€’ "Remind me to call mom"<br><br>
<strong>🎀 Click the microphone and say something!</strong>
</div>
</div>
</div>
<div class="input-area">
<div class="input-group">
<input type="text" id="messageInput" placeholder="Type or speak your command..." onkeypress="handleKeyPress(event)">
<button onclick="sendMessage()">Send</button>
<button onclick="startVoiceInput()" id="voiceBtn" class="voice-btn" title="Click to speak">🎀 Speak</button>
<button onclick="clearChat()" class="clear-btn">Clear</button>
</div>
<div class="quick-buttons">
<button class="quick-btn" onclick="quickCommand('Hello')">Hello</button>
<button class="quick-btn" onclick="quickCommand('What time is it?')">Time</button>
<button class="quick-btn" onclick="quickCommand('Search for Python tutorials')">Search Web</button>
<button class="quick-btn" onclick="quickCommand('Tell me a joke')">Joke</button>
<button class="quick-btn" onclick="quickCommand('Calculate 100 / 4')">Math</button>
<button class="quick-btn" onclick="quickCommand('Remind me to buy milk')">Remind</button>
<button class="quick-btn" onclick="quickCommand('Help')">Help</button>
</div>
</div>
<div class="status">
🟒 Online | 🎀 Voice Enabled | πŸ” Web Search Active | πŸ’» System Ready
</div>
</div>
<script>
let reminders = [];
let recognition = null;
let isListening = false;
// Web search function using DuckDuckGo API
async function webSearch(query) {
try {
const encodedQuery = encodeURIComponent(query);
const response = await fetch(`https://api.duckduckgo.com/?q=${encodedQuery}&format=json&no_html=1&skip_disambig=1`);
const data = await response.json();
if (data.AbstractText) {
return `πŸ” <strong>Search results for "${query}":</strong><br><br>${data.AbstractText}<br><br>πŸ“Ž <a href="${data.AbstractURL}" target="_blank">Read more</a>`;
} else if (data.RelatedTopics && data.RelatedTopics.length > 0) {
let results = `<strong>πŸ” Search results for "${query}":</strong><br><br>`;
for (let i = 0; i < Math.min(3, data.RelatedTopics.length); i++) {
if (data.RelatedTopics[i].Text) {
results += `β€’ ${data.RelatedTopics[i].Text}<br>`;
}
}
results += `<br>πŸ’‘ Try searching directly on <a href="https://www.google.com/search?q=${encodedQuery}" target="_blank">Google</a> for more results.`;
return results;
} else {
return `πŸ” I searched for "${query}" but found no direct answer.<br><br>πŸ“Ž <a href="https://www.google.com/search?q=${encodedQuery}" target="_blank">Click here to see Google results</a>`;
}
} catch (error) {
console.error('Search error:', error);
return `πŸ” I couldn't complete the search for "${query}".<br><br>πŸ“Ž <a href="https://www.google.com/search?q=${encodeURIComponent(query)}" target="_blank">Click here to search on Google</a>`;
}
}
// Check if browser supports speech recognition
if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
recognition = new SpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.lang = 'en-US';
recognition.onstart = function() {
isListening = true;
const voiceBtn = document.getElementById('voiceBtn');
voiceBtn.classList.add('listening');
document.getElementById('voiceIndicator').classList.add('active');
document.getElementById('voiceStatusText').textContent = '🎀 Listening... Speak now!';
voiceBtn.textContent = 'πŸ”΄ Listening...';
};
recognition.onend = function() {
isListening = false;
const voiceBtn = document.getElementById('voiceBtn');
voiceBtn.classList.remove('listening');
document.getElementById('voiceIndicator').classList.remove('active');
document.getElementById('voiceStatusText').textContent = 'Click 🎀 to speak';
voiceBtn.textContent = '🎀 Speak';
};
recognition.onresult = function(event) {
const transcript = event.results[0][0].transcript;
document.getElementById('messageInput').value = transcript;
document.getElementById('voiceStatusText').textContent = 'βœ“ Command received: "' + transcript + '"';
setTimeout(() => {
document.getElementById('voiceStatusText').textContent = 'Click 🎀 to speak';
}, 2000);
sendMessage();
};
recognition.onerror = function(event) {
console.error('Speech recognition error:', event.error);
let errorMsg = 'Voice error: ';
switch(event.error) {
case 'not-allowed':
errorMsg += 'Please allow microphone access.';
break;
case 'no-speech':
errorMsg += 'No speech detected. Please try again.';
break;
default:
errorMsg += event.error;
}
document.getElementById('voiceStatusText').textContent = errorMsg;
setTimeout(() => {
document.getElementById('voiceStatusText').textContent = 'Click 🎀 to speak';
}, 3000);
recognition.stop();
};
} else {
console.log('Speech recognition not supported');
document.getElementById('voiceStatusText').textContent = '⚠️ Voice not supported in this browser';
}
function startVoiceInput() {
if (!recognition) {
alert('Sorry, voice recognition is not supported in your browser. Please use Chrome, Edge, or Safari.');
return;
}
if (isListening) {
recognition.stop();
} else {
try {
recognition.start();
} catch (e) {
console.error('Error starting recognition:', e);
}
}
}
function handleKeyPress(event) {
if (event.key === 'Enter') {
sendMessage();
}
}
function addMessage(text, isUser) {
const chatArea = document.getElementById('chatArea');
const messageDiv = document.createElement('div');
messageDiv.className = isUser ? 'message user-message' : 'message bot-message';
const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
contentDiv.innerHTML = text.replace(/\\n/g, '<br>');
messageDiv.appendChild(contentDiv);
chatArea.appendChild(messageDiv);
chatArea.scrollTop = chatArea.scrollHeight;
}
function clearChat() {
const chatArea = document.getElementById('chatArea');
chatArea.innerHTML = '';
addMessage("Chat cleared! How can I help you? πŸš€", false);
}
function quickCommand(cmd) {
document.getElementById('messageInput').value = cmd;
sendMessage();
}
async function sendMessage() {
const input = document.getElementById('messageInput');
const message = input.value.trim();
if (!message) return;
// Add user message
addMessage(escapeHtml(message), true);
input.value = '';
// Show thinking indicator
const thinkingId = setTimeout(() => {
addMessage("πŸ€” Thinking...", false);
}, 100);
// Process command
const response = await processCommand(message);
// Remove thinking indicator if it was added
clearTimeout(thinkingId);
// Add bot response
setTimeout(() => {
addMessage(response, false);
// Text-to-speech for short responses
if (window.speechSynthesis && response.length < 200) {
speakResponse(response);
}
}, 100);
}
function speakResponse(text) {
const cleanText = text.replace(/<[^>]*>/g, '').replace(/[^\w\s]/g, '');
if (cleanText.length < 100) {
const utterance = new SpeechSynthesisUtterance(cleanText);
utterance.lang = 'en-US';
utterance.rate = 1.0;
utterance.pitch = 1.0;
window.speechSynthesis.cancel();
window.speechSynthesis.speak(utterance);
}
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
async function processCommand(message) {
const msg = message.toLowerCase();
// ============================================
// WEB SEARCH COMMANDS
// ============================================
if (msg.includes('search for') || msg.includes('search the web for') ||
msg.includes('google') || msg.includes('find ') ||
(msg.includes('search') && !msg.includes('search for'))) {
let searchQuery = message;
// Extract search query
if (msg.includes('search for')) {
searchQuery = message.replace(/search for/i, '').trim();
} else if (msg.includes('google')) {
searchQuery = message.replace(/google/i, '').trim();
} else if (msg.includes('find')) {
searchQuery = message.replace(/find/i, '').trim();
}
addMessage("πŸ” Searching the web...", false);
const searchResult = await webSearch(searchQuery);
return searchResult;
}
// ============================================
// SYSTEM CONTROL COMMANDS (for local PC)
// Note: These will show instructions for local setup
// ============================================
if (msg.includes('shutdown') || msg.includes('shut down')) {
return `⚠️ <strong>System Control Setup Required:</strong><br><br>
To enable shutdown commands on your local PC:<br><br>
1. Save this HTML file on your computer<br>
2. Run it as a local file (not on Hugging Face)<br>
3. Add this JavaScript function:<br><br>
<code>function shutdown() {<br>
&nbsp;&nbsp;window.location.href = 'shutdown://';<br>
}</code><br><br>
Or use this Python script on your PC:<br>
<code>import os; os.system('shutdown /s /t 5')</code><br><br>
πŸ’‘ <strong>Note:</strong> This requires running Jarvis locally on your PC!`;
}
if (msg.includes('open ') && (msg.includes('chrome') || msg.includes('browser') || msg.includes('folder') || msg.includes('file'))) {
let app = message.replace(/open/i, '').trim();
return `πŸ“‚ <strong>To open "${app}" on your PC:</strong><br><br>
Run this Python script locally:<br><br>
<code>import os<br>
os.system('start ${app}')</code><br><br>
Or download the <strong>Local Jarvis Launcher</strong> script below.`;
}
// Reminders
if (msg === 'list reminders') {
if (reminders.length === 0) {
return "πŸ“ You have no active reminders.";
}
return "πŸ“‹ Your reminders:<br>" + reminders.map(r => " β€’ " + escapeHtml(r)).join("<br>");
}
if (msg === 'clear reminders') {
const count = reminders.length;
reminders = [];
return `πŸ—‘οΈ Cleared ${count} reminder(s).`;
}
if (msg.startsWith('remind me to ')) {
const reminder = message.substring(12).trim();
reminders.push(reminder);
return `βœ… Reminder set: "${escapeHtml(reminder)}"`;
}
// Time
if (msg.includes('time') || msg.includes('clock')) {
const now = new Date();
let hours = now.getHours();
const minutes = now.getMinutes();
const ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12 || 12;
const timeStr = `${hours}:${minutes.toString().padStart(2, '0')} ${ampm}`;
return `πŸ• The current time is ${timeStr}`;
}
// Date
if (msg.includes('date') || msg.includes('today')) {
const now = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
return `πŸ“… Today is ${now.toLocaleDateString('en-US', options)}`;
}
// Jokes
if (msg.includes('joke') || msg.includes('funny') || msg.includes('laugh')) {
const jokes = [
"Why don't scientists trust atoms? Because they make up everything! πŸ˜„",
"What do you call a fake noodle? An impasta! 🍝",
"Why did the scarecrow win an award? He was outstanding in his field! 🌾",
"What do you call a bear with no teeth? A gummy bear! 🐻",
"Why don't eggs tell jokes? They'd crack each other up! πŸ₯š",
"What do you call a fish wearing a bowtie? Sofishticated! 🐠",
"Why did the coffee file a police report? It got mugged! β˜•",
"What do you call a programmer who doesn't comment code? A masochist! πŸ’»"
];
return "πŸ˜„ " + jokes[Math.floor(Math.random() * jokes.length)];
}
// Quotes
if (msg.includes('quote') || msg.includes('motivate') || msg.includes('inspire')) {
const quotes = [
"The only limit is your mind. Keep pushing forward! πŸ’ͺ",
"Every expert was once a beginner. You've got this! 🌟",
"Success is not final, failure is not fatal. It's the courage to continue that counts.",
"Your potential is endless. Keep learning and growing! πŸš€",
"Believe you can and you're halfway there. - Theodore Roosevelt",
"It does not matter how slowly you go as long as you do not stop. - Confucius"
];
return "πŸ’« " + quotes[Math.floor(Math.random() * quotes.length)];
}
// Math
const mathMatch = msg.match(/([\\d.]+)\\s*(?:plus|\\+)\\s*([\\d.]+)/);
if (mathMatch) {
const result = parseFloat(mathMatch[1]) + parseFloat(mathMatch[2]);
return `πŸ”’ ${mathMatch[1]} + ${mathMatch[2]} = ${result}`;
}
const minusMatch = msg.match(/([\\d.]+)\\s*(?:minus|-)\\s*([\\d.]+)/);
if (minusMatch) {
const result = parseFloat(minusMatch[1]) - parseFloat(minusMatch[2]);
return `πŸ”’ ${minusMatch[1]} - ${minusMatch[2]} = ${result}`;
}
const timesMatch = msg.match(/([\\d.]+)\\s*(?:times|\\*|x)\\s*([\\d.]+)/);
if (timesMatch) {
const result = parseFloat(timesMatch[1]) * parseFloat(timesMatch[2]);
return `πŸ”’ ${timesMatch[1]} Γ— ${timesMatch[2]} = ${result}`;
}
const divideMatch = msg.match(/([\\d.]+)\\s*(?:divided by|\\/)\\s*([\\d.]+)/);
if (divideMatch) {
if (parseFloat(divideMatch[2]) === 0) {
return "❌ Cannot divide by zero!";
}
const result = parseFloat(divideMatch[1]) / parseFloat(divideMatch[2]);
return `πŸ”’ ${divideMatch[1]} Γ· ${divideMatch[2]} = ${result}`;
}
// Greetings
if (msg.includes('hello') || msg.includes('hi') || msg.includes('hey')) {
const greetings = [
"Hello! How can I assist you today? πŸŽ™οΈ",
"Hi there! Ready to help! πŸ’«",
"Greetings! What can I do for you? ✨",
"Hey! Jarvis at your service! πŸš€"
];
return greetings[Math.floor(Math.random() * greetings.length)];
}
// Farewell
if (msg.includes('bye') || msg.includes('goodbye')) {
return "Goodbye! I'm always here when you need me. πŸ‘‹";
}
// About
if (msg.includes('who are you') || msg.includes('your name')) {
return "I'm Jarvis, your advanced voice-enabled AI assistant! I can search the web, manage reminders, tell jokes, do math, and more! πŸ€–";
}
// How are you
if (msg.includes('how are you')) {
return "I'm doing great! Thanks for asking! How can I help you today? 😊";
}
// Thanks
if (msg.includes('thank')) {
return "You're welcome! Always happy to help! 😊";
}
// Help
if (msg === 'help' || msg === 'what can you do') {
return `🎯 <strong>Jarvis Advanced Commands</strong><br><br>
πŸ” <strong>Web Search:</strong><br>
β€’ "Search for Python tutorials"<br>
β€’ "Google how to make pizza"<br>
β€’ "Find restaurants near me"<br><br>
πŸ’» <strong>System Control (Local PC):</strong><br>
β€’ "Shutdown computer" - Requires local setup<br>
β€’ "Open Chrome" - Requires local setup<br>
β€’ "Open my documents" - Requires local setup<br><br>
⏰ <strong>Time & Date:</strong><br>
β€’ "What time is it?"<br>
β€’ "Today's date"<br><br>
πŸ˜„ <strong>Fun:</strong><br>
β€’ "Tell me a joke"<br>
β€’ "Give me a quote"<br><br>
πŸ”’ <strong>Math:</strong><br>
β€’ "Calculate 5 + 3"<br>
β€’ "10 times 6"<br><br>
πŸ“ <strong>Reminders:</strong><br>
β€’ "Remind me to call mom"<br>
β€’ "List reminders"<br>
β€’ "Clear reminders"<br><br>
🎀 <strong>Voice Tips:</strong><br>
β€’ Click the 🎀 button and speak naturally!<br><br>
<strong>Try saying: "Search for Python" or "Tell me a joke" πŸš€</strong>`;
}
// Default
return `I heard: "${escapeHtml(message)}". Try saying 'help' to see all my features, or try a web search! 🎯`;
}
</script>
</body>
</html>
"""
# Create a simple HTTP server
from http.server import HTTPServer, BaseHTTPRequestHandler
import os
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(html_template.encode())
else:
self.send_response(404)
self.end_headers()
def log_message(self, format, *args):
print(f"{datetime.now().strftime('%H:%M:%S')} - {format % args}")
if __name__ == '__main__':
port = int(os.environ.get('PORT', 7860))
server = HTTPServer(('0.0.0.0', port), Handler)
print("=" * 60)
print("πŸŽ™οΈ Advanced Jarvis AI with Web Search!")
print(f"πŸ“ Server: http://0.0.0.0:{port}")
print("βœ… Features: Web Search + Voice + Math + Reminders")
print("=" * 60)
print("\nπŸ” WEB SEARCH COMMANDS:")
print(" β€’ 'Search for Python tutorials'")
print(" β€’ 'Google how to make coffee'")
print(" β€’ 'Find restaurants near me'")
print("\nπŸ’‘ SYSTEM CONTROL (Local PC only):")
print(" β€’ Download the Local Jarvis Launcher below")
print("\nπŸš€ Server ready!")
print("=" * 60)
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nπŸ‘‹ Shutting down...")
server.shutdown()