Spaces:
Build error
Build error
Update app.py
Browse files123434566789910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293579495969798991001011021031041051061071081091101111121131141151161175960616263641181191201211221231241251261271281291301311321331346667686970135136727313713813914014114214314414514614714814915015115215315415515615715815975767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198import streamlit as stimport pandas as pdimport numpy as npfrom datetime import datetimeimport foliumfrom streamlit_folium import folium_staticimport jdatetimeimport plotly.express as pximport sqlite3import jsonfrom pathlib import Path
# تنظیمات اولیهst.set_page_config(page_title="سامانه مدیریت مزارع نیشکر", layout="wide", direction="rtl")
# ایجاد دیتابیسdef init_db(): conn = sqlite3.connect('sugarcane_farms.db') c = conn.cursor() c.execute(''' CREATE TABLE IF NOT EXISTS farm_data ( id INTEGER PRIMARY KEY AUTOINCREMENT, row_number INTEGER, representative TEXT, channel INTEGER, department INTEGER, production INTEGER, cultivation_area REAL, sub_area REAL, variety TEXT, age TEXT, station1 REAL, station2 REAL, station3 REAL, station4 REAL, station5 REAL, current_height REAL, previous_height REAL, current_growth REAL, previous_growth REAL, current_nitrogen REAL, current_nitrogen_std REAL, previous_nitrogen REAL, previous_nitrogen_std REAL, current_moisture REAL, current_moisture_std REAL, previous_moisture REAL, previous_moisture_std REAL, well1_depth REAL, well2_depth REAL, reading_date DATE ) ''') conn.commit() conn.close()
# فرم ورود دادهdef data_entry_form(): st.header("فرم ورود دادههای مزارع نیشکر")# تنظیمات اولیه صفحهst.set_page_config( page_title="مدیریت چاهکهای مزارع نیشکر", page_icon="🌱", layout="wide", initial_sidebar_state="expanded")
# CSS برای راست به چپ کردن متنهاst.markdown( """ <style> .css-1d391kg { direction: rtl; } .stButton>button { float: right; } .stSelectbox>div>div { direction: rtl; text-align: right; } </style> """, unsafe_allow_html=True)
# تعریف دادههای اولیه@st.cache_datadef load_initial_data(): data = { 'مزرعه': ['01-28', '02-19', '02-27', '03-08', '03-30', '03-32'], 'کانال': ['01', '02', '02', '03', '03', '03'], 'اداره': [1, 2, 2, 1, 1, 1], 'واریته': ['CP69', 'CP69', 'CP69', 'CP69', 'IR01-412', 'IRC00-14'], 'مساحت': [23.83, 24.53, 24.84, 23.17, 23.35, 22.97], 'چاهک_1_نصب': [False] * 6, 'چاهک_1_تکنسین': [''] * 6, 'چاهک_1_تاریخ': [''] * 6, 'چاهک_1_lat': [0.0] * 6, 'چاهک_1_lon': [0.0] * 6, 'چاهک_2_نصب': [False] * 6, 'چاهک_2_تکنسین': [''] * 6, 'چاهک_2_تاریخ': [''] * 6, 'چاهک_2_lat': [0.0] * 6, 'چاهک_2_lon': [0.0] * 6, } return pd.DataFrame(data)
# لود دادههاif 'farms_data' not in st.session_state: st.session_state.farms_data = load_initial_data()
# تعریف تکنسینهاTECHNICIANS = [ 'علی دغاغله', 'علیرضا حمیدی', 'مسعود بن موسی', 'امین هنری']
# عنوان اصلیst.title("🌱 مدیریت چاهکهای مزارع نیشکر")
# سایدبار برای فیلتر کردنwith st.sidebar: st.header("فیلترها") selected_department = st.selectbox( "انتخاب اداره", options=[0, 1, 2, 3, 4], format_func=lambda x: "همه ادارات" if x == 0 else f"اداره {x}", ) search_term = st.text_input("جستجو بر اساس نام مزرعه یا کانال")
# فیلتر کردن دادههاfiltered_data = st.session_state.farms_data.copy()if selected_department != 0: filtered_data = filtered_data[filtered_data['اداره'] == selected_department]if search_term: mask = (filtered_data['مزرعه'].str.contains(search_term)) | (filtered_data['کانال'].str.contains(search_term)) filtered_data = filtered_data[mask]
# نمایش آمار کلی col1, col2, col3 = st.columns(3)col1, col2, col3 = st.columns(3)with col1: total_wells = len(filtered_data) * 2 installed_wells = filtered_data['چاهک_1_نصب'].sum() + filtered_data['چاهک_2_نصب'].sum() st.metric("کل چاهکها", total_wells)
with col2: st.metric("چاهکهای نصب شده", installed_wells)
with col3: st.metric("چاهکهای باقیمانده", total_wells - installed_wells)
# نمایش نقشهst.header("🗺️ نقشه چاهکها")m = folium.Map(location=[31.3183, 48.6706], zoom_start=10)
for idx, row in filtered_data.iterrows(): if row['چاهک_1_نصب'] and row['چاهک_1_lat'] != 0: folium.Marker( [row['چاهک_1_lat'], row['چاهک_1_lon']], popup=f"مزرعه: {row['مزرعه']}<br>چاهک: 1<br>تکنسین: {row['چاهک_1_تکنسین']}<br>تاریخ: {row['چاهک_1_تاریخ']}", icon=folium.Icon(color='red') ).add_to(m) with col1: row_number = st.number_input("ردیف", min_value=1, max_value=99) representative = st.text_input("نماینده (مثال: 01-22)") channel = st.selectbox("کانال", options=[i for i in range(1, 31) if i != 28]) department = st.selectbox("اداره", options=[1, 2, 3, 4]) production = st.selectbox("تولید", options=[1, 2]) if row['چاهک_2_نصب'] and row['چاهک_2_lat'] != 0: folium.Marker( [row['چاهک_2_lat'], row['چاهک_2_lon']], popup=f"مزرعه: {row['مزرعه']}<br>چاهک: 2<br>تکنسین: {row['چاهک_2_تکنسین']}<br>تاریخ: {row['چاهک_2_تاریخ']}", icon=folium.Icon(color='blue') ).add_to(m)
folium_static(m)
# لیست مزارع و ثبت چاهکst.header("📝 لیست مزارع و ثبت چاهک")
for idx, row in filtered_data.iterrows(): with st.expander(f"مزرعه {row['مزرعه']} - کانال {row['کانال']}"): st.write(f"واریته: {row['واریته']}") st.write(f"مساحت: {row['مساحت']} هکتار") with col2: cultivation_area = st.number_input("مساحت داشت", min_value=0.0) sub_area = st.number_input("مساحت زیرمجموعه", min_value=0.0) variety = st.selectbox("واریته", options=["CP69", "CP48", "CP57"]) age = st.selectbox("سن", options=["R1", "R2", "P"]) col1, col2 = st.columns(2) with col3: reading_date = st.date_input("تاریخ قرائت") # چاهک 1 with col1: st.subheader("چاهک 1") if not row['چاهک_1_نصب']: if st.button(f"ثبت نصب چاهک 1 - مزرعه {row['مزرعه']}", key=f"well1_{idx}"): technician = st.selectbox( "انتخاب تکنسین", options=TECHNICIANS, key=f"tech1_{idx}" ) lat = st.number_input("عرض جغرافیایی", value=31.3183, key=f"lat1_{idx}") lon = st.number_input("طول جغرافیایی", value=48.6706, key=f"lon1_{idx}") if st.button("ثبت نهایی", key=f"save1_{idx}"): st.session_state.farms_data.at[idx, 'چاهک_1_نصب'] = True st.session_state.farms_data.at[idx, 'چاهک_1_تکنسین'] = technician st.session_state.farms_data.at[idx, 'چاهک_1_تاریخ'] = jdatetime.datetime.now().strftime("%Y/%m/%d") st.session_state.farms_data.at[idx, 'چاهک_1_lat'] = lat st.session_state.farms_data.at[idx, 'چاهک_1_lon'] = lon st.success("چاهک 1 با موفقیت ثبت شد") st.rerun() else: st.info(f"نصب شده توسط {row['چاهک_1_تکنسین']} در تاریخ {row['چاهک_1_تاریخ']}") # ایستگاههای اندازهگیری st.subheader("ایستگاههای اندازهگیری") col1, col2, col3, col4, col5 = st.columns(5) with col1: station1 = st.number_input("ایستگاه 1", min_value=0.0) with col2: station2 = st.number_input("ایستگاه 2", min_value=0.0) with col3: station3 = st.number_input("ایستگاه 3", min_value=0.0) with col4: station4 = st.number_input("ایستگاه 4", min_value=0.0) with col5: station5 = st.number_input("ایستگاه 5", min_value=0.0) # محاسبه خودکار ارتفاع هفته جاری current_height = np.mean([station1, station2, station3, station4, station5]) st.info(f"ارتفاع هفته جاری مزرعه (محاسبه شده): {current_height:.2f}") # ادامه فرم... col1, col2 = st.columns(2) with col1: previous_height = st.number_input("ارتفاع هفته گذشته مزرعه", min_value=0.0) current_growth = current_height - previous_height st.info(f"رشد هفته جاری (محاسبه شده): {current_growth:.2f}") previous_growth = st.number_input("رشد هفته گذشته", min_value=0.0)
# دکمه ذخیره if st.button("ذخیره اطلاعات"): save_data(locals()) st.success("اطلاعات با موفقیت ذخیره شد!")
# تابع ذخیرهسازی دادههاdef save_data(data): conn = sqlite3.connect('sugarcane_farms.db') c = conn.cursor() # ایجاد query برای ذخیره دادهها query = """ INSERT INTO farm_data ( row_number, representative, channel, department, production, cultivation_area, sub_area, variety, age, station1, station2, station3, station4, station5, current_height, previous_height, current_growth, previous_growth, reading_date ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """ values = ( data['row_number'], data['representative'], data['channel'], data['department'], data['production'], data['cultivation_area'], data['sub_area'], data['variety'], data['age'], data['station1'], data['station2'], data['station3'], data['station4'], data['station5'], data['current_height'], data['previous_height'], data['current_growth'], data['previous_growth'], data['reading_date'] ) c.execute(query, values) conn.commit() conn.close()
# اجرای برنامهif __name__ == "__main__": init_db() data_entry_form() # چاهک 2 with col2: st.subheader("چاهک 2") if not row['چاهک_2_نصب']: if st.button(f"ثبت نصب چاهک 2 - مزرعه {row['مزرعه']}", key=f"well2_{idx}"): technician = st.selectbox( "انتخاب تکنسین", options=TECHNICIANS, key=f"tech2_{idx}" ) lat = st.number_input("عرض جغرافیایی", value=31.3183, key=f"lat2_{idx}") lon = st.number_input("طول جغرافیایی", value=48.6706, key=f"lon2_{idx}") if st.button("ثبت نهایی", key=f"save2_{idx}"): st.session_state.farms_data.at[idx, 'چاهک_2_نصب'] = True st.session_state.farms_data.at[idx, 'چاهک_2_تکنسین'] = technician st.session_state.farms_data.at[idx, 'چاهک_2_تاریخ'] = jdatetime.datetime.now().strftime("%Y/%m/%d") st.session_state.farms_data.at[idx, 'چاهک_2_lat'] = lat st.session_state.farms_data.at[idx, 'چاهک_2_lon'] = lon st.success("چاهک 2 با موفقیت ثبت شد") st.rerun() else: st.info(f"نصب شده توسط {row['چاهک_2_تکنسین']} در تاریخ {row['چاهک_2_تاریخ']}")
# نمودار پیشرفت نصب به تفکیک ادارهst.header("📊 گزارش پیشرفت نصب")progress_data = []for dept in range(1, 5): dept_data = st.session_state.farms_data[st.session_state.farms_data['اداره'] == dept] total = len(dept_data) * 2 installed = dept_data['چاهک_1_نصب'].sum() + dept_data['چاهک_2_نصب'].sum() progress_data.append({ 'اداره': f'اداره {dept}', 'درصد پیشرفت': (installed / total * 100) if total > 0 else 0 })
progress_df = pd.DataFrame(progress_data)fig = px.bar(progress_df, x='اداره', y='درصد پیشرفت', title='درصد پیشرفت نصب چاهکها به تفکیک اداره')st.plotly_chart(fig)app.py+188-129