Spaces:
Running
Running
File size: 8,706 Bytes
7ca901a |
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 |
#!/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()
|