-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
790 lines (662 loc) ยท 31.8 KB
/
app.py
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
import streamlit as st
import pyrebase
import firebase_admin
from firebase_admin import credentials, firestore
import datetime
import google.generativeai as genai
from PIL import Image
import requests
import json
import folium
from streamlit_folium import st_folium
import pandas as pd
import matplotlib.pyplot as plt
import random
import os
import time
# --- Configuration ---
# 1. Firebase Setup
# Replace placeholders with your actual Firebase project details
firebase_config = {
"apiKey": " ",
"authDomain": " ",
"projectId": " ",
"storageBucket": " ",
"messagingSenderId": "",
"appId": "",
"databaseURL": ""
}
# Initialize Firebase for authentication
firebase = pyrebase.initialize_app(firebase_config)
auth = firebase.auth()
# Initialize Firebase Admin for database access
#cred = credentials.Certificate('prithvi-45d3f-firebase-adminsdk-o4c77-62e1d077aa.json')
#firebase_admin.initialize_app(cred)
#db = firestore.client()
if 'firebase_app' not in st.session_state:
cred = credentials.Certificate('.json')
st.session_state['firebase_app'] = firebase_admin.initialize_app(cred)
db = firestore.client()
else:
db = firestore.client()
# 2. API Keys
# Replace with your actual API keys
SERPER_API_KEY = ""
GEMINI_API_KEY = ""
genai.configure(api_key=GEMINI_API_KEY)
# --- Helper Functions ---
def get_location_info(use_live_location):
if use_live_location:
try:
response = requests.get('https://ipinfo.io')
data = response.json()
return data['city'], data['region'], data['country'], data['loc']
except Exception as e:
st.error(f"Error fetching location: {e}")
return None, None, None, None
else:
return None, None, None, None
def display_error_message(e):
error_message = str(e)
if "WEAK_PASSWORD" in error_message:
st.error("Weak password. It should be at least 6 characters.")
elif "EMAIL_EXISTS" in error_message:
st.error("This email is already registered. Try logging in.")
elif "INVALID_EMAIL" in error_message:
st.error("Invalid email address. Please check your input.")
elif "EMAIL_NOT_FOUND" in error_message:
st.error("No account found with this email. Please sign up first.")
elif "INVALID_PASSWORD" in error_message:
st.error("Incorrect password. Please try again.")
else:
st.error(f"Authentication failed: {error_message}")
# --- App Modules ---
def login_signup():
if 'login_widgets_created' not in st.session_state:
st.session_state.login_widgets_created = False
if not st.session_state.login_widgets_created:
st.title("Welcome to Prithvi ๐พ")
st.subheader("Login / Sign Up ๐ป")
st.markdown(
"""
<style>
.stApp {
background-image: url('https://c1.wallpaperflare.com/preview/884/928/958/home-outside-thailand-cornfield-rice.jpg');
background-size: cover;
background-position: center;
}
</style>
""",
unsafe_allow_html=True
)
st.session_state.choice = st.selectbox("Select an option:", ["Login", "Sign Up"], index=0, key="login_signup_choice")
st.session_state.email = st.text_input("Enter your email โ๏ธ", placeholder="[email protected]", key="login_email")
st.session_state.password = st.text_input("Enter your password ๐", type="password", placeholder="Your Password", key="login_password")
st.session_state.login_widgets_created = True
choice = st.session_state.choice
email = st.session_state.email
password = st.session_state.password
if choice == "Sign Up":
if st.button("Sign Up ๐"):
try:
user = auth.create_user_with_email_and_password(email, password)
st.success("Account created successfully! Please log in.")
except Exception as e:
display_error_message(e)
elif choice == "Login":
if st.button("Login ๐ช"):
try:
user = auth.sign_in_with_email_and_password(email, password)
st.success("Login successful! ๐")
st.balloons()
st.write(f"Welcome {email} ๐ผ")
except Exception as e:
display_error_message(e)
def water_management():
st.title("Water Management System")
with st.sidebar:
st.markdown("""
1. ๐๏ธ Select your region or location
2. ๐
View historical water levels and trends
3. ๐ Get suggestions on optimal water management practices
""")
st.success("Use this tool to improve irrigation and water use efficiency!")
def predict_water_level(acres, crop, season, location):
prompt = f"""
Predict future water levels for the following conditions:
- Land area: {acres} acres
- Crop: {crop}
- Season: {season}
- Location: {location}
Provide a prediction for water levels in a format of:
- Sufficient: (Green)
- Enough: (Blue)
- Not Enough: (Red)
Also provide brief reasoning for the prediction with 2-3 points.
in neat format
"""
model = genai.GenerativeModel('gemini-1.0-pro')
response = model.generate_content(prompt)
return response.text
def flood_analysis(location):
prompt = f"Provide a flood analysis for the location: {location}"
model = genai.GenerativeModel('gemini-1.0-pro')
response = model.generate_content(prompt)
return response.text
def create_water_level_graph(season_data):
df = pd.DataFrame(season_data)
plt.figure(figsize=(10, 5))
plt.plot(df['Season'], df['Water Level'], marker='o')
plt.title('Season-wise Water Level Predictions')
plt.xlabel('Season')
plt.ylabel('Water Level (cm)')
plt.xticks(rotation=45)
plt.grid()
plt.tight_layout()
st.pyplot(plt)
def create_average_water_level_graph(season_data):
# Bar chart for average water levels
df = pd.DataFrame(season_data)
plt.figure(figsize=(10, 5))
plt.bar(df['Season'], df['Water Level'], color='blue', alpha=0.7)
plt.title('Average Water Levels by Season')
plt.xlabel('Season')
plt.ylabel('Average Water Level (cm)')
plt.grid(axis='y')
plt.tight_layout()
st.pyplot(plt)
def create_water_level_distribution_graph(prediction_results):
# Pie chart for water level distribution
labels = list(prediction_results.keys())
sizes = [result[0] for result in prediction_results.values()]
colors = ['green', 'blue', 'red']
plt.figure(figsize=(8, 8))
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140)
plt.axis('equal') # Equal aspect ratio ensures pie chart is circular.
plt.title('Water Level Distribution')
st.pyplot(plt)
# ... (Rest of the water_management functions)
def main():
st.title("๐ง Water Management System for Crop Growth ๐พ")
st.markdown(
"""
<style>
.title {
text-align: center;
font-size: 2.5em;
color: #3E7C17;
}
.header {
text-align: center;
font-size: 1.5em;
color: #2C4D25;
}
</style>
""",
unsafe_allow_html=True
)
acres = st.number_input("Enter land area (in acres)", min_value=1, value=10, step=1)
crop = st.text_input("Enter crop type (e.g., Rice, Wheat)")
season = st.selectbox("Select season", ["Summer", "Winter", "Rainy", "Monsoon"])
use_live_location = st.checkbox("Use live location")
if use_live_location:
city, region, country, coords = get_location_info(True)
st.write(f"Location: **{city}, {region}, {country}**")
location = f"{city}, {region}, {country}"
else:
st.write("Select location on the map:")
m = folium.Map(location=[20, 0], zoom_start=2)
m.add_child(folium.ClickForMarker())
map_data = st_folium(m, width=700, height=500)
location = None
if map_data and map_data['last_clicked'] is not None:
lat = map_data['last_clicked']['lat']
lon = map_data['last_clicked']['lng']
location = f"Latitude: {lat}, Longitude: {lon}"
if st.button("Predict Water Level ๐ง"):
if location and crop:
with st.spinner("Predicting water levels..."):
water_level_prediction = predict_water_level(acres, crop, season, location)
st.subheader("Water Level Prediction ๐")
st.write(water_level_prediction)
flood_info = flood_analysis(location)
st.subheader("Flood Analysis ๐")
st.write(flood_info)
random.seed(42)
# Create mock season data for graph demonstration
season_data = [
{"Season": "Summer", "Water Level": },
{"Season": "Winter", "Water Level": },
{"Season": "Rainy", "Water Level": },
{"Season": "Monsoon", "Water Level": },
]
# Create and display the water level graph
create_water_level_graph(season_data)
create_average_water_level_graph(season_data)
random.seed(42)
# Mock prediction results for pie chart
prediction_results = {
"Sufficient": (random.randint(20, 40), "Green"),
"Enough": (random.randint(15, 30), "Blue"),
"Not Enough": (random.randint(5, 20), "Red"),
}
create_water_level_distribution_graph(prediction_results)
if __name__ == "__main__":
main()
def crop_market_analysis():
def get_location_info(use_live_location):
if use_live_location:
response = requests.get('https://ipinfo.io')
data = response.json()
return data['city'], data['region'], data['country'], data['loc']
else:
return None, None, None, None
def get_crop_suggestions(acres, soil_type, start_month, end_month, location):
prompt = f"""
Suggest suitable crops for the following conditions:
- Land area: {acres} acres
- Soil type: {soil_type}
- Growing season: {start_month} to {end_month}
- Location: {location}
Provide a list of 3 recommended crops with very small 1-2 points brief explanations.
"""
model = genai.GenerativeModel('gemini-1.0-pro')
response = model.generate_content(prompt)
return response.text
def get_market_trends(location, crop):
url = "https://google.serper.dev/search"
payload = json.dumps({
"q": f"crop market trends {crop} {location} whether good or bad or neutral at least give something don't give inconclusive"
})
headers = {
'X-API-KEY': SERPER_API_KEY,
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
return response.json()
def analyze_market_trends(trends_data, crop, location):
if not trends_data.get("organic"):
return f"Market analysis for {crop} in {location} is inconclusive. Consider checking local sources for insights."
trend_info = trends_data.get("organic", [])
market_data = {}
for result in trend_info:
snippet = result.get('snippet', '').lower()
if "price" in snippet:
market_data["Current Market Price"] = result['snippet']
if "demand" in snippet:
market_data["Demand Level"] = result['snippet']
if "future" in snippet:
market_data["Future Price Prediction"] = result['snippet']
if not market_data:
return f"Market analysis for {crop} in {location} is not available. Based on general trends, it might be considered neutral."
summary = f"### Market Analysis for {crop} in {location}:\n"
for key, value in market_data.items():
summary += f"- **{key}**: {value}\n"
overall_sentiment = "Neutral" if "neutral" in summary.lower() else "Good"
summary += f"\n- **Overall Market Sentiment**: {overall_sentiment}"
return summary
def main():
# Set Streamlit page configuration
# Add a title and header with some styling
st.title("๐ฑ Crop Suggestion and Market Analysis ๐พ")
st.markdown(
"""
<style>
.title {
text-align: center;
font-size: 2.5em;
color: #3E7C17;
}
.header {
text-align: center;
font-size: 1.5em;
color: #2C4D25;
}
.stButton > button {
background-color: #4CAF50; /* Green */
color: white;
border: none;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
border-radius: 5px;
}
.stTextInput > div > input {
border-radius: 5px;
border: 2px solid #4CAF50; /* Green */
}
</style>
""",
unsafe_allow_html=True
)
with st.sidebar:
st.markdown("""
1. ๐ Select the crop you're interested in
2. ๐ View market trends and price fluctuations
3. ๐ Get insights on optimal selling times and regions
""")
st.warning("Use this tool to stay ahead in the crop market!")
# User inputs
acres = st.number_input("Enter land area (in acres)", min_value=1, value=10, step=1)
soil_type = st.selectbox("Select soil type", ["Loamy", "Black", "Red", "Sandy", "Clay", "Silt", "Peat"], key="soil_type_select")
start_month = st.selectbox("Select start month", ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], key="start_month_select")
end_month = st.selectbox("Select end month", ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], key="end_month_select")
use_live_location = st.checkbox("Use live location")
if use_live_location:
city, region, country, coords = get_location_info(True)
st.write(f"Location: **{city}, {region}, {country}**")
location = f"{city}, {region}, {country}"
else:
st.write("Select location on the map:")
m = folium.Map(location=[20, 0], zoom_start=2)
m.add_child(folium.ClickForMarker())
map_data = st_folium(m, width=700, height=500)
location = None
if map_data and map_data['last_clicked'] is not None:
lat = map_data['last_clicked']['lat']
lon = map_data['last_clicked']['lng']
location = f"Latitude: {lat}, Longitude: {lon}"
# Button to get crop suggestions
if st.button("Get Crop Suggestions ๐พ"):
if location:
with st.spinner("Generating crop suggestions..."):
suggestions = get_crop_suggestions(acres, soil_type, start_month, end_month, location)
st.subheader("Crop Suggestions ๐ฟ")
st.write(suggestions)
suggested_crops = [line.split(':')[0].strip() for line in suggestions.split('\n') if ':' in line]
st.subheader("Market Analysis ๐")
for crop in suggested_crops[:3]: # Analyze top 3 suggested crops
with st.spinner(f"Analyzing market trends for {crop}..."):
trends_data = get_market_trends(location, crop)
analysis = analyze_market_trends(trends_data, crop, location)
st.write(f"### {crop}")
st.write(analysis)
if __name__ == "__main__":
main()
def disease_prediction():
genai.configure(api_key="")
generation_config = {
"temperature": 0.15,
"top_p": 0.95,
"top_k": 64,
"max_output_tokens": 350,
}
# Initialize Gemini models
vision_model = genai.GenerativeModel("gemini-1.5-flash",generation_config=generation_config)
# Function to get location information
def get_location():
try:
response = requests.get('https://ipinfo.io')
if response.status_code == 200:
data = response.json()
return data.get('city', ''), data.get('region', ''), data.get('country', '')
else:
return None, None, None
except Exception as e:
st.error(f"Error fetching location: {str(e)}")
return None, None, None
# Improved prompt for crop disease diagnosis with location
def generate_prompt(city, region, country):
return f"""You are an expert in crop diseases and their cures, with specific knowledge about agricultural practices in {city}, {region}, {country}. Analyze the provided image and user's description to:
1. ๐ Identify the crop and any visible diseases or pest infestations.
2. ๐ฆ Provide a detailed explanation of the identified issue(s).
3. ๐ Recommend appropriate treatment methods and preventive measures, considering local climate and soil conditions in {city}, {region}.
4. ๐ฑ Suggest sustainable farming practices specific to {region}, {country} to avoid future occurrences.
5. ๐ Mention any local regulations or common practices in {country} related to the identified issue or recommended treatments.
also recommend few shops for it their location just ention famous shop stores (you must)
Please provide your analysis in a clear, concise manner, using emojis where appropriate to enhance readability. Limit your response to 250 words.
If the image or description is unclear or unrelated to crop diseases, politely ask for a clearer image or more specific information about the crop issue.
Try to wrap up the response within 250 words and in point form, with clean responses.
"""
# Streamlit UI
st.header(" ๐ฟ Crop Doctor: Location-Aware Disease Diagnosis & Treatment")
st.markdown("##### Upload an image of your crop to get expert advice tailored to your location!")
# Fetch location
city, region, country = get_location()
# Display location
if city and region and country:
st.success(f"๐ Your detected location: {city}, {region}, {country}")
else:
st.warning("๐ Unable to detect location. Recommendations may not be location-specific.")
# Sidebar for instructions
with st.sidebar:
st.header("๐ How to Use")
st.markdown("""
1. ๐ธ Upload a clear image of the affected crop
2. ๐ Describe the symptoms or concerns
3. ๐ฑ๏ธ Click 'Analyze Crop' for results
""")
st.info("For best results, ensure the image clearly shows the affected parts of the plant.")
# Main content area
col1, col2 = st.columns([1, 1])
with col1:
uploaded_file = st.file_uploader("๐ค Upload Crop Image", type=["jpg", "jpeg", "png"])
if uploaded_file:
image = Image.open(uploaded_file)
st.image(image, caption="Uploaded Crop Image", use_column_width=True)
with col2:
user_description = st.text_area("๐๏ธ Describe the symptoms or concerns (optional)", height=100)
analyze_button = st.button("๐ฌ Analyze Crop", type="primary")
if analyze_button and uploaded_file:
with st.spinner("๐ง Analyzing your crop based on local conditions..."):
# Generate location-aware prompt
prompt = generate_prompt(city, region, country)
# Combine image and text inputs for the model
response = vision_model.generate_content([prompt, image, user_description])
# Display results
st.success("โ
Analysis Complete!")
st.markdown("### ๐ Location-Aware Diagnosis and Recommendations")
st.markdown(response.text)
# Additional UI elements for a richer experience
st.snow()
elif analyze_button and not uploaded_file:
st.warning("โ ๏ธ Please upload an image before analysis.")
# Footer
st.markdown("---")
st.markdown("๐ Helping farmers grow healthier crops with location-specific advice, one diagnosis at a time.")
def chatbot_assistance():
# ... (Similar structure to water_management)
initial_prompt = """I am a highly knowledgeable farmer expert, ready to answer your questions on various aspects of agriculture, including:
* Crop selection and planting techniques
* Soil management and fertilization practices
* Irrigation and water management strategies
* Pest control and disease prevention methods
* Sustainable agricultural practices
* Livestock management and animal husbandry
* Agricultural tools and equipment
* And much more!
Feel free to ask me anything related to farming, and I'll provide you with informative and comprehensive answers.
Only respond for questions related to farming, other than farming don't answer anything.
Give tokes within 200 and wrap up the response within 200 words and in point form, with clean responses
"""
# Create the generation configuration with safety settings
generation_config = {
"temperature": 0.15,
"top_p": 0.95,
"top_k": 64,
"max_output_tokens": 200,
}
# Initialize the Gemini models
text_model = genai.GenerativeModel(model_name="gemini-1.5-flash", generation_config=generation_config)
vision_model = genai.GenerativeModel(model_name="gemini-1.5-flash", generation_config=generation_config)
# Initialize session state for conversation history
if 'conversation_history' not in st.session_state:
st.session_state.conversation_history = []
# Set page config
#st.set_page_config(page_title="Prithvi: Farmer Expert Chatbot", page_icon="๐พ", layout="wide")
# Custom CSS for better styling
st.markdown("""
<style>
.stApp {
background-color: #f0f4f8;
}
.css-1d391kg {
padding-top: 3rem;
}
.st-bw {
background-color: #ffffff;
}
</style>
""", unsafe_allow_html=True)
# Main layout
col1, col2 = st.columns([2, 1])
with col1:
st.title("๐พ Prithvi: Your Farmer Expert Chatbot")
st.subheader("๐ฑ Ask me anything related to farming!")
user_input = st.text_input("๐ฌ Your question:")
uploaded_file = st.file_uploader("๐ธ Upload an image (optional):", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image, caption="Uploaded Image", use_column_width=True)
if st.button("๐ Get Answer"):
if user_input:
with st.spinner("๐ค Thinking..."):
if uploaded_file:
# If image is uploaded, use the vision model
response = vision_model.generate_content([ image, user_input,initial_prompt])
else:
# If no image, use the text model
prompt = initial_prompt + "\nYou: " + user_input
response = text_model.generate_content(prompt)
st.write("๐งโ๐พ **Expert:**", response.text)
# Update the conversation history in session state
st.session_state.conversation_history.append(("You:", user_input))
st.session_state.conversation_history.append(("Expert:", response.text))
with col2:
st.sidebar.title("๐ฌ Chat History")
if st.session_state.conversation_history:
for message in st.session_state.conversation_history:
if message[0] == "You:":
st.sidebar.markdown(f"๐ **You:** {message[1]}")
else:
st.sidebar.markdown(f"๐งโ๐พ **Expert:** {message[1]}")
st.sidebar.markdown("---")
# Footer
st.markdown("---")
st.markdown("๐ฟ Powered by Prithvi - Your AI Farming Assistant")
def farmer_community():
import streamlit as st
import firebase_admin
from firebase_admin import credentials, firestore
import datetime
from streamlit_chat import message
# Initialize Firebase Admin with appropriate error handling
try:
cred = credentials.Certificate('json')
if not firebase_admin._apps: # Ensure Firebase is initialized only once
firebase_admin.initialize_app(cred)
db = firestore.client()
print("Firebase Admin initialized successfully!")
except Exception as e:
st.error(f"Error initializing Firebase Admin: {e}")
# Function to share farming tip or discussion post
def share_tip(group_id, farm_name, message_text):
try:
db.collection('farmers_community').document(group_id).collection('tips').add({
'farm_name': farm_name,
'tip': message_text,
'timestamp': datetime.datetime.now()
})
st.success('Tip shared with the community!')
except Exception as e:
st.error(f"Error sharing the tip: {e}")
# Function to fetch tips from Firestore
def fetch_tips(group_id):
try:
tips_ref = db.collection('farmers_community').document(group_id).collection('tips').order_by('timestamp')
tips = tips_ref.stream()
return [(tip.to_dict()['farm_name'], tip.to_dict()['tip']) for tip in tips]
except Exception as e:
st.error(f"Error fetching tips: {e}")
return [] # Return an empty list on error
# Streamlit UI
st.markdown("<h1 style='text-align: center; color: green;'>Farmers Community Page ๐พ</h1>", unsafe_allow_html=True)
# Create a two-column layout: One for the input and another for the discussion
col1, col2 = st.columns([1, 2])
# Sidebar for community group and farm name
with col1:
st.markdown("<h3 style='color: darkgreen;'>Join a Discussion Group</h3>", unsafe_allow_html=True)
group_id = st.text_input('Enter Community Group:', value='General Farming', key='group_input')
farm_name = st.text_input('Enter Your Farm Name:', key='farm_input')
st.markdown("<p style='font-style: italic; color: grey;'>E.g., Crop Management, Market Trends</p>", unsafe_allow_html=True)
# Main chat interface on the right
with col2:
if farm_name:
st.markdown(f"<h4 style='color: green;'>Welcome, {farm_name}!</h4>", unsafe_allow_html=True)
message_text = st.text_area('Share your tip or advice:', key='message_input', height=100)
if st.button('Share'):
share_tip(group_id, farm_name, message_text)
# Display messages in chat format
if group_id:
st.subheader(f'Group: {group_id} Discussions')
tips = fetch_tips(group_id)
if tips:
for farm, tip in tips:
message(tip, is_user=(farm == farm_name), key=f"{farm}_{tip}")
else:
st.write("No tips shared yet. Be the first to contribute!")
# Additional styling for chat bubbles
st.markdown("""
<style>
.streamlit-expanderHeader {
font-size: 1.2rem;
color: darkgreen;
}
.streamlit-chat-message {
border: 1px solid #E8E8E8;
border-radius: 10px;
padding: 10px;
margin: 10px 0;
background-color: #F9F9F9;
}
.streamlit-chat-message-user {
background-color: #DFF0D8;
border-left: 5px solid #4CAF50;
}
</style>
""", unsafe_allow_html=True)
def main_app():
st.sidebar.title("Prithvi Dashboard๐")
app_mode = st.sidebar.selectbox("Choose a feature",
["Home", "Water Management", "Crop Market Analysis",
"Disease Prediction", "Chatbot Assistance", "Farmer Community"],key="main_app_mode")
if app_mode == "Home":
st.image("component 1.png")
st.title("๐พ Welcome to Prithvi ๐พ")
st.write("Prithvi is an advanced agricultural assistance platform designed to empower farmers with cutting-edge technology and data-driven insights.")
st.markdown("### ๐ฑ **Empowering Farmers with Data-Driven Insights**")
st.markdown("""
## **Prithvi: Your AI-Powered Farming Assistant** ๐
๐ **Water Management:**
- ๐ฎ **Predict Future Water Levels**: Get AI-powered forecasts for water availability to ensure efficient irrigation.
- ๐ **Flood Analysis**: Understand flood risks in your region with detailed analysis.
- ๐ **Visualize Water Data**: Season-wise water trends and predictions, all in one place.
๐พ **Crop Market Analysis:**
- ๐ก **Crop Suggestions**: Receive tailored recommendations based on your land, soil, and season.
- ๐ **Market Trends**: Analyze current and forecasted prices to determine the best time to sell.
๐ฆ **Disease Prediction:**
- ๐ท **Image-Based Diagnosis**: Upload images of your crops to identify diseases and pests.
- ๐ **Location-Aware Recommendations**: Get advice tailored to your region's conditions for effective treatment.
๐ฌ **Chatbot Assistance**:
- ๐ฃ๏ธ **Instant Farming Advice**: Ask questions and get instant solutions from the AI chatbot.
- ๐ผ๏ธ **Image Support**: Upload crop images for more personalized insights.
๐ฉโ๐พ **Farmer Community**:
- ๐ค **Connect with Farmers**: Share experiences, tips, and ask questions in the community.
- ๐ฌ **Group Discussions**: Participate in specific discussions on topics like crop management and market trends.
""")
elif app_mode == "Water Management":
water_management()
elif app_mode == "Crop Market Analysis":
crop_market_analysis()
elif app_mode == "Disease Prediction":
disease_prediction()
elif app_mode == "Chatbot Assistance":
chatbot_assistance()
elif app_mode == "Farmer Community":
farmer_community()
if __name__ == "__main__":
main_app()