Spaces:
Sleeping
Sleeping
Download app.py from danudenny/random_geojson_generator: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/spaces/danudenny/random_geojson_generator/resolve/main/app.py
- Command line
-
hf download hf://spaces/danudenny/random_geojson_generator/app.py
-
curl -L -o app.py https://huggingface.co/spaces/danudenny/random_geojson_generator/resolve/main/app.py
12.1 kB
| import json | |
| import math | |
| import random | |
| from datetime import datetime, timedelta | |
| from typing import List, Dict, Tuple, Optional | |
| import folium | |
| import geopandas as gpd | |
| import numpy as np | |
| import streamlit as st | |
| from folium.plugins import HeatMap, MarkerCluster | |
| from pyproj import Transformer | |
| from shapely.geometry import MultiPoint, Point, Polygon, box | |
| from shapely.ops import unary_union | |
| from streamlit_folium import folium_static | |
| # Enhanced property generators | |
| def generate_crop_data() -> Dict: | |
| """Generate realistic crop-related data.""" | |
| crops = { | |
| "Cocoa": {"yield_range": (0.4, 1.2), "price_range": (2000, 3000)}, | |
| "Coffee": {"yield_range": (0.8, 2.0), "price_range": (3000, 4500)}, | |
| "Palm Oil": {"yield_range": (3.0, 5.0), "price_range": (700, 1200)}, | |
| "Rubber": {"yield_range": (1.2, 2.5), "price_range": (1500, 2500)} | |
| } | |
| crop_type = random.choice(list(crops.keys())) | |
| crop_data = crops[crop_type] | |
| return { | |
| "crop_type": crop_type, | |
| "yield_per_ha": round(random.uniform(*crop_data["yield_range"]), 2), | |
| "price_per_ton": round(random.uniform(*crop_data["price_range"]), 2) | |
| } | |
| def generate_soil_data() -> Dict: | |
| """Generate realistic soil quality data.""" | |
| return { | |
| "ph_level": round(random.uniform(5.5, 7.5), 1), | |
| "organic_matter": round(random.uniform(2.0, 5.0), 1), | |
| "nitrogen": round(random.uniform(0.1, 0.5), 2), | |
| "phosphorus": round(random.uniform(10, 50), 1), | |
| "potassium": round(random.uniform(100, 300), 1) | |
| } | |
| def generate_certification_data() -> Dict: | |
| """Generate certification and audit data.""" | |
| certifications = ["Organic", "Fairtrade", "Rainforest Alliance", "UTZ"] | |
| return { | |
| "certifications": random.sample(certifications, random.randint(1, 3)), | |
| "last_audit_date": (datetime.now() - timedelta(days=random.randint(0, 365))).strftime("%Y-%m-%d"), | |
| "certification_status": random.choice(["Active", "Pending Renewal", "Under Review"]) | |
| } | |
| def generate_weather_pattern() -> Dict: | |
| """Generate local weather pattern data.""" | |
| return { | |
| "annual_rainfall": round(random.uniform(1500, 2500), 1), | |
| "avg_temperature": round(random.uniform(22, 28), 1), | |
| "humidity": round(random.uniform(60, 85), 1), | |
| "sunshine_hours": round(random.uniform(1800, 2200), 1) | |
| } | |
| class AdvancedPolygonGenerator: | |
| def __init__(self, bbox: List[float]): | |
| self.bbox = bbox | |
| self.transformer_to_3857 = Transformer.from_crs("EPSG:4326", "EPSG:3857", always_xy=True) | |
| self.transformer_to_4326 = Transformer.from_crs("EPSG:3857", "EPSG:4326", always_xy=True) | |
| self.setup_coordinate_systems() | |
| def setup_coordinate_systems(self): | |
| """Setup coordinate system transformations.""" | |
| min_lon, min_lat, max_lon, max_lat = self.bbox | |
| min_x, min_y = self.transformer_to_3857.transform(min_lon, min_lat) | |
| max_x, max_y = self.transformer_to_3857.transform(max_lon, max_lat) | |
| self.bbox_3857 = box(min_x, min_y, max_x, max_y) | |
| def generate_clustered_polygons( | |
| self, | |
| num_clusters: int, | |
| polygons_per_cluster: int, | |
| cluster_radius: float, | |
| **kwargs | |
| ) -> List[Tuple[Polygon, float]]: | |
| """Generate clusters of polygons around central points.""" | |
| clusters = [] | |
| for _ in range(num_clusters): | |
| center_x = random.uniform(self.bbox[0], self.bbox[2]) | |
| center_y = random.uniform(self.bbox[1], self.bbox[3]) | |
| # Generate polygons around cluster center | |
| cluster_polygons = [] | |
| for _ in range(polygons_per_cluster): | |
| offset_x = random.gauss(0, cluster_radius) | |
| offset_y = random.gauss(0, cluster_radius) | |
| local_center = (center_x + offset_x, center_y + offset_y) | |
| polygon = self.generate_single_polygon(local_center, **kwargs) | |
| if polygon[0]: | |
| cluster_polygons.append(polygon) | |
| clusters.extend(cluster_polygons) | |
| return clusters | |
| def generate_single_polygon( | |
| self, | |
| center: Optional[Tuple[float, float]] = None, | |
| min_area: float = 100, | |
| max_area: float = 1000, | |
| max_distance: float = 5, | |
| irregularity: float = 0.4, | |
| spikiness: float = 0.4 | |
| ) -> Tuple[Optional[Polygon], Optional[float]]: | |
| """Generate a single polygon with controlled irregularity and spikiness.""" | |
| if center is None: | |
| center_x = random.uniform(self.bbox[0], self.bbox[2]) | |
| center_y = random.uniform(self.bbox[1], self.bbox[3]) | |
| else: | |
| center_x, center_y = center | |
| num_vertices = random.randint(6, 12) | |
| angles = np.linspace(0, 2 * np.pi, num_vertices) | |
| # Add irregularity to angles | |
| angles = angles + np.random.uniform(-irregularity, irregularity, num_vertices) | |
| # Generate distances with controlled spikiness | |
| distances = np.random.uniform( | |
| max_distance * (1 - spikiness), | |
| max_distance * (1 + spikiness), | |
| num_vertices | |
| ) | |
| points = [] | |
| for angle, distance in zip(angles, distances): | |
| x = center_x + distance * np.cos(angle) | |
| y = center_y + distance * np.sin(angle) | |
| points.append((x, y)) | |
| try: | |
| poly = Polygon(points) | |
| if poly.is_valid and min_area <= poly.area <= max_area: | |
| return poly, poly.area | |
| except: | |
| pass | |
| return None, None | |
| def main(): | |
| st.title("Advanced Random GeoJSON Generator") | |
| # Enhanced UI with tabs | |
| tab1, tab2, tab3 = st.tabs(["Basic Settings", "Advanced Features", "Visualization"]) | |
| with tab1: | |
| st.header("Basic Settings") | |
| bbox_input = st.text_input( | |
| "Bounding Box (min_lon, min_lat, max_lon, max_lat)", | |
| value="106.8400,-6.2120,106.8512,-6.2070" | |
| ) | |
| try: | |
| bbox = [float(coord.strip()) for coord in bbox_input.split(",")] | |
| if len(bbox) != 4: | |
| st.error("Please enter exactly 4 values separated by commas.") | |
| return | |
| except ValueError: | |
| st.error("Invalid input. Please enter numeric values separated by commas.") | |
| return | |
| polygon_count = st.number_input("Number of Polygons", min_value=1, value=50) | |
| with tab2: | |
| st.header("Advanced Features") | |
| # Clustering options | |
| enable_clustering = st.checkbox("Enable Polygon Clustering", value=True) | |
| if enable_clustering: | |
| num_clusters = st.number_input("Number of Clusters", min_value=1, value=5) | |
| cluster_radius = st.slider("Cluster Radius", 0.001, 0.01, 0.005) | |
| # Shape controls | |
| st.subheader("Shape Controls") | |
| irregularity = st.slider("Shape Irregularity", 0.0, 1.0, 0.4) | |
| spikiness = st.slider("Shape Spikiness", 0.0, 1.0, 0.4) | |
| # Data generation options | |
| st.subheader("Data Generation") | |
| include_crop_data = st.checkbox("Include Crop Data", value=True) | |
| include_soil_data = st.checkbox("Include Soil Data", value=True) | |
| include_certification = st.checkbox("Include Certification Data", value=True) | |
| include_weather = st.checkbox("Include Weather Data", value=True) | |
| with tab3: | |
| st.header("Visualization Options") | |
| map_style = st.selectbox( | |
| "Map Style", | |
| ["CartoDB Dark_Matter", "CartoDB Positron", "OpenStreetMap"] | |
| ) | |
| show_heatmap = st.checkbox("Show Density Heatmap", value=True) | |
| show_clusters = st.checkbox("Show Marker Clusters", value=True) | |
| if st.button("Generate GeoJSON"): | |
| generator = AdvancedPolygonGenerator(bbox) | |
| # Initialize map | |
| center_lat = (bbox[1] + bbox[3]) / 2 | |
| center_lon = (bbox[0] + bbox[2]) / 2 | |
| m = folium.Map(location=[center_lat, center_lon], zoom_start=17, tiles=map_style) | |
| features = [] | |
| heatmap_data = [] | |
| with st.spinner("Generating polygons..."): | |
| if enable_clustering: | |
| polygons = generator.generate_clustered_polygons( | |
| num_clusters=num_clusters, | |
| polygons_per_cluster=polygon_count // num_clusters, | |
| cluster_radius=cluster_radius, | |
| irregularity=irregularity, | |
| spikiness=spikiness | |
| ) | |
| else: | |
| polygons = [ | |
| generator.generate_single_polygon( | |
| min_area=100, | |
| max_area=1000, | |
| irregularity=irregularity, | |
| spikiness=spikiness | |
| ) | |
| for _ in range(polygon_count) | |
| ] | |
| for i, (polygon, area) in enumerate(filter(lambda x: x[0] is not None, polygons)): | |
| properties = { | |
| "id": f"PLOT-{i+1:04d}", | |
| "area_ha": round(area / 10000, 2) | |
| } | |
| # Add optional data based on user selection | |
| if include_crop_data: | |
| properties.update(generate_crop_data()) | |
| if include_soil_data: | |
| properties.update({"soil_data": generate_soil_data()}) | |
| if include_certification: | |
| properties.update({"certification": generate_certification_data()}) | |
| if include_weather: | |
| properties.update({"weather": generate_weather_pattern()}) | |
| # Create GeoJSON feature | |
| feature = { | |
| "type": "Feature", | |
| "properties": properties, | |
| "geometry": polygon.__geo_interface__ | |
| } | |
| features.append(feature) | |
| # Add to map | |
| folium.GeoJson( | |
| feature, | |
| style_function=lambda x: { | |
| "fillColor": f"#{random.randint(0, 0xFFFFFF):06x}", | |
| "color": "black", | |
| "weight": 1, | |
| "fillOpacity": 0.7 | |
| }, | |
| popup=folium.Popup( | |
| f"<b>Plot {properties['id']}</b><br>" | |
| f"Area: {properties['area_ha']} ha<br>" | |
| f"Crop: {properties.get('crop_type', 'N/A')}" | |
| ) | |
| ).add_to(m) | |
| # Add center point to heatmap data | |
| centroid = polygon.centroid | |
| heatmap_data.append([centroid.y, centroid.x]) | |
| # Add heatmap if enabled | |
| if show_heatmap and heatmap_data: | |
| HeatMap(heatmap_data).add_to(m) | |
| # Create GeoJSON object | |
| geojson = { | |
| "type": "FeatureCollection", | |
| "features": features, | |
| "metadata": { | |
| "generated_at": datetime.now().isoformat(), | |
| "polygon_count": len(features), | |
| "settings": { | |
| "clustering_enabled": enable_clustering, | |
| "irregularity": irregularity, | |
| "spikiness": spikiness | |
| } | |
| } | |
| } | |
| # Create download button for GeoJSON | |
| st.download_button( | |
| label="Download GeoJSON", | |
| data=json.dumps(geojson, indent=2), | |
| file_name="advanced_random_polygons.geojson", | |
| mime="application/json", | |
| ) | |
| # Display the map | |
| folium_static(m) | |
| # Display statistics | |
| st.subheader("Generation Statistics") | |
| st.json({ | |
| "total_polygons": len(features), | |
| "average_area": round(sum(f["properties"]["area_ha"] for f in features) / len(features), 2), | |
| "total_area": round(sum(f["properties"]["area_ha"] for f in features), 2) | |
| }) | |
| if __name__ == "__main__": | |
| main() |