import streamlit as st import PyPDF2 import openai openai.api_key = "" "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" <- API key, input in the code to activate def extract_text_from_pdf(pdf_path): text = "" try: with open(pdf_path, "rb") as file: reader = PyPDF2.PdfReader(file) for page in reader.pages: page_text = page.extract_text() if page_text: text += page_text + "\n" except Exception as e: text += f"\n[Error reading {pdf_path}: {e}]\n" return text def farm_tier(investment, area): if area <= 1 and investment < 10000: return "very small-scale" elif area <= 5: return "small to mid-scale" elif area <= 20: return "mid-size" else: return "large-scale" pdf_files = [ "108827-conservation-agriculture-systems-thinking-for-sustainable-farming.pdf", "CACH-2023-1-SpecialityCropsCA.pdf", "ojss_2022062314320512.pdf", "qt01r0c66r.pdf", "R44093.pdf", "success_stories.pdf" ] combined_pdf_text = "" for pdf in pdf_files: combined_pdf_text += extract_text_from_pdf(pdf) custom_css = """ """ st.markdown(custom_css, unsafe_allow_html=True) st.markdown('

California Crop & Sustainable Practices Recommendation

', unsafe_allow_html=True) st.markdown('

Farm Information

', unsafe_allow_html=True) region = st.text_input("Enter Region in CA:") investment = st.number_input("Enter Estimated Investment per Year ($):", min_value=0) area = st.number_input("Enter Area of the Farm (km²):", min_value=0.0, step=0.1) crop_preference = st.text_input("Enter Crop Preference (leave blank for recommendation):") tier = farm_tier(investment, area) st.markdown('

Sustainable Practices Queries

', unsafe_allow_html=True) soil_health_prompts = [ "None", "How can I improve the health of my soil in a sustainable way?", "What are the benefits of reducing tillage on my small farm?", "Can you explain how cover crops can help my soil and which ones are suitable for my region?", "What are some sustainable ways to add nutrients to my soil besides synthetic fertilizers?", "How can I use compost to improve my soil health?", "My soil has issues with salinity. What are some sustainable practices to manage this?", "How can I optimize my fertilizer application to protect water quality and soil health?", "What are organic amendments and how can they benefit my farm?", "Tell me more about soil biological services and how to support them." ] selected_soil = st.selectbox("Soil Health", soil_health_prompts) water_management_prompts = [ "None", "What are some ways to use water more efficiently on my farm?", "How can I prepare my farm for drought conditions?", "What are some sustainable methods for irrigation on a small scale?", "How can I capture and reuse rainwater on my property?", "What is agricultural managed aquifer recharge (AgMAR) and is it something a small farmer can implement?", "How can I manage my land to increase water infiltration and reduce runoff?" ] selected_water = st.selectbox("Water Management", water_management_prompts) pest_management_prompts = [ "None", "What are some sustainable ways to reduce pest pressure on my crops?", "How can I create a farm environment that attracts beneficial insects?", "What are some practices to reduce the risk of plant diseases without relying heavily on synthetic chemicals?", "How can I sustainably manage weeds and invasive plants on my farm?", "What is integrated pest management (IPM) and how can I apply it on my small farm?" ] selected_pest = st.selectbox("Pest & Disease Management", pest_management_prompts) temperature_change_prompts = [ "None", "How can I adapt my farming practices to warmer temperatures?", "What are some ways to manage the changing seasons and their impact on my crops?", "Are there crop varieties that are more tolerant to heat or changing conditions?", "What can I do to protect my crops from frost in changing weather patterns?" ] selected_temperature = st.selectbox("Adapting to Temperature Change", temperature_change_prompts) extreme_events_prompts = [ "None", "How can I prepare my farm for extreme heat events?", "What are some sustainable ways to manage extreme precipitation and flooding?", "How can I make my farm more resilient to high winds?", "What steps can I take to prepare for and respond to wildfires and smoke impacts?" ] selected_extreme = st.selectbox("Preparing for Extreme Events", extreme_events_prompts) landscape_biodiversity_prompts = [ "None", "How can I integrate natural ecosystems into my farm to benefit my crops?", "What are the benefits of promoting biodiversity on and around my farm?", "How can I create pollinator habitat on my small farm?", "Why is it important to conserve farmland and how can I contribute?" ] selected_landscape = st.selectbox("Landscape & Biodiversity", landscape_biodiversity_prompts) climate_change_mitigation_prompts = [ "None", "What are some ways small-scale farmers can reduce on-farm greenhouse gas emissions?", "How can I increase carbon sequestration in my farm's soil?", "Is conservation agriculture a way to mitigate climate change?" ] selected_climate = st.selectbox("Climate Change Mitigation", climate_change_mitigation_prompts) general_sustainable_prompts = [ "None", "What are the main principles of conservation agriculture?", "Can you give me some examples of co-benefit efforts that address both adaptation and mitigation of climate change?", "Where can I find more resources and guidance on climate adaptation for my farm?", "What is the Resist-Accept-Direct (RAD) framework and how could it apply to my farm management?", "Can you explain the Resistance-Resilience-Transformation (RRT) framework for climate adaptation?", "What are the five steps of adaptation planning for climate change?" ] selected_general = st.selectbox("General Sustainable Practices", general_sustainable_prompts) if st.button("Get Recommendation"): prompt = f""" As a sustainable agriculture expert, analyze the following farm's conditions and constraints, and provide a highly personalized plan. Every piece of advice should directly tie back to the specific features mentioned. Farm Profile: - Region in California: {region} - Annual Investment Capacity: ${investment} - Farm Area: {area} km² - Tier: {tier} farm (based on budget and size) - Crop Preference: {crop_preference if crop_preference.strip() else "No preference specified"} Consider the implications of region-specific soil types, water access, heat exposure, and economic capacity. Suggest strategies that match this farm's scale and situation. Use clear, practical steps and name at least one crop variety or farm practice that’s likely to succeed. Sustainable Practices Selected: """ if selected_soil != "None": prompt += f"1. Soil Health – {selected_soil}\n" if selected_water != "None": prompt += f"2. Water Management – {selected_water}\n" if selected_pest != "None": prompt += f"3. Pest Management – {selected_pest}\n" if selected_temperature != "None": prompt += f"4. Temperature Change – {selected_temperature}\n" if selected_extreme != "None": prompt += f"5. Extreme Events – {selected_extreme}\n" if selected_landscape != "None": prompt += f"6. Biodiversity – {selected_landscape}\n" if selected_climate != "None": prompt += f"7. Climate Mitigation – {selected_climate}\n" if selected_general != "None": prompt += f"8. General – {selected_general}\n" prompt += f""" Use the following research background to support your response: {combined_pdf_text[:3000]} Respond with a direct, specific, and actionable farm plan. """ response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": ( "You are a highly specialized sustainable agriculture consultant for farms in California. " "You must tailor every recommendation to the unique features of the farm including region, size, investment level, and crop interest. " "Always connect the suggestions directly to these inputs and mention the region or farm size when appropriate. " "If data is missing (e.g., no crop preference), suggest practical alternatives based on region and investment tier. " "All advice must feel like it was written for this specific farm." )}, {"role": "user", "content": prompt} ] ) st.markdown("### 🌾 Your Personalized Recommendation:") st.write(response["choices"][0]["message"]["content"])