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 
 
 
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import os
import gradio as gr
import folium
from folium import plugins
import geopandas as gpd
import rasterio
from rasterio.warp import transform_bounds
import json
import tempfile
import shutil
import uuid
import logging
import traceback
import numpy as np
from PIL import Image

# Configure logging for HF Spaces
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[logging.StreamHandler()]
)
logger = logging.getLogger('forestai')

# ================================
# CONFIGURATIONS
# ================================

# Feature styles for trees only
FEATURE_STYLES = {
    'trees': {"color": "green", "fillColor": "yellow", "fillOpacity": 0.3, "weight": 2}
}

# Example file path
EXAMPLE_FILE_PATH = "example.tif"

# ================================
# TEMP DIRECTORY SETUP
# ================================

def setup_temp_dirs():
    """Create temporary directories."""
    temp_base = tempfile.mkdtemp(prefix="forestai_")
    dirs = {
        'uploads': os.path.join(temp_base, 'uploads'),
        'processed': os.path.join(temp_base, 'processed'),
        'static': os.path.join(temp_base, 'static')
    }
    
    for dir_path in dirs.values():
        os.makedirs(dir_path, exist_ok=True)
    
    return dirs

# Global temp directories
TEMP_DIRS = setup_temp_dirs()

# ================================
# CORE FUNCTIONS
# ================================

def get_bounds_from_geotiff(geotiff_path):
    """Extract bounds from GeoTIFF and convert to WGS84."""
    try:
        with rasterio.open(geotiff_path) as src:
            bounds = src.bounds
            if src.crs:
                west, south, east, north = transform_bounds(
                    src.crs, 'EPSG:4326',
                    bounds.left, bounds.bottom, bounds.right, bounds.top
                )
                return west, south, east, north
            else:
                return -74.1, 40.6, -73.9, 40.8
    except Exception as e:
        logger.error(f"Error extracting bounds: {str(e)}")
        return -74.1, 40.6, -73.9, 40.8

def create_split_view_map(geojson_data, bounds):
    """Create split-view map with detected trees."""
    try:
        west, south, east, north = bounds
        center = [(south + north) / 2, (west + east) / 2]
        
        # Calculate zoom level
        lat_diff = north - south
        lon_diff = east - west
        max_diff = max(lat_diff, lon_diff)
        
        if max_diff < 0.01:
            zoom = 16
        elif max_diff < 0.05:
            zoom = 14
        elif max_diff < 0.1:
            zoom = 12
        else:
            zoom = 10

        # Create base map
        m = folium.Map(location=center, zoom_start=zoom)

        # Create tile layers
        left_layer = folium.TileLayer(
            tiles='OpenStreetMap',
            name='OpenStreetMap',
            overlay=False,
            control=False
        )
        
        right_layer = folium.TileLayer(
            tiles='https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
            attr='Esri',
            name='Satellite',
            overlay=False,
            control=False
        )

        left_layer.add_to(m)
        right_layer.add_to(m)

        # Add detected trees
        if geojson_data and 'features' in geojson_data and geojson_data['features']:
            style = FEATURE_STYLES['trees']
            
            geojson_layer = folium.GeoJson(
                geojson_data,
                name='Detected Trees',
                style_function=lambda x: style,
                popup=folium.GeoJsonPopup(
                    fields=['confidence'] if 'confidence' in str(geojson_data) else [],
                    aliases=['Confidence:'] if 'confidence' in str(geojson_data) else [],
                    localize=True
                )
            )
            geojson_layer.add_to(m)

        # Add split view plugin
        plugins.SideBySideLayers(
            layer_left=left_layer,
            layer_right=right_layer
        ).add_to(m)

        # Add layer control
        folium.LayerControl().add_to(m)

        # Fit bounds
        m.fit_bounds([[south, west], [north, east]], padding=(20, 20))

        return m

    except Exception as e:
        logger.error(f"Error creating map: {str(e)}")
        # Return basic map on error
        m = folium.Map(location=[40.7, -74.0], zoom_start=10)
        return m

def process_image_file(image_file):
    """Process uploaded image file for tree detection."""
    if image_file is None:
        return None, "Please upload an image file or use the example file"

    try:
        # Create unique ID
        unique_id = str(uuid.uuid4().hex)[:8]
        
        # Handle file upload
        if hasattr(image_file, 'name'):
            filename = os.path.basename(image_file.name)
        else:
            filename = os.path.basename(image_file)

        # Save uploaded file
        image_path = os.path.join(TEMP_DIRS['uploads'], f"{unique_id}_{filename}")

        if hasattr(image_file, 'read'):
            file_content = image_file.read()
            with open(image_path, "wb") as f:
                f.write(file_content)
        else:
            shutil.copy(image_file, image_path)

        logger.info(f"File saved to {image_path}")

        # Check if it's a GeoTIFF file for advanced processing
        if filename.lower().endswith(('.tif', '.tiff')):
            # Use advanced extraction for GeoTIFF files
            from utils.advanced_extraction import extract_features_from_geotiff
            
            logger.info("Extracting tree features from GeoTIFF...")
            geojson_data = extract_features_from_geotiff(image_path, TEMP_DIRS['processed'], "trees")
        else:
            # Use general image processing for other formats
            from utils.geospatial import process_image_to_geojson
            from utils.image_processing import process_image
            
            logger.info("Processing regular image for tree detection...")
            processed_image_path = process_image(image_path, TEMP_DIRS['processed'])
            geojson_data = process_image_to_geojson(processed_image_path, feature_type="trees", original_file_path=image_path)

        if not geojson_data or not geojson_data.get('features'):
            return None, "No trees detected in the image"

        # Get bounds and create map
        if filename.lower().endswith(('.tif', '.tiff')):
            bounds = get_bounds_from_geotiff(image_path)
        else:
            # For regular images, use default bounds or extract from metadata
            bounds = get_bounds_from_geotiff(image_path)  # This will use defaults for non-GeoTIFF files
        
        map_obj = create_split_view_map(geojson_data, bounds)

        if map_obj:
            # Save map
            html_path = os.path.join(TEMP_DIRS['static'], f"map_{unique_id}.html")
            map_obj.save(html_path)

            # Read HTML content
            with open(html_path, 'r', encoding='utf-8') as f:
                html_content = f.read()

            # Create iframe
            iframe_html = f'''
            <div style="width:100%; height:600px; border:1px solid #ddd; border-radius:8px; overflow:hidden;">
                <iframe srcdoc="{html_content.replace('"', '&quot;')}"
                        width="100%" height="600px" style="border:none;"></iframe>
            </div>
            '''

            num_features = len(geojson_data['features'])
            return iframe_html, f"βœ… Detected {num_features} tree areas in {filename}"
        else:
            return None, "Failed to create map"
            
    except Exception as e:
        logger.error(f"Error processing file: {str(e)}")
        return None, f"❌ Error: {str(e)}"

def load_example_file():
    """Load the example.tif file and return it for processing."""
    try:
        if os.path.exists(EXAMPLE_FILE_PATH):
            logger.info("Loading example file...")
            return EXAMPLE_FILE_PATH
        else:
            logger.warning("Example file not found")
            return None
    except Exception as e:
        logger.error(f"Error loading example file: {str(e)}")
        return None

def process_example_file():
    """Process the example file and return results."""
    example_file = load_example_file()
    if example_file:
        return process_geotiff_file(example_file)
    else:
        return None, "❌ Example file (example.tif) not found in the root directory"

def check_example_file_exists():
    """Check if example file exists and return appropriate message."""
    if os.path.exists(EXAMPLE_FILE_PATH):
        return f"βœ… Example file found: {EXAMPLE_FILE_PATH}"
    else:
        return f"⚠️ Example file not found: {EXAMPLE_FILE_PATH}"

# ================================
# GRADIO INTERFACE
# ================================

def create_gradio_interface():
    """Create the Gradio interface for tree detection."""
    
    css = """
    .gradio-container {
        max-width: 100% !important;
        width: 100% !important;
        margin: 0 !important;
        padding: 10px !important;
    }
    .map-container {
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        width: 100% !important;
    }
    body {
        margin: 0 !important;
        padding: 0 !important;
    }
    .contain {
        max-width: none !important;
        padding: 0 !important;
    }
    .example-button {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%) !important;
        border: none !important;
        color: white !important;
    }
    """
    
    with gr.Blocks(title="🌲 ForestAI - Tree Detection", css=css, theme=gr.themes.Soft()) as app:
        
        # Simple header
        gr.HTML("""
        <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; margin-bottom: 20px;">
            <h1 style="color: white; margin: 0; font-size: 2.5em;">🌲 ForestAI</h1>
            <p style="color: white; margin: 10px 0 0 0; font-size: 1.2em;">Tree Detection from Satellite & Aerial Imagery</p>
        </div>
        """)

        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("### Upload GeoTIFF File")
                
                file_input = gr.File(
                    label="Select Image File",
                    file_types=[".tif", ".tiff", ".png", ".jpg", ".jpeg", ".bmp", ".gif"],
                    type="filepath"
                )
                
                with gr.Row():
                    analyze_btn = gr.Button(
                        "πŸ” Detect Trees", 
                        variant="primary",
                        size="lg",
                        scale=2
                    )
                    
                    example_btn = gr.Button(
                        "πŸ“ Use Example File",
                        variant="secondary",
                        size="lg",
                        scale=1,
                        elem_classes=["example-button"]
                    )
                
                # Example file status
                example_status = gr.Textbox(
                    label="Example File Status",
                    value=check_example_file_exists(),
                    interactive=False,
                    lines=1
                )
                
                gr.Markdown("### Status")
                status_output = gr.Textbox(
                    label="Processing Status",
                    interactive=False,
                    placeholder="Upload a file and click 'Detect Trees' or use the example file...",
                    lines=3
                )

            with gr.Column(scale=2):
                gr.Markdown("### Results Map")
                
                map_output = gr.HTML(
                    value='''
                    <div style="width:100%; height:600px; border:1px solid #ddd; border-radius:8px; 
                                display:flex; align-items:center; justify-content:center; 
                                background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);">
                        <div style="text-align:center; color:#666;">
                            <h3>🌲 Upload an image file or use example to see detected trees</h3>
                            <p>Interactive map will appear here</p>
                        </div>
                    </div>
                    ''',
                    elem_classes=["map-container"]
                )

        # Event handlers
        analyze_btn.click(
            fn=process_image_file,
            inputs=[file_input],
            outputs=[map_output, status_output],
            show_progress=True
        )
        
        example_btn.click(
            fn=process_example_file,
            inputs=[],
            outputs=[map_output, status_output],
            show_progress=True
        )

        # Simple instructions
        gr.Markdown("""
        ### How to Use:
        1. **Upload** an image file (GeoTIFF, PNG, JPG, etc.) OR click "Use Example File" to try with the included sample
        2. **Click** "Detect Trees" to analyze your uploaded image
        3. **Explore** the interactive map with detected tree areas
        4. **Use** the split-view slider to compare base map and satellite imagery

        ### Supported Formats:
        - **GeoTIFF (.tif, .tiff)**: Best for satellite imagery with geographic data
        - **Regular Images (.png, .jpg, .jpeg, .bmp, .gif)**: For general image analysis
        - **Processing**: GeoTIFF files use advanced NDVI analysis, other formats use general image processing

        ### Map Controls:
        - **Split View**: Drag the vertical slider to compare layers
        - **Zoom**: Scroll to zoom in/out, drag to pan
        - **Layers**: Use layer control to toggle trees on/off
        
        ### Example File:
        - The example file should be named `example.tif` and placed in the same directory as this application
        - Click "Use Example File" to quickly test the tree detection without uploading your own file
        """)

    return app

if __name__ == "__main__":
    logger.info("🌲 Starting ForestAI Tree Detection")
    app = create_gradio_interface()
    app.launch()