CoolFace
Apppublic

meladeayol/Road_Segmentation_with_Depth_Estimation

sourceHugging Faceapache-2.0updated 1y agoView on Hugging Face
0likes
setup.py283 linesDownload Raw Back to root
1#!/usr/bin/env python32"""3Setup script for the Semantic Segmentation Gradio App4This script helps install dependencies and set up the environment5"""6 7import subprocess8import sys9import os10from pathlib import Path11 12def run_command(command, description):13    """Run a command and handle errors."""14    print(f"\n๐Ÿ”„ {description}...")15    try:16        result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)17        print(f"โœ… {description} completed successfully")18        return True19    except subprocess.CalledProcessError as e:20        print(f"โŒ Error during {description}:")21        print(f"Command: {command}")22        print(f"Error: {e.stderr}")23        return False24 25def check_python_version():26    """Check if Python version is compatible."""27    version = sys.version_info28    if version.major < 3 or (version.major == 3 and version.minor < 8):29        print("โŒ Python 3.8 or higher is required")30        sys.exit(1)31    print(f"โœ… Python {version.major}.{version.minor}.{version.micro} detected")32 33def install_dependencies():34    """Install required dependencies."""35    requirements = [36        "gradio>=4.0.0",37        "torch>=1.9.0",38        "torchvision>=0.10.0", 39        "transformers>=4.21.0",40        "pillow>=8.0.0",41        "numpy>=1.21.0",42        "matplotlib>=3.5.0",43        "requests>=2.25.0",44    ]45    46    print("\n๐Ÿ“ฆ Installing dependencies...")47    for req in requirements:48        if not run_command(f"pip install {req}", f"Installing {req.split('>=')[0]}"):49            return False50    return True51 52def create_directory_structure():53    """Create necessary directories."""54    directories = [55        "src",56        "src/models",57        "sample_images",58        "outputs"59    ]60    61    for directory in directories:62        Path(directory).mkdir(parents=True, exist_ok=True)63        print(f"๐Ÿ“ Created directory: {directory}")64 65def download_sample_images():66    """Download some sample images for testing."""67    import requests68    from PIL import Image69    import io70    71    sample_urls = {72        "street_scene_1.jpg": "https://images.unsplash.com/photo-1449824913935-59a10b8d2000?w=800",73        "street_scene_2.jpg": "https://images.unsplash.com/photo-1502920917128-1aa500764cbd?w=800",74        "urban_road.jpg": "https://images.unsplash.com/photo-1516738901171-8eb4fc13bd20?w=800",75    }76    77    sample_dir = Path("sample_images")78    sample_dir.mkdir(exist_ok=True)79    80    print("\n๐Ÿ–ผ๏ธ Downloading sample images...")81    for filename, url in sample_urls.items():82        try:83            response = requests.get(url, timeout=30)84            response.raise_for_status()85            86            image = Image.open(io.BytesIO(response.content))87            image_path = sample_dir / filename88            image.save(image_path)89            print(f"โœ… Downloaded: {filename}")90            91        except Exception as e:92            print(f"โš ๏ธ Failed to download {filename}: {e}")93 94def create_launch_script():95    """Create a simple launch script."""96    launch_script = '''#!/usr/bin/env python397"""98Launch script for the Semantic Segmentation App99"""100 101import sys102import os103 104# Add the current directory to the path105sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))106 107# Import and run the app108try:109    from complete_gradio_app import create_gradio_interface110    import torch111    112    print("๐Ÿš€ Starting Semantic Segmentation App...")113    print("๐Ÿ’ป Device:", "CUDA" if torch.cuda.is_available() else "CPU")114    115    demo = create_gradio_interface()116    demo.launch(117        share=True,118        debug=True,119        server_name="0.0.0.0",120        server_port=7860121    )122    123except ImportError as e:124    print(f"โŒ Import error: {e}")125    print("Please make sure all dependencies are installed by running: python setup.py")126    127except Exception as e:128    print(f"โŒ Error starting app: {e}")129'''130    131    with open("launch_app.py", "w") as f:132        f.write(launch_script)133    134    # Make it executable on Unix systems135    if os.name != 'nt':136        os.chmod("launch_app.py", 0o755)137    138    print("โœ… Created launch script: launch_app.py")139 140def create_readme():141    """Create a README file with usage instructions."""142    readme_content = '''# Semantic Segmentation Gradio App143 144A user-friendly web interface for semantic segmentation using OneFormer and Mask2Former models.145 146## ๐Ÿš€ Quick Start147 1481. **Install dependencies:**149   ```bash150   python setup.py151   ```152 1532. **Launch the app:**154   ```bash155   python launch_app.py156   ```157   158   Or run directly:159   ```bash160   python complete_gradio_app.py161   ```162 1633. **Open your browser** and go to the provided local URL (usually http://localhost:7860)164 165## ๐Ÿ“‹ Requirements166 167- Python 3.8+168- CUDA-compatible GPU (optional, but recommended)169- At least 8GB RAM170- Internet connection (for model downloads)171 172## ๐ŸŽฏ Features173 174- **Two State-of-the-Art Models:**175  - OneFormer: Universal segmentation (semantic, instance, panoptic)176  - Mask2Former: High-accuracy semantic segmentation177 178- **User-Friendly Interface:**179  - Upload custom images180  - Select from sample images181  - Adjustable overlay transparency182  - Real-time processing183 184- **Professional Output:**185  - Colored segmentation overlays186  - Detailed class statistics187  - High-quality visualizations188 189## ๐Ÿ”ง Troubleshooting190 191### Common Issues:192 1931. **CUDA out of memory:**194   - Reduce image size195   - Use CPU instead of GPU196 1972. **Model download fails:**198   - Check internet connection199   - Try again (models are large ~1-2GB each)200 2013. **ImportError:**202   - Run `python setup.py` again203   - Check Python version (3.8+ required)204 205### Performance Tips:206 207- First model load takes time (downloading from HuggingFace)208- GPU acceleration significantly speeds up processing209- Images are automatically resized to prevent memory issues210 211## ๐Ÿ“Š Supported Classes212 213The models are trained on Cityscapes dataset and can recognize:214- Road, sidewalk, building, wall, fence215- Traffic light, traffic sign, pole216- Vegetation, terrain, sky217- Person, rider, car, truck, bus, train, motorcycle, bicycle218 219## ๐ŸŽจ Color Coding220 221Each class is visualized with a specific color following Cityscapes conventions:222- Road: Dark purple223- Sky: Steel blue  224- Person: Crimson225- Car: Dark blue226- Vegetation: Olive green227- And more...228 229## ๐Ÿ“„ License230 231This project uses pre-trained models from HuggingFace:232- OneFormer: [Model License](https://huggingface.co/shi-labs/oneformer_cityscapes_swin_large)233- Mask2Former: [Model License](https://huggingface.co/facebook/mask2former-swin-large-cityscapes-semantic)234 235## ๐Ÿค Contributing236 237Feel free to submit issues and enhancement requests!238'''239    240    with open("README.md", "w") as f:241        f.write(readme_content)242    243    print("โœ… Created README.md")244 245def main():246    """Main setup function."""247    print("๐ŸŽฏ Semantic Segmentation App Setup")248    print("=" * 50)249    250    # Check Python version251    check_python_version()252    253    # Create directory structure254    create_directory_structure()255    256    # Install dependencies257    if not install_dependencies():258        print("\nโŒ Failed to install some dependencies. Please check the errors above.")259        return False260    261    # Download sample images262    try:263        download_sample_images()264    except Exception as e:265        print(f"โš ๏ธ Warning: Could not download sample images: {e}")266    267    # Create launch script268    create_launch_script()269    270    # Create README271    create_readme()272    273    print("\n" + "=" * 50)274    print("โœ… Setup completed successfully!")275    print("\n๐Ÿš€ To launch the app, run:")276    print("   python launch_app.py")277    print("\n๐Ÿ“š For more information, see README.md")278    279    return True280 281if __name__ == "__main__":282    success = main()283    sys.exit(0 if success else 1)