Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,140 +1,171 @@
|
|
1 |
import gradio as gr
|
2 |
import pandas as pd
|
3 |
from datetime import datetime
|
4 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
5 |
|
6 |
# ----------------------
|
7 |
-
#
|
8 |
# ----------------------
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
system_prompt = """You are CropSeek AI, an expert agricultural assistant.
|
24 |
-
Provide detailed, professional crop recommendations based on:
|
25 |
-
- Soil type
|
26 |
-
- Climate conditions
|
27 |
-
- Historical yield data
|
28 |
-
- Regional market trends
|
29 |
-
- Sustainability practices
|
30 |
-
|
31 |
-
Structure responses with:
|
32 |
-
1. Top 3 recommended crops
|
33 |
-
2. Confidence percentages
|
34 |
-
3. Cultivation guidelines
|
35 |
-
4. Risk factors
|
36 |
-
5. Market outlook"""
|
37 |
-
|
38 |
-
prompt = f"""<s>[INST] <<SYS>>
|
39 |
-
{system_prompt}
|
40 |
-
<</SYS>>
|
41 |
-
|
42 |
-
User Query: {query} [/INST]"""
|
43 |
-
|
44 |
-
response = agriculture_pipe(
|
45 |
-
prompt,
|
46 |
-
max_new_tokens=512,
|
47 |
-
temperature=0.7,
|
48 |
-
repetition_penalty=1.1,
|
49 |
-
do_sample=True
|
50 |
-
)[0]['generated_text'].split('[/INST]')[-1].strip()
|
51 |
-
|
52 |
return response
|
53 |
|
54 |
# ----------------------
|
55 |
-
#
|
56 |
-
# ----------------------
|
57 |
-
def analyze_agricultural_data(soil_type, climate, farm_data):
|
58 |
-
# Generate text analysis using the LLM
|
59 |
-
query = f"""Analyze farming conditions for:
|
60 |
-
- Soil type: {soil_type}
|
61 |
-
- Climate: {climate}
|
62 |
-
- Farm data: {pd.read_csv(farm_data.name).describe() if farm_data else 'No data'}
|
63 |
-
|
64 |
-
Provide recommendations in table format with columns:
|
65 |
-
Crop | Confidence | Planting Window | Water Needs | Fertilizer | Yield Potential"""
|
66 |
-
|
67 |
-
response = generate_agricultural_response(query)
|
68 |
-
|
69 |
-
# Convert response to structured data
|
70 |
-
try:
|
71 |
-
df = pd.DataFrame([x.split('|') for x in response.split('\n') if '|' in x],
|
72 |
-
columns=["Crop", "Confidence", "Planting Window", "Water Needs", "Fertilizer", "Yield Potential"])
|
73 |
-
return df
|
74 |
-
except:
|
75 |
-
return response
|
76 |
-
|
77 |
-
# ----------------------
|
78 |
-
# Gradio Interface
|
79 |
# ----------------------
|
80 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="emerald"), title="CropSeek AI") as demo:
|
81 |
-
#
|
|
|
|
|
82 |
gr.HTML("""
|
83 |
-
<div style="text-align:center; background: linear-gradient(to right, #2c5f2d, #97bc62); padding: 20px; border-radius: 10px;">
|
84 |
-
<
|
85 |
-
|
|
|
|
|
86 |
</div>
|
87 |
""")
|
88 |
|
|
|
89 |
# Main Analysis Interface
|
90 |
-
|
|
|
91 |
with gr.Row():
|
92 |
with gr.Column(scale=2):
|
93 |
-
|
94 |
-
label="
|
95 |
avatar_images=("🧑🌾", "🤖"),
|
96 |
-
height=
|
|
|
97 |
)
|
98 |
-
|
99 |
with gr.Column(scale=1):
|
100 |
-
gr.Markdown("###
|
101 |
-
|
102 |
-
|
103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
)
|
105 |
-
|
106 |
-
|
107 |
-
|
|
|
|
|
108 |
)
|
109 |
-
farm_data = gr.File(label="Upload Field Data (CSV)")
|
110 |
-
analyze_btn = gr.Button("🚜 Generate Cultivation Plan", variant="primary")
|
111 |
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
)
|
118 |
|
119 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
gr.Markdown("---")
|
|
|
|
|
|
|
|
|
|
|
121 |
gr.Markdown("""
|
122 |
-
<div style="text-align: center; padding: 15px;">
|
123 |
-
<small
|
124 |
-
<a href="https://huggingface.co/DARJYO/darjyo-AgriLLM-GRPO" target="_blank">Model Documentation</a></small>
|
125 |
</div>
|
126 |
""")
|
127 |
|
128 |
# ----------------------
|
129 |
-
#
|
130 |
# ----------------------
|
131 |
-
requirements = """
|
132 |
-
gradio>=4.0
|
133 |
-
torch>=2.0
|
134 |
-
transformers>=4.30
|
135 |
-
pandas>=2.0
|
136 |
-
accelerate
|
137 |
-
"""
|
138 |
-
|
139 |
if __name__ == "__main__":
|
140 |
-
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>© 2025 DARJYO AI CropSeek | Agricultural Intelligence Platform | Contact: [email protected]</small>
|
|
|
164 |
</div>
|
165 |
""")
|
166 |
|
167 |
# ----------------------
|
168 |
+
# Launch Application
|
169 |
# ----------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
170 |
if __name__ == "__main__":
|
171 |
+
demo.launch()
|