-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
355 lines (311 loc) · 13.8 KB
/
streamlit_app.py
File metadata and controls
355 lines (311 loc) · 13.8 KB
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
"""
FunctionMac - Streamlit Web App
Provides a web interface to interact with all macOS functions locally using natural language
"""
import streamlit as st
import json
import traceback
from datetime import datetime
from macos_functions import AVAILABLE_FUNCTIONS
from macos_ai_assistant import MacOSAIAssistant
# Configure page
st.set_page_config(
page_title="FunctionMac",
page_icon="🍎",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for better styling
st.markdown("""
<style>
.main-header {
text-align: center;
color: #1f77b4;
padding: 20px 0;
}
.function-card {
background-color: #f8f9fa;
padding: 15px;
border-radius: 10px;
border: 1px solid #e9ecef;
margin: 10px 0;
}
.success-box {
background-color: #d4edda;
border: 1px solid #c3e6cb;
color: #155724;
padding: 15px;
border-radius: 5px;
margin: 10px 0;
}
.error-box {
background-color: #f8d7da;
border: 1px solid #f5c6cb;
color: #721c24;
padding: 15px;
border-radius: 5px;
margin: 10px 0;
}
</style>
""", unsafe_allow_html=True)
# Main title
st.markdown('<h1 class="main-header">🍎 FunctionMac</h1>', unsafe_allow_html=True)
st.markdown('<p style="text-align: center; color: #6c757d;">Natural language control for macOS - runs 100% locally</p>', unsafe_allow_html=True)
# Function categories
FUNCTION_CATEGORIES = {
"📋 Basic System": [
"take_screenshot", "copy_to_clipboard", "get_clipboard_content", "paste_from_clipboard"
],
"🎨 Theme & Appearance": [
"change_theme", "get_current_theme"
],
"🔊 Audio Control": [
"set_volume", "get_volume", "mute_volume", "unmute_volume"
],
"💡 Display Control": [
"set_brightness", "get_brightness"
],
"🔕 Do Not Disturb": [
"enable_do_not_disturb", "disable_do_not_disturb"
],
"📂 File Operations": [
"find_files", "open_file", "open_folder", "process_text_file"
],
"📱 Applications": [
"open_application", "quit_application", "list_running_applications"
],
"📊 System Information": [
"get_battery_info", "get_system_info", "get_cpu_usage", "get_memory_usage", "get_disk_usage"
],
"🖱️ GUI Automation": [
"click_at_coordinates", "drag_mouse", "type_text", "send_keyboard_shortcut", "scroll_screen",
"get_mouse_position", "get_screen_info"
],
"📅 Productivity": [
"create_reminder", "send_message", "get_calendar_events", "get_current_datetime"
],
"🎵 Music Control": [
"control_music"
],
"🧮 Data & Analysis": [
"calculate_expression", "analyze_data", "generate_qr_code"
],
"🌐 Network": [
"get_wifi_networks"
],
"🔧 Utilities": [
"run_applescript", "run_shell_command", "execute_function"
]
}
def execute_function(func_name: str, params: dict) -> dict:
"""Execute a function with given parameters and return result"""
try:
if func_name not in AVAILABLE_FUNCTIONS:
return {"success": False, "error": f"Function '{func_name}' not found"}
func = AVAILABLE_FUNCTIONS[func_name]
result = func(**params)
# Parse JSON result if it's a string
if isinstance(result, str):
try:
result = json.loads(result)
except:
result = {"success": True, "message": result}
return result
except Exception as e:
return {"success": False, "error": f"Error executing {func_name}: {str(e)}"}
def display_result(result: dict):
"""Display function execution result"""
if result.get("success"):
st.markdown('<div class="success-box">✅ Success!</div>', unsafe_allow_html=True)
# Display message if available
if "message" in result:
st.info(f"**Message:** {result['message']}")
# Display result data (excluding success and message)
result_data = {k: v for k, v in result.items() if k not in ['success', 'message']}
if result_data:
st.json(result_data)
else:
st.markdown('<div class="error-box">❌ Error occurred!</div>', unsafe_allow_html=True)
st.error(f"**Error:** {result.get('error', 'Unknown error')}")
# Sidebar for mode selection
st.sidebar.title("🚀 Interface Mode")
app_mode = st.sidebar.radio(
"Choose how to interact:",
["🤖 AI Assistant", "🔧 Direct Functions"],
help="AI Assistant uses natural language with Ollama, Direct Functions provides immediate access"
)
# Initialize AI Assistant if needed
if app_mode == "🤖 AI Assistant":
if 'ai_assistant' not in st.session_state:
try:
st.session_state.ai_assistant = MacOSAIAssistant()
st.session_state.ai_ready = True
except Exception as e:
st.session_state.ai_ready = False
st.session_state.ai_error = str(e)
# Main content area based on selected mode
if app_mode == "🤖 AI Assistant":
st.header("🤖 AI Assistant Mode")
if not st.session_state.get('ai_ready', False):
st.error("❌ AI Assistant not available")
st.error(f"Error: {st.session_state.get('ai_error', 'Unknown error')}")
st.info("Make sure Ollama is running and FunctionGemma model is installed:")
st.code("ollama pull functiongemma:270m")
else:
st.success("✅ AI Assistant ready!")
st.markdown("Type your requests in natural language and I'll help you control your Mac.")
# Example queries
with st.expander("💡 Example Queries"):
st.markdown("""
- "Take a screenshot and save it to desktop"
- "Set volume to 50 percent"
- "Turn on dark mode"
- "Show me battery information"
- "Find all PDF files in my Documents folder"
- "Get my current system information"
- "Set brightness to 70%"
- "What's my CPU usage?"
""")
# Chat interface
st.markdown("---")
# Initialize chat history
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
# Display chat history
chat_container = st.container()
with chat_container:
for i, chat in enumerate(st.session_state.chat_history):
with st.chat_message("user"):
st.write(chat['query'])
with st.chat_message("assistant"):
if chat['success']:
st.write(chat['final_response'])
# Show function calls if any
if chat.get('function_calls'):
with st.expander(f"🔧 Function Details ({len(chat['function_calls'])} called)"):
for func_call in chat['function_calls']:
if func_call['success']:
st.success(f"✅ {func_call['function']}")
if func_call.get('arguments'):
st.json(func_call['arguments'])
else:
st.error(f"❌ {func_call['function']}: {func_call.get('error', 'Unknown error')}")
else:
st.error(f"❌ {chat.get('error', 'Unknown error')}")
# Query input
user_query = st.chat_input("Ask me anything about your Mac...")
if user_query:
# Add user message to history immediately
st.session_state.chat_history.append({
'query': user_query,
'success': False,
'processing': True
})
# Process the query
with st.spinner("🤖 Processing your request..."):
try:
result = st.session_state.ai_assistant.process_query(user_query)
# Update the last entry with results
st.session_state.chat_history[-1] = result
except Exception as e:
st.session_state.chat_history[-1] = {
'query': user_query,
'error': str(e),
'success': False
}
# Rerun to show the new message
st.rerun()
else:
# Direct Functions Mode
st.header("🔧 Direct Functions Mode")
st.sidebar.title("🛠️ Function Categories")
selected_category = st.sidebar.selectbox("Choose a category:", list(FUNCTION_CATEGORIES.keys()))
# Get functions for selected category
category_functions = FUNCTION_CATEGORIES[selected_category]
for func_name in category_functions:
with st.expander(f"🔧 {func_name.replace('_', ' ').title()}"):
func = AVAILABLE_FUNCTIONS[func_name]
# Display function documentation
if func.__doc__:
st.markdown(f"**Description:** {func.__doc__.strip()}")
# Create input fields based on function signature
import inspect
sig = inspect.signature(func)
params = {}
for param_name, param in sig.parameters.items():
param_type = param.annotation if param.annotation != inspect.Parameter.empty else str
default_value = param.default if param.default != inspect.Parameter.empty else None
# Create appropriate input widget based on parameter type
if param_type == int:
if default_value is not None:
params[param_name] = st.number_input(f"{param_name}:", value=default_value, key=f"{func_name}_{param_name}")
else:
params[param_name] = st.number_input(f"{param_name}:", key=f"{func_name}_{param_name}")
elif param_type == float:
if default_value is not None:
params[param_name] = st.number_input(f"{param_name}:", value=float(default_value), key=f"{func_name}_{param_name}")
else:
params[param_name] = st.number_input(f"{param_name}:", value=0.0, key=f"{func_name}_{param_name}")
elif param_type == bool:
default_bool = default_value if default_value is not None else False
params[param_name] = st.checkbox(f"{param_name}:", value=default_bool, key=f"{func_name}_{param_name}")
elif param_type == list or "List" in str(param_type):
list_input = st.text_area(f"{param_name} (comma-separated):", key=f"{func_name}_{param_name}")
if list_input.strip():
try:
# Try to parse as numbers if possible
params[param_name] = [float(x.strip()) for x in list_input.split(',')]
except ValueError:
params[param_name] = [x.strip() for x in list_input.split(',')]
else:
params[param_name] = []
else:
# String or other types
if default_value is not None and default_value != "":
params[param_name] = st.text_input(f"{param_name}:", value=str(default_value), key=f"{func_name}_{param_name}")
else:
params[param_name] = st.text_input(f"{param_name}:", key=f"{func_name}_{param_name}")
# Remove empty parameters if they have defaults
if default_value is not None and params[param_name] == (0 if param_type in [int, float] else ""):
if param_name in params:
del params[param_name]
# Execute button
if st.button(f"Execute {func_name}", key=f"execute_{func_name}"):
with st.spinner("Executing..."):
result = execute_function(func_name, params)
display_result(result)
# Footer
st.markdown("---")
st.markdown("**ℹ️ About:** This app provides direct access to all macOS functions without requiring the AI assistant or Ollama.")
st.markdown("**⚠️ Note:** Some functions may require special permissions on macOS. Please grant necessary permissions when prompted.")
# Add execution log in sidebar
if st.sidebar.checkbox("Show Execution Log"):
st.sidebar.subheader("📝 Recent Executions")
# This would store execution history if needed
if 'execution_log' not in st.session_state:
st.session_state.execution_log = []
for i, log_entry in enumerate(reversed(st.session_state.execution_log[-5:])):
st.sidebar.text(f"{log_entry['time']}: {log_entry['function']}")
if log_entry['success']:
st.sidebar.success("✅")
else:
st.sidebar.error("❌")
# Quick actions sidebar
st.sidebar.markdown("---")
st.sidebar.subheader("🚀 Quick Actions")
# Quick screenshot
if st.sidebar.button("📸 Take Screenshot"):
result = execute_function("take_screenshot", {})
st.sidebar.write("Screenshot result:")
if result.get("success"):
st.sidebar.success("✅ Screenshot taken!")
else:
st.sidebar.error("❌ Failed")
# Quick system info
if st.sidebar.button("📊 System Info"):
result = execute_function("get_system_info", {})
st.sidebar.write("System info retrieved")
# Quick battery info
if st.sidebar.button("🔋 Battery Info"):
result = execute_function("get_battery_info", {})
st.sidebar.write("Battery info retrieved")