Spaces:
Sleeping
Sleeping
| #!/usr/bin/env python3 | |
| """ | |
| Demo script for the Agricultural Analysis Tool | |
| Showcases the main features and functionality of the MCP server and analysis tools. | |
| """ | |
| import warnings | |
| warnings.filterwarnings('ignore') | |
| from data_loader import AgriculturalDataLoader | |
| from analysis_tools import AgriculturalAnalyzer | |
| import pandas as pd | |
| def main(): | |
| """Run the demo of agricultural analysis features.""" | |
| print("๐" + "="*60) | |
| print(" AGRICULTURAL ANALYSIS TOOL - DEMO") | |
| print(" Station Expรฉrimentale de Kerguรฉhennec") | |
| print("="*63) | |
| print() | |
| # Initialize components | |
| print("๐ง Initializing components...") | |
| data_loader = AgriculturalDataLoader() | |
| analyzer = AgriculturalAnalyzer(data_loader) | |
| print("โ Components initialized successfully") | |
| print() | |
| # Load data | |
| print("๐ Loading agricultural intervention data...") | |
| df = data_loader.load_all_files() | |
| print(f"โ Loaded {len(df):,} intervention records") | |
| print(f"๐ Data spans {df.year.nunique()} years: {sorted(df.year.unique())}") | |
| print(f"๐ฑ Covers {df.crop_type.nunique()} different crop types") | |
| print(f"๐ Across {df.plot_name.nunique()} different plots") | |
| print(f"๐ Including {df.is_herbicide.sum():,} herbicide applications") | |
| print() | |
| # Show top crops and plots | |
| print("๐พ TOP CROPS ANALYZED:") | |
| top_crops = df.crop_type.value_counts().head(10) | |
| for i, (crop, count) in enumerate(top_crops.items(), 1): | |
| print(f" {i:2}. {crop:<30} ({count:3} interventions)") | |
| print() | |
| print("๐ TOP PLOTS ANALYZED:") | |
| top_plots = df.plot_name.value_counts().head(10) | |
| for i, (plot, count) in enumerate(top_plots.items(), 1): | |
| print(f" {i:2}. {plot:<30} ({count:3} interventions)") | |
| print() | |
| # Analyze weed pressure | |
| print("๐ฟ WEED PRESSURE ANALYSIS (IFT - Treatment Frequency Index)") | |
| print("-" * 60) | |
| trends = analyzer.analyze_weed_pressure_trends() | |
| summary = trends['summary'] | |
| print(f"๐ Overall IFT Statistics:") | |
| print(f" โข Mean IFT: {summary['mean_ift']:.2f}") | |
| print(f" โข Standard deviation: {summary['std_ift']:.2f}") | |
| print(f" โข Minimum IFT: {summary['min_ift']:.2f}") | |
| print(f" โข Maximum IFT: {summary['max_ift']:.2f}") | |
| print() | |
| # Show IFT trends by year | |
| if 'yearly_ift' in trends: | |
| yearly_data = pd.DataFrame(trends['yearly_ift']) | |
| print("๐ IFT Evolution by Year:") | |
| for _, row in yearly_data.iterrows(): | |
| year = int(row['year']) | |
| ift = row['ift_herbicide'] | |
| risk_indicator = "๐ข" if ift < 1.0 else "๐ก" if ift < 2.0 else "๐ด" | |
| print(f" {year}: {ift:.2f} {risk_indicator}") | |
| print() | |
| # Prediction demo | |
| print("๐ฎ WEED PRESSURE PREDICTIONS (2025-2027)") | |
| print("-" * 60) | |
| try: | |
| predictions = analyzer.predict_weed_pressure(target_years=[2025, 2026, 2027]) | |
| model_perf = predictions['model_performance'] | |
| print(f"๐ค Model Performance:") | |
| print(f" โข Rยฒ Score: {model_perf['r2']:.3f}") | |
| print(f" โข Mean Squared Error: {model_perf['mse']:.3f}") | |
| print() | |
| # Show predictions for each year | |
| for year in [2025, 2026, 2027]: | |
| if year in predictions['predictions']: | |
| year_pred = predictions['predictions'][year] | |
| print(f"๐ Predictions for {year}:") | |
| # Group by risk level | |
| risk_counts = year_pred['risk_level'].value_counts() | |
| for risk_level in ['low', 'medium', 'high']: | |
| count = risk_counts.get(risk_level, 0) | |
| emoji = {"low": "๐ข", "medium": "๐ก", "high": "๐ด"}[risk_level] | |
| print(f" {emoji} {risk_level.capitalize()} risk: {count} plots") | |
| # Show a few examples | |
| low_risk = year_pred[year_pred['risk_level'] == 'low'] | |
| if len(low_risk) > 0: | |
| print(f" ๐ฑ Best plots for sensitive crops:") | |
| for _, row in low_risk.head(5).iterrows(): | |
| print(f" โข {row['plot_name']}: IFT {row['predicted_ift']:.2f}") | |
| print() | |
| except Exception as e: | |
| print(f"โ Prediction error: {e}") | |
| print() | |
| # Suitable plots for sensitive crops | |
| print("๐ฏ PLOTS SUITABLE FOR SENSITIVE CROPS (peas, beans)") | |
| print("-" * 60) | |
| try: | |
| suitable_plots = analyzer.identify_suitable_plots_for_sensitive_crops( | |
| target_years=[2025, 2026, 2027], | |
| max_ift_threshold=1.0 | |
| ) | |
| for year, plots in suitable_plots.items(): | |
| print(f"๐ {year}: {len(plots)} suitable plots") | |
| if plots: | |
| for plot in plots[:5]: # Show first 5 | |
| print(f" โ {plot}") | |
| if len(plots) > 5: | |
| print(f" ... and {len(plots) - 5} more") | |
| else: | |
| print(" โ No plots meet the criteria") | |
| print() | |
| except Exception as e: | |
| print(f"โ Analysis error: {e}") | |
| print() | |
| # Crop rotation analysis | |
| print("๐ CROP ROTATION IMPACT ANALYSIS") | |
| print("-" * 60) | |
| try: | |
| rotation_impact = analyzer.analyze_crop_rotation_impact() | |
| if not rotation_impact.empty: | |
| print("๐ Best rotations (lowest average IFT):") | |
| best_rotations = rotation_impact.head(10) | |
| for i, (_, row) in enumerate(best_rotations.iterrows(), 1): | |
| print(f" {i:2}. {row['rotation_type']:<40} IFT: {row['mean_ift']:.2f}") | |
| print() | |
| print("โ ๏ธ Worst rotations (highest average IFT):") | |
| worst_rotations = rotation_impact.tail(5) | |
| for i, (_, row) in enumerate(worst_rotations.iterrows(), 1): | |
| print(f" {i:2}. {row['rotation_type']:<40} IFT: {row['mean_ift']:.2f}") | |
| else: | |
| print("โ Insufficient data for rotation analysis") | |
| print() | |
| except Exception as e: | |
| print(f"โ Rotation analysis error: {e}") | |
| print() | |
| # Herbicide usage analysis | |
| print("๐ HERBICIDE USAGE ANALYSIS") | |
| print("-" * 60) | |
| try: | |
| herbicide_analysis = analyzer.analyze_herbicide_alternatives() | |
| print("๐ Most frequently used herbicides:") | |
| top_herbicides = herbicide_analysis.head(10) | |
| for i, (_, row) in enumerate(top_herbicides.iterrows(), 1): | |
| crop_info = f" ({row['crop_type']})" if pd.notna(row['crop_type']) else "" | |
| print(f" {i:2}. {row['produit']:<30}{crop_info}") | |
| print(f" Applications: {row['applications']:<3} | Total qty: {row['total_quantity']:.1f}") | |
| print() | |
| except Exception as e: | |
| print(f"โ Herbicide analysis error: {e}") | |
| print() | |
| # Summary and recommendations | |
| print("๐ SUMMARY AND RECOMMENDATIONS") | |
| print("="*60) | |
| print("โ ACHIEVEMENTS:") | |
| print(" โข Successfully loaded and analyzed 10 years of intervention data") | |
| print(" โข Calculated weed pressure trends using IFT methodology") | |
| print(" โข Developed predictive model for future weed pressure") | |
| print(" โข Identified suitable plots for sensitive crops") | |
| print(" โข Analyzed impact of crop rotations") | |
| print() | |
| print("๐ฏ KEY INSIGHTS:") | |
| avg_ift = summary['mean_ift'] | |
| if avg_ift < 1.0: | |
| print(" โข Overall weed pressure is LOW - good for sensitive crops") | |
| elif avg_ift < 2.0: | |
| print(" โข Overall weed pressure is MODERATE - requires monitoring") | |
| else: | |
| print(" โข Overall weed pressure is HIGH - needs intervention") | |
| print(f" โข Current average IFT: {avg_ift:.2f}") | |
| print(f" โข {df.plot_name.nunique()} plots available for analysis") | |
| print(f" โข {df.crop_type.nunique()} different crop types in rotation") | |
| print() | |
| print("๐ NEXT STEPS:") | |
| print(" โข Use the Gradio interface for interactive analysis") | |
| print(" โข Deploy on Hugging Face Spaces for broader access") | |
| print(" โข Configure MCP server for LLM integration") | |
| print(" โข Upload dataset to Hugging Face Hub") | |
| print() | |
| print("๐ ACCESS THE TOOL:") | |
| print(" โข Gradio Interface: python gradio_app.py") | |
| print(" โข MCP Server: python mcp_server.py") | |
| print(" โข HF Deployment: python app.py") | |
| print() | |
| print("๐" + "="*60) | |
| print(" DEMO COMPLETED SUCCESSFULLY!") | |
| print("="*63) | |
| if __name__ == "__main__": | |
| main() | |