File size: 4,253 Bytes
c110c9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Startup script to ensure all required files are available before running the main app
"""
import os
import sys
import subprocess
import urllib.request
import zipfile
import geopandas as gpd
from pathlib import Path

def ensure_shapefile_exists():
    """Ensure the India State Boundary shapefile exists"""
    shapefile_path = "shapefiles/India_State_Boundary.shp"
    
    if os.path.exists(shapefile_path):
        print(f"βœ“ Shapefile found at {shapefile_path}")
        return True
    
    print(f"βœ— Shapefile not found at {shapefile_path}")
    
    # Try to pull from git lfs if available
    try:
        if os.path.exists(".git"):
            print("Attempting to pull LFS files...")
            result = subprocess.run(["git", "lfs", "pull"], capture_output=True, text=True)
            if result.returncode == 0 and os.path.exists(shapefile_path):
                print("βœ“ Successfully pulled LFS files")
                return True
            else:
                print("βœ— Git LFS pull failed or file still missing")
    except Exception as e:
        print(f"βœ— Git LFS not available: {e}")
    
    # Download alternative shapefile
    print("Downloading alternative India boundary data...")
    try:
        # Create shapefiles directory
        os.makedirs("shapefiles", exist_ok=True)
        
        # Download from Natural Earth (reliable source)
        url = "https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/50m/cultural/ne_50m_admin_0_countries.zip"
        zip_path = "temp_countries.zip"
        
        print("Downloading Natural Earth country boundaries...")
        urllib.request.urlretrieve(url, zip_path)
        
        # Extract
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall("temp_extract")
        
        # Load and filter for India
        world_data = gpd.read_file("temp_extract/ne_50m_admin_0_countries.shp")
        india_data = world_data[world_data['NAME'] == 'India']
        
        if len(india_data) == 0:
            # Try alternative name matching
            india_data = world_data[world_data['NAME_EN'] == 'India']
        
        if len(india_data) > 0:
            # Save as our expected shapefile
            india_data.to_file(shapefile_path)
            print(f"βœ“ Successfully created {shapefile_path}")
        else:
            raise Exception("Could not find India in the world data")
        
        # Cleanup
        os.remove(zip_path)
        import shutil
        shutil.rmtree("temp_extract", ignore_errors=True)
        
        return True
        
    except Exception as e:
        print(f"βœ— Failed to download alternative shapefile: {e}")
        
        # Create a simple fallback
        print("Creating fallback boundary...")
        try:
            from shapely.geometry import Polygon
            
            # Simple India bounding box
            india_bounds = [68.0, 6.0, 97.5, 37.0]  # [min_lon, min_lat, max_lon, max_lat]
            
            polygon = Polygon([
                (india_bounds[0], india_bounds[1]),  # SW
                (india_bounds[2], india_bounds[1]),  # SE  
                (india_bounds[2], india_bounds[3]),  # NE
                (india_bounds[0], india_bounds[3]),  # NW
                (india_bounds[0], india_bounds[1])   # Close
            ])
            
            gdf = gpd.GeoDataFrame([1], geometry=[polygon], crs="EPSG:4326")
            gdf['NAME'] = 'India'
            gdf.to_file(shapefile_path)
            
            print(f"βœ“ Created fallback boundary at {shapefile_path}")
            return True
            
        except Exception as e2:
            print(f"βœ— Failed to create fallback: {e2}")
            return False

if __name__ == "__main__":
    print("πŸš€ Starting CAMS Pollution Dashboard...")
    print("Checking required files...")
    
    if ensure_shapefile_exists():
        print("βœ“ All required files are ready")
        print("Starting Flask application...")
        
        # Import and run the main app
        from app import app
        app.run(host='0.0.0.0', port=7860, debug=False)
    else:
        print("βœ— Failed to ensure required files exist")
        sys.exit(1)