# ============================================================
# REMATCH - HUGGING FACE SPACE APP
# Keep generation.py and the assets folder beside this file.
# ============================================================
import html
import json
from pathlib import Path
from urllib.parse import quote
import gradio as gr
import numpy as np
import pandas as pd
import torch
from huggingface_hub import hf_hub_download
from torch import nn
from generation import generate_property_explanation
# Put the generated illustrative images in an `assets` folder beside this file.
# In a Hugging Face Space, upload the same folder to the repository root.
ASSET_DIR = Path("assets")
PROPERTY_IMAGES = {
"single_family": "illustrative_single_family_home.png",
"single_family_home": "illustrative_single_family_home.png",
"singlefamily": "illustrative_single_family_home.png",
"townhouse": "illustrative_townhouse.png",
"condo": "illustrative_condo.png",
"multi_family": "illustrative_multi_family.png",
"multifamily": "illustrative_multi_family.png",
"luxury_home": "illustrative_luxury_home.png",
}
DEFAULT_PROPERTY_IMAGE = "illustrative_default_property.png"
REMATCH_LOGO_URL = "/gradio_api/file=" + quote(
str((ASSET_DIR / "rematch_logo.png").resolve())
)
def property_image_url(property_type):
"""Return a Gradio-served URL for a generic illustrative property image."""
normalized_type = (
str(property_type or "")
.strip()
.lower()
.replace(" ", "_")
.replace("-", "_")
)
image_name = PROPERTY_IMAGES.get(normalized_type, DEFAULT_PROPERTY_IMAGE)
image_path = (ASSET_DIR / image_name).resolve()
return "/gradio_api/file=" + quote(str(image_path))
# Part 3 intentionally stays CPU-only.
DEVICE = torch.device("cpu")
print("Runtime device:", DEVICE)
# ============================================================
# LOAD APPROVED MODEL ARTIFACTS
# ============================================================
MODEL_REPO_ID = "omershahar/REmatch-DCN-v2"
MODEL_CONFIG_PATH = hf_hub_download(
repo_id=MODEL_REPO_ID,
filename="model_config.json",
)
VOCABULARY_PATH = hf_hub_download(
repo_id=MODEL_REPO_ID,
filename="preprocessor_vocabulary.json",
)
CHECKPOINT_PATH = hf_hub_download(
repo_id=MODEL_REPO_ID,
filename="dcn_v2_checkpoint.pt",
)
with open(MODEL_CONFIG_PATH, "r", encoding="utf-8") as file:
model_config = json.load(file)
with open(VOCABULARY_PATH, "r", encoding="utf-8") as file:
vocabulary_payload = json.load(file)
I = model_config["investor_cols"]
P = model_config["property_cols"]
F = model_config["feature_cols"]
assert F == I + P
assert vocabulary_payload["feature_cols"] == F
# ============================================================
# LOAD DATASET B DIRECTLY FROM HUGGING FACE DATASET REPO
# ============================================================
DATASET_REPO_ID = "omershahar/REmatch-Investment-Matching-Dataset"
DATASET_FILENAME = "rematch_properties.csv"
DATASET_REVISION = "main"
DATASET_B_PATH = hf_hub_download(
repo_id=DATASET_REPO_ID,
repo_type="dataset",
filename=DATASET_FILENAME,
revision=DATASET_REVISION,
)
B = pd.read_csv(DATASET_B_PATH)
required_property_columns = set(
P
+ [
"id",
"formattedAddress",
"city_rentcast",
"state",
"propertyType",
"price",
"monthly_rent",
"gross_rental_yield_percent",
"value_forecast_12months",
"price_volatility_percent",
"property_description",
]
)
missing_property_columns = required_property_columns - set(B.columns)
assert not missing_property_columns, (
"Dataset B is missing required columns: "
+ str(sorted(missing_property_columns))
)
for column in P:
B[column] = (
B[column]
.fillna("__MISSING__")
.astype(str)
.str.strip()
)
print("Loaded Dataset B from Hugging Face")
print("Property inventory rows:", len(B))
# ============================================================
# LOAD SAVED DCN-v2 PROPERTY EMBEDDINGS FROM THE SPACE
# ============================================================
EMBEDDINGS_PATH = Path(
"rematch_dataset_b_dcn_v2_embeddings.parquet"
)
if not EMBEDDINGS_PATH.exists():
raise FileNotFoundError(
"Missing rematch_dataset_b_dcn_v2_embeddings.parquet. "
"Upload it to the root of this Hugging Face Space."
)
EMBEDDINGS = pd.read_parquet(EMBEDDINGS_PATH)
EMBEDDING_COLS = sorted(
[
column
for column in EMBEDDINGS.columns
if column.startswith("dcn_v2_property_embedding_")
],
key=lambda column: int(column.rsplit("_", 1)[1]),
)
assert len(EMBEDDING_COLS) == 60, (
f"Expected 60 DCN-v2 embedding columns, found {len(EMBEDDING_COLS)}."
)
assert "id" in EMBEDDINGS.columns, (
"The embedding Parquet file must contain an id column."
)
# IDs are the bridge between the vector index and Dataset B.
B["id"] = B["id"].astype(str)
EMBEDDINGS["id"] = EMBEDDINGS["id"].astype(str)
EMBEDDINGS = EMBEDDINGS[
["id"] + EMBEDDING_COLS
].drop_duplicates("id")
missing_embedding_ids = set(B["id"]) - set(EMBEDDINGS["id"])
assert not missing_embedding_ids, (
"Some Dataset B properties have no saved embedding. "
f"Missing count: {len(missing_embedding_ids)}"
)
print("Loaded DCN-v2 property embedding index from Parquet")
print("Embedding rows:", len(EMBEDDINGS))
print("Embedding dimensions:", len(EMBEDDING_COLS))
# ============================================================
# LOAD DATASET A FOR REPRESENTATIVE INVESTOR DESCRIPTIONS
# ============================================================
DATASET_A_PATH = hf_hub_download(
repo_id=DATASET_REPO_ID,
repo_type="dataset",
filename="rematch_investor_profiles.csv",
revision=DATASET_REVISION,
)
A = pd.read_csv(DATASET_A_PATH)
required_investor_columns = {
"investor_id",
"budget_level",
"max_budget_usd",
"financing_willingness",
"liquidity_importance",
"risk_profile",
"primary_goal",
"investor_description",
}
missing_investor_columns = required_investor_columns - set(A.columns)
assert not missing_investor_columns, (
"Dataset A is missing required columns: "
+ str(sorted(missing_investor_columns))
)
for column in [
"budget_level",
"financing_willingness",
"liquidity_importance",
"risk_profile",
"primary_goal",
]:
A[column] = A[column].astype(str).str.strip()
A["max_budget_usd"] = pd.to_numeric(
A["max_budget_usd"],
errors="coerce",
)
print("Loaded Dataset A from Hugging Face")
print("Investor profile rows:", len(A))
# ============================================================
# APPROVED DCN-v2 ARCHITECTURE
# ============================================================
class Prep:
def __init__(self, vocabularies):
self.v = vocabularies
def transform(self, dataframe):
encoded = np.zeros(
(len(dataframe), len(F)),
dtype=np.int64,
)
for index, column in enumerate(F):
encoded[:, index] = (
dataframe[column]
.astype(str)
.map(self.v[column])
.fillna(0)
.astype(int)
)
return encoded
@property
def sizes(self):
return [len(self.v[column]) for column in F]
class Emb(nn.Module):
def __init__(self, sizes, dim=12):
super().__init__()
self.t = nn.ModuleList(
[nn.Embedding(size, dim) for size in sizes]
)
def forward(self, inputs):
return torch.stack(
[
embedding(inputs[:, index])
for index, embedding in enumerate(self.t)
],
dim=1,
)
class Cross(nn.Module):
def __init__(self, input_size):
super().__init__()
self.w = nn.Parameter(torch.randn(input_size) * 0.01)
self.b = nn.Parameter(torch.zeros(input_size))
def forward(self, initial_input, current_input):
return (
initial_input
* (current_input * self.w).sum(1, keepdim=True)
+ self.b
+ current_input
)
class DCNv2(nn.Module):
def __init__(self, sizes, dim=12):
super().__init__()
self.e = Emb(sizes, dim)
flattened_size = len(sizes) * dim
self.c = nn.ModuleList(
[
Cross(flattened_size),
Cross(flattened_size),
]
)
self.d = nn.Sequential(
nn.Linear(flattened_size, 96),
nn.ReLU(),
nn.Dropout(0.15),
nn.Linear(96, 48),
nn.ReLU(),
)
self.o = nn.Linear(flattened_size + 48, 1)
def forward(self, inputs):
initial_input = self.e(inputs).flatten(1)
crossed_input = initial_input
for cross_layer in self.c:
crossed_input = cross_layer(
initial_input,
crossed_input,
)
return self.o(
torch.cat(
[
crossed_input,
self.d(initial_input),
],
dim=1,
)
).squeeze(1)
# ============================================================
# LOAD TRAINED MODEL
# ============================================================
prep = Prep(vocabulary_payload["vocabularies"])
embedding_dimension = int(model_config["embedding_dim"])
model = DCNv2(
sizes=prep.sizes,
dim=embedding_dimension,
).to(DEVICE)
checkpoint = torch.load(
CHECKPOINT_PATH,
map_location=DEVICE,
)
assert checkpoint["model_name"] == "DCN-v2"
assert checkpoint["feature_cols"] == F
assert checkpoint["investor_cols"] == I
assert checkpoint["property_cols"] == P
model.load_state_dict(checkpoint["state_dict"])
model.eval()
print("Loaded trained model: DCN-v2")
# ============================================================
# PART 3 - RECOMMENDATION ENGINE
# ============================================================
RECOMMENDATION_FIELDS = [
"id",
"formattedAddress",
"city_rentcast",
"state",
"propertyType",
"price",
"monthly_rent",
"gross_rental_yield_percent",
"value_forecast_12months",
"price_volatility_percent",
"property_description",
]
def predict(model, encoded_features):
model.eval()
outputs = []
with torch.inference_mode():
for start in range(0, len(encoded_features), 1024):
batch = torch.tensor(
encoded_features[start:start + 1024],
dtype=torch.long,
device=DEVICE,
)
prediction = torch.sigmoid(model(batch))
outputs.append(prediction.cpu().numpy())
return np.concatenate(outputs)
def percentile_rank(series, ascending=True):
ranks = (
pd.to_numeric(series, errors="coerce")
.rank(pct=True)
.fillna(0.5)
)
return ranks if ascending else 1 - ranks
def cosine_similarity(vector_a, vector_b):
"""Cosine similarity for two already numeric property vectors."""
denominator = np.linalg.norm(vector_a) * np.linalg.norm(vector_b)
if denominator == 0:
return 0.0
return float(np.dot(vector_a, vector_b) / denominator)
def select_diverse_top_3(ranked_candidates, diversity_weight=0.015):
"""
Select three strong recommendations while using the saved DCN-v2
property embeddings to avoid returning three almost identical assets.
DCN-v2 fit score remains the main ranking signal.
The embedding similarity penalty is intentionally small.
"""
pool = ranked_candidates.head(100).copy()
selected_rows = []
selected_vectors = []
for _, row in pool.iterrows():
candidate_vector = row[EMBEDDING_COLS].to_numpy(
dtype=np.float32
)
if not selected_vectors:
max_similarity = 0.0
else:
max_similarity = max(
cosine_similarity(candidate_vector, selected_vector)
for selected_vector in selected_vectors
)
selection_score = (
float(row["final_score"])
- diversity_weight * max_similarity
)
selected_rows.append(
(
selection_score,
row,
candidate_vector,
)
)
# At each round, take the best currently available candidate.
best = max(
selected_rows,
key=lambda item: item[0],
)
# Only select when this row is the best remaining option.
if best[1]["id"] == row["id"]:
selected_vectors.append(candidate_vector)
if len(selected_vectors) == 3:
break
# Keep only rows not already selected.
selected_ids = {
str(vector_row[1]["id"])
for vector_row in selected_rows
if any(
np.array_equal(
vector_row[2],
selected_vector,
)
for selected_vector in selected_vectors
)
}
pool = pool[
~pool["id"].astype(str).isin(selected_ids)
]
# A clearer greedy implementation, preserving original DCN score.
chosen = []
chosen_vectors = []
remaining = ranked_candidates.head(100).copy()
while len(chosen) < 3 and not remaining.empty:
selection_scores = []
for index, row in remaining.iterrows():
candidate_vector = row[EMBEDDING_COLS].to_numpy(
dtype=np.float32
)
if chosen_vectors:
max_similarity = max(
cosine_similarity(
candidate_vector,
selected_vector,
)
for selected_vector in chosen_vectors
)
else:
max_similarity = 0.0
selection_score = (
float(row["final_score"])
- diversity_weight * max_similarity
)
selection_scores.append(
(index, selection_score, max_similarity)
)
best_index, best_selection_score, best_similarity = max(
selection_scores,
key=lambda item: item[1],
)
selected_row = remaining.loc[best_index].copy()
selected_row["embedding_similarity_penalty"] = best_similarity
selected_row["selection_score"] = best_selection_score
chosen.append(selected_row)
chosen_vectors.append(
selected_row[EMBEDDING_COLS].to_numpy(
dtype=np.float32
)
)
remaining = remaining.drop(index=best_index)
return pd.DataFrame(chosen)
def recommend_top_3(
budget_level,
max_budget_usd,
financing_willingness,
liquidity_importance,
risk_profile,
primary_goal,
enforce_budget=True,
):
answers = dict(
zip(
I,
[
budget_level,
financing_willingness,
liquidity_importance,
risk_profile,
primary_goal,
],
)
)
for column, value in answers.items():
if value not in prep.v[column]:
raise ValueError(f"Unsupported {column}: {value}")
max_budget_usd = float(max_budget_usd)
if not np.isfinite(max_budget_usd) or max_budget_usd <= 0:
raise ValueError(
"max_budget_usd must be greater than zero."
)
# Dataset B remains the source of truth for every property.
candidates = B.copy()
candidates["price"] = pd.to_numeric(
candidates["price"],
errors="coerce",
)
# Strict eligibility rules run before any recommendation scoring.
candidates = candidates[
candidates["price"].notna()
& (candidates["price"] > 0)
]
if enforce_budget:
candidates = candidates[
candidates["price"] <= max_budget_usd
]
if risk_profile == "conservative":
candidates = candidates[
(candidates["volatility_band"] != "high_volatility")
& (candidates["forecast_band"] != "negative_forecast")
]
if candidates.empty:
return pd.DataFrame(
columns=RECOMMENDATION_FIELDS
+ [
"predicted_match_fit",
"final_score",
"selection_score",
]
)
# Join each live Dataset B property to its saved DCN-v2 embedding.
# Only the embedding vectors come from the Parquet file.
candidates = candidates.merge(
EMBEDDINGS,
on="id",
how="inner",
validate="one_to_one",
)
if candidates.empty:
raise RuntimeError(
"No eligible Dataset B properties could be matched "
"to the saved embedding index."
)
# DCN-v2 computes personalized match quality from the five answers.
model_features = candidates[P].copy()
for column, value in answers.items():
model_features[column] = value
candidates["predicted_match_fit"] = predict(
model,
prep.transform(model_features[F]),
)
# Deterministic property-quality tie-breaker.
tie_breaker = (
0.35 * percentile_rank(
candidates["gross_rental_yield_percent"]
)
+ 0.30 * percentile_rank(
candidates["value_forecast_12months"]
)
+ 0.20 * percentile_rank(
candidates["price_volatility_percent"],
ascending=False,
)
)
if enforce_budget:
tie_breaker += (
0.15
* (
1 - candidates["price"] / max_budget_usd
).clip(0, 1)
)
else:
# No budget headroom exists in fallback mode.
# Rescale the remaining 85% of the tie-breaker to 100%.
tie_breaker = tie_breaker / 0.85
candidates["final_score"] = (
0.85 * candidates["predicted_match_fit"]
+ 0.15 * tie_breaker
)
ranked_candidates = candidates.sort_values(
[
"final_score",
"predicted_match_fit",
"price",
"id",
],
ascending=[
False,
False,
True,
True,
],
kind="mergesort",
)
# The saved Parquet vectors now actively influence the final three:
# selected results remain high-fit, but are less repetitive.
result = select_diverse_top_3(ranked_candidates)
assert len(result) <= 3
if enforce_budget:
assert (result["price"] <= max_budget_usd).all(), (
"Exact budget guard failed"
)
if risk_profile == "conservative":
assert not (
result["volatility_band"] == "high_volatility"
).any(), "Conservative volatility guard failed"
assert not (
result["forecast_band"] == "negative_forecast"
).any(), "Conservative forecast guard failed"
return result[
RECOMMENDATION_FIELDS
+ [
"predicted_match_fit",
"final_score",
"selection_score",
]
]
# ============================================================
# PART 5A - REGRESSION TEST
# ============================================================
regression_results = recommend_top_3(
budget_level="medium",
max_budget_usd=450000,
financing_willingness="no",
liquidity_importance="medium",
risk_profile="conservative",
primary_goal="income",
).reset_index(drop=True)
expected_address_starts = [
"435 Canberra Dr",
"3508 Dance Ave",
"400 Dublin Dr",
]
assert len(regression_results) == 3
for actual, expected in zip(
regression_results["formattedAddress"].astype(str).tolist(),
expected_address_starts,
):
assert actual.startswith(expected), (
f"Expected {expected}, got {actual}"
)
assert (regression_results["price"] <= 450000).all()
regression_details = regression_results.merge(
B[
[
"id",
"volatility_band",
"forecast_band",
]
],
on="id",
how="left",
)
assert not (
regression_details["volatility_band"] == "high_volatility"
).any()
assert not (
regression_details["forecast_band"] == "negative_forecast"
).any()
print("Part 5A regression test passed.")
# ============================================================
# PART 4 - GROUNDED EXPLANATIONS
# ============================================================
def derive_budget_level(max_budget_usd):
amount = float(max_budget_usd)
if amount < 150000:
return "low"
if amount < 300000:
return "lower_mid"
if amount < 500000:
return "medium"
return "high"
def render_representative_investor_profile(
max_budget_usd,
financing_willingness,
liquidity_importance,
risk_profile,
primary_goal,
):
"""Return one deterministic Dataset A description matching the user."""
budget_level = derive_budget_level(max_budget_usd)
budget = float(max_budget_usd)
matches = A[
(A["budget_level"] == budget_level)
& (A["financing_willingness"] == financing_willingness)
& (A["liquidity_importance"] == liquidity_importance)
& (A["risk_profile"] == risk_profile)
& (A["primary_goal"] == primary_goal)
& A["max_budget_usd"].notna()
& A["investor_description"].notna()
].copy()
if matches.empty:
return ""
matches["budget_distance"] = (
matches["max_budget_usd"] - budget
).abs()
selected = matches.sort_values(
["budget_distance", "investor_id"],
ascending=[True, True],
kind="mergesort",
).iloc[0]
description = html.escape(
str(selected["investor_description"]).strip()
)
return f"""
YOUR INVESTOR PROFILE
A profile that matches your selections
“{description}”
"""
PART4_PROPERTY_FIELDS = [
"id",
"formattedAddress",
"city_rentcast",
"propertyType",
"yield_band",
"liquidity_band",
"volatility_band",
"forecast_band",
]
def python_value(value):
if isinstance(value, np.generic):
return value.item()
if pd.isna(value):
return None
return value
def property_record_for_generation(property_id):
matches = B[B["id"].astype(str) == str(property_id)]
if len(matches) != 1:
raise ValueError(
f"Expected one property for ID {property_id}; found {len(matches)}."
)
row = matches.iloc[0]
return {
field: python_value(row[field])
for field in PART4_PROPERTY_FIELDS
if field in B.columns
}
def generate_top_3_explanations(
investor_profile,
property_records,
):
generation_results = []
for property_record in property_records:
explanation = generate_property_explanation(
investor_profile=investor_profile,
property_record=property_record,
)
generation_results.append(explanation)
return generation_results
def prepare_part_4(
max_budget_usd,
financing_willingness,
liquidity_importance,
risk_profile,
primary_goal,
):
budget_level = derive_budget_level(max_budget_usd)
results = recommend_top_3(
budget_level=budget_level,
max_budget_usd=max_budget_usd,
financing_willingness=financing_willingness,
liquidity_importance=liquidity_importance,
risk_profile=risk_profile,
primary_goal=primary_goal,
).reset_index(drop=True)
budget_fallback = False
if results.empty:
results = recommend_top_3(
budget_level=budget_level,
max_budget_usd=max_budget_usd,
financing_willingness=financing_willingness,
liquidity_importance=liquidity_importance,
risk_profile=risk_profile,
primary_goal=primary_goal,
enforce_budget=False,
).reset_index(drop=True)
budget_fallback = not results.empty
if results.empty:
return [], {}, []
investor_profile = {
"budget_level": budget_level,
"financing_willingness": financing_willingness,
"liquidity_importance": liquidity_importance,
"risk_profile": risk_profile,
"primary_goal": primary_goal,
}
ranked_records = []
for record in results.to_dict(orient="records"):
clean_record = {
key: python_value(value)
for key, value in record.items()
}
clean_record["budget_fallback"] = budget_fallback
clean_record["requested_budget_usd"] = float(max_budget_usd)
ranked_records.append(clean_record)
property_records = [
property_record_for_generation(row["id"])
for row in ranked_records
]
return ranked_records, investor_profile, property_records
def format_explanation_html(explanation):
"""
Removes the duplicate opening heading and converts important
explanation section titles into bold visual headings.
"""
text = str(explanation or "").strip()
lines = text.splitlines()
# Remove blank lines at the beginning.
while lines and not lines[0].strip():
lines.pop(0)
# Remove duplicate first line shown beneath the card heading.
if lines:
first_line = lines[0].strip().strip("*").lower()
if first_line in {
"why this property may fit:",
"why this property may fit",
"why this property matches you:",
"why this property matches you",
}:
lines.pop(0)
headings = {
"key consideration:",
"key property indicators:",
"what to verify:",
}
formatted_lines = []
for line in lines:
clean_line = line.strip()
if not clean_line:
formatted_lines.append("")
continue
escaped_line = html.escape(clean_line)
normalized_line = clean_line.strip("*").lower()
if normalized_line in headings:
formatted_lines.append(
f"
{escaped_line}
"
)
else:
formatted_lines.append(
f"
{escaped_line}
"
)
return "".join(formatted_lines)
# ============================================================
# RESULT CARDS
# ============================================================
def render_part_4_results(
ranked_records,
generation_results,
):
if not ranked_records:
return """
No eligible properties found
Try adjusting the budget or investor preferences.
"""
if len(ranked_records) != len(generation_results):
raise ValueError(
"Recommendation and generation result counts do not match."
)
cards = []
budget_fallback = bool(
ranked_records[0].get("budget_fallback", False)
)
fallback_message = ""
if budget_fallback:
requested_budget = float(
ranked_records[0]["requested_budget_usd"]
)
lowest_displayed_price = min(
float(record["price"])
for record in ranked_records
)
gap = lowest_displayed_price - requested_budget
fallback_message = f"""
No eligible property was found within your
${requested_budget:,.0f} budget.
We’re showing the strongest matching alternatives
outside your current budget. The lowest-priced option
shown is ${lowest_displayed_price:,.0f},
which is ${gap:,.0f} above your entered budget.
"""
for rank, (property_record, explanation) in enumerate(
zip(ranked_records, generation_results),
start=1,
):
address = html.escape(
str(property_record.get("formattedAddress", "Address unavailable"))
)
property_type = html.escape(
str(property_record.get("propertyType", "Property"))
)
image_url = property_image_url(
property_record.get("propertyType", "")
)
try:
price = f"${float(property_record.get('price')):,.0f}"
except (TypeError, ValueError):
price = "Price unavailable"
try:
price_value = float(property_record.get("price"))
except (TypeError, ValueError):
price_value = None
try:
monthly_rent = float(
property_record.get("monthly_rent")
)
except (TypeError, ValueError):
monthly_rent = None
try:
rental_yield = float(
property_record.get("gross_rental_yield_percent")
)
except (TypeError, ValueError):
rental_yield = None
try:
value_forecast = float(
property_record.get("value_forecast_12months")
)
except (TypeError, ValueError):
value_forecast = None
annual_rent = (
monthly_rent * 12
if monthly_rent is not None
else None
)
projected_value_change = (
price_value * value_forecast / 100
if price_value is not None
and value_forecast is not None
else None
)
estimated_gross_return = (
rental_yield + value_forecast
if rental_yield is not None
and value_forecast is not None
else None
)
rental_yield_text = (
f"{rental_yield:.1f}%"
if rental_yield is not None
else "N/A"
)
annual_rent_text = (
f"~${annual_rent:,.0f}/yr"
if annual_rent is not None
else "N/A"
)
forecast_text = (
f"{value_forecast:+.1f}%"
if value_forecast is not None
else "N/A"
)
value_change_text = (
f"~${projected_value_change:+,.0f}"
if projected_value_change is not None
else "N/A"
)
gross_return_text = (
f"{estimated_gross_return:.1f}%"
if estimated_gross_return is not None
else "N/A"
)
explanation_text = format_explanation_html(explanation)
cards.append(
f"""
MATCH #{rank}
{address}
PROPERTY TYPE{property_type}
PRICE{price}
EST. 12-MONTH GROSS RETURN
{gross_return_text}
RENTAL INCOME
{rental_yield_text}
{annual_rent_text}
+
VALUE FORECAST
{forecast_text}
{value_change_text}
Gross estimate before expenses, taxes,
financing and transaction costs.
Illustrative property image
Why this property matches you
{explanation_text}
"""
)
return f"""
{fallback_message}
Your top matches
Three properties selected for your investment profile.
{''.join(cards)}
"""
# ============================================================
# QUICK STARTER USER EXAMPLES
# ============================================================
USER_EXAMPLES = {
"Custom profile": None,
"Eyal Ofer": {
"max_budget_usd": 1_000_000,
"financing_willingness": "no",
"liquidity_importance": "low",
"risk_profile": "aggressive",
"primary_goal": "growth",
},
"Gary Barnett": {
"max_budget_usd": 450_000,
"financing_willingness": "no",
"liquidity_importance": "medium",
"risk_profile": "balanced",
"primary_goal": "preservation",
},
"Adam Neumann": {
"max_budget_usd": 125_000,
"financing_willingness": "yes",
"liquidity_importance": "high",
"risk_profile": "conservative",
"primary_goal": "income",
},
}
# Upload these three authorised image files to the assets folder. The app uses
# an initials-based placeholder until the corresponding image has been added.
EXAMPLE_DETAILS = {
"Eyal Ofer": {
"photo": "eyal_ofer.jpg",
"initials": "EO",
"bio": (
"Eyal Ofer founded Ofer Global, a private portfolio of international businesses. "
"Its areas of activity include maritime shipping, real estate and hotels, technology, banking and energy. "
"This example profile represents a high-budget, growth-oriented investment approach."
),
},
"Gary Barnett": {
"photo": "gary_barnett.jpg",
"initials": "GB",
"bio": (
"Gary Barnett is the founder and chairman of Extell Development. "
"Extell develops luxury residential, commercial and hospitality properties in New York City and beyond. "
"This example profile represents a balanced, preservation-oriented investment approach."
),
},
"Adam Neumann": {
"photo": "adam_neumann.jpg",
"initials": "AN",
"bio": (
"Adam Neumann co-founded WeWork and later founded Flow, a residential real-estate company. "
"Flow focuses on a technology-enabled residential experience for owners, operators and residents. "
"This example profile represents a lower-budget, income-oriented investment approach."
),
},
}
def example_image_url(example):
"""Use an authorised local image when present, otherwise show initials."""
photo_path = ASSET_DIR / EXAMPLE_DETAILS[example]["photo"]
if photo_path.exists():
return "/gradio_api/file=" + quote(str(photo_path.resolve()))
initials = EXAMPLE_DETAILS[example]["initials"]
return (
"data:image/svg+xml;utf8,"
+ quote(
f""
)
)
def render_example_profiles():
cards = []
for name, details in EXAMPLE_DETAILS.items():
cards.append(
f"""
{html.escape(name)}
{html.escape(details['bio'])}
"""
)
return f"
{''.join(cards)}
"
def render_selected_example(example_name):
"""Show an investor bio only when the visitor selects an example."""
if example_name == "Custom profile":
return ""
details = EXAMPLE_DETAILS[example_name]
return f"""