-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
189 lines (150 loc) Β· 6.22 KB
/
app.py
File metadata and controls
189 lines (150 loc) Β· 6.22 KB
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import streamlit as st
import pandas as pd
import os
import subprocess
EXPLANATIONS_FILE = "top3_gpt_explanations.csv"
FEEDBACK_FILE = "feedback_log.csv"
df = pd.read_csv(EXPLANATIONS_FILE)
# Appraisal Selection
order_ids = sorted(df["orderID"].unique())
selected_order = st.selectbox("Select an Appraisal (orderID)", order_ids)
appraisal_df = df[df["orderID"] == selected_order].sort_values("rank")
st.title("π Property Comparison Feedback")
st.subheader(f"Subject Property: {appraisal_df['subject_address'].iloc[0]}")
st.markdown("---")
feedback_records = []
def format_int(val):
try:
return int(round(float(val)))
except:
return "Not available"
def format_price(val):
try:
return f"${int(round(float(val))):,}"
except:
return "Not available"
# Selected Comp Loop
valid_prices = []
for _, row in appraisal_df.iterrows():
st.markdown(f"### ποΈ Candidate Property (Rank {int(row['rank'])}):")
st.markdown(f"**Address:** {row['candidate_address']}")
st.markdown(f"**Model Score:** `{row['score']:.2f}`")
st.markdown(f"**Explanation:** {row['explanation']}")
# Feature Comparison Table
st.markdown("#### π Feature Comparison")
comparison_data = {
"Feature": [
"Bedrooms", "Full Bathrooms", "Half Bathrooms",
"GLA (sq ft)", "Lot Size (SqFt)",
"Property Type", "Condition"
],
"Subject": [
format_int(row.get("subject_bedrooms")),
format_int(row.get("subject_num_full_baths")),
format_int(row.get("subject_num_half_baths")),
format_int(row.get("subject_gla")),
format_int(row.get("subject_lot_size_sf")),
row.get('subject_property_type') or "Not available",
row.get('subject_condition') or "Not available"
],
"Candidate": [
format_int(row.get("candidate_bedrooms")),
format_int(row.get("candidate_num_full_baths")),
format_int(row.get("candidate_num_half_baths")),
format_int(row.get("candidate_gla")),
format_int(row.get("candidate_lot_size_sf")),
row.get('candidate_property_type') or "Not available",
row.get('candidate_condition') or "Not available"
]
}
comparison_df = pd.DataFrame(comparison_data).astype(str)
st.table(comparison_df)
close_price = row.get("candidate_close_price")
st.markdown(f"**Candidate Close Price:** {format_price(close_price)}")
# Collect price for suggestion calculation
try:
valid_prices.append(float(close_price))
except:
pass
# Feedback Radio Button
key = f"feedback_{row['orderID']}_{row['rank']}"
feedback = st.radio("Do you agree this is a good comparable?", ("π Yes", "π No"), key=key)
feedback_records.append({
"orderID": row["orderID"],
"rank": row["rank"],
"candidate_address": row["candidate_address"],
"subject_address": row["subject_address"],
"score": row["score"],
"is_comp": row["is_comp"],
"user_feedback": 1 if feedback == "π Yes" else 0
})
st.markdown("---")
# Suggested Price Estimate
st.header("π° Suggested Value Estimate")
if valid_prices:
avg_price = sum(valid_prices) / len(valid_prices)
min_price = min(valid_prices)
max_price = max(valid_prices)
mid_point = min_price + ((max_price-min_price) / 2)
st.markdown(
f"""
<div style='margin-top: 1rem;'>
<span style='font-size: 1.15rem; font-weight: 600;'>Average Price of Top-3 Comps:</span>
<span style='font-size: 1.15rem; font-weight: 500; margin-left: 0.5rem;'>
{format_price(avg_price)}
</span>
</div>
<div style='margin-top: 1rem;'>
<span style='font-size: 1.15rem; font-weight: 600;'>Suggested Price Range:</span>
<span style='font-size: 1.15rem; font-weight: 500; margin-left: 0.5rem;'>
{format_price(min_price)} - {format_price(max_price)}
</span>
</div>
<div style='margin-top: 1rem;'>
<span style='font-size: 1.15rem; font-weight: 600;'>Suggested Price Range Midpoint:</span>
<span style='font-size: 1.15rem; font-weight: 500; margin-left: 0.5rem;'>
{format_price(mid_point)}
</span>
</div>
<div style='margin-top: 1rem; margin-bottom: 1rem'>
<span style='font-size: 0.8rem; font-weight: 600; color: grey'>
This estimate is based on the closing prices of the top 3 comparable properties selected by the model.
</span>
</div>
""",
unsafe_allow_html=True
)
else:
st.markdown("Not enough valid close price data to calculate a suggested value.")
# Submit Feedback
if st.button("β
Submit Feedback"):
feedback_df = pd.DataFrame(feedback_records)
if os.path.exists(FEEDBACK_FILE):
try:
existing = pd.read_csv(FEEDBACK_FILE)
# Drop duplicates by orderID and candidate_address
combined = pd.concat([existing, feedback_df])
combined = combined.drop_duplicates(
subset=["orderID", "candidate_address"], keep="last"
)
combined.to_csv(FEEDBACK_FILE, index=False)
except pd.errors.EmptyDataError:
feedback_df.to_csv(FEEDBACK_FILE, index=False)
else:
feedback_df.to_csv(FEEDBACK_FILE, index=False)
st.success("β
Feedback saved to feedback_log.csv!")
# Re-run the pipeline from training_data onwards
st.info("π Updating model with new feedback...")
subprocess.run(["/usr/local/bin/python3.12", "training_data.py"])
subprocess.run(["/usr/local/bin/python3.12", "train_model.py"])
subprocess.run(["/usr/local/bin/python3.12", "top3_explanations.py"])
st.success("β
Model updated with feedback.")
st.rerun()
if st.button("π Reset Feedback and Model"):
if os.path.exists(FEEDBACK_FILE):
os.remove(FEEDBACK_FILE)
st.warning("ποΈ Feedback log reset.")
st.info("π Rebuilding model with original data...")
subprocess.run(["/usr/local/bin/python3.12", "data_pipeline.py"])
st.success("β
Model and explanations reset.")
st.rerun()