File size: 10,304 Bytes
338d95d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
CompI Phase 3 Final Dashboard Launcher

Launch the complete Phase 3 integrated dashboard that combines ALL CompI features:

Phase 3.A/3.B: True multimodal fusion with real processing
- Real audio transcription and analysis
- Actual data processing and visualization  
- Sentiment analysis and emotion detection
- Live real-time data feeds (weather, news)

Phase 3.C: Advanced references with role assignment
- Multi-image upload and URL support
- Style vs structure role assignment
- Live ControlNet previews (Canny/Depth)
- Hybrid CN+I2I generation modes

Phase 3.D: Professional workflow management
- Gallery with advanced filtering
- Rating, tagging, and annotation system
- Preset save/load functionality
- Complete export bundles with metadata

Phase 3.E: Performance management and model switching
- SD 1.5 ↔ SDXL model switching
- LoRA integration with scale control
- Performance optimizations (xFormers, attention slicing, VAE)
- VRAM monitoring and OOM auto-retry
- Optional latent upscaling

Usage:
    python run_phase3_final_dashboard.py
    
    or
    
    streamlit run src/ui/compi_phase3_final_dashboard.py --server.port 8506
"""

import os
import sys
import subprocess
from pathlib import Path

def check_dependencies():
    """Check for required dependencies"""
    print("πŸ“¦ Checking dependencies...")

    required_packages = {
        "torch": "PyTorch",
        "diffusers": "Diffusers",
        "transformers": "Transformers",
        "accelerate": "Accelerate",
        "streamlit": "Streamlit",
        "pillow": "Pillow (PIL)",
        "numpy": "NumPy",
        "pandas": "Pandas",
        "librosa": "Librosa (audio processing)",
        "matplotlib": "Matplotlib (plotting)",
        "requests": "Requests (HTTP)",
        "feedparser": "FeedParser (RSS feeds)",
        "textblob": "TextBlob (sentiment analysis)"
    }

    # Special check for OpenCV (accept either opencv-python or opencv-python-headless)
    opencv_available = False
    try:
        import cv2
        opencv_available = True
        required_packages["cv2"] = "OpenCV (image processing)"
    except ImportError:
        pass

    missing_packages = []
    available_packages = []

    for package, name in required_packages.items():
        try:
            __import__(package.replace("-", "_"))
            available_packages.append(name)
        except ImportError:
            if package != "cv2":  # cv2 already checked above
                missing_packages.append(package)

    # Add opencv to missing if not available
    if not opencv_available:
        missing_packages.append("opencv-python")

    print(f"βœ… Available: {', '.join(available_packages)}")

    if missing_packages:
        print(f"❌ Missing: {', '.join(missing_packages)}")
        return False

    return True

def check_optional_features():
    """Check for optional features"""
    print("\nπŸ” Checking optional features...")
    
    # Check Whisper
    try:
        import whisper
        print("βœ… Whisper available for audio transcription")
    except ImportError:
        print("⚠️  Whisper not available (will be installed on first use)")
    
    # Check SDXL availability
    try:
        from diffusers import StableDiffusionXLPipeline
        print("βœ… SDXL support available")
    except ImportError:
        print("⚠️  SDXL not available (requires newer diffusers)")
    
    # Check ControlNet availability
    try:
        from diffusers import StableDiffusionControlNetPipeline
        print("βœ… ControlNet available")
    except ImportError:
        print("⚠️  ControlNet not available")
    
    # Check upscaler availability
    try:
        from diffusers import StableDiffusionLatentUpscalePipeline
        print("βœ… Latent Upscaler available")
    except ImportError:
        print("⚠️  Latent Upscaler not available")
    
    # Check xFormers
    try:
        import xformers
        print("βœ… xFormers available for memory optimization")
    except ImportError:
        print("⚠️  xFormers not available (optional performance boost)")

def check_gpu_setup():
    """Check GPU setup and provide recommendations"""
    print("\nπŸ” Checking GPU setup...")
    
    try:
        import torch
        
        if torch.cuda.is_available():
            gpu_count = torch.cuda.device_count()
            gpu_name = torch.cuda.get_device_name(0)
            total_memory = torch.cuda.get_device_properties(0).total_memory / (1024**3)
            
            print(f"βœ… CUDA available: {gpu_count} GPU(s)")
            print(f"   Primary GPU: {gpu_name}")
            print(f"   VRAM: {total_memory:.1f} GB")
            
            if total_memory >= 12.0:
                print("βœ… Excellent VRAM for all features including SDXL")
            elif total_memory >= 8.0:
                print("βœ… Good VRAM for SDXL and most features")
            elif total_memory >= 6.0:
                print("βœ… Sufficient VRAM for SD 1.5 and most features")
                print("⚠️  SDXL may require optimizations")
            elif total_memory >= 4.0:
                print("βœ… Minimum VRAM for SD 1.5")
                print("⚠️  Use aggressive optimizations for best performance")
            else:
                print("⚠️  Limited VRAM - consider CPU mode or cloud GPU")
            
            return True
        else:
            print("⚠️  CUDA not available - will use CPU mode")
            print("πŸ’‘ CPU mode is slower but still functional")
            return False
            
    except ImportError:
        print("❌ PyTorch not found")
        return False

def install_missing_dependencies():
    """Install missing dependencies"""
    print("\nπŸ“¦ Installing missing dependencies...")
    
    try:
        # Core dependencies
        core_packages = [
            "torch", "torchvision", "torchaudio",
            "diffusers>=0.21.0", "transformers", "accelerate",
            "streamlit", "pillow", "numpy", "pandas",
            "librosa", "opencv-python", "matplotlib",
            "requests", "feedparser", "textblob"
        ]
        
        print("Installing core packages...")
        subprocess.check_call([
            sys.executable, "-m", "pip", "install"
        ] + core_packages)
        
        print("βœ… Core dependencies installed")
        
        # Optional performance packages (skip xformers due to compatibility issues)
        print("⚠️  Skipping xFormers installation (compatibility issues with current PyTorch version)")
        
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"❌ Installation failed: {e}")
        return False

def main():
    """Launch Phase 3 Final Dashboard"""
    
    print("πŸ§ͺ CompI Phase 3 Final Dashboard")
    print("=" * 80)
    print()
    print("🎯 Complete Phase 3 Integration (3.A β†’ 3.E):")
    print("  β€’ 🧩 Multimodal Inputs: Text, Audio, Data, Emotion, Real-time")
    print("  β€’ πŸ–ΌοΈ Advanced References: Role assignment, ControlNet, live previews")
    print("  β€’ βš™οΈ Model & Performance: SD 1.5/SDXL, LoRA, VRAM monitoring")
    print("  β€’ πŸŽ›οΈ Intelligent Generation: Hybrid modes, OOM recovery")
    print("  β€’ πŸ–ΌοΈ Professional Gallery: Filtering, rating, annotation")
    print("  β€’ πŸ’Ύ Preset Management: Save/load configurations")
    print("  β€’ πŸ“¦ Export System: Complete bundles with metadata")
    print()
    
    # Check if the UI file exists
    ui_file = Path("src/ui/compi_phase3_final_dashboard.py")
    if not ui_file.exists():
        print(f"❌ Error: {ui_file} not found!")
        print("Make sure you're running this from the project root directory.")
        return 1
    
    # Check dependencies
    if not check_dependencies():
        print("\n❌ Missing dependencies detected.")
        install = input("Install missing dependencies? (y/n): ").lower().strip()
        
        if install == 'y':
            if not install_missing_dependencies():
                print("❌ Failed to install dependencies")
                return 1
        else:
            print("❌ Cannot proceed without required dependencies")
            return 1
    
    # Check GPU setup
    has_gpu = check_gpu_setup()
    
    # Check optional features
    check_optional_features()
    
    print()
    print("πŸš€ Launching Phase 3 Final Dashboard...")
    print("πŸ“ Access at: http://localhost:8506")
    print()
    
    if has_gpu:
        print("πŸ’‘ GPU Tips:")
        print("  β€’ Monitor VRAM usage in the top metrics bar")
        print("  β€’ Use performance optimizations in Model & Performance tab")
        print("  β€’ Enable OOM auto-retry for reliability")
        print("  β€’ Try SDXL for higher quality (requires 8+ GB VRAM)")
    else:
        print("πŸ’‘ CPU Tips:")
        print("  β€’ Generation will be slower but still functional")
        print("  β€’ Use smaller image sizes (512x512 or less)")
        print("  β€’ Reduce inference steps for faster generation")
        print("  β€’ Stick to SD 1.5 model for best performance")
    
    print()
    print("🎨 Getting Started:")
    print("  1. 🧩 Configure multimodal inputs (audio, data, emotion, real-time)")
    print("  2. πŸ–ΌοΈ Upload reference images and assign roles (style vs structure)")
    print("  3. βš™οΈ Choose model and optimize performance settings")
    print("  4. πŸŽ›οΈ Generate with intelligent fusion of all inputs")
    print("  5. πŸ–ΌοΈ Review results in gallery and add annotations")
    print("  6. πŸ’Ύ Save presets for reuse")
    print("  7. πŸ“¦ Export complete bundles with metadata")
    print()
    
    # Launch Streamlit
    try:
        cmd = [
            sys.executable, "-m", "streamlit", "run",
            str(ui_file),
            "--server.port", "8506",
            "--server.headless", "true",
            "--browser.gatherUsageStats", "false"
        ]
        
        subprocess.run(cmd)
        
    except KeyboardInterrupt:
        print("\nπŸ‘‹ Phase 3 Final Dashboard stopped by user")
        return 0
    except Exception as e:
        print(f"❌ Error launching Streamlit: {e}")
        return 1
    
    return 0

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)