Mr-Thop commited on
Commit
5d19084
·
verified ·
1 Parent(s): e73e59d

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +184 -12
  2. app.py +29 -0
  3. gradio_app.py +636 -0
  4. requirements.txt +39 -0
README.md CHANGED
@@ -1,12 +1,184 @@
1
- ---
2
- title: NLPWMAD
3
- emoji: 📉
4
- colorFrom: red
5
- colorTo: gray
6
- sdk: gradio
7
- sdk_version: 5.49.1
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AI Assistant - Gradio Web Application
2
+
3
+ A comprehensive AI Assistant built with Gradio that combines chat functionality, notes management, reminders, document processing, and system monitoring in a single web interface.
4
+
5
+ ## 🚀 Features
6
+
7
+ - **💬 Smart Chat**: Intelligent conversations with AI assistance
8
+ - **📝 Notes Management**: Create, edit, and organize your notes
9
+ - **⏰ Reminders**: Set and manage time-based notifications
10
+ - **📄 Document Processing**: Upload and analyze PDF, TXT, and Markdown files
11
+ - **💻 System Monitoring**: Real-time system performance metrics
12
+
13
+ ## 🛠️ Technology Stack
14
+
15
+ - **Frontend**: Gradio web interface
16
+ - **Backend**: Python with integrated AI capabilities
17
+ - **AI Integration**: Google Gemini API (configurable)
18
+ - **Data Storage**: JSON-based local storage
19
+ - **File Processing**: Support for multiple document formats
20
+
21
+ ## 🏃‍♂️ Quick Start
22
+
23
+ ### Local Development
24
+
25
+ 1. **Clone the repository**
26
+ ```bash
27
+ git clone <your-repo-url>
28
+ cd ai-assistant-gradio
29
+ ```
30
+
31
+ 2. **Install dependencies**
32
+ ```bash
33
+ pip install -r requirements.txt
34
+ ```
35
+
36
+ 3. **Set up environment variables** (optional)
37
+ ```bash
38
+ # Create .env file
39
+ GEMINI_API_KEY=your_gemini_api_key_here
40
+ OPENAI_API_KEY=your_openai_api_key_here
41
+ ```
42
+
43
+ 4. **Run the application**
44
+ ```bash
45
+ python gradio_app.py
46
+ ```
47
+
48
+ 5. **Open your browser**
49
+ Navigate to `http://localhost:7860`
50
+
51
+ ### Hugging Face Spaces Deployment
52
+
53
+ 1. **Create a new Space** on [Hugging Face Spaces](https://huggingface.co/spaces)
54
+ 2. **Select Gradio** as the SDK
55
+ 3. **Upload these files**:
56
+ - `gradio_app.py` (main application)
57
+ - `requirements.txt` (dependencies)
58
+ - `README.md` (this file)
59
+ 4. **Add secrets** (if using AI APIs):
60
+ - `GEMINI_API_KEY`: Your Google Gemini API key
61
+ - `OPENAI_API_KEY`: Your OpenAI API key
62
+ 5. **Deploy** and your app will be live!
63
+
64
+ ## 📱 Usage Guide
65
+
66
+ ### Chat Interface
67
+ - Type messages in the chat box to interact with the AI
68
+ - Use example prompts to get started quickly
69
+ - Chat history is automatically saved
70
+
71
+ ### Notes Management
72
+ - Create notes with titles and content
73
+ - View all notes in an organized display
74
+ - Delete notes by exact title match
75
+ - Notes persist between sessions
76
+
77
+ ### Reminders System
78
+ - Set reminders with specific dates and times
79
+ - Add descriptions for detailed reminders
80
+ - Mark reminders as completed
81
+ - View active and completed reminders
82
+
83
+ ### Document Processing
84
+ - Upload PDF, TXT, or Markdown files
85
+ - Get automatic analysis and content preview
86
+ - Files are saved for future reference
87
+ - Content can be queried through chat
88
+
89
+ ### System Monitoring
90
+ - View real-time system performance
91
+ - Monitor CPU, memory, and disk usage
92
+ - Track application statistics
93
+ - Auto-refresh every 30 seconds
94
+
95
+ ## 🔧 Configuration
96
+
97
+ ### Environment Variables
98
+
99
+ - `GEMINI_API_KEY`: Google Gemini API key for AI responses
100
+ - `OPENAI_API_KEY`: OpenAI API key (alternative AI provider)
101
+ - `DEBUG`: Set to `true` for debug mode
102
+ - `PORT`: Custom port (default: 7860)
103
+
104
+ ### Customization
105
+
106
+ The application is designed to be easily customizable:
107
+
108
+ - **AI Provider**: Modify the `_generate_mock_response` method to integrate with different AI services
109
+ - **Storage**: Replace JSON storage with database integration
110
+ - **UI Theme**: Customize the Gradio theme and CSS
111
+ - **Features**: Add or remove tabs and functionality as needed
112
+
113
+ ## 📊 Data Storage
114
+
115
+ Data is stored locally in JSON files:
116
+ - `data/notes.json`: User notes
117
+ - `data/reminders.json`: User reminders
118
+ - `data/chat_history.json`: Chat conversation history
119
+ - `data/documents/`: Uploaded documents
120
+
121
+ ## 🔒 Security Notes
122
+
123
+ - Data is stored locally and not shared externally
124
+ - API keys should be kept secure and not committed to version control
125
+ - File uploads are processed locally and stored in the data directory
126
+ - Consider implementing user authentication for production use
127
+
128
+ ## 🚀 Deployment Options
129
+
130
+ ### Hugging Face Spaces (Recommended)
131
+ - Free hosting for public applications
132
+ - Automatic deployment from Git repository
133
+ - Built-in secrets management
134
+ - Easy sharing and collaboration
135
+
136
+ ### Other Platforms
137
+ - **Streamlit Cloud**: Alternative free hosting
138
+ - **Railway**: Easy deployment with custom domains
139
+ - **Heroku**: Traditional cloud platform
140
+ - **DigitalOcean**: VPS deployment
141
+ - **Local Server**: Self-hosted solution
142
+
143
+ ## 🤝 Contributing
144
+
145
+ Contributions are welcome! Please feel free to submit issues, feature requests, or pull requests.
146
+
147
+ ### Development Setup
148
+
149
+ 1. Fork the repository
150
+ 2. Create a feature branch
151
+ 3. Make your changes
152
+ 4. Test thoroughly
153
+ 5. Submit a pull request
154
+
155
+ ## 📄 License
156
+
157
+ This project is open source and available under the MIT License.
158
+
159
+ ## 🆘 Support
160
+
161
+ If you encounter any issues or have questions:
162
+
163
+ 1. Check the [Issues](https://github.com/your-repo/issues) page
164
+ 2. Create a new issue with detailed information
165
+ 3. Join the discussion in the community
166
+
167
+ ## 🎯 Roadmap
168
+
169
+ Future enhancements planned:
170
+ - [ ] User authentication and multi-user support
171
+ - [ ] Database integration (PostgreSQL, MongoDB)
172
+ - [ ] Advanced AI integrations
173
+ - [ ] Mobile app companion
174
+ - [ ] API endpoints for external integration
175
+ - [ ] Advanced document analysis
176
+ - [ ] Email and calendar integration
177
+ - [ ] Voice commands and speech synthesis
178
+ - [ ] Plugin system for extensibility
179
+
180
+ ---
181
+
182
+ **Built with ❤️ using Gradio and Python**
183
+
184
+ *Perfect for deployment on Hugging Face Spaces!*
app.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ AI Assistant - Hugging Face Spaces Entry Point
4
+ This is the main entry point for Hugging Face Spaces deployment
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ # Add the current directory to Python path
12
+ sys.path.append(str(Path(__file__).parent))
13
+
14
+ # Import and run the Gradio application
15
+ from gradio_app import create_gradio_interface
16
+
17
+ if __name__ == "__main__":
18
+ # Create the Gradio interface
19
+ app = create_gradio_interface()
20
+
21
+ # Launch with Hugging Face Spaces compatible settings
22
+ app.launch(
23
+ server_name="0.0.0.0",
24
+ server_port=int(os.environ.get("PORT", 7860)),
25
+ share=False,
26
+ debug=False,
27
+ show_error=True,
28
+ quiet=False
29
+ )
gradio_app.py ADDED
@@ -0,0 +1,636 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ AI Assistant - Gradio Web Application
4
+ Combines frontend and backend functionality in a single Gradio interface
5
+ Suitable for deployment on Hugging Face Spaces
6
+ """
7
+
8
+ import gradio as gr
9
+ import json
10
+ import os
11
+ import tempfile
12
+ import shutil
13
+ from datetime import datetime, timedelta
14
+ from typing import List, Dict, Any, Optional, Tuple
15
+ import logging
16
+ from pathlib import Path
17
+
18
+ # Import your existing backend components
19
+ try:
20
+ from voice_assistant import AIAssistant
21
+ from config_manager import ConfigManager
22
+ from error_handler import ErrorHandler
23
+ except ImportError:
24
+ # Fallback imports if modules are not available
25
+ print("Warning: Some backend modules not found. Using mock implementations.")
26
+ AIAssistant = None
27
+ ConfigManager = None
28
+ ErrorHandler = None
29
+
30
+ # Configure logging
31
+ logging.basicConfig(level=logging.INFO)
32
+ logger = logging.getLogger(__name__)
33
+
34
+ class GradioAIAssistant:
35
+ """Gradio-compatible AI Assistant wrapper"""
36
+
37
+ def __init__(self):
38
+ self.data_dir = Path("data")
39
+ self.data_dir.mkdir(exist_ok=True)
40
+
41
+ # Initialize backend components
42
+ self.config_manager = ConfigManager() if ConfigManager else None
43
+ self.error_handler = ErrorHandler() if ErrorHandler else None
44
+ self.ai_assistant = AIAssistant() if AIAssistant else None
45
+
46
+ # Initialize data storage
47
+ self.notes_file = self.data_dir / "notes.json"
48
+ self.reminders_file = self.data_dir / "reminders.json"
49
+ self.chat_history_file = self.data_dir / "chat_history.json"
50
+ self.documents_dir = self.data_dir / "documents"
51
+ self.documents_dir.mkdir(exist_ok=True)
52
+
53
+ # Load existing data
54
+ self.notes = self._load_json(self.notes_file, [])
55
+ self.reminders = self._load_json(self.reminders_file, [])
56
+ self.chat_history = self._load_json(self.chat_history_file, [])
57
+
58
+ logger.info("Gradio AI Assistant initialized successfully")
59
+
60
+ def _load_json(self, file_path: Path, default: Any) -> Any:
61
+ """Load JSON data from file with fallback to default"""
62
+ try:
63
+ if file_path.exists():
64
+ with open(file_path, 'r', encoding='utf-8') as f:
65
+ return json.load(f)
66
+ except Exception as e:
67
+ logger.error(f"Error loading {file_path}: {e}")
68
+ return default
69
+
70
+ def _save_json(self, file_path: Path, data: Any) -> bool:
71
+ """Save data to JSON file"""
72
+ try:
73
+ with open(file_path, 'w', encoding='utf-8') as f:
74
+ json.dump(data, f, indent=2, ensure_ascii=False, default=str)
75
+ return True
76
+ except Exception as e:
77
+ logger.error(f"Error saving {file_path}: {e}")
78
+ return False
79
+
80
+ def chat_with_ai(self, message: str, history: List[List[str]]) -> Tuple[str, List[List[str]]]:
81
+ """Handle chat interaction with AI"""
82
+ if not message.strip():
83
+ return "", history
84
+
85
+ try:
86
+ # Use AI assistant if available, otherwise provide mock response
87
+ if self.ai_assistant:
88
+ response = self.ai_assistant.process_query(message)
89
+ ai_response = response.get('response', 'Sorry, I could not process your request.')
90
+ else:
91
+ # Mock AI response for demo purposes
92
+ ai_response = self._generate_mock_response(message)
93
+
94
+ # Update history
95
+ history.append([message, ai_response])
96
+
97
+ # Save chat history
98
+ self.chat_history = history
99
+ self._save_json(self.chat_history_file, history)
100
+
101
+ return "", history
102
+
103
+ except Exception as e:
104
+ logger.error(f"Error in chat: {e}")
105
+ error_response = f"Sorry, I encountered an error: {str(e)}"
106
+ history.append([message, error_response])
107
+ return "", history
108
+
109
+ def _generate_mock_response(self, message: str) -> str:
110
+ """Generate mock AI responses for demo purposes"""
111
+ message_lower = message.lower()
112
+
113
+ if any(word in message_lower for word in ['hello', 'hi', 'hey']):
114
+ return "Hello! I'm your AI Assistant. How can I help you today?"
115
+
116
+ elif any(word in message_lower for word in ['note', 'notes']):
117
+ return f"I can help you manage notes! You currently have {len(self.notes)} notes. Would you like to create a new note or view existing ones?"
118
+
119
+ elif any(word in message_lower for word in ['reminder', 'remind']):
120
+ return f"I can help you set reminders! You have {len(self.reminders)} active reminders. What would you like to be reminded about?"
121
+
122
+ elif any(word in message_lower for word in ['weather']):
123
+ return "I'd love to help with weather information! In a full deployment, I would connect to weather APIs to provide current conditions and forecasts."
124
+
125
+ elif any(word in message_lower for word in ['code', 'programming', 'python']):
126
+ return "I can help with coding! Here's a simple Python example:\n\n```python\ndef greet(name):\n return f'Hello, {name}!'\n\nprint(greet('World'))\n```\n\nWhat programming topic would you like help with?"
127
+
128
+ elif any(word in message_lower for word in ['help', 'what can you do']):
129
+ return """I'm your AI Assistant! Here's what I can help you with:
130
+
131
+ 🗨️ **Chat**: Have conversations and ask questions
132
+ 📝 **Notes**: Create, edit, and manage your notes
133
+ ⏰ **Reminders**: Set and manage time-based reminders
134
+ 📄 **Documents**: Upload and analyze documents
135
+ 📊 **System Info**: Monitor system performance
136
+ 💻 **Code Help**: Programming assistance and examples
137
+
138
+ Try asking me about any of these topics!"""
139
+
140
+ else:
141
+ return f"Thank you for your message: '{message}'. In a full deployment with AI integration, I would provide intelligent responses based on advanced language models. For now, I'm running in demo mode!"
142
+
143
+ def create_note(self, title: str, content: str) -> str:
144
+ """Create a new note"""
145
+ if not title.strip():
146
+ return "❌ Please provide a title for the note."
147
+
148
+ note = {
149
+ "id": len(self.notes) + 1,
150
+ "title": title.strip(),
151
+ "content": content.strip(),
152
+ "created_at": datetime.now().isoformat(),
153
+ "updated_at": datetime.now().isoformat()
154
+ }
155
+
156
+ self.notes.append(note)
157
+ self._save_json(self.notes_file, self.notes)
158
+
159
+ return f"✅ Note '{title}' created successfully!"
160
+
161
+ def get_notes_display(self) -> str:
162
+ """Get formatted display of all notes"""
163
+ if not self.notes:
164
+ return "📝 No notes found. Create your first note above!"
165
+
166
+ notes_text = f"📝 **Your Notes ({len(self.notes)} total)**\n\n"
167
+
168
+ for note in sorted(self.notes, key=lambda x: x['created_at'], reverse=True):
169
+ created = datetime.fromisoformat(note['created_at']).strftime("%Y-%m-%d %H:%M")
170
+ notes_text += f"**{note['title']}**\n"
171
+ notes_text += f"*Created: {created}*\n"
172
+ notes_text += f"{note['content'][:200]}{'...' if len(note['content']) > 200 else ''}\n"
173
+ notes_text += "---\n"
174
+
175
+ return notes_text
176
+
177
+ def delete_note(self, note_title: str) -> Tuple[str, str]:
178
+ """Delete a note by title"""
179
+ if not note_title.strip():
180
+ return "❌ Please provide a note title to delete.", self.get_notes_display()
181
+
182
+ original_count = len(self.notes)
183
+ self.notes = [note for note in self.notes if note['title'].lower() != note_title.lower().strip()]
184
+
185
+ if len(self.notes) < original_count:
186
+ self._save_json(self.notes_file, self.notes)
187
+ return f"✅ Note '{note_title}' deleted successfully!", self.get_notes_display()
188
+ else:
189
+ return f"❌ Note '{note_title}' not found.", self.get_notes_display()
190
+
191
+ def create_reminder(self, title: str, description: str, reminder_time: str) -> str:
192
+ """Create a new reminder"""
193
+ if not title.strip():
194
+ return "❌ Please provide a title for the reminder."
195
+
196
+ try:
197
+ # Parse the reminder time (expecting format like "2024-12-25 14:30")
198
+ if reminder_time:
199
+ reminder_datetime = datetime.fromisoformat(reminder_time.replace('T', ' '))
200
+ else:
201
+ reminder_datetime = datetime.now() + timedelta(hours=1) # Default to 1 hour from now
202
+
203
+ reminder = {
204
+ "id": len(self.reminders) + 1,
205
+ "title": title.strip(),
206
+ "description": description.strip(),
207
+ "reminder_time": reminder_datetime.isoformat(),
208
+ "created_at": datetime.now().isoformat(),
209
+ "completed": False
210
+ }
211
+
212
+ self.reminders.append(reminder)
213
+ self._save_json(self.reminders_file, self.reminders)
214
+
215
+ return f"✅ Reminder '{title}' set for {reminder_datetime.strftime('%Y-%m-%d %H:%M')}!"
216
+
217
+ except ValueError:
218
+ return "❌ Invalid time format. Please use YYYY-MM-DD HH:MM format."
219
+
220
+ def get_reminders_display(self) -> str:
221
+ """Get formatted display of all reminders"""
222
+ if not self.reminders:
223
+ return "⏰ No reminders found. Create your first reminder above!"
224
+
225
+ active_reminders = [r for r in self.reminders if not r.get('completed', False)]
226
+ completed_reminders = [r for r in self.reminders if r.get('completed', False)]
227
+
228
+ reminders_text = f"⏰ **Your Reminders**\n\n"
229
+
230
+ if active_reminders:
231
+ reminders_text += f"**Active Reminders ({len(active_reminders)})**\n\n"
232
+ for reminder in sorted(active_reminders, key=lambda x: x['reminder_time']):
233
+ reminder_time = datetime.fromisoformat(reminder['reminder_time']).strftime("%Y-%m-%d %H:%M")
234
+ reminders_text += f"**{reminder['title']}**\n"
235
+ reminders_text += f"*Time: {reminder_time}*\n"
236
+ if reminder['description']:
237
+ reminders_text += f"{reminder['description']}\n"
238
+ reminders_text += "---\n"
239
+
240
+ if completed_reminders:
241
+ reminders_text += f"\n**Completed Reminders ({len(completed_reminders)})**\n\n"
242
+ for reminder in completed_reminders[-5:]: # Show last 5 completed
243
+ reminder_time = datetime.fromisoformat(reminder['reminder_time']).strftime("%Y-%m-%d %H:%M")
244
+ reminders_text += f"~~{reminder['title']}~~ ✅\n"
245
+
246
+ return reminders_text
247
+
248
+ def complete_reminder(self, reminder_title: str) -> Tuple[str, str]:
249
+ """Mark a reminder as completed"""
250
+ if not reminder_title.strip():
251
+ return "❌ Please provide a reminder title to complete.", self.get_reminders_display()
252
+
253
+ for reminder in self.reminders:
254
+ if reminder['title'].lower() == reminder_title.lower().strip():
255
+ reminder['completed'] = True
256
+ self._save_json(self.reminders_file, self.reminders)
257
+ return f"✅ Reminder '{reminder_title}' marked as completed!", self.get_reminders_display()
258
+
259
+ return f"❌ Reminder '{reminder_title}' not found.", self.get_reminders_display()
260
+
261
+ def process_document(self, file) -> str:
262
+ """Process uploaded document"""
263
+ if file is None:
264
+ return "❌ Please upload a file."
265
+
266
+ try:
267
+ # Get file info
268
+ file_path = Path(file.name)
269
+ file_size = os.path.getsize(file.name)
270
+ file_extension = file_path.suffix.lower()
271
+
272
+ # Copy file to documents directory
273
+ dest_path = self.documents_dir / f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{file_path.name}"
274
+ shutil.copy2(file.name, dest_path)
275
+
276
+ # Read file content based on type
277
+ content_preview = ""
278
+ if file_extension in ['.txt', '.md']:
279
+ with open(file.name, 'r', encoding='utf-8') as f:
280
+ content = f.read()
281
+ content_preview = content[:500] + "..." if len(content) > 500 else content
282
+ elif file_extension == '.pdf':
283
+ content_preview = "PDF file uploaded successfully. In a full deployment, I would extract and analyze the PDF content."
284
+ else:
285
+ content_preview = f"File type {file_extension} uploaded successfully."
286
+
287
+ # Generate analysis (mock for demo)
288
+ analysis = f"""📄 **Document Analysis**
289
+
290
+ **File:** {file_path.name}
291
+ **Size:** {file_size:,} bytes
292
+ **Type:** {file_extension}
293
+ **Uploaded:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
294
+
295
+ **Content Preview:**
296
+ {content_preview}
297
+
298
+ **AI Analysis:**
299
+ This document appears to contain {len(content_preview.split())} words. In a full deployment with AI integration, I would provide:
300
+ - Detailed content summary
301
+ - Key topics and themes
302
+ - Extracted insights
303
+ - Question-answering capabilities
304
+ - Content categorization
305
+
306
+ The document has been saved and can be referenced in future conversations!"""
307
+
308
+ return analysis
309
+
310
+ except Exception as e:
311
+ logger.error(f"Error processing document: {e}")
312
+ return f"❌ Error processing document: {str(e)}"
313
+
314
+ def get_system_info(self) -> str:
315
+ """Get system information"""
316
+ try:
317
+ import psutil
318
+ import platform
319
+
320
+ # Get system info
321
+ cpu_percent = psutil.cpu_percent(interval=1)
322
+ memory = psutil.virtual_memory()
323
+ disk = psutil.disk_usage('/')
324
+
325
+ system_info = f"""💻 **System Information**
326
+
327
+ **Platform:** {platform.system()} {platform.release()}
328
+ **Python:** {platform.python_version()}
329
+ **Architecture:** {platform.machine()}
330
+
331
+ **Performance Metrics:**
332
+ - **CPU Usage:** {cpu_percent}%
333
+ - **Memory Usage:** {memory.percent}% ({memory.used // (1024**3):.1f}GB / {memory.total // (1024**3):.1f}GB)
334
+ - **Disk Usage:** {disk.percent}% ({disk.used // (1024**3):.1f}GB / {disk.total // (1024**3):.1f}GB)
335
+
336
+ **Application Status:**
337
+ - **Notes:** {len(self.notes)} stored
338
+ - **Reminders:** {len([r for r in self.reminders if not r.get('completed', False)])} active
339
+ - **Chat History:** {len(self.chat_history)} messages
340
+ - **Documents:** {len(list(self.documents_dir.glob('*')))} files
341
+
342
+ *Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*"""
343
+
344
+ return system_info
345
+
346
+ except ImportError:
347
+ return """💻 **System Information**
348
+
349
+ *System monitoring requires psutil package*
350
+
351
+ **Application Status:**
352
+ - **Notes:** {len(self.notes)} stored
353
+ - **Reminders:** {len([r for r in self.reminders if not r.get('completed', False)])} active
354
+ - **Chat History:** {len(self.chat_history)} messages
355
+
356
+ *Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*"""
357
+ except Exception as e:
358
+ return f"❌ Error getting system info: {str(e)}"
359
+
360
+ def create_gradio_interface():
361
+ """Create and configure the Gradio interface"""
362
+
363
+ # Initialize the AI Assistant
364
+ assistant = GradioAIAssistant()
365
+
366
+ # Custom CSS for better styling
367
+ custom_css = """
368
+ .gradio-container {
369
+ max-width: 1200px !important;
370
+ }
371
+ .tab-nav {
372
+ background: linear-gradient(90deg, #0ea5e9, #3b82f6) !important;
373
+ }
374
+ .tab-nav button {
375
+ color: white !important;
376
+ }
377
+ .tab-nav button.selected {
378
+ background: rgba(255,255,255,0.2) !important;
379
+ }
380
+ """
381
+
382
+ # Create the main interface
383
+ with gr.Blocks(
384
+ title="AI Assistant - Your Intelligent Companion",
385
+ theme=gr.themes.Soft(),
386
+ css=custom_css
387
+ ) as app:
388
+
389
+ gr.Markdown("""
390
+ # 🤖 AI Assistant - Your Intelligent Companion
391
+
392
+ Welcome to your personal AI Assistant! This application combines chat, notes, reminders, document processing, and system monitoring in one place.
393
+
394
+ **Features:**
395
+ - 💬 **Smart Chat**: Intelligent conversations and assistance
396
+ - 📝 **Notes**: Create and manage your notes
397
+ - ⏰ **Reminders**: Set time-based notifications
398
+ - 📄 **Documents**: Upload and analyze files
399
+ - 💻 **System**: Monitor performance metrics
400
+ """)
401
+
402
+ with gr.Tabs():
403
+
404
+ # Chat Tab
405
+ with gr.Tab("💬 Chat", id="chat"):
406
+ gr.Markdown("### Chat with your AI Assistant")
407
+
408
+ chatbot = gr.Chatbot(
409
+ value=assistant.chat_history,
410
+ height=400,
411
+ show_label=False,
412
+ container=True,
413
+ bubble_full_width=False
414
+ )
415
+
416
+ with gr.Row():
417
+ msg_input = gr.Textbox(
418
+ placeholder="Type your message here...",
419
+ show_label=False,
420
+ scale=4,
421
+ container=False
422
+ )
423
+ send_btn = gr.Button("Send", variant="primary", scale=1)
424
+
425
+ gr.Examples(
426
+ examples=[
427
+ "Hello! How can you help me?",
428
+ "What can you do?",
429
+ "Help me with Python code",
430
+ "Tell me about my notes",
431
+ "What reminders do I have?",
432
+ "Explain machine learning",
433
+ ],
434
+ inputs=msg_input
435
+ )
436
+
437
+ # Chat functionality
438
+ msg_input.submit(
439
+ assistant.chat_with_ai,
440
+ inputs=[msg_input, chatbot],
441
+ outputs=[msg_input, chatbot]
442
+ )
443
+ send_btn.click(
444
+ assistant.chat_with_ai,
445
+ inputs=[msg_input, chatbot],
446
+ outputs=[msg_input, chatbot]
447
+ )
448
+
449
+ # Notes Tab
450
+ with gr.Tab("📝 Notes", id="notes"):
451
+ gr.Markdown("### Manage Your Notes")
452
+
453
+ with gr.Row():
454
+ with gr.Column(scale=1):
455
+ gr.Markdown("#### Create New Note")
456
+ note_title = gr.Textbox(label="Title", placeholder="Enter note title...")
457
+ note_content = gr.Textbox(
458
+ label="Content",
459
+ placeholder="Enter note content...",
460
+ lines=5
461
+ )
462
+ create_note_btn = gr.Button("Create Note", variant="primary")
463
+ create_note_status = gr.Textbox(label="Status", interactive=False)
464
+
465
+ gr.Markdown("#### Delete Note")
466
+ delete_title = gr.Textbox(label="Note Title to Delete", placeholder="Enter exact title...")
467
+ delete_note_btn = gr.Button("Delete Note", variant="secondary")
468
+ delete_note_status = gr.Textbox(label="Delete Status", interactive=False)
469
+
470
+ with gr.Column(scale=2):
471
+ gr.Markdown("#### Your Notes")
472
+ notes_display = gr.Markdown(value=assistant.get_notes_display())
473
+ refresh_notes_btn = gr.Button("Refresh Notes", variant="secondary")
474
+
475
+ # Notes functionality
476
+ create_note_btn.click(
477
+ assistant.create_note,
478
+ inputs=[note_title, note_content],
479
+ outputs=create_note_status
480
+ ).then(
481
+ lambda: ("", ""),
482
+ outputs=[note_title, note_content]
483
+ ).then(
484
+ assistant.get_notes_display,
485
+ outputs=notes_display
486
+ )
487
+
488
+ delete_note_btn.click(
489
+ assistant.delete_note,
490
+ inputs=delete_title,
491
+ outputs=[delete_note_status, notes_display]
492
+ ).then(
493
+ lambda: "",
494
+ outputs=delete_title
495
+ )
496
+
497
+ refresh_notes_btn.click(
498
+ assistant.get_notes_display,
499
+ outputs=notes_display
500
+ )
501
+
502
+ # Reminders Tab
503
+ with gr.Tab("⏰ Reminders", id="reminders"):
504
+ gr.Markdown("### Manage Your Reminders")
505
+
506
+ with gr.Row():
507
+ with gr.Column(scale=1):
508
+ gr.Markdown("#### Create New Reminder")
509
+ reminder_title = gr.Textbox(label="Title", placeholder="Enter reminder title...")
510
+ reminder_desc = gr.Textbox(
511
+ label="Description",
512
+ placeholder="Enter reminder description...",
513
+ lines=3
514
+ )
515
+ reminder_time = gr.Textbox(
516
+ label="Time (YYYY-MM-DD HH:MM)",
517
+ placeholder="2024-12-25 14:30",
518
+ info="Leave empty for 1 hour from now"
519
+ )
520
+ create_reminder_btn = gr.Button("Create Reminder", variant="primary")
521
+ create_reminder_status = gr.Textbox(label="Status", interactive=False)
522
+
523
+ gr.Markdown("#### Complete Reminder")
524
+ complete_title = gr.Textbox(label="Reminder Title to Complete", placeholder="Enter exact title...")
525
+ complete_reminder_btn = gr.Button("Complete Reminder", variant="secondary")
526
+ complete_reminder_status = gr.Textbox(label="Complete Status", interactive=False)
527
+
528
+ with gr.Column(scale=2):
529
+ gr.Markdown("#### Your Reminders")
530
+ reminders_display = gr.Markdown(value=assistant.get_reminders_display())
531
+ refresh_reminders_btn = gr.Button("Refresh Reminders", variant="secondary")
532
+
533
+ # Reminders functionality
534
+ create_reminder_btn.click(
535
+ assistant.create_reminder,
536
+ inputs=[reminder_title, reminder_desc, reminder_time],
537
+ outputs=create_reminder_status
538
+ ).then(
539
+ lambda: ("", "", ""),
540
+ outputs=[reminder_title, reminder_desc, reminder_time]
541
+ ).then(
542
+ assistant.get_reminders_display,
543
+ outputs=reminders_display
544
+ )
545
+
546
+ complete_reminder_btn.click(
547
+ assistant.complete_reminder,
548
+ inputs=complete_title,
549
+ outputs=[complete_reminder_status, reminders_display]
550
+ ).then(
551
+ lambda: "",
552
+ outputs=complete_title
553
+ )
554
+
555
+ refresh_reminders_btn.click(
556
+ assistant.get_reminders_display,
557
+ outputs=reminders_display
558
+ )
559
+
560
+ # Documents Tab
561
+ with gr.Tab("📄 Documents", id="documents"):
562
+ gr.Markdown("### Document Processing")
563
+
564
+ with gr.Row():
565
+ with gr.Column(scale=1):
566
+ gr.Markdown("#### Upload Document")
567
+ file_upload = gr.File(
568
+ label="Choose File",
569
+ file_types=[".txt", ".md", ".pdf"],
570
+ type="filepath"
571
+ )
572
+ process_btn = gr.Button("Process Document", variant="primary")
573
+
574
+ with gr.Column(scale=2):
575
+ gr.Markdown("#### Document Analysis")
576
+ doc_analysis = gr.Markdown(value="Upload a document to see analysis here...")
577
+
578
+ # Document processing functionality
579
+ process_btn.click(
580
+ assistant.process_document,
581
+ inputs=file_upload,
582
+ outputs=doc_analysis
583
+ )
584
+
585
+ file_upload.change(
586
+ assistant.process_document,
587
+ inputs=file_upload,
588
+ outputs=doc_analysis
589
+ )
590
+
591
+ # System Tab
592
+ with gr.Tab("💻 System", id="system"):
593
+ gr.Markdown("### System Information")
594
+
595
+ system_display = gr.Markdown(value=assistant.get_system_info())
596
+ refresh_system_btn = gr.Button("Refresh System Info", variant="primary")
597
+
598
+ refresh_system_btn.click(
599
+ assistant.get_system_info,
600
+ outputs=system_display
601
+ )
602
+
603
+ # Auto-refresh every 30 seconds
604
+ app.load(
605
+ assistant.get_system_info,
606
+ outputs=system_display,
607
+ every=30
608
+ )
609
+
610
+ gr.Markdown("""
611
+ ---
612
+
613
+ **About this AI Assistant:**
614
+ - Built with Gradio for easy deployment on Hugging Face Spaces
615
+ - Combines chat, notes, reminders, document processing, and system monitoring
616
+ - Data is stored locally and persists between sessions
617
+ - Designed for both personal use and demonstration purposes
618
+
619
+ **Deployment Ready:** This application can be easily deployed to Hugging Face Spaces, Streamlit Cloud, or any Python hosting platform.
620
+ """)
621
+
622
+ return app
623
+
624
+ if __name__ == "__main__":
625
+ # Create and launch the Gradio app
626
+ app = create_gradio_interface()
627
+
628
+ # Launch with appropriate settings
629
+ app.launch(
630
+ server_name="0.0.0.0", # Allow external access
631
+ server_port=7860, # Standard Gradio port
632
+ share=False, # Set to True for public sharing
633
+ debug=True, # Enable debug mode
634
+ show_error=True, # Show detailed errors
635
+ quiet=False # Show startup logs
636
+ )
requirements.txt ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core dependencies for Gradio AI Assistant
2
+ gradio>=4.0.0
3
+ python-dotenv>=1.0.0
4
+ requests>=2.31.0
5
+
6
+ # AI and ML libraries
7
+ google-generativeai>=0.3.0
8
+ openai>=1.0.0
9
+
10
+ # Data processing
11
+ pandas>=2.0.0
12
+ numpy>=1.24.0
13
+
14
+ # File processing
15
+ PyPDF2>=3.0.0
16
+ python-docx>=0.8.11
17
+ markdown>=3.5.0
18
+
19
+ # System monitoring
20
+ psutil>=5.9.0
21
+
22
+ # Audio processing (optional)
23
+ SpeechRecognition>=3.10.0
24
+ pyttsx3>=2.90
25
+
26
+ # Web scraping (optional)
27
+ beautifulsoup4>=4.12.0
28
+ requests-html>=0.10.0
29
+
30
+ # Database (optional)
31
+ sqlite3
32
+
33
+ # Utilities
34
+ python-dateutil>=2.8.0
35
+ pytz>=2023.3
36
+
37
+ # Development tools (optional)
38
+ black>=23.0.0
39
+ flake8>=6.0.0