CoolFace
Apppublic

MehtabAhmed/Crop_Yields_Predicton

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py102 linesDownload Raw Back to root
1import os2import streamlit as st3import pandas as pd4from streamlit_extras.colored_header import colored_header5from streamlit_extras.add_vertical_space import add_vertical_space6from groq import Groq7 8# Initialize Groq API9 10client = Groq(api_key=os.getenv("crop_prediction"))11 12# Function to query Groq API13def query_groq(prompt, model="llama3-8b-8192"):14    chat_completion = client.chat.completions.create(15        messages=[{"role": "user", "content": prompt}],16        model=model,17    )18    return chat_completion.choices[0].message.content19 20# Streamlit UI21st.set_page_config(22    page_title="Crop Yield Insights",23    page_icon="๐ŸŒพ",24    layout="wide",25)26 27# Sidebar28with st.sidebar:29    st.image("https://cdn-icons-png.flaticon.com/512/868/868909.png", width=120)30    st.title("Crop Yield Assistant ๐ŸŒฑ")31    st.markdown("Get recommendations and predictions for crops based on data insights.")32    add_vertical_space(3)33    st.info("Upload your CSV file to get started!")34 35# Main app36st.title("๐ŸŒพ Crop Yield Insights")37st.markdown("Upload your dataset and select an ID to get relevant insights, predictions, and recommendations.")38 39# File uploader40uploaded_file = st.file_uploader("Upload your CSV file", type=["csv"], accept_multiple_files=False)41 42if uploaded_file:43    df = pd.read_csv(uploaded_file)44 45    # Data preprocessing46    if df.isnull().sum().any():47        st.warning("Missing values detected. Filling with median values.")48        df.fillna(df.median(numeric_only=True), inplace=True)49 50    # Display dataset preview51    st.subheader("๐Ÿ“Š Dataset Overview")52    st.dataframe(df.head())53 54    # Ensure there is an 'ID' column55    if 'ID' not in df.columns:56        st.error("The dataset must contain an 'ID' column.")57    else:58        # Select ID59        record_id = st.selectbox("Select an ID:", df['ID'].unique())60 61        if st.button("Generate Insights"):62            # Generate insights63            record = df[df['ID'] == record_id]64            65            if record.empty:66                st.error(f"No record found for ID: {record_id}")67            else:68                soil_quality = record.iloc[0]['Soil_Quality']69                seed_variety = record.iloc[0]['Seed_Variety']70                fertilizer_amount = record.iloc[0]['Fertilizer_Amount_kg_per_hectare']71                sunny_days = record.iloc[0]['Sunny_Days']72                rainfall = record.iloc[0]['Rainfall_mm']73                irrigation_schedule = record.iloc[0]['Irrigation_Schedule']74 75                prompt = (76                    f"The dataset includes the following information for ID {record_id}:\n"77                    f"- Soil Quality: {soil_quality}\n"78                    f"- Seed Variety: {seed_variety}\n"79                    f"- Fertilizer Amount (kg/ha): {fertilizer_amount}\n"80                    f"- Sunny Days: {sunny_days}\n"81                    f"- Rainfall (mm): {rainfall}\n"82                    f"- Irrigation Schedule: {irrigation_schedule}\n\n"83                    "Using this data, provide insights into expected crop yield, "84                    "recommendations for improving productivity, and potential challenges."85                )86 87                with st.spinner("Fetching insights..."):88                    response = query_groq(prompt)89                90                st.success(f"๐ŸŒŸ Insights for ID {record_id}")91                st.markdown(response)92 93else:94    st.info("Please upload a CSV file to proceed.")95 96# Footer97st.markdown("---")98st.markdown(99    "<h4 style='text-align: center;'>Powered by ๐Ÿง  Groq AI | Designed with โค๏ธ Streamlit</h4>",100    unsafe_allow_html=True,101)102