# %pip install anthropic --upgrade
# Install required libraries
# %pip install streamlit
# %pip install anthropic
# %pip install python-dotenv
# %pip install Pillow
In this project, we will explore how artificial intelligence can be leveraged to streamline and enhance various aspects of the real estate industry. We will focus on two key areas: property appraisal and event newsletter generation.
Through this project, you will learn:
- Property Appraisal with AI:
- How to utilize AI models like Anthropic’s Claude to generate detailed and comprehensive property appraisals based on textual descriptions.
- Techniques for incorporating visual information by processing and encoding property images to provide more context to the AI model.
- Adapting the AI-generated appraisals to suit specific markets, such as the Australian real estate market.
- Event Newsletter Generation with AI:
- Leveraging AI to create engaging and personalized newsletters for real estate events.
- Techniques for structuring prompts to guide the AI model in generating event-specific content, including catchy marketing slogans for featured properties.
- Customizing the newsletter generation process to highlight the unique features of each property in relation to the event theme.
- Streamlit App Development:
- Building an interactive web application using the Streamlit framework to showcase the AI-powered property appraisal and newsletter generation functionalities.
- Designing a user-friendly interface that allows users to input property descriptions, upload images, and generate appraisals and newsletters with ease.
- Integrating the AI models seamlessly into the Streamlit app for a smooth user experience.
By the end of this project, you will have gained practical knowledge and hands-on experience in applying AI techniques to automate and enhance property appraisal and event newsletter creation. You will also have developed a functional Streamlit app that demonstrates the power of AI in the real estate domain.
Let’s dive in and explore how AI can revolutionize the way we approach property appraisal and event marketing in the real estate industry!
Project 1: Property Appraisal
import os
import anthropic
from dotenv import load_dotenv
# Load API keys from .env file
load_dotenv()= os.getenv("ANTHROPIC_API_KEY") anthropic.api_key
= anthropic.Anthropic() client
def summarize_text(text):
import anthropic
= f"Please provide a detailed (approx 1000 words) and comprehensive property appraisal suitable for the Australian market based on the following information, using placeholders for the values:\n\n{text}"
prompt # Generate a summary using Claude model
= client.messages.create(
response ="claude-3-opus-20240229",
model="You are an intelligent property appraiser with expertise in the Australian real estate market. Your goal is to write detailed and comprehensive property appraisals.",
system=4000,
max_tokens=0.7,
temperature=[
messages"role": "user", "content": prompt}
{
]
)return response
= """
property_description
This property is a modern, two-story residential home located in a quiet, suburban neighborhood in Melbourne, Australia.
Built in 2015, it features 4 bedrooms, 2 bathrooms, and an open-plan living area.
The 180 sq. m. house sits on a 600 sq. m. lot with a landscaped garden, a patio, and a single-car garage.
"""
= summarize_text(property_description)
appraisal
print(appraisal)
Message(id='msg_01A2Pg1wCV6R72Y9LuBFCi3U', content=[ContentBlock(text="Property Appraisal Report\n\nSubject Property: Modern Two-Story Residential Home\nLocation: [Address], Melbourne, Australia\n\nIntroduction:\nThe purpose of this appraisal is to estimate the market value of the subject property, a modern, two-story residential home located in a quiet, suburban neighborhood in Melbourne, Australia. The appraisal is based on a thorough inspection of the property, an analysis of comparable properties in the area, and a consideration of current market conditions.\n\nProperty Description:\nThe subject property is a well-maintained, two-story residential home built in 2015. The house features a contemporary design with a rendered brick exterior and a tiled roof. The property offers a total living area of approximately 180 square meters (1,938 square feet) and is situated on a generous 600 square meter (6,458 square feet) lot.\n\nThe ground floor comprises an open-plan living area that seamlessly combines the living room, dining room, and kitchen. The modern kitchen features high-quality appliances, ample storage space, and a breakfast bar. The living area has large windows that allow for an abundance of natural light and provide views of the landscaped garden. A sliding glass door leads to the patio, perfect for outdoor entertaining.\n\nThe upper floor consists of four well-appointed bedrooms and two bathrooms. The master bedroom features a walk-in closet and an en-suite bathroom with a double vanity, a shower, and a bathtub. The remaining three bedrooms are served by a shared bathroom with a shower and a single vanity. All bedrooms have built-in wardrobes and carpet flooring.\n\nAdditional features of the property include:\n- Ducted air conditioning throughout the house\n- High ceilings (2.7 meters) on both floors\n- Double-glazed windows for improved energy efficiency\n- Hardwood flooring in the living areas and tiles in the wet areas\n- A single-car garage with internal access to the house\n- A landscaped front and rear garden with mature trees and shrubs\n- A paved patio area perfect for outdoor dining and entertaining\n\nNeighborhood Analysis:\nThe subject property is located in a well-established, quiet suburban neighborhood in Melbourne. The area is characterized by similar modern, single-family homes on medium to large-sized lots. The neighborhood has well-maintained streets, sidewalks, and streetlights. It is conveniently located near schools, parks, shopping centers, and public transportation, making it an attractive location for families and professionals.\n\nMarket Analysis:\nThe Melbourne residential property market has shown resilience and steady growth over the past few years, despite the challenges posed by the COVID-19 pandemic. Low interest rates, government incentives, and a strong demand for housing have contributed to the market's stability. The suburb in which the subject property is located has experienced a moderate increase in median house prices over the past 12 months, with a growing demand for modern, well-maintained homes.\n\nComparable Sales:\nThe following comparable sales were selected based on their similarity to the subject property in terms of location, size, age, and condition:\n\n1. [Address], Melbourne - A modern, two-story home with 4 bedrooms, 2 bathrooms, and a total living area of 185 sq. m. on a 580 sq. m. lot. Sold for $[X] in [Month, Year].\n\n2. [Address], Melbourne - A 2016-built, two-story home with 4 bedrooms, 2 bathrooms, and a total living area of 175 sq. m. on a 610 sq. m. lot. Sold for $[Y] in [Month, Year].\n\n3. [Address], Melbourne - A modern, two-story home with 4 bedrooms, 2 bathrooms, and a total living area of 190 sq. m. on a 595 sq. m. lot. Sold for $[Z] in [Month, Year].\n\nValuation:\nBased on the analysis of the subject property, the neighborhood, the current market conditions, and the comparable sales, the estimated market value of the subject property as of [Date] is:\n\n$[Estimated Market Value]\n\nThis value estimate is subject to the following assumptions and limiting conditions:\n1. The appraiser has inspected the property, but no structural or mechanical tests were conducted.\n2. The appraiser assumes no responsibility for hidden defects or non-apparent conditions of the property.\n3. The information provided by the client and other sources is assumed to be accurate and reliable.\n4. This appraisal is for the sole use of the client and intended users and should not be relied upon by any other party.\n\nConclusion:\nThe subject property is a well-maintained, modern two-story residential home in a desirable suburban neighborhood in Melbourne. Its features, location, and condition make it an attractive option for potential buyers in the current market. The estimated market value of $[Estimated Market Value] reflects the property's characteristics and is supported by the analysis of comparable sales and market trends.\n\nAppraiser:\n[Appraiser's Name]\n[Appraiser's Certification/License Number]\n[Appraisal Company Name]", type='text')], model='claude-3-opus-20240229', role='assistant', stop_reason='end_turn', stop_sequence=None, type='message', usage=Usage(input_tokens=170, output_tokens=1154))
# display using markdown
from IPython.display import Markdown
# Display the summary in markdown format
0].text))
display(Markdown(appraisal.content[
Property Appraisal Report
Property Description: The subject property is a contemporary, two-story residential dwelling situated in a tranquil, suburban neighborhood in Melbourne, Australia. Constructed in 2015, this well-maintained home offers a comfortable living space for a family or individuals seeking a modern lifestyle. The property features 4 bedrooms, 2 bathrooms, and an open-plan living area, providing ample space for both relaxation and entertainment. With a total living area of 180 square meters (1,938 square feet), the house sits on a generous 600 square meter (6,458 square feet) lot, which includes a beautifully landscaped garden, a patio, and a single-car garage.
Location and Neighborhood: The property is located in a desirable suburban area of Melbourne, known for its safety, convenience, and family-friendly atmosphere. The neighborhood is characterized by well-maintained homes, manicured lawns, and tree-lined streets, creating a pleasant and visually appealing environment. The area is served by reputable schools, both primary and secondary, making it an ideal location for families with school-aged children. Additionally, the property is in close proximity to local amenities such as shopping centers, restaurants, parks, and recreational facilities, ensuring a convenient and enjoyable lifestyle for residents.
Accessibility and Transportation: The property benefits from excellent accessibility and transportation links. It is situated within easy reach of major roads and highways, providing convenient access to Melbourne’s central business district and other key areas of the city. Public transportation options, including bus and train services, are readily available, offering an alternative and sustainable mode of travel for commuters. The nearby train station is located within a 10-minute walk from the property, while bus stops are conveniently placed throughout the neighborhood.
Property Condition and Features: The two-story residential home is in excellent condition, having been well-maintained since its construction in 2015. The exterior of the property features a modern and attractive design, with a combination of brick and rendered finishes, complemented by large windows that allow for ample natural light to enter the home. The landscaped garden, which is well-established and thoughtfully designed, provides a pleasant outdoor space for relaxation and entertaining. The patio area is perfect for alfresco dining and enjoying the mild Melbourne climate.
Inside, the open-plan living area creates a spacious and inviting atmosphere, ideal for family gatherings and entertaining guests. The living area seamlessly connects to the modern, well-appointed kitchen, which features high-quality appliances, ample storage space, and a breakfast bar for casual dining. The kitchen’s layout and finishes make it both functional and visually appealing.
The home offers 4 bedrooms, providing comfortable accommodation for a family or guests. The master bedroom is generously sized and includes a private en-suite bathroom and built-in wardrobes, offering a luxurious and convenient space for the homeowners. The remaining bedrooms are well-proportioned and feature built-in wardrobes, ensuring ample storage space for occupants.
The two bathrooms in the property are modern and well-maintained, with high-quality fixtures and fittings. The family bathroom services the three additional bedrooms, while the en-suite bathroom attached to the master bedroom provides added privacy and convenience.
The property also includes a single-car garage, providing secure parking for one vehicle and additional storage space for household items. The garage is accessible from the main house, offering a convenient and sheltered entry point.
Market Analysis and Comparable Sales: To determine the market value of the subject property, a thorough analysis of recent sales of similar properties in the area has been conducted. The following comparable sales have been identified:
- [Address], sold for $[X] in [Month, Year]
- Similar in size, age, and condition
- 4 bedrooms, 2 bathrooms, single-car garage
- 190 sq. m. house on a 580 sq. m. lot
- [Address], sold for $[Y] in [Month, Year]
- Comparable location and neighborhood
- 4 bedrooms, 2 bathrooms, single-car garage
- 175 sq. m. house on a 610 sq. m. lot
- [Address], sold for $[Z] in [Month, Year]
- Similar age and condition
- 4 bedrooms, 2 bathrooms, double-car garage
- 185 sq. m. house on a 595 sq. m. lot
Based on these comparable sales and taking into account the subject property’s unique features, location, and condition, the estimated market value of the property is between $[A] and $[B].
Conclusion: The subject property, a modern two-story residential home in a desirable Melbourne suburb, presents an excellent opportunity for potential buyers seeking a well-maintained, spacious, and conveniently located family home. With its 4 bedrooms, 2 bathrooms, open-plan living area, and attractive outdoor spaces, the property offers a comfortable and contemporary living environment. Its proximity to schools, amenities, and transportation links further enhances its appeal and value.
Considering the property’s features, condition, location, and recent comparable sales in the area, the estimated market value of the property is between $[A] and $[B]. This valuation reflects the property’s desirability and its potential to provide a high quality of life for its occupants in a sought-after Melbourne neighborhood.
Project 2: Property Appraisal with a house images
from IPython.display import display, HTML
def display_images_side_by_side(image_paths):
= "<div style='display: flex; justify-content: space-between;'>"
html for path in image_paths:
+= f"<img src='{path}' style='width: 30%; height: auto;'>"
html += "</div>"
html
display(HTML(html))
= [
image_paths "front_view.webp","side_view.webp"
]
display_images_side_by_side(image_paths)
import os
import anthropic
from dotenv import load_dotenv
from IPython.display import Markdown, Image
import base64
from PIL import Image as PILImage
import io
# Load API keys from .env file
load_dotenv()= os.getenv("ANTHROPIC_API_KEY")
anthropic.api_key
def appraise_property(description, image_paths):
# Read and encode the images
= []
encoded_images for path in image_paths:
with open(path, "rb") as image_file:
= PILImage.open(image_file)
image
# Convert the image to PNG format
= io.BytesIO()
png_image format="PNG")
image.save(png_image, 0)
png_image.seek(= base64.b64encode(png_image.read()).decode("utf-8")
encoded_image
encoded_images.append(encoded_image)# Construct the prompt with description and images
= f"Please provide a detailed (approx 1000 words), use placeholders for the values, and comprehensive property appraisal suitable for the Australian market based on the following information and images:\n\nDescription:\n{description}\n\nImages:\n"
prompt
# Create the content array with text and image blocks
= [{"type": "text", "text": prompt}]
content for i, encoded_image in enumerate(encoded_images, start=1):
"type": "text", "text": f"Image {i}:"})
content.append({
content.append({"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": encoded_image
}
})
# Generate appraisal using Claude model
= anthropic.Anthropic().messages.create(
response ="claude-3-opus-20240229",
model="You are an intelligent property appraiser working for a real estate firm. You are an expert at property appraisal. Your goal is to write detailed and comprehensive property appraisals.",
system=4000,
max_tokens=0.7,
temperature=[{"role": "user", "content": content}]
messages
)return response.content[0].text
# Example usage
= """
property_description This property is a modern, two-story residential home located in a quiet, suburban neighborhood in Melbourne, Australia.
Built in 2015, it features 4 bedrooms, 2 bathrooms, and an open-plan living area.
The 180 sq. m. house sits on a 600 sq. m. lot with a landscaped garden, a patio, and a single-car garage.
"""
= [
image_paths "front_view.webp","side_view.webp"
]
= appraise_property(property_description, image_paths)
appraisal
# Display the appraisal in markdown format
display(Markdown(appraisal))
Property Appraisal Report
Property Overview: The subject property is a contemporary, two-story residential home situated in a tranquil, suburban neighborhood in Melbourne, Australia. Constructed in 2015, this [PROPERTY_AGE]-year-old home offers 4 bedrooms, 2 bathrooms, and an open-plan living area. The house, measuring approximately 180 sq. m., is positioned on a generous 600 sq. m. lot that features a well-maintained landscaped garden, a patio, and a single-car garage.
Exterior: The home boasts a striking, modern architectural design with clean lines and a blend of materials, including wood, brick, and glass. The exterior showcases warm, earthy tones, complemented by expansive windows that allow ample natural light to flood the interior spaces. The landscaped garden is meticulously maintained, offering a serene and inviting outdoor environment. The patio, accessible from the living area, provides an ideal space for outdoor entertaining and relaxation. The single-car garage offers secure parking and additional storage space.
Interior: The open-plan living area is the heart of the home, seamlessly connecting the kitchen, dining, and living spaces. This layout creates a sense of spaciousness and facilitates a smooth flow between the various functional areas. The interior features a contemporary, neutral color palette, with high-quality finishes and modern fixtures throughout.
The kitchen is well-appointed with sleek, modern cabinetry, premium appliances, and ample counter space, making it ideal for both everyday cooking and entertaining. The living room is designed to maximize comfort and style, with large windows that offer picturesque views of the surrounding landscape.
The home features 4 bedrooms, providing comfortable accommodation for a family or guests. The master bedroom likely includes an en-suite bathroom and built-in wardrobes, offering a private retreat for the homeowners. The remaining bedrooms are well-proportioned and can easily accommodate various furniture configurations.
The 2 bathrooms in the home are expected to feature contemporary tiling, modern fixtures, and ample storage space, ensuring both functionality and style.
Location: The property’s location in a quiet, suburban neighborhood in Melbourne is a significant asset. Melbourne, being one of Australia’s most livable cities, offers a wide range of amenities, including excellent schools, shopping centers, recreational facilities, and public transportation. The home’s proximity to these amenities, combined with its peaceful setting, makes it an attractive option for families and professionals alike.
Market Analysis: The Melbourne property market has demonstrated resilience and consistent growth over the past several years. Despite the challenges posed by the COVID-19 pandemic, the market has remained stable, with a steady demand for quality housing. The median house price in Melbourne as of [CURRENT_DATE] is approximately [MEDIAN_HOUSE_PRICE], indicating a healthy market conditions.
Properties similar to the subject home, featuring modern architecture, open-plan living, and a desirable location, have been in high demand. Comparable sales in the area range from [COMPARABLE_SALE_RANGE], depending on the specific location, lot size, and condition of the property.
Valuation: Based on the property’s features, location, and current market conditions, the estimated value of the subject property is [ESTIMATED_VALUE]. This valuation takes into account the home’s modern design, spacious living areas, desirable location, and the overall demand for similar properties in the Melbourne market.
Conclusion: The subject property presents an excellent opportunity for homebuyers seeking a modern, well-appointed home in a sought-after Melbourne neighborhood. Its contemporary design, open-plan living, and attractive outdoor spaces make it well-suited for a range of buyers, from families to professionals. With the Melbourne property market demonstrating consistent growth and demand, this home is expected to maintain its value and provide a solid investment opportunity for prospective buyers.
Streamlit App
Create a file named app.py, copy the next cell content, and run the following command in your terminal to start the Streamlit app:
streamlit run app.py
import streamlit as st
import anthropic
from dotenv import load_dotenv
import os
import base64
from PIL import Image as PILImage
import io
# Load API keys from .env file
load_dotenv()= os.getenv("ANTHROPIC_API_KEY")
anthropic.api_key
def summarize_text(text):
import anthropic
= f"Please provide a detailed ( approx 1000 words) and comprehensive property appraisal suitable for the Australian market based on the following information, use placeholders for the values :\n\n{text}"
prompt # Generate a summary using Claude model
= anthropic.Anthropic().messages.create(
response ="claude-3-opus-20240229",
model="You are an intelligent property appraiser with expertise in the Australian real estate market. Your goal is to write detailed and comprehensive property appraisals.",
system=4000,
max_tokens=0.7,
temperature=[{"role": "user", "content": prompt}],
messages
)# Assuming the response structure contains a 'text' field with the summary
return response
def appraise_property(description, image_paths):
# Read and encode the images
= []
encoded_images for path in image_paths:
with open(path, "rb") as image_file:
= PILImage.open(image_file)
image
# Convert the image to PNG format
= io.BytesIO()
png_image format="PNG")
image.save(png_image, 0)
png_image.seek(= base64.b64encode(png_image.read()).decode("utf-8")
encoded_image
encoded_images.append(encoded_image)# Construct the prompt with description and images
= f"Please provide a detailed (approx 1000 words), use placeholders for the values, and comprehensive property appraisal suitable for the Australian market based on the following information and images:\n\nDescription:\n{description}\n\n"
prompt
# Create the content array with text and image blocks
= [{"type": "text", "text": prompt}]
content for i, encoded_image in enumerate(encoded_images, start=1):
"type": "text", "text": f"Image {i}:"})
content.append({
content.append(
{"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": encoded_image,
},
}
)
# Generate appraisal using Claude model
= anthropic.Anthropic().messages.create(
response ="claude-3-opus-20240229",
model="You are an intelligent property appraiser with expertise in the Australian real estate market. Your goal is to write detailed and comprehensive property appraisals.",
system=4000,
max_tokens=0.7,
temperature=[{"role": "user", "content": content}],
messages
)return response.content[0].text
def create_event_newsletter(event, properties):
# Construct the prompt with event and property details
= f"Create a newsletter for the {event} event, featuring the following properties:\n\n"
prompt for i, (name, description) in enumerate(properties, start=1):
+= f"Property {i}: {name}\nDescription: {description}\n\n"
prompt
+= f"For each property, generate a catchy marketing slogan related to the {event} event. The newsletter should be engaging and highlight the unique features of each property in relation to the event., aim 300 words for each property"
prompt
# Generate newsletter using Claude model
= anthropic.Anthropic().messages.create(
response ="claude-3-opus-20240229",
model="You are a creative marketing assistant specializing in real estate. Your goal is to write engaging newsletters featuring properties for specific events, including catchy marketing slogans.",
system=4000,
max_tokens=0.7,
temperature=[{"role": "user", "content": prompt}],
messages
)return response.content[0].text
def main():
="wide")
st.set_page_config(layout
"Property Appraisal and Newsletter Generator")
st.title(
= st.radio(
project "Select a project",
"Property Appraisal", "Property Appraisal with Images", "Event Newsletter"),
(
)
= """This property is a residential home located in a neighborhood.
proj1_val It features bedrooms, bathrooms, and a living area.
The house sits on a lot with a garden, a deck, and a garage."""
= """("Property 1", "A spacious property with a large backyard, perfect for family gatherings."),
proj3_val ("Property 2", "An intimate property ideal for a quiet retreat with loved ones."),
("Property 3", "A luxurious property with stunning views, offering a serene setting for an unforgettable celebration.")
]"""
if project == "Property Appraisal":
"Project 1: Property Appraisal")
st.header(= st.text_area("Enter property description", value=proj1_val)
property_description if st.button("Generate Appraisal"):
= summarize_text(property_description)
appraisal 0].text)
st.markdown(appraisal.content[
elif project == "Property Appraisal with Images":
"Project 2: Property Appraisal with Images")
st.header(= st.text_area("Enter property description", value=proj1_val)
property_description = st.file_uploader(
uploaded_images "Upload property images",
type=["png", "jpg", "jpeg"],
=True,
accept_multiple_files
)if st.button("Generate Appraisal"):
if uploaded_images:
= []
image_paths for uploaded_image in uploaded_images:
= PILImage.open(uploaded_image)
image = f"{uploaded_image.name}"
image_path
image.save(image_path)
image_paths.append(image_path)=uploaded_image.name, use_column_width=True)
st.image(image, caption= appraise_property(property_description, image_paths)
appraisal
st.markdown(appraisal)else:
"Please upload at least one image.")
st.warning(
elif project == "Event Newsletter":
"Project 3: Event Newsletter")
st.header(= st.text_input("Enter event name", value="Summer Festival")
event = st.number_input(
num_properties "Number of properties", min_value=1, max_value=10, value=3, step=1
)= []
properties for i in range(num_properties):
f"Property {i+1}")
st.subheader(= st.text_input(f"Enter property name {i+1}", value=f"Property {i+1}")
name = st.text_area(f"Enter property description {i+1}", value=f"A beautiful property perfect for the {event}.")
description
properties.append((name, description))if st.button("Generate Newsletter"):
= create_event_newsletter(event, properties)
newsletter
st.markdown(newsletter)
if __name__ == "__main__":
main()