Mtkhang90 commited on
Commit
3cfdc07
·
verified ·
1 Parent(s): 86c546a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -27
app.py CHANGED
@@ -2,16 +2,21 @@ import streamlit as st
2
  import pandas as pd
3
  import numpy as np
4
  import torch
5
- import openai
6
  import os
7
  from sentence_transformers import SentenceTransformer
8
  from sklearn.metrics.pairwise import cosine_similarity
9
  import matplotlib.pyplot as plt
10
  import io
 
11
 
12
- # Set up Groq API
13
- openai.api_key = os.getenv("GROQ_API_KEY")
14
- openai.api_base = "https://api.groq.com/openai/v1"
 
 
 
 
 
15
  GROQ_MODEL = "llama3-8b-8192"
16
 
17
  # Load Excel file
@@ -23,11 +28,7 @@ def load_excel(file):
23
 
24
  # Chunk data
25
  def chunk_data(df, chunk_size=5):
26
- chunks = []
27
- for i in range(0, len(df), chunk_size):
28
- chunk = df.iloc[i:i+chunk_size].to_string(index=False)
29
- chunks.append(chunk)
30
- return chunks
31
 
32
  # Embed chunks
33
  @st.cache_resource
@@ -43,7 +44,7 @@ def query_embedding(user_query, chunks, embeddings, model):
43
  top_idx = np.argmax(similarities)
44
  return chunks[top_idx]
45
 
46
- # Generate estimate
47
  def generate_estimate(context, user_input):
48
  prompt = f"""You are a construction estimator working in Pakistan. Using the following schedule of rates:
49
 
@@ -53,13 +54,14 @@ Generate a detailed BOQ estimate including item numbers, full descriptions, unit
53
  {user_input}
54
 
55
  Present the result in a markdown table with columns: Item No, Description, Qty, Unit, Rate, Amount."""
56
- response = openai.ChatCompletion.create(
 
57
  model=GROQ_MODEL,
58
  messages=[{"role": "user", "content": prompt}]
59
  )
60
- return response['choices'][0]['message']['content']
61
 
62
- # Calculate quantities
63
  def calculate_quantities(rooms, area, baths, car_porch, living):
64
  return {
65
  "Total Area (sqft)": area,
@@ -69,19 +71,16 @@ def calculate_quantities(rooms, area, baths, car_porch, living):
69
  "Car Porch Area (est.)": car_porch * 200
70
  }
71
 
72
- # Generate scaled sketch
73
  def draw_floor_plan(rooms, baths, living, car_porch, area):
74
  total_spaces = rooms + baths + living + car_porch
75
  cols = int(np.ceil(np.sqrt(total_spaces)))
76
  rows = int(np.ceil(total_spaces / cols))
77
 
78
  fig, ax = plt.subplots(figsize=(10, 8))
79
-
80
- scale = np.sqrt(area) / 10 # Simple scale factor
81
  width, height = scale, scale * 0.75
82
-
83
- labels = (["Room"] * rooms + ["Bath"] * baths +
84
- ["Living"] * living + ["Car Porch"] * car_porch)
85
 
86
  for i, label in enumerate(labels):
87
  row = i // cols
@@ -102,9 +101,8 @@ def draw_floor_plan(rooms, baths, living, car_porch, area):
102
  buf.seek(0)
103
  return buf
104
 
105
- # Main app
106
  def main():
107
- st.set_page_config(page_title="Construction Estimator", layout="centered")
108
  st.title("🧱 Construction Estimator (RAG + LLaMA 3 + Sketch)")
109
 
110
  excel_file = st.file_uploader("Upload Schedule of Rates (.xlsx or .xlsm)", type=["xlsx", "xlsm"])
@@ -131,14 +129,9 @@ def main():
131
  st.json(quantities)
132
 
133
  st.subheader("💸 Estimated Construction Cost (BOQ Style)")
134
- st.markdown(
135
- """
136
- **The BOQ generated here is a SIMPLIFIED ESTIMATE. A detailed and accurate BOQ requires professional quantity surveying and design specifications.**
137
- """
138
- )
139
  st.markdown(response)
140
 
141
- # Generate Sketch
142
  buf = draw_floor_plan(rooms, baths, living, car_porch, area)
143
  st.subheader("🏠 Tentative Floor Plan Sketch")
144
  st.image(buf, caption="Auto-generated Line Plan", use_column_width=True)
 
2
  import pandas as pd
3
  import numpy as np
4
  import torch
 
5
  import os
6
  from sentence_transformers import SentenceTransformer
7
  from sklearn.metrics.pairwise import cosine_similarity
8
  import matplotlib.pyplot as plt
9
  import io
10
+ from openai import OpenAI
11
 
12
+ # Set page config FIRST
13
+ st.set_page_config(page_title="Construction Estimator", layout="centered")
14
+
15
+ # Setup OpenAI/Groq client
16
+ client = OpenAI(
17
+ api_key=os.getenv("GROQ_API_KEY"),
18
+ base_url="https://api.groq.com/openai/v1"
19
+ )
20
  GROQ_MODEL = "llama3-8b-8192"
21
 
22
  # Load Excel file
 
28
 
29
  # Chunk data
30
  def chunk_data(df, chunk_size=5):
31
+ return [df.iloc[i:i+chunk_size].to_string(index=False) for i in range(0, len(df), chunk_size)]
 
 
 
 
32
 
33
  # Embed chunks
34
  @st.cache_resource
 
44
  top_idx = np.argmax(similarities)
45
  return chunks[top_idx]
46
 
47
+ # Generate estimate with Groq
48
  def generate_estimate(context, user_input):
49
  prompt = f"""You are a construction estimator working in Pakistan. Using the following schedule of rates:
50
 
 
54
  {user_input}
55
 
56
  Present the result in a markdown table with columns: Item No, Description, Qty, Unit, Rate, Amount."""
57
+
58
+ response = client.chat.completions.create(
59
  model=GROQ_MODEL,
60
  messages=[{"role": "user", "content": prompt}]
61
  )
62
+ return response.choices[0].message.content
63
 
64
+ # Quantity logic
65
  def calculate_quantities(rooms, area, baths, car_porch, living):
66
  return {
67
  "Total Area (sqft)": area,
 
71
  "Car Porch Area (est.)": car_porch * 200
72
  }
73
 
74
+ # Sketch generator
75
  def draw_floor_plan(rooms, baths, living, car_porch, area):
76
  total_spaces = rooms + baths + living + car_porch
77
  cols = int(np.ceil(np.sqrt(total_spaces)))
78
  rows = int(np.ceil(total_spaces / cols))
79
 
80
  fig, ax = plt.subplots(figsize=(10, 8))
81
+ scale = np.sqrt(area) / 10
 
82
  width, height = scale, scale * 0.75
83
+ labels = (["Room"] * rooms + ["Bath"] * baths + ["Living"] * living + ["Car Porch"] * car_porch)
 
 
84
 
85
  for i, label in enumerate(labels):
86
  row = i // cols
 
101
  buf.seek(0)
102
  return buf
103
 
104
+ # -------------------- MAIN APP --------------------
105
  def main():
 
106
  st.title("🧱 Construction Estimator (RAG + LLaMA 3 + Sketch)")
107
 
108
  excel_file = st.file_uploader("Upload Schedule of Rates (.xlsx or .xlsm)", type=["xlsx", "xlsm"])
 
129
  st.json(quantities)
130
 
131
  st.subheader("💸 Estimated Construction Cost (BOQ Style)")
132
+ st.markdown("**This BOQ is a simplified estimate. Use it for planning, not execution.**")
 
 
 
 
133
  st.markdown(response)
134
 
 
135
  buf = draw_floor_plan(rooms, baths, living, car_porch, area)
136
  st.subheader("🏠 Tentative Floor Plan Sketch")
137
  st.image(buf, caption="Auto-generated Line Plan", use_column_width=True)