Spaces:
Runtime error
Runtime error
File size: 5,960 Bytes
c3d3272 e698d56 c3d3272 e698d56 c3d3272 e698d56 c3d3272 e698d56 c3d3272 e698d56 | 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 | import os
import json
import requests
from io import BytesIO
from PIL import Image
import replicate
import google.generativeai as genai
import streamlit as st
# === API Keys ===
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
REPLICATE_API_TOKEN = os.getenv("REPLICATE_API_TOKEN")
ZYTE_API_KEY = os.getenv("ZYTE_API_KEY") # π Add this to Hugging Face Secrets
genai.configure(api_key=GEMINI_API_KEY)
os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_TOKEN
# β
Real-time material price fetcher using Zyte
def fetch_real_price_zyte(query):
api_key = ZYTE_API_KEY
url = "https://api.zyte.com/v1/extract"
headers = {
"Authorization": f"Apikey {api_key}",
"Content-Type": "application/json"
}
payload = {
"url": f"https://www.homedepot.ca/search?q={query}",
"browserHtml": True
}
try:
response = requests.post(url, headers=headers, json=payload)
data = response.json()
# Update based on Zyte response structure
if "price" in data:
return float(data["price"])
else:
return 999
except:
return 999
# === Streamlit UI ===
st.title("π‘ Tiny Home AI Designer")
st.subheader("Generate a tiny home design with AI")
user_input = st.text_area("Enter your tiny home requirements:",
"Design a 300 sq ft rustic-style off-grid cabin for British Columbia that is suitable for rainy weather. "
"Include key spaces like sleeping area, small kitchen, bathroom, and storage."
)
if st.button("Generate Design"):
with st.spinner("Generating layout..."):
# === Agent 1: Generate Layout Description ===
agent1_prompt = f"""
You're a professional architectural planner and tiny home designer.
Your task is to produce an extremely detailed tiny home plan based on the user concept below.
Respond in a structured, rich layout description that includes:
- Overall dimensions
- Exterior materials, foundation, roof type, and regional considerations
- Complete room-by-room interior layout (dimensions, fixtures, furniture ideas)
- Storage features and off-grid systems (water, solar, composting toilet)
- Special design considerations for British Columbia's rainy climate
- Rustic style interior and material suggestions
- Regulatory and building code notes for BC
- Any labeled floorplan sketch ideas or text representations (ASCII-style ok)
- Bonus tips for maximizing space and sustainability
User concept:
\"\"\"{user_input}\"\"\"
"""
try:
model = genai.GenerativeModel("gemini-2.0-flash-thinking-exp-01-21")
response = model.generate_content(agent1_prompt)
layout_summary = response.text.strip()
st.success("β
Gemini AI successfully generated the layout description!")
st.text_area("Generated Layout Description", layout_summary, height=300)
except Exception as e:
st.error(f"β Gemini failed: {e}")
layout_summary = None
# === Agent 2: Generate Layout Image via Replicate ===
if layout_summary:
st.subheader("π¨ Generating Layout Image...")
image_prompt = (
layout_summary.strip()
+ "\n\nTop-down architectural blueprint layout, labeled rooms, clean black lines, technical drawing, white background"
)
try:
output = replicate.run(
"bytedance/sdxl-lightning-4step:6f7a773af6fc3e8de9d5a3c00be77c17308914bf67772726aff83496ba1e3bbe",
input={"prompt": image_prompt}
)
if isinstance(output, list) and output:
for index, url in enumerate(output):
response = requests.get(url)
image = Image.open(BytesIO(response.content))
st.image(image, caption=f"Tiny Home Layout {index+1}")
else:
st.warning("β οΈ No image returned from Replicate.")
except Exception as e:
st.error(f"β Replicate API failed: {e}")
# === Agent 3: Extract Materials and Estimate Cost ===
if layout_summary:
st.subheader("π Extracting Building Materials...")
material_prompt = f"""
Based on the following tiny home layout description:
{layout_summary}
List exactly 5 major building materials that would be required to build this tiny home.
Focus on general material types, not specific brands.
Return ONLY a raw JSON array like this:
["Framing lumber", "Spray foam insulation", "Triple-glazed windows", "Metal roofing", "Solar panel kit"]
"""
try:
material_model = genai.GenerativeModel("gemini-1.5-pro")
material_response = material_model.generate_content(material_prompt)
materials = json.loads(material_response.text.strip())
st.success("β
Materials Identified:")
for material in materials:
st.write(f"- {material}")
# π° Estimated Cost Section (Live Prices)
if materials:
st.subheader("π° Estimated Costs (Live via Zyte)")
total_cost = 0
for mat in materials:
price = fetch_real_price_zyte(mat)
st.write(f"- {mat}: ${price}")
total_cost += price
st.success(f"π§Ύ Total Estimated Cost: ${total_cost}")
else:
st.warning("β οΈ No materials were parsed. Try regenerating layout.")
except Exception as e:
st.error(f"β Failed to extract materials or estimate cost: {e}")
|