persadian commited on
Commit
54ce4f3
Β·
verified Β·
1 Parent(s): ded9744

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -32
app.py CHANGED
@@ -1,82 +1,171 @@
1
  import gradio as gr
2
  import pandas as pd
 
3
 
 
 
 
4
  def get_crop_recommendation(soil_type, climate, history):
5
- # Replace with your actual model inference logic
6
  recommendations = {
7
- "soil": soil_type,
8
- "climate": climate,
9
- "recommended_crops": ["Pepper", "Tomato", "Chilli"],
10
- "confidence": [0.85, 0.76, 0.68]
 
 
 
 
 
11
  }
12
  return pd.DataFrame(recommendations)
13
 
14
  def analyze_conditions(query, history):
15
- # Condition analysis handler (connect to your LLM)
16
- response = f"🌱 CropAI Analysis: Optimal cultivation patterns suggest {get_crop_recommendation('Loam', 'Tropical', '').iloc[0]['recommended_crops'][0]} for these conditions."
 
17
  return response
18
 
19
- with gr.Blocks(theme=gr.themes.Soft(), title="CropSeek LLM") as demo:
 
 
 
 
 
 
20
  gr.HTML("""
21
- <div style="text-align:center">
22
  <img src="https://huggingface.co/spaces/DARJYO/CropSeek-LLM/resolve/main/assets/logo.png"
23
- style="height:80px; margin-bottom:20px;">
 
 
24
  </div>
25
  """)
26
-
27
- gr.Markdown("### 🌾 AI-Driven Crop Optimization System")
28
-
 
29
  with gr.Tab("🌱 Field Analysis Console"):
30
  with gr.Row():
31
  with gr.Column(scale=2):
32
  analysis_log = gr.Chatbot(
33
  label="Crop Diagnosis History",
34
  avatar_images=("πŸ§‘πŸŒΎ", "πŸ€–"),
35
- height=400
 
36
  )
 
37
  with gr.Column(scale=1):
 
38
  field_input = gr.Textbox(
39
- label="Describe Soil & Climate Conditions:",
40
- placeholder="e.g. 'Clay soil in tropical climate with moderate rainfall...'"
 
41
  )
42
- analyze_btn = gr.Button("🌦️ Analyze Agricultural Patterns", variant="primary")
43
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  analyze_btn.click(
45
  analyze_conditions,
46
  [field_input, analysis_log],
47
  [field_input, analysis_log]
48
  )
49
-
 
 
 
50
  with gr.Tab("πŸ“ˆ Yield Optimization Advisor"):
51
  with gr.Row():
52
  soil_dd = gr.Dropdown(
53
- ["Loamy", "Clay", "Sandy"],
54
  label="Soil Composition",
55
- info="Select predominant soil type"
 
56
  )
57
  climate_dd = gr.Dropdown(
58
- ["Tropical", "Temperate", "Arid"],
59
  label="Climate Profile",
60
- info="Select regional climate pattern"
 
61
  )
62
- farm_data = gr.File(
63
- label="Upload Field Sensor Data (CSV)",
64
- file_types=[".csv"]
65
- )
66
- simulate_btn = gr.Button("🚜 Generate Cultivation Plan", variant="primary")
 
 
 
 
 
 
 
 
67
  results = gr.Dataframe(
68
  headers=["Parameter", "Value", "Recommendation"],
69
  interactive=False,
70
  wrap=True,
71
- datatype=["str", "number", "str"]
 
72
  )
73
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  simulate_btn.click(
75
  fn=get_crop_recommendation,
76
  inputs=[soil_dd, climate_dd, farm_data],
77
  outputs=results
78
  )
79
 
80
- gr.Markdown("---\n*Agricultural Intelligence Platform | v2.1*")
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
- demo.launch()
 
 
 
 
 
1
  import gradio as gr
2
  import pandas as pd
3
+ from datetime import datetime
4
 
5
+ # ----------------------
6
+ # Mock Model Components
7
+ # ----------------------
8
  def get_crop_recommendation(soil_type, climate, history):
9
+ """Mock recommendation engine"""
10
  recommendations = {
11
+ "Parameter": ["Soil Type", "Climate Zone", "Top Crop", "Alternative 1", "Alternative 2"],
12
+ "Value": [soil_type, climate, "Pepper (0.85)", "Tomato (0.76)", "Chilli (0.68)"],
13
+ "Recommendation": [
14
+ "Optimal for root development",
15
+ "Ideal temperature range",
16
+ "High market demand",
17
+ "Good disease resistance",
18
+ "Drought tolerant"
19
+ ]
20
  }
21
  return pd.DataFrame(recommendations)
22
 
23
  def analyze_conditions(query, history):
24
+ """Mock analysis engine"""
25
+ response = f"🌱 **CropAI Analysis**: Based on '{query}', optimal cultivation patterns suggest **Pepper** (85% confidence) followed by Tomato and Chilli. "
26
+ response += "Recommended practices: Drip irrigation with weekly pH monitoring."
27
  return response
28
 
29
+ # ----------------------
30
+ # UI Components
31
+ # ----------------------
32
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="emerald"), title="CropSeek AI") as demo:
33
+ # ----------------------
34
+ # Enhanced Header
35
+ # ----------------------
36
  gr.HTML("""
37
+ <div style="text-align:center; background: linear-gradient(to right, #2c5f2d, #97bc62); padding: 20px; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
38
  <img src="https://huggingface.co/spaces/DARJYO/CropSeek-LLM/resolve/main/assets/logo.png"
39
+ style="height:100px; filter: drop-shadow(2px 2px 4px #00000060);">
40
+ <h1 style="color: white; margin: 10px 0; font-family: 'Arial Rounded MT Bold', sans-serif;">CropSeek AI</h1>
41
+ <h3 style="color: #fafafa; font-weight: 300;">Next-Gen Agricultural Intelligence Platform</h3>
42
  </div>
43
  """)
44
+
45
+ # ----------------------
46
+ # Main Analysis Interface
47
+ # ----------------------
48
  with gr.Tab("🌱 Field Analysis Console"):
49
  with gr.Row():
50
  with gr.Column(scale=2):
51
  analysis_log = gr.Chatbot(
52
  label="Crop Diagnosis History",
53
  avatar_images=("πŸ§‘πŸŒΎ", "πŸ€–"),
54
+ height=450,
55
+ bubble_full_width=False
56
  )
57
+
58
  with gr.Column(scale=1):
59
+ gr.Markdown("### 🌦️ Environmental Parameters")
60
  field_input = gr.Textbox(
61
+ label="Describe Conditions:",
62
+ placeholder="e.g. 'Clay soil in tropical climate with 1200mm rainfall...'",
63
+ lines=3
64
  )
65
+
66
+ gr.Examples(
67
+ examples=[
68
+ ["Sandy loam soil with temperate climate and irrigation access"],
69
+ ["Arid region with limited water resources and alkaline soil"],
70
+ ["Volcanic soil in subtropical highland climate"]
71
+ ],
72
+ inputs=field_input,
73
+ label="πŸ’‘ Try Example Scenarios:"
74
+ )
75
+
76
+ analyze_btn = gr.Button(
77
+ "πŸ” Analyze Agricultural Patterns",
78
+ variant="primary",
79
+ size="lg"
80
+ )
81
+
82
  analyze_btn.click(
83
  analyze_conditions,
84
  [field_input, analysis_log],
85
  [field_input, analysis_log]
86
  )
87
+
88
+ # ----------------------
89
+ # Data Analysis Interface
90
+ # ----------------------
91
  with gr.Tab("πŸ“ˆ Yield Optimization Advisor"):
92
  with gr.Row():
93
  soil_dd = gr.Dropdown(
94
+ ["Loamy", "Clay", "Sandy", "Volcanic", "Peaty"],
95
  label="Soil Composition",
96
+ info="USDA soil classification",
97
+ interactive=True
98
  )
99
  climate_dd = gr.Dropdown(
100
+ ["Tropical", "Temperate", "Arid", "Mediterranean", "Continental"],
101
  label="Climate Profile",
102
+ info="KΓΆppen climate classification",
103
+ interactive=True
104
  )
105
+
106
+ with gr.Row():
107
+ farm_data = gr.File(
108
+ label="Upload Field Sensor Data (CSV)",
109
+ file_types=[".csv"],
110
+ height=50
111
+ )
112
+ simulate_btn = gr.Button(
113
+ "🚜 Generate Cultivation Plan",
114
+ variant="primary",
115
+ size="lg"
116
+ )
117
+
118
  results = gr.Dataframe(
119
  headers=["Parameter", "Value", "Recommendation"],
120
  interactive=False,
121
  wrap=True,
122
+ datatype=["str", "markdown", "str"],
123
+ height=400
124
  )
125
+
126
+ # ----------------------
127
+ # Data Validation
128
+ # ----------------------
129
+ @demo.load(inputs=farm_data, outputs=results)
130
+ def validate_data(file_input):
131
+ if file_input:
132
+ try:
133
+ df = pd.read_csv(file_input.name)
134
+ required_columns = ['pH', 'Nitrogen', 'Phosphorus', 'Potassium']
135
+ if not all(col in df.columns for col in required_columns):
136
+ raise ValueError("Missing required soil analysis columns")
137
+ return df.head().style.set_properties(**{
138
+ 'background-color': '#f0f7e4',
139
+ 'color': '#2c5f2d',
140
+ 'border-color': '#97bc62'
141
+ })
142
+ except Exception as e:
143
+ raise gr.Error(f"⚠️ Data validation error: {str(e)}")
144
+ return pd.DataFrame()
145
+
146
  simulate_btn.click(
147
  fn=get_crop_recommendation,
148
  inputs=[soil_dd, climate_dd, farm_data],
149
  outputs=results
150
  )
151
 
152
+ # ----------------------
153
+ # Footer & Status
154
+ # ----------------------
155
+ gr.Markdown("---")
156
+ with gr.Row():
157
+ gr.Markdown(f"**Last Updated:** {datetime.now().strftime('%Y-%m-%d %H:%M')}")
158
+ gr.Markdown("**System Status:** 🟒 Operational")
159
+ gr.Markdown("**Version:** 2.1.0")
160
+
161
+ gr.Markdown("""
162
+ <div style="text-align: center; padding: 15px; background-color: #f8f9fa; border-radius: 8px; margin-top: 20px;">
163
+ <small>Β© 2023 CropSeek AI | Agricultural Intelligence Platform | Contact: [email protected]</small>
164
+ </div>
165
+ """)
166
 
167
+ # ----------------------
168
+ # Launch Application
169
+ # ----------------------
170
+ if __name__ == "__main__":
171
+ demo.launch()