tree-volume / app.py
DynamicPacific
Integrate Meta CHM as primary data source and fix UI inconsistencies
706d150
Raw History Blame Contribute Delete
43 kB
import gradio as gr
import geopandas as gpd
import folium
import tempfile
import os
import math
import pandas as pd
import pyproj
import sys
import requests
import zipfile
from rasterstats import zonal_stats
import numpy as np
import logging
from chm_utils import estimate_volume_from_chm
from folium import plugins
import rasterio
from rasterio.warp import transform_bounds
from shapely.geometry import Point
import time
# 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('tree-volume')
# PDF Report Generation Imports
try:
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image, PageBreak
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import colors
REPORTLAB_AVAILABLE = True
except ImportError:
REPORTLAB_AVAILABLE = False
logger.warning("ReportLab not available - PDF generation disabled")
try:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
SELENIUM_AVAILABLE = True
except ImportError:
SELENIUM_AVAILABLE = False
logger.warning("Selenium not available - map image generation disabled")
# Parameters for timber volume calculation
RASTER_FILENAME = "GEDI04_B_MW019MW223_02_002_02_R01000M_MU.tif"
RASTER_PATH = RASTER_FILENAME # Will be downloaded to local path
MERCHANTABLE_FRACTION = 0.6
WOOD_DENSITY = 0.5 # Mg/m³
# Google Drive file ID from the shared link
GDRIVE_FILE_ID = "1HrookOHJyopZ8ENOgIGxneTGADVHEx6F"
# Use a more reliable download URL format
GDRIVE_DOWNLOAD_URL = f"https://drive.google.com/uc?export=download&id={GDRIVE_FILE_ID}"
# Fix PROJ database context issue
os.environ['PROJ_LIB'] = '/opt/homebrew/Caskroom/miniforge/base/envs/geoenv/share/proj'
# Initialize PROJ database context
try:
import pyproj
pyproj.datadir.set_data_dir('/opt/homebrew/Caskroom/miniforge/base/envs/geoenv/share/proj')
except:
pass
# FIA API Functions
def fiadb_api_POST(parameterDictionary):
"""Official FIA API POST method from documentation"""
try:
# make request
resp = requests.post("https://apps.fs.usda.gov/fiadb-api/fullreport", data=parameterDictionary, timeout=30)
# parse response to json
data = resp.json()
# create output dictionary and populate it with estimate data frames
outDict = {}
# append estimates
outDict['estimates'] = pd.DataFrame(data['estimates'])
# append subtotals and totals if present
if 'subtotals' in data.keys():
subT = {}
for i in data['subtotals'].keys():
subT[i] = pd.DataFrame(data['subtotals'][i])
outDict['subtotals'] = subT
outDict['totals'] = pd.DataFrame(data['totals'])
# append metadata
outDict['metadata'] = data['metadata']
return outDict
except Exception as e:
logger.error(f"FIA API POST Error: {e}")
return None
def get_fia_volume_data(state_code, year="2022"):
"""Get FIA volume data for a state"""
try:
# State codes: 21=Kentucky, 22=Louisiana, etc.
wc = f"{state_code}{year}"
params = {
'snum': 11015, # Net bole bark volume (ft³/acre)
'wc': wc,
'rselected': 'ALL',
'cselected': 'NONE',
'outputFormat': 'NJSON'
}
logger.info(f"Querying FIA API for state {state_code}, year {year}")
data = fiadb_api_POST(params)
if data and not data['estimates'].empty:
# Get the total volume estimate
volume_estimate = data['estimates']['ESTIMATE'].iloc[0]
plot_count = data['estimates']['PLOT_COUNT'].iloc[0]
se = data['estimates']['SE'].iloc[0]
logger.info(f"FIA volume data: {volume_estimate:.0f} ft³, {plot_count} plots, SE: {se:.0f}")
return {
'volume_ft3': volume_estimate,
'plot_count': plot_count,
'standard_error': se,
'source': 'FIA'
}
else:
logger.warning(f"No FIA data available for state {state_code}")
return None
except Exception as e:
logger.error(f"Error getting FIA data for state {state_code}: {e}")
return None
def estimate_timber_value(volume_m3, species_mix="mixed_hardwood"):
"""Estimate timber value based on volume and species mix"""
# Convert m³ to ft³ (1 m³ = 35.3147 ft³)
volume_ft3 = volume_m3 * 35.3147
# Market prices per ft³ (2024 estimates)
prices = {
'mixed_hardwood': 0.35, # $0.35/ft³ for mixed hardwoods
'oak': 0.45, # $0.45/ft³ for oak
'poplar': 0.25, # $0.25/ft³ for poplar
'pine': 0.30, # $0.30/ft³ for pine
'cherry': 0.60, # $0.60/ft³ for cherry
'walnut': 0.80 # $0.80/ft³ for walnut
}
price_per_ft3 = prices.get(species_mix, prices['mixed_hardwood'])
total_value = volume_ft3 * price_per_ft3
return {
'volume_ft3': volume_ft3,
'price_per_ft3': price_per_ft3,
'total_value': total_value,
'species_mix': species_mix
}
def download_raster_file():
"""Download the GEDI raster file from Google Drive if it doesn't exist locally"""
if os.path.exists(RASTER_PATH):
logger.info(f"Raster file already exists: {RASTER_PATH}")
return True
try:
logger.info(f"Downloading raster file from Google Drive...")
logger.info(f"URL: {GDRIVE_DOWNLOAD_URL}")
# Create a session to handle Google Drive's download process
session = requests.Session()
# First request to get the download page
response = session.get(GDRIVE_DOWNLOAD_URL, stream=True)
response.raise_for_status()
# Check if we got a redirect or the actual file
if 'text/html' in response.headers.get('content-type', ''):
# This is a Google Drive page, we need to extract the actual download link
logger.info("Detected Google Drive page, extracting download link...")
# For now, let's try a different approach - use the direct download URL
direct_url = f"https://drive.google.com/uc?export=download&confirm=t&id={GDRIVE_FILE_ID}"
response = session.get(direct_url, stream=True)
response.raise_for_status()
# Get file size for progress tracking
total_size = int(response.headers.get('content-length', 0))
logger.info(f"File size: {total_size / (1024*1024):.1f} MB")
# Download with progress
downloaded_size = 0
with open(RASTER_PATH, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
downloaded_size += len(chunk)
if total_size > 0:
progress = (downloaded_size / total_size) * 100
if downloaded_size % (1024*1024) == 0: # Log every MB
logger.info(f"Download progress: {progress:.1f}% ({downloaded_size/(1024*1024):.1f} MB)")
# Verify the downloaded file is valid
try:
import rasterio
with rasterio.open(RASTER_PATH) as src:
logger.info(f"Downloaded file verified: CRS={src.crs}, Shape={src.shape}")
except Exception as e:
logger.error(f"Downloaded file is not a valid raster: {e}")
# Remove the corrupted file
if os.path.exists(RASTER_PATH):
os.remove(RASTER_PATH)
return False
logger.info(f"Successfully downloaded and verified raster file: {RASTER_PATH}")
return True
except Exception as e:
logger.error(f"Error downloading raster file: {e}")
# Remove any partially downloaded file
if os.path.exists(RASTER_PATH):
os.remove(RASTER_PATH)
# Provide helpful error message
logger.error(f"""
Failed to download raster file from Google Drive.
This could be due to:
1. Network connectivity issues
2. Google Drive access restrictions
3. File size limitations
Please check the Google Drive link: https://drive.google.com/file/d/{GDRIVE_FILE_ID}/view
""")
return False
def create_raster_overlay(raster_path, map_obj):
"""Create a simple raster overlay for the map"""
try:
import rasterio
from rasterio.warp import transform_bounds
import numpy as np
with rasterio.open(raster_path) as src:
# Get raster bounds in WGS84
raster_bounds = transform_bounds(src.crs, 'EPSG:4326', *src.bounds)
# Create a simple overlay rectangle to show raster extent
folium.Rectangle(
bounds=[[raster_bounds[1], raster_bounds[0]], [raster_bounds[3], raster_bounds[2]]],
color='red',
weight=2,
fillColor='red',
fillOpacity=0.1,
popup=f'Meta CHM Canopy Height<br>CRS: {src.crs}<br>Shape: {src.shape}',
name='Raster Extent'
).add_to(map_obj)
logger.info(f"Added raster extent overlay")
return True
except Exception as e:
logger.error(f"Error creating raster overlay: {e}")
return False
def process_kml_and_visualize(kml_file):
"""Process uploaded KML file and return map visualization"""
if kml_file is None:
return "Please upload a KML file or use the sample file.", None
try:
# Read the KML file
if isinstance(kml_file, str):
# Default file path
gdf = gpd.read_file(kml_file, crs='EPSG:4326')
else:
# Uploaded file
gdf = gpd.read_file(kml_file.name, crs='EPSG:4326')
# Ensure the CRS is properly set
if gdf.crs is None:
gdf.set_crs('EPSG:4326', inplace=True)
# Clean styling columns
columns_to_drop = [col for col in ["style", "fill_color"] if col in gdf.columns]
clean_gdf = gdf.drop(columns=columns_to_drop)
# Create map with satellite as default
centroid = gdf.geometry.union_all().centroid
m = folium.Map(
location=[centroid.y, centroid.x],
zoom_start=14
)
# Add satellite tiles as default with proper attribution
folium.TileLayer(
tiles='https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
attr='Esri',
name='Imagery',
overlay=False,
control=True
).add_to(m)
# Add OpenStreetMap as alternate base layer
folium.TileLayer(
tiles='OpenStreetMap',
name='Street Map',
overlay=False,
control=True
).add_to(m)
# Set Imagery as the default visible layer
m.get_root().html.add_child(folium.Element("""
<script>
document.addEventListener('DOMContentLoaded', function() {
setTimeout(function() {
// Show Imagery layer as default
var imageryInputs = document.querySelectorAll('input[value="Imagery"]');
imageryInputs.forEach(function(input) {
if (!input.checked) {
input.checked = true;
input.dispatchEvent(new Event('change'));
}
});
}, 500);
});
</script>
"""))
# Add GeoJSON to map with unique colors
colors = ['red', 'blue', 'green', 'orange', 'purple', 'darkred', 'lightred', 'beige']
# Calculate CHM-based stats per polygon for popup display
volume_data = {}
try:
for idx, row in clean_gdf.iterrows():
single_gdf = gpd.GeoDataFrame([{'geometry': row.geometry}], crs=clean_gdf.crs)
chm_s = estimate_volume_from_chm(single_gdf, cache_dir="chm_cache")
if chm_s:
volume_data[idx] = {
'mean_canopy_height': chm_s.get('mean_canopy_height', 0),
'canopy_cover_pct': chm_s.get('canopy_cover_pct', 0),
'volume': chm_s.get('total_volume_m3'),
'area': chm_s.get('total_area_ha', 0),
}
else:
volume_data[idx] = {'mean_canopy_height': None, 'canopy_cover_pct': None, 'volume': None, 'area': 0}
except Exception as e:
logger.error(f"Error calculating CHM volumes for popup: {e}")
for idx, row in clean_gdf.iterrows():
color = colors[idx % len(colors)]
# Calculate area in hectares and acres using proper UTM projection
try:
# Create a temporary GeoDataFrame for accurate area calculation
temp_gdf = gpd.GeoDataFrame([{'geometry': row.geometry}], crs='EPSG:4326')
# Convert to UTM Zone 17N for Kentucky
temp_gdf_utm = temp_gdf.to_crs('EPSG:32617')
area_m2 = temp_gdf_utm.geometry.iloc[0].area
area_ha = area_m2 / 10000
area_acres = round(area_ha * 2.47105)
except Exception as e:
# Fallback to approximation if UTM projection fails
area_ha = row.geometry.area * (111.32 * 111.32 / 10000)
area_acres = round(area_ha * 2.47105)
# Get CHM volume data for popup
volume_info = ""
if idx in volume_data:
vol_data = volume_data[idx]
if vol_data['volume'] is not None:
volume_info = (
f"<br>Canopy Height: {vol_data['mean_canopy_height']:.1f} m"
f"<br>Canopy Cover: {vol_data['canopy_cover_pct']:.0f}%"
f"<br>Volume (CHM): {vol_data['volume']:.0f} m³"
)
else:
volume_info = "<br>CHM data: N/A"
folium.GeoJson(
row.geometry,
name=f"Flight Area: {row.get('Name', f'Area {idx+1}')}",
style_function=lambda x, c=color: {
'fillColor': c,
'color': c,
'weight': 2,
'fillOpacity': 0.3
},
tooltip=folium.Tooltip(f"Flight Area: {row.get('Name', f'Area {idx+1}')}<br>Area: {area_acres} acres ({area_ha:.1f} ha){volume_info}")
).add_to(m)
# Raster layer is now integrated into the main tile layers above
# Add layer control
folium.LayerControl().add_to(m)
# Convert map to HTML
map_html = m._repr_html_()
# Summary info
total_area = 0
for geom in clean_gdf.geometry:
try:
# Create a temporary GeoDataFrame for accurate area calculation
temp_gdf = gpd.GeoDataFrame([{'geometry': geom}], crs='EPSG:4326')
# Convert to UTM Zone 17N for Kentucky
temp_gdf_utm = temp_gdf.to_crs('EPSG:32617')
area_m2 = temp_gdf_utm.geometry.iloc[0].area
area_ha = area_m2 / 10000
total_area += area_ha
except Exception as e:
# Fallback to approximation if UTM projection fails
area_ha = geom.area * (111.32 * 111.32 / 10000)
total_area += area_ha
summary = ""
return summary, map_html
except Exception as e:
return f"Error processing file: {str(e)}", None
def estimate_timber_volume(kml_file):
"""Estimate timber volume using Meta Canopy Height Model (~1m resolution)."""
if kml_file is None:
return None, "Please upload a KML file or use the sample file."
try:
# Read the KML file
path = kml_file if isinstance(kml_file, str) else kml_file.name
logger.info(f"Reading KML file from: {path}")
gdf = gpd.read_file(path)
if gdf.crs is None:
gdf = gdf.set_crs("EPSG:4326")
logger.info(f"Loaded GDF with {len(gdf)} rows, bounds: {gdf.to_crs('EPSG:4326').total_bounds}")
# Clean styling columns
drop = [c for c in ["style", "fill_color"] if c in gdf.columns]
clean_gdf = gdf.drop(columns=drop, errors="ignore")
# --- CHM pipeline ---
logger.info("Running Meta CHM pipeline...")
chm_stats = estimate_volume_from_chm(clean_gdf, cache_dir="chm_cache")
if chm_stats:
logger.info(f"CHM stats: {chm_stats}")
total_area_ha = chm_stats["total_area_ha"]
total_area_acres = chm_stats["total_area_acres"]
total_volume_m3 = chm_stats["total_volume_m3"]
mean_height = chm_stats["mean_height"]
canopy_cover = chm_stats["canopy_cover_pct"]
agb_mg_ha = chm_stats["agb_mg_ha"]
# Estimate timber value (used for summary; per-polygon values computed below)
# Build table row(s) — one per polygon in the KML
results = []
for idx, row in clean_gdf.iterrows():
name = row.get("Name", f"Area {idx+1}")
display_name = "Kentucky Pilot Project" if "FURR DONOVAN" in str(name) else name
# Per-polygon area
try:
tmp = gpd.GeoDataFrame([{"geometry": row.geometry}], crs=clean_gdf.crs)
tmp_utm = tmp.to_crs(tmp.estimate_utm_crs())
poly_ha = tmp_utm.geometry.iloc[0].area / 10_000
except Exception:
poly_ha = total_area_ha / max(len(clean_gdf), 1)
# Scale total volume proportionally to polygon area
poly_volume = total_volume_m3 * (poly_ha / total_area_ha) if total_area_ha > 0 else 0
poly_value = estimate_timber_value(poly_volume, "mixed_hardwood")["total_value"]
results.append([
display_name,
f"{poly_ha:.1f}",
f"{poly_volume:.0f}" if poly_volume > 0 else "N/A",
f"${poly_value:,.0f}" if poly_volume > 0 else "N/A",
f"Estimated (Meta CHM {mean_height:.1f}m avg, {canopy_cover:.0f}% cover)"
])
total_value = sum(
float(r[3].replace("$", "").replace(",", ""))
for r in results if r[3] != "N/A"
)
avg_per_acre = total_value / total_area_acres if total_area_acres > 0 else 0
summary = f"""
**📊 Summary (Meta CHM ~1m resolution):**
- **Total Area:** {total_area_ha:.1f} ha ({total_area_acres:.1f} acres)
- **Total Volume:** {total_volume_m3:,.0f} m³ ({total_volume_m3 * 35.3147:,.0f} ft³)
- **Total Value:** ${total_value:,.0f}
- **Average per Acre:** ${avg_per_acre:,.0f}/acre
- **Mean Canopy Height:** {mean_height:.1f} m
- **Canopy Cover:** {canopy_cover:.1f}%
- **Above-Ground Biomass:** {agb_mg_ha:.1f} Mg/ha
- **Data Source:** Meta CHM (alsgedi_global_v6_float)
- **Areas Processed:** {len(results)}
"""
return results, summary
# --- Fallback: GEDI 1km pipeline ---
logger.warning("CHM pipeline failed, falling back to GEDI raster.")
# Download raster file if it doesn't exist
if not os.path.exists(RASTER_PATH):
logger.info("Raster file not found locally, downloading from Google Drive...")
if not download_raster_file():
return None, f"""
**Raster Data Download Failed**
Unable to download CHM tiles or GEDI raster file.
Please check your internet connection and try again.
**Expected file:** {RASTER_PATH}
**Data source:** GEDI (Global Ecosystem Dynamics Investigation) biomass dataset
**Google Drive ID:** {GDRIVE_FILE_ID}
"""
# Verify the raster file is valid
try:
with rasterio.open(RASTER_PATH) as src:
logger.info(f"Raster file verified: CRS={src.crs}, Shape={src.shape}")
except Exception as e:
logger.error(f"Raster file is corrupted or invalid: {e}")
if os.path.exists(RASTER_PATH):
os.remove(RASTER_PATH)
if not download_raster_file():
return None, f"**Raster File Corrupted** — {str(e)}"
# Debug raster file properties
try:
with rasterio.open(RASTER_PATH) as src:
logger.info(f"Raster CRS: {src.crs}, bounds: {src.bounds}, shape: {src.shape}, nodata: {src.nodata}")
except Exception as e:
logger.error(f"Error reading raster file: {e}")
# Calculate zonal statistics from raster
logger.info(f"Calculating zonal stats for {len(clean_gdf)} geometries")
logger.info(f"Raster path: {RASTER_PATH}")
logger.info(f"Clean GDF columns: {clean_gdf.columns.tolist()}")
logger.info(f"GDF CRS: {clean_gdf.crs}")
logger.info(f"GDF bounds: {clean_gdf.total_bounds}")
# Check if geometries overlap with raster bounds
try:
with rasterio.open(RASTER_PATH) as src:
raster_bounds = src.bounds
gdf_bounds = clean_gdf.total_bounds
logger.info(f"Raster bounds: {raster_bounds}")
logger.info(f"GDF bounds: {gdf_bounds}")
# Check overlap
overlap = (
gdf_bounds[0] <= raster_bounds[2] and # minx <= maxx
gdf_bounds[2] >= raster_bounds[0] and # maxx >= minx
gdf_bounds[1] <= raster_bounds[3] and # miny <= maxy
gdf_bounds[3] >= raster_bounds[1] # maxy >= miny
)
logger.info(f"Geometries overlap with raster: {overlap}")
except Exception as e:
logger.error(f"Error checking bounds: {e}")
try:
# Reproject geometries to match raster CRS for accurate zonal statistics
logger.info(f"Reprojecting geometries to raster CRS...")
clean_gdf_reprojected = clean_gdf.to_crs('EPSG:6933')
logger.info(f"Reprojected GDF CRS: {clean_gdf_reprojected.crs}")
stats = zonal_stats(clean_gdf_reprojected, RASTER_PATH, stats=["mean"], nodata=-9999, geojson_out=True)
logger.info(f"Zonal stats completed. Got {len(stats)} results")
results = []
for i, f in enumerate(stats):
logger.info(f"Processing result {i+1}: {type(f)}")
logger.info(f"Result keys: {f.keys() if isinstance(f, dict) else 'Not a dict'}")
if isinstance(f, dict) and "properties" in f:
props = f["properties"]
name = props.get("Name", f"Area {i+1}")
mean_agb = props.get("mean")
# Calculate area using the original geometry from clean_gdf
if i < len(clean_gdf):
# Convert to a projected CRS for accurate area calculation
geom = clean_gdf.iloc[i].geometry
# Use UTM projection for the area (approximate based on coordinates)
# You might need to adjust this based on your actual location
try:
# Create a GeoDataFrame with the geometry for proper CRS transformation
from shapely.geometry import Polygon
temp_gdf = gpd.GeoDataFrame([{'geometry': geom}], crs='EPSG:4326')
# Convert to UTM Zone 15N for Louisiana (around 30.7°N, 90.9°W)
temp_gdf_projected = temp_gdf.to_crs('EPSG:32615') # UTM Zone 15N
area_m2 = temp_gdf_projected.geometry.iloc[0].area
area_ha = area_m2 / 10000 # Convert m² to ha
logger.info(f"Area {i+1} calculated with UTM projection: {area_ha:.6f} ha ({area_m2:.2f} m²)")
except Exception as e:
logger.error(f"UTM projection failed for area {i+1}: {e}")
# Fallback to simple approximation
# This is a rough approximation but should give reasonable results
area_ha = geom.area * (111.32 * 111.32 / 10000)
logger.info(f"Area {i+1} calculated with approximation: {area_ha:.6f} ha")
else:
area_ha = 0
logger.info(f"Area {i+1}: name={name}, mean_agb={mean_agb}, area_ha={area_ha}")
# Calculate volume with quality checks
if mean_agb is not None and mean_agb != -9999 and mean_agb > 0 and area_ha is not None and not math.isnan(area_ha) and area_ha > 0:
volume = mean_agb * area_ha * MERCHANTABLE_FRACTION / WOOD_DENSITY
biomass_status = "✅ Valid"
else:
volume = None
if mean_agb == -9999:
biomass_status = "❌ No data"
elif mean_agb is None or mean_agb <= 0:
biomass_status = "❌ Invalid"
elif area_ha is None or math.isnan(area_ha) or area_ha <= 0:
biomass_status = "❌ Area error"
else:
biomass_status = "❌ Invalid"
# Calculate area in acres for display (rounded to whole numbers)
area_acres = round(area_ha * 2.47105)
# Replace FURR DONOVAN with Kentucky Pilot Project
display_name = "Kentucky Pilot Project" if "FURR DONOVAN" in name else name
# Update status to Estimated/Unestimated
if biomass_status == "✅ Valid":
status = "Estimated"
elif biomass_status == "❌ No data":
status = "Unestimated"
elif biomass_status == "❌ Invalid":
status = "Unestimated"
else:
status = "Unestimated"
# Estimate timber value
if volume:
value_data = estimate_timber_value(volume, "mixed_hardwood")
value_str = f"${value_data['total_value']:,.0f}"
else:
value_str = "N/A"
results.append([
display_name,
f"{area_ha:.1f}",
f"{volume:.0f}" if volume else "N/A",
value_str,
status
])
else:
logger.warning(f"Unexpected result format: {f}")
except Exception as e:
logger.error(f"Error in zonal_stats: {str(e)}")
# Fallback to mock calculation if raster processing fails
logger.info("Falling back to mock calculation")
results = []
for idx, row in clean_gdf.iterrows():
# Calculate area using proper UTM projection
try:
temp_gdf = gpd.GeoDataFrame([{'geometry': row.geometry}], crs='EPSG:4326')
temp_gdf_utm = temp_gdf.to_crs('EPSG:32617')
area_m2 = temp_gdf_utm.geometry.iloc[0].area
area_ha = area_m2 / 10000
except Exception as e:
# Fallback to approximation if UTM projection fails
area_ha = row.geometry.area * (111.32 * 111.32 / 10000)
biomass_density = 67.8 # Mg/ha (mock value)
volume_m3 = area_ha * biomass_density * MERCHANTABLE_FRACTION / WOOD_DENSITY
area_acres = round(area_ha * 2.47105)
# Replace FURR DONOVAN with Kentucky Pilot Project
name = row.get('Name', f'Area {idx+1}')
display_name = "Kentucky Pilot Project" if "FURR DONOVAN" in name else name
# Estimate timber value
value_data = estimate_timber_value(volume_m3, "mixed_hardwood")
value_str = f"${value_data['total_value']:,.0f}"
results.append([
display_name,
f"{area_ha:.1f}",
f"{volume_m3:.0f}",
value_str,
"Estimated (Mock)"
])
# Calculate summary statistics
total_area_ha = sum([float(row[1]) for row in results if row[1] != "N/A"])
total_area_acres = round(total_area_ha * 2.47105)
total_volume = sum([float(row[2]) for row in results if row[2] != "N/A"])
total_value = sum([float(row[3].replace('$', '').replace(',', '')) for row in results if row[3] != "N/A"])
summary = f"""
**📊 Summary (GEDI 1km fallback):**
- **Total Area:** {total_area_ha:.1f} ha ({total_area_acres:.1f} acres)
- **Total Volume:** {total_volume:,.0f} m³ ({total_volume * 35.3147:,.0f} ft³)
- **Total Value:** ${total_value:,.0f}
- **Average per Acre:** ${total_value / total_area_acres:,.0f}/acre
- **Data Source:** GEDI (Meta CHM unavailable for this area)
- **Areas Processed:** {len(results)}
"""
return results, summary
except Exception as e:
return None, f"Error in volume estimation: {str(e)}"
# PDF Report Generation Functions
def save_map_as_image(map_html, output_image="map_snapshot.png"):
"""Save the folium HTML map as a PNG image using Selenium"""
if not SELENIUM_AVAILABLE:
logger.warning("Selenium not available - cannot generate map image")
return None
try:
with open("temp_map.html", "w") as f:
f.write(map_html)
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--window-size=1200,800')
driver = webdriver.Chrome(options=options)
driver.get(f"file://{os.path.abspath('temp_map.html')}")
time.sleep(3) # Let tiles load
driver.save_screenshot(output_image)
driver.quit()
os.remove("temp_map.html")
logger.info(f"Map image saved: {output_image}")
return output_image
except Exception as e:
logger.error(f"Error saving map image: {e}")
# Clean up temp file if it exists
if os.path.exists("temp_map.html"):
os.remove("temp_map.html")
return None
def generate_pdf_report(map_html, volume_table_data, summary_text, output_path="ForestAI_Report.pdf"):
"""
Create a professional PDF report with map, summary, and results table
"""
if not REPORTLAB_AVAILABLE:
logger.error("ReportLab not available - cannot generate PDF")
return None, "PDF generation requires ReportLab library"
try:
# Save map image
map_image_path = save_map_as_image(map_html)
if not map_image_path or not os.path.exists(map_image_path):
logger.warning("Could not generate map image, creating PDF without map")
map_image_path = None
# Setup PDF
doc = SimpleDocTemplate(output_path, pagesize=letter)
styles = getSampleStyleSheet()
elements = []
# --- Title Page ---
elements.append(Spacer(1, 80))
elements.append(Paragraph("🌲 ForestAI - Timber Volume Estimation Report", styles['Title']))
elements.append(Spacer(1, 20))
elements.append(Paragraph("Generated by ForestAI", styles['Normal']))
elements.append(Paragraph("Date: <b>%s</b>" % time.strftime("%Y-%m-%d"), styles['Normal']))
elements.append(PageBreak())
# --- Map Page (if available) ---
if map_image_path:
elements.append(Paragraph("📍 Area Map", styles['Heading2']))
elements.append(Spacer(1, 10))
elements.append(Image(map_image_path, width=400, height=280))
elements.append(Spacer(1, 20))
# --- Volume Table ---
# Check if volume_table_data is empty (handle both DataFrame and list cases)
if volume_table_data is not None:
# Handle DataFrame case
if hasattr(volume_table_data, 'empty'):
has_data = not volume_table_data.empty
# Handle list case
else:
has_data = len(volume_table_data) > 0
if has_data:
elements.append(Paragraph("🪵 Timber Volume & Value Estimates", styles['Heading2']))
elements.append(Spacer(1, 12))
headers = ["Area / Parcel", "Area (ha)", "Volume (m³)", "Value ($)", "Status"]
# Handle DataFrame case
if hasattr(volume_table_data, 'values'):
# Convert DataFrame to list of lists
table_data = [headers] + volume_table_data.values.tolist()
else:
# Handle list case
table_data = [headers] + volume_table_data
t = Table(table_data, repeatRows=1, hAlign='LEFT')
t.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.green),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, -1), 9),
('BOTTOMPADDING', (0, 0), (-1, 0), 10),
('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
]))
elements.append(t)
# --- Final Build ---
doc.build(elements)
logger.info(f"✅ PDF report saved to: {output_path}")
# Clean up map image
if map_image_path and os.path.exists(map_image_path):
os.remove(map_image_path)
return output_path, "PDF report generated successfully!"
except Exception as e:
logger.error(f"Error generating PDF report: {e}")
return None, f"Error generating PDF: {str(e)}"
def generate_report_wrapper(kml_file, map_html, volume_table_data, summary_text):
"""Wrapper function for Gradio to generate PDF report"""
if not kml_file:
return None, "Please upload a KML file and run volume estimation first."
# Check if volume_table_data is empty (handle both DataFrame and list cases)
if volume_table_data is None:
return None, "Please run volume estimation first to generate report data."
# Handle DataFrame case
if hasattr(volume_table_data, 'empty'):
if volume_table_data.empty:
return None, "Please run volume estimation first to generate report data."
# Handle list case
elif not volume_table_data or len(volume_table_data) == 0:
return None, "Please run volume estimation first to generate report data."
if not map_html:
return None, "Map visualization not available. Please upload a KML file first."
# Check if dependencies are available
if not REPORTLAB_AVAILABLE:
return None, "❌ PDF generation requires ReportLab library. Please install: pip install reportlab"
if not SELENIUM_AVAILABLE:
return None, "⚠️ Selenium not available - PDF will be generated without map image. Install: pip install selenium"
# Generate unique filename
timestamp = time.strftime("%Y%m%d_%H%M%S")
output_path = f"ForestAI_Report_{timestamp}.pdf"
result_path, message = generate_pdf_report(map_html, volume_table_data, summary_text, output_path)
if result_path and os.path.exists(result_path):
return result_path, f"✅ {message}\n📄 Report ready for download!"
else:
return None, f"❌ {message}"
# Create Gradio interface
with gr.Blocks(title="ForestAI - Timber Volume Estimation", theme=gr.themes.Soft()) as demo:
gr.Markdown("# 🌲 ForestAI - Timber Volume Estimation")
gr.Markdown("Upload a KML file to visualize boundaries and estimate timber volume. Sample: Kentuck Pilot Land (1,252 acres of hardwoods and poplar).")
with gr.Row():
with gr.Column(scale=1):
kml_input = gr.File(
label="Upload KML File",
file_types=[".kml"],
type="filepath"
)
with gr.Row():
with gr.Column(scale=2):
volume_btn = gr.Button("Timber Volume Estimation", variant="primary", size="lg")
with gr.Column(scale=1):
sample_btn = gr.Button("Use Example Area", variant="secondary", size="lg")
# File info display under buttons
file_info = gr.Markdown("Upload a KML file or use the example area to get started. Map will display automatically.")
with gr.Column(scale=2):
# Map display area on the right
map_output = gr.HTML(label="Map Visualization")
# Volume estimation output
with gr.Row():
with gr.Column(scale=2):
volume_table = gr.Dataframe(
headers=["Area / Parcel", "Area (ha)", "Volume (m³)", "Value ($)", "Status"],
label="Timber Volume & Value Estimation Results",
interactive=False
)
with gr.Column(scale=1):
volume_summary = gr.Markdown("Click 'Timber Volume Estimation' to see results...")
# PDF Report Generation
with gr.Row():
with gr.Column(scale=1):
pdf_btn = gr.Button("📄 Generate PDF Report", variant="secondary", size="lg")
with gr.Column(scale=2):
pdf_output = gr.File(
label="📄 Download PDF Report",
file_types=[".pdf"],
interactive=False,
visible=False
)
pdf_status = gr.Markdown("Click 'Generate PDF Report' to create a professional report with map and results table.")
# Explanation section
with gr.Accordion("📋 Calculation Details & Dataset Info", open=False):
explanation_text = gr.Markdown("""
**Calculation Method (Meta CHM primary):**
1. Canopy pixels (height ≥ 2 m) identified from ~1 m resolution CHM
2. AGB (Mg/ha) = 1.82 × mean_canopy_height^1.72 × canopy_cover_fraction *(Jenkins et al. 2003)*
3. Volume (m³/ha) = AGB × Merchantable Fraction ÷ Wood Density
4. Value ($) = Volume (ft³) × Market Price ($/ft³)
**Parameters:**
- **Merchantable Fraction:** 0.6 (60% of AGB is merchantable timber)
- **Wood Density:** 0.5 Mg/m³ (average hardwood density)
- **Market Prices:** Current timber market rates (mixed hardwood: $0.35/ft³)
**Data Sources:**
- **Meta CHM (primary):** ~1 m resolution canopy height model from AWS Open Data
(`s3://dataforgood-fb-data/forests/v1/alsgedi_global_v6_float/chm/`)
- **GEDI (fallback):** Satellite-based biomass data (1 km resolution) if CHM unavailable
- **FIA:** USDA Forest Service ground survey data (where available)
- **Market Prices:** Current timber market rates
**Meta CHM Dataset Info:**
- **Coverage:** Global forested areas
- **Resolution:** ~1.19 m per pixel (Web Mercator / EPSG:3857)
- **Tile system:** Bing Maps quadkeys zoom level 9
- **Units:** Canopy height in meters (uint8, max 254 m)
**Data Quality Legend:**
- **Estimated:** CHM tiles downloaded and used for calculation
- **Unestimated:** CHM tiles unavailable or no canopy pixels found
**PDF Report Generation:**
- **ReportLab:** Required for PDF generation (pip install reportlab)
- **Selenium + Chrome:** Required for map image capture (pip install selenium)
- **Chrome/Chromium:** Must be installed on the system for map screenshots
- Reports include: Title page, area map, summary, and detailed results table
""")
# Event handlers
# Automatic visualization when file is uploaded
kml_input.change(
fn=process_kml_and_visualize,
inputs=[kml_input],
outputs=[file_info, map_output]
)
volume_btn.click(
fn=estimate_timber_volume,
inputs=[kml_input],
outputs=[volume_table, volume_summary]
)
# Sample file handler
def use_sample_file():
if os.path.exists("Kentuck_Pilot_Land.kml"):
# Return the file path to update the file input component
return "Kentuck_Pilot_Land.kml", process_kml_and_visualize("Kentuck_Pilot_Land.kml")[0], process_kml_and_visualize("Kentuck_Pilot_Land.kml")[1]
else:
return None, "Sample file not found. Please upload a KML file.", None
sample_btn.click(
fn=use_sample_file,
outputs=[kml_input, file_info, map_output]
)
# PDF Report Generation
pdf_btn.click(
fn=generate_report_wrapper,
inputs=[kml_input, map_output, volume_table, volume_summary],
outputs=[pdf_output, pdf_status]
)
if __name__ == "__main__":
demo.launch(share=True, server_name="0.0.0.0", server_port=7860)