mcp / demo.py
Tracy Andrรฉ
updated
7ca901a
raw
history blame
8.71 kB
#!/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()