File size: 7,839 Bytes
14cb7ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
190
191
192
193
# models/property_summary.py

from .model_loader import load_model
from .logging_config import logger
from .utils import summarize_text

def validate_and_format_data(data):
    """Validate and format property data"""
    # Format square feet
    try:
        sq_ft = float(data.get('sq_ft', 0))
        if sq_ft < 100:  # If square feet seems too small, it might be in wrong unit
            sq_ft *= 100  # Convert to square feet if it was in square meters
        data['sq_ft'] = int(sq_ft)
    except:
        data['sq_ft'] = 0

    # Format market value
    try:
        market_value = float(data.get('market_value', 0))
        if market_value > 1000000000:  # If value seems too high
            market_value = market_value / 100  # Adjust if there's a decimal point issue
        data['market_value'] = int(market_value)
    except:
        data['market_value'] = 0

    # Format amenities
    if data.get('amenities'):
        if isinstance(data['amenities'], str):
            amenities = [a.strip() for a in data['amenities'].split(',') if a.strip()]
            data['amenities'] = amenities
        elif isinstance(data['amenities'], list):
            data['amenities'] = [a.strip() for a in data['amenities'] if a.strip()]
    else:
        data['amenities'] = []

    return data

def format_price(price):
    """Format price in Indian currency format"""
    try:
        price = float(price)
        if price >= 10000000:  # 1 Crore
            return f"₹{price/10000000:.2f} Cr"
        elif price >= 100000:  # 1 Lakh
            return f"₹{price/100000:.2f} L"
        else:
            return f"₹{price:,.2f}"
    except:
        return f"₹{price}"

def generate_static_summary(data):
    """Generate a conversational property summary"""
    # Validate and format data
    data = validate_and_format_data(data)
    price = format_price(data.get('market_value', '0'))
    
    # Get property type with proper formatting
    property_type = data.get('property_type', 'property').strip()
    if property_type.lower() == 'apartment':
        property_type = '2 BHK Apartment'  # Add BHK information if available
    
    summary = f"""
    Namaste! Let me tell you about this wonderful {property_type} that's {data.get('status', 'available').lower()}.

    This beautiful property is located in {data.get('city', 'the city')}, {data.get('state', '')}. It's a spacious {property_type} spanning {data.get('sq_ft', '0')} square feet, perfect for your family.

    Key Highlights:
    • Price: {price}
    • Bedrooms: {data.get('bedrooms', '0')} spacious bedrooms
    • Bathrooms: {data.get('bathrooms', '0')} modern bathrooms
    • Year Built: {data.get('year_built', 'N/A')}
    • Parking: {data.get('parking_spaces', '0')} covered parking spaces
    """

    # Add property description if available
    if data.get('property_description'):
        summary += f"\n\nProperty Description:\n{data.get('property_description')}"

    # Add possession date if available
    if data.get('possession_date'):
        summary += f"\n• Ready for possession from: {data.get('possession_date')}"

    # Add amenities if available
    if data.get('amenities'):
        amenities = data['amenities']
        if len(amenities) > 0:
            summary += "\n\nNearby Amenities:\n• " + "\n• ".join(amenities)

    # Add nearby landmarks if available
    if data.get('nearby_landmarks'):
        landmarks = data['nearby_landmarks']
        if isinstance(landmarks, str):
            landmarks = [l.strip() for l in landmarks.split(',') if l.strip()]
        if len(landmarks) > 0:
            summary += "\n\nNearby Landmarks:\n• " + "\n• ".join(landmarks)

    # Add a friendly closing
    summary += "\n\nThis property offers excellent value for money and is located in a prime area. Would you like to know more details about this property?"

    return summary.strip()

def generate_property_summary(data):
    try:
        # Validate and format data first
        data = validate_and_format_data(data)

        # Create a detailed context for summary generation
        property_context = f"""
        Property Details:
        Name: {data.get('property_name', '')}
        Type: {data.get('property_type', '')}
        Status: {data.get('status', '')}
        Location: {data.get('address', '')}, {data.get('city', '')}, {data.get('state', '')}, {data.get('country', '')}
        Size: {data.get('sq_ft', '')} sq. ft.
        Price: {format_price(data.get('market_value', '0'))}
        Bedrooms: {data.get('bedrooms', '')}
        Bathrooms: {data.get('bathrooms', '')}
        Year Built: {data.get('year_built', '')}
        Parking: {data.get('parking_spaces', '')} spaces
        Description: {data.get('property_description', '')}
        Possession Date: {data.get('possession_date', '')}
        Amenities: {', '.join(data.get('amenities', []))}
        Nearby Landmarks: {data.get('nearby_landmarks', '')}
        """

        # Try to use BART for summary generation
        try:
            summarizer = load_model("summarization", "sshleifer/distilbart-cnn-6-6")
            summary_result = summarizer(property_context, max_length=500, min_length=100, do_sample=False)
            initial_summary = summary_result[0]['summary_text']
        except Exception as model_error:
            logger.warning(f"Model generation failed, using static summary: {str(model_error)}")
            initial_summary = generate_static_summary(data)

        # Enhance summary with key features
        key_features = []

        # Add property type and status
        if data.get('property_type') and data.get('status'):
            key_features.append(f"This {data['property_type']} is {data['status'].lower()}")

        # Add location if available
        location_parts = []
        if data.get('city'):
            location_parts.append(data['city'])
        if data.get('state'):
            location_parts.append(data['state'])
        if location_parts:
            key_features.append(f"Located in {', '.join(location_parts)}")

        # Add size and price if available
        if data.get('sq_ft'):
            key_features.append(f"Spans {data['sq_ft']} sq. ft.")
        if data.get('market_value'):
            key_features.append(f"Priced at {format_price(data['market_value'])}")

        # Add rooms information
        rooms_info = []
        if data.get('bedrooms'):
            rooms_info.append(f"{data['bedrooms']} bedroom{'s' if data['bedrooms'] != '1' else ''}")
        if data.get('bathrooms'):
            rooms_info.append(f"{data['bathrooms']} bathroom{'s' if data['bathrooms'] != '1' else ''}")
        if rooms_info:
            key_features.append(f"Features {' and '.join(rooms_info)}")

        # Add parking information
        if data.get('parking_spaces'):
            key_features.append(f"Includes {data['parking_spaces']} covered parking space{'s' if data['parking_spaces'] != '1' else ''}")

        # Add possession date if available
        if data.get('possession_date'):
            key_features.append(f"Ready for possession from {data['possession_date']}")

        # Add amenities if available
        if data.get('amenities'):
            amenities = data['amenities']
            if len(amenities) > 0:
                key_features.append(f"Amenities: {', '.join(amenities)}")

        # Combine initial summary with key features
        enhanced_summary = initial_summary
        if key_features:
            enhanced_summary += "\n\nKey Features:\n• " + "\n• ".join(key_features)

        # Clean up the summary
        enhanced_summary = enhanced_summary.replace("  ", " ").strip()

        return enhanced_summary
    except Exception as e:
        logger.error(f"Error generating property summary: {str(e)}")
        return generate_static_summary(data)