Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234567891011121314151617181920214 unmodified lines2627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111import osimport jsonimport gradio as grimport google.generativeai as genaiimport replicateimport requestsfrom PIL import Imagefrom io import BytesIO# === API Keys (Enter your own keys in Hugging Face Secrets) ===GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")REPLICATE_API_TOKEN = os.getenv("REPLICATE_API_TOKEN")# β Configure APIsgenai.configure(api_key=GEMINI_API_KEY)os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_TOKEN# β Simulated Zyte Pricing Functiondef zyte_search_price(material_name):mock_prices = {"Framing lumber": 1550,4 unmodified lines"Mini wood stove": 750,"SIP panels": 1850}return mock_prices.get(material_name, 999) # Fallback price# β Function to Generate Tiny Home Designdef generate_tiny_home(user_input):try:# === Step 1: Generate Layout Description with Gemini ===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.User concept:\"\"\"{user_input}\"\"\""""model = genai.GenerativeModel("gemini-2.0-flash-thinking-exp-01-21")response = model.generate_content(agent1_prompt)layout_summary = response.text.strip()# === Step 2: Extract Building Materials with Gemini ===material_prompt = f"""Based on the following tiny home layout description:{layout_summary}List exactly 5 major building materials required to build this tiny home.Return ONLY a JSON array.Example:["Framing lumber", "Spray foam insulation", "Triple-glazed windows", "Metal roofing", "Solar panel kit"]"""material_model = genai.GenerativeModel("gemini-1.5-pro")material_response = material_model.generate_content(material_prompt)raw_materials = material_response.text.strip()materials = json.loads(raw_materials) if raw_materials else []# === Step 3: Generate Image with Replicate ===image_prompt = layout_summary + "\n\nTop-down architectural blueprint layout, labeled rooms, clean black lines, technical drawing, white background"image_urls = replicate.run("bytedance/sdxl-lightning-4step:6f7a773af6fc3e8de9d5a3c00be77c17308914bf67772726aff83496ba1e3bbe",input={"prompt": image_prompt})# Fetch and save imagesimages = []if isinstance(image_urls, list) and image_urls:for url in image_urls:response = requests.get(url)image = Image.open(BytesIO(response.content))images.append(image)# === Step 4: Calculate Estimated Costs ===total_cost = 0price_list = []for mat in materials:price = zyte_search_price(mat)price_list.append(f"{mat}: ${price}")total_cost += pricereturn layout_summary, price_list, f"Total Estimated Cost: ${total_cost}", imagesexcept Exception as e:return f"β Error: {e}", [], "β οΈ Could not generate cost estimates.", []# === Create Gradio UI ===iface = gr.Interface(fn=generate_tiny_home,inputs=gr.Textbox(label="Enter Tiny Home Design Request"),outputs=[gr.Textbox(label="Generated Layout Description"),gr.Label(label="Estimated Costs"),gr.Textbox(label="Total Cost"),gr.Gallery(label="Generated Blueprint", show_label=False),],title="π‘ Tiny Home AI Designer",description="Enter your tiny home idea, and AI will generate a design layout, cost estimate, and blueprint.")# === Launch App ===if __name__ == "__main__":iface.launch()1234567891011121314151617181920214 unmodified lines2627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import osimport gradio as grimport google.generativeai as genaiimport replicate# β Load API Keys with Default Fallbacks (for Debugging)GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "YOUR_GEMINI_KEY_HERE") # Replace if testing locallyREPLICATE_API_TOKEN = os.getenv("REPLICATE_API_TOKEN", "")# β Ensure REPLICATE_API_TOKEN is Not Noneif not REPLICATE_API_TOKEN:raise ValueError("β οΈ REPLICATE_API_TOKEN is missing! Set it in Hugging Face Secrets.")# β Configure APIsgenai.configure(api_key=GEMINI_API_KEY)os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_TOKEN# β Simulated Zyte pricing function (acts like a scraper)def zyte_search_price(material_name):mock_prices = {"Framing lumber": 1550,4 unmodified lines"Mini wood stove": 750,"SIP panels": 1850}return mock_prices.get(material_name, 999) # Fallback price if material not found# β Extract materials & estimate costsdef extract_materials_and_costs(home_type, location, style, size, climate):# Simulated response from Gemini APImaterials = ["Framing lumber", "Spray foam insulation", "Triple-glazed windows"]# β Calculate total costprint("\nπ° Estimated Costs (Zyte Mock Prices):")total_cost = 0cost_breakdown = []for mat in materials:price = zyte_search_price(mat)cost_breakdown.append(f"- {mat}: ${price}")total_cost += priceresult = "\n".join(cost_breakdown) + f"\n\nπ§Ύ Total Estimated Cost: ${total_cost}"return result# β Gradio UIwith gr.Blocks() as demo:gr.Markdown("# π‘ Tiny House Cost Estimator")home_type = gr.Textbox(label="Home Type")location = gr.Textbox(label="Location")style = gr.Textbox(label="Style")size = gr.Textbox(label="Size (sq ft)")climate = gr.Textbox(label="Climate")estimate_btn = gr.Button("Estimate Cost")output = gr.Textbox(label="Estimated Cost Breakdown")estimate_btn.click(extract_materials_and_costs,inputs=[home_type, location, style, size, climate],outputs=output)# β Launch Appif __name__ == "__main__":demo.launch()
app.py+48-90