File size: 4,010 Bytes
1e542fb af9302e 1e542fb | 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 | import streamlit as st
import json
import time
from datetime import datetime
from openai import OpenAI
from prompts import FERTILIZATION_PLAN_PROMPT_CORRECTED
# ===============================
# CONFIGURATION
# ===============================
OPENROUTER_API_KEY = "Add-your-openrouter-key"
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=OPENROUTER_API_KEY,
)
# ===============================
# STREAMLIT UI
# ===============================
st.set_page_config(
page_title="ThinkLawn Fertilization Plan Generator",
page_icon="π±",
layout="centered",
)
st.title("πΏ ThinkLawn Fertilization Plan Generator")
st.caption("Generate professional fertilization plans based on soil test data and location details.")
# Input area
st.subheader("π§Ύ Enter Input Data (JSON Format or Text)")
user_input = st.text_area(
"Paste your soil and questionnaire data below:",
height=350,
placeholder="Paste your JSON input here...",
)
# When user submits
if st.button("π Generate Fertilization Plan"):
if not user_input.strip():
st.error("Please provide input data before submitting.")
else:
with st.spinner("Generating fertilization plan... Please wait β³"):
start_time = time.time()
try:
# Try to load JSON (fallback to treat as text)
try:
input_data = json.loads(user_input)
formatted_input = json.dumps(input_data, indent=2)
except json.JSONDecodeError:
formatted_input = user_input.strip()
user_message = f"Generate fertilization plan:\n\n{formatted_input}"
# LLM Call
response = client.chat.completions.create(
model="openai/gpt-4o-mini",
messages=[
{"role": "system", "content": FERTILIZATION_PLAN_PROMPT_CORRECTED},
{"role": "user", "content": user_message}
],
temperature=0.3,
extra_headers={
"HTTP-Referer": "https://github.com/thinklawn/fertilization-optimizer",
"X-Title": "ThinkLawn Corrected Schema"
}
)
# Extract and clean response
content = response.choices[0].message.content.strip()
if content.startswith("```"):
content = content.split("```")[1]
if content.startswith("json"):
content = content[4:]
content = content.strip()
# Parse JSON
result = json.loads(content)
elapsed = time.time() - start_time
st.success("β
Fertilization Plan Generated Successfully!")
st.write(f"**Processing Time:** {elapsed:.2f} seconds")
# Display result nicely
st.subheader("π¦ Fertilization Plan JSON Output")
st.json(result)
# Download button
result_text = json.dumps(result, indent=2, ensure_ascii=False)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"fertilization_plan_{timestamp}.txt"
st.download_button(
label="πΎ Download Result (.txt)",
data=result_text.encode("utf-8"),
file_name=filename,
mime="text/plain"
)
# Copyable output section
st.subheader("π Copyable JSON Output")
st.code(result_text, language="json")
except json.JSONDecodeError as e:
st.error(f"β οΈ JSON Parsing Error: {e}")
st.text_area("Raw Response", content, height=300)
except Exception as e:
st.error(f"β Error: {e}")
st.exception(e)
|